Skip to main content

brep_plugins/
lib.rs

1//! Pinned JavaScript CAD packages on Boa, backed by exact kernel solids.
2//!
3//! Trusted, explicitly provisioned packages. Saved pins never carry executable code.
4//!
5//! A [`PackageBundle`] is validated and pinned by digest ([`PackageBundle::pin`],
6//! [`PluginPin`]). [`Runtime::new`] installs bundles and builds the [`Registry`] of
7//! feature, action, workbench, panel, annotation and post descriptors;
8//! [`Registry::for_document`] selects a document's exact pins. The runtime is the
9//! kernel's extension provider: [`Runtime::execute_history`] and
10//! [`Runtime::with_provider`] scope it around kernel calls, and
11//! [`Runtime::execute_action`], [`Runtime::execute_annotation`] and
12//! [`execute_script`] run callbacks. See the README for the JavaScript API and its
13//! limits.
14pub use brep_kernel::feature_pipeline::extension::PluginPin;
15use brep_kernel::feature_pipeline::{self as kernel, FeatureContext, FeatureResult};
16use serde::{Deserialize, Serialize};
17use serde_json::{json, Value};
18use sha2::{Digest, Sha256};
19use std::{
20    collections::{BTreeMap, BTreeSet},
21    rc::Rc,
22};
23mod annotations;
24mod invocation;
25#[derive(Clone, Debug, Serialize, Deserialize)]
26#[serde(rename_all = "camelCase", deny_unknown_fields)]
27pub struct PackageManifest {
28    pub id: String,
29    pub version: String,
30    pub api_version: u32,
31    pub name: String,
32    pub entry: String,
33}
34#[derive(Clone, Debug, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase", deny_unknown_fields)]
36pub struct PackageBundle {
37    pub manifest: PackageManifest,
38    pub modules: BTreeMap<String, String>,
39    #[serde(default)]
40    pub assets: BTreeMap<String, Vec<u8>>,
41}
42fn local_path(s: &str) -> bool {
43    !s.is_empty()
44        && !s.contains('\\')
45        && !s.contains(':')
46        && s.split('/').all(|p| !p.is_empty() && p != "." && p != "..")
47}
48impl PackageBundle {
49    pub fn pin(&self) -> Result<PluginPin, String> {
50        let m = &self.manifest;
51        if m.api_version != 1
52            || m.id.is_empty()
53            || m.id.contains('/')
54            || !m
55                .id
56                .chars()
57                .all(|c| c.is_ascii_alphanumeric() || ".-_".contains(c))
58            || m.version.is_empty()
59            || m.name.is_empty()
60        {
61            return Err(format!(
62                "{}: invalid manifest or unsupported API version",
63                m.id
64            ));
65        }
66        if !local_path(&m.entry)
67            || !self.modules.contains_key(&m.entry)
68            || self.modules.len() > 128
69            || self
70                .modules
71                .keys()
72                .chain(self.assets.keys())
73                .any(|p| !local_path(p))
74        {
75            return Err(format!(
76                "{}: invalid package-local paths or module count",
77                m.id
78            ));
79        }
80        if self.modules.values().map(String::len).sum::<usize>()
81            + self.assets.values().map(Vec::len).sum::<usize>()
82            > 8 * 1024 * 1024
83        {
84            return Err("package exceeds 8 MiB".into());
85        }
86        let digest = format!(
87            "{:x}",
88            Sha256::digest(serde_json::to_vec(self).map_err(|e| e.to_string())?)
89        );
90        Ok(PluginPin {
91            id: m.id.clone(),
92            version: m.version.clone(),
93            api_version: m.api_version,
94            digest,
95        })
96    }
97}
98#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct FeatureRegistration {
101    pub id: String,
102    pub label: String,
103    pub glyph: String,
104    pub ribbon_path: String,
105    pub command_size: String,
106    pub short_name: String,
107    pub input_params_schema: Value,
108    pub package: PluginPin,
109}
110#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
111#[serde(rename_all = "camelCase")]
112pub struct ActionRegistration {
113    pub id: String,
114    pub label: String,
115    pub glyph: String,
116    pub ribbon_path: String,
117    pub command_size: String,
118    pub input_params_schema: Value,
119    pub package: PluginPin,
120}
121#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123pub struct WorkbenchRegistration {
124    pub id: String,
125    pub label: String,
126    pub feature_types: Vec<String>,
127    pub actions: Vec<String>,
128    pub panels: Vec<String>,
129    pub package: PluginPin,
130}
131#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct AnnotationRegistration {
134    pub id: String,
135    pub label: String,
136    pub input_params_schema: Value,
137    pub package: PluginPin,
138}
139/// A CAM post-processor a package ships: `module` names the package-local
140/// script (a `post.define({...})` file for BREP_cam's post host). The package
141/// runtime only registers it; the CAM workbench reads the module text and
142/// runs it on BREP_cam's post runtime.
143#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
144#[serde(rename_all = "camelCase")]
145pub struct PostRegistration {
146    pub id: String,
147    pub label: String,
148    pub module: String,
149    pub package: PluginPin,
150}
151#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153pub struct PanelRegistration {
154    pub id: String,
155    pub label: String,
156    pub controls: Vec<PanelControl>,
157    pub package: PluginPin,
158}
159#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
160#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
161pub enum PanelControl {
162    Text {
163        text: String,
164    },
165    Table {
166        columns: Vec<String>,
167        rows: Vec<Vec<String>>,
168    },
169    Action {
170        id: String,
171        label: String,
172        action: String,
173        #[serde(default = "empty_object")]
174        params: Value,
175    },
176    Form {
177        id: String,
178        label: String,
179        action: String,
180        #[serde(default = "empty_object")]
181        params: Value,
182    },
183}
184fn empty_object() -> Value {
185    json!({})
186}
187#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
188pub struct Registry {
189    features: Vec<FeatureRegistration>,
190    actions: Vec<ActionRegistration>,
191    workbenches: Vec<WorkbenchRegistration>,
192    #[serde(default)]
193    panels: Vec<PanelRegistration>,
194    #[serde(default)]
195    annotations: Vec<AnnotationRegistration>,
196    #[serde(default)]
197    posts: Vec<PostRegistration>,
198    packages: Vec<PluginPin>,
199    revision: String,
200}
201impl Registry {
202    pub fn panels(&self) -> &[PanelRegistration] {
203        &self.panels
204    }
205    pub fn posts(&self) -> &[PostRegistration] {
206        &self.posts
207    }
208    pub fn annotations(&self) -> &[AnnotationRegistration] {
209        &self.annotations
210    }
211    pub fn features(&self) -> &[FeatureRegistration] {
212        &self.features
213    }
214    pub fn actions(&self) -> &[ActionRegistration] {
215        &self.actions
216    }
217    pub fn workbenches(&self) -> &[WorkbenchRegistration] {
218        &self.workbenches
219    }
220    pub fn revision(&self) -> &str {
221        &self.revision
222    }
223    pub fn install(packages: &[PackageBundle]) -> Result<Self, String> {
224        let mut result = Self::default();
225        let mut seen = BTreeSet::new();
226        for package in packages {
227            let pin = package.pin()?;
228            if !seen.insert((pin.id.clone(), pin.digest.clone())) {
229                return Err(format!("duplicate package {}", pin.id));
230            }
231            let r = invocation::invoke(package, None, None, None, None)?.0;
232            result.packages.push(pin);
233            result.features.extend(r.features);
234            result.actions.extend(r.actions);
235            result.workbenches.extend(r.workbenches);
236            result.panels.extend(r.panels);
237            result.annotations.extend(r.annotations);
238            result.posts.extend(r.posts);
239        }
240        result.revision = format!("{:x}", Sha256::digest(serde_json::to_vec(&result).unwrap()));
241        Ok(result)
242    }
243    pub fn for_document(&self, pins: &[PluginPin]) -> Result<Self, String> {
244        let mut ids = BTreeSet::new();
245        for pin in pins {
246            if !ids.insert(&pin.id) {
247                return Err(format!("duplicate document pin {}", pin.id));
248            }
249            if !self.packages.contains(pin) {
250                return Err(format!("missing or disabled pinned package {}", pin.id));
251            }
252        }
253        let mut r = self.clone();
254        r.packages = pins.to_vec();
255        r.features.retain(|x| pins.contains(&x.package));
256        r.actions.retain(|x| pins.contains(&x.package));
257        r.workbenches.retain(|x| pins.contains(&x.package));
258        r.panels.retain(|x| pins.contains(&x.package));
259        r.annotations.retain(|x| pins.contains(&x.package));
260        r.posts.retain(|x| pins.contains(&x.package));
261        r.revision = format!("{:x}", Sha256::digest(serde_json::to_vec(&r).unwrap()));
262        Ok(r)
263    }
264}
265#[derive(Clone, Debug, Serialize, Deserialize)]
266#[serde(tag = "op", rename_all = "camelCase")]
267pub enum DocumentCommand {
268    AddFeature {
269        #[serde(rename = "featureType")]
270        feature_type: String,
271        #[serde(rename = "inputParams")]
272        input_params: Value,
273        #[serde(rename = "persistentData")]
274        persistent_data: Value,
275    },
276    UpdateFeature {
277        id: String,
278        #[serde(rename = "inputParams")]
279        input_params: Value,
280    },
281    DeleteFeature {
282        id: String,
283    },
284}
285#[derive(Clone, Debug, Default, Serialize, Deserialize)]
286pub struct ActionPlan {
287    pub commands: Vec<DocumentCommand>,
288    pub notifications: Vec<String>,
289}
290
291/// Execute an explicitly submitted editor script without installing or pinning it.
292/// The source is a function body with `cad` (the action context) and `ui.notify`.
293/// Only the resulting document commands survive; built-in features replay normally.
294pub fn execute_script(source: &str, input: &Value) -> Result<ActionPlan, String> {
295    let package = PackageBundle {
296        manifest: PackageManifest {
297            id: "cad.editor".into(), version: "1".into(), api_version: 1,
298            name: "JavaScript editor".into(), entry: "editor.js".into(),
299        },
300        modules: BTreeMap::from([("editor.js".into(), format!(r#"
301export default function install(app) {{
302    app.registerAction({{id: 'cad.editor/run', label: 'Run script', run(cad) {{
303        const ui = Object.freeze({{notify: cad.notify}});
304        const result = (function(cad, ui) {{
305{source}
306        }})(cad, ui);
307        if (result && typeof result.then === 'function') throw Error('Promise results are unsupported');
308        if (result !== undefined) console.log('Result:', JSON.stringify(result));
309    }} }});
310}}
311"#))]),
312        assets: BTreeMap::new(),
313    };
314    let (_, value, _) = invocation::invoke(
315        &package, Some(("action", "cad.editor/run")), Some(input), None, None,
316    )?;
317    serde_json::from_value(value).map_err(|e| e.to_string())
318}
319#[derive(Clone)]
320pub struct Runtime {
321    packages: Vec<PackageBundle>,
322    registry: Registry,
323}
324impl Runtime {
325    pub fn new(packages: Vec<PackageBundle>) -> Result<Self, String> {
326        let registry = Registry::install(&packages)?;
327        Ok(Self { packages, registry })
328    }
329    /// Rehydrate a registry validated by a trusted worker. This is not an install API
330    /// for untrusted metadata. Hash/owner checks do not execute JavaScript.
331    pub fn from_validated(
332        packages: Vec<PackageBundle>,
333        registry: Registry,
334    ) -> Result<Self, String> {
335        let pins = packages
336            .iter()
337            .map(PackageBundle::pin)
338            .collect::<Result<Vec<_>, _>>()?;
339        if pins != registry.packages {
340            return Err("validated registry package pins mismatch".into());
341        }
342        for (id, pin) in registry
343            .features
344            .iter()
345            .map(|r| (&r.id, &r.package))
346            .chain(registry.actions.iter().map(|r| (&r.id, &r.package)))
347            .chain(registry.workbenches.iter().map(|r| (&r.id, &r.package)))
348            .chain(registry.panels.iter().map(|r| (&r.id, &r.package)))
349            .chain(registry.annotations.iter().map(|r| (&r.id, &r.package)))
350            .chain(registry.posts.iter().map(|r| (&r.id, &r.package)))
351        {
352            if !pins.contains(pin) || !id.starts_with(&format!("{}/", pin.id)) {
353                return Err("validated registry ownership mismatch".into());
354            }
355        }
356        Ok(Self { packages, registry })
357    }
358    pub fn registry(&self) -> &Registry {
359        &self.registry
360    }
361    pub fn with_provider<R>(&self, f: impl FnOnce() -> R) -> R {
362        kernel::extension::with_provider(Rc::new(self.clone()), f)
363    }
364    pub fn execute_history(&self, request: &kernel::HistoryRequest) -> kernel::HistoryResult {
365        self.with_provider(|| kernel::execute_history(request))
366    }
367    fn package(&self, pins: &[PluginPin], id: &str) -> Result<&PackageBundle, String> {
368        let owner = id.split('/').next().unwrap_or("");
369        let matches: Vec<_> = pins.iter().filter(|p| p.id == owner).collect();
370        if matches.len() != 1 {
371            return Err(format!("{} requires exactly one document plugin pin", id));
372        }
373        self.packages
374            .iter()
375            .find(|p| p.pin().as_ref() == Ok(matches[0]))
376            .ok_or_else(|| format!("missing or disabled pinned package for {id}"))
377    }
378    pub fn execute_action(
379        &self,
380        pins: &[PluginPin],
381        id: &str,
382        input: &Value,
383    ) -> Result<ActionPlan, String> {
384        let p = self.package(pins, id)?;
385        let (r, v, _) = invocation::invoke(
386            p,
387            Some(("action", id)),
388            Some(input),
389            None,
390            Some(&self.registry.for_document(&[p.pin()?])?),
391        )?;
392        self.verify(p, &r)?;
393        serde_json::from_value(v).map_err(|e| e.to_string())
394    }
395    fn verify(&self, p: &PackageBundle, r: &Registry) -> Result<(), String> {
396        let expected = self.registry.for_document(&[p.pin()?])?;
397        if expected.features != r.features
398            || expected.actions != r.actions
399            || expected.workbenches != r.workbenches
400            || expected.panels != r.panels
401            || expected.annotations != r.annotations
402        {
403            return Err("registration metadata changed during invocation".into());
404        }
405        Ok(())
406    }
407}
408impl kernel::extension::ExtensionProvider for Runtime {
409    fn execute_annotation(
410        &self,
411        pins: &[PluginPin],
412        annotation: &kernel::pmi::PmiAnnotation,
413        context: &kernel::pmi::PmiContext<'_>,
414    ) -> Result<kernel::pmi::PluginAnnotationOutput, String> {
415        Runtime::execute_annotation(self, pins, annotation, context)
416    }
417    fn identity(&self, pins: &[PluginPin], kind: &str) -> Result<String, String> {
418        let p = self.package(pins, kind)?;
419        if !self
420            .registry
421            .features
422            .iter()
423            .any(|r| r.id == kind && r.package == p.pin().unwrap())
424        {
425            return Err(format!("unregistered plugin feature {kind}"));
426        }
427        Ok(format!("{}:{}:1", p.pin()?.digest, kind))
428    }
429    fn execute(&self, pins: &[PluginPin], ctx: &FeatureContext<'_>) -> FeatureResult {
430        let run = || -> Result<FeatureResult, String> {
431            let p = self.package(pins, &ctx.feature_type)?;
432            let reg = self
433                .registry
434                .features
435                .iter()
436                .find(|r| r.id == ctx.feature_type && r.package == p.pin().unwrap())
437                .ok_or("feature registration unavailable")?;
438            let mut params = ctx.params.clone();
439            validate_params(&reg.input_params_schema, &mut params, Some(ctx))?;
440            let input = json!({"params":params,"persistentData":ctx.persistent,"featureId":ctx.id,"units":"mm"});
441            let (r, _, result) = invocation::invoke(
442                p,
443                Some(("feature", &ctx.feature_type)),
444                Some(&input),
445                Some(ctx),
446                Some(&self.registry.for_document(&[p.pin()?])?),
447            )?;
448            self.verify(p, &r)?;
449            // Invocation publishes only after metadata, return and all handles validate.
450            result.ok_or_else(|| "missing feature result".into())
451        };
452        match run() {
453            Ok(r) => r,
454            Err(e) => ctx.fail(e),
455        }
456    }
457}
458fn validate_params(
459    schema: &Value,
460    params: &mut Value,
461    ctx: Option<&FeatureContext<'_>>,
462) -> Result<(), String> {
463    let obj = params
464        .as_object_mut()
465        .ok_or("parameters must be an object")?;
466    let fields = schema.as_object().ok_or("schema must be object")?;
467    for key in obj.keys() {
468        if key != "id" && !fields.contains_key(key) {
469            return Err(format!("unknown parameter {key}"));
470        }
471    }
472    if obj.get("id").is_some_and(|v| !v.is_string()) {
473        return Err("feature id must be string".into());
474    }
475    for (key, s) in schema.as_object().ok_or("schema must be object")? {
476        if !obj.contains_key(key) {
477            if let Some(v) = s.get("default_value") {
478                obj.insert(key.clone(), v.clone());
479            }
480        }
481        let v = obj
482            .get_mut(key)
483            .ok_or_else(|| format!("missing parameter {key}"))?;
484        match s["type"].as_str().unwrap_or("") {
485            "number" => {
486                let n = if let Some(n) = v.as_f64() {
487                    n
488                } else if let (Some(c), Some(text)) = (ctx, v.as_str()) {
489                    c.env.eval(text)?
490                } else {
491                    return Err(format!("{key} must be numeric"));
492                };
493                if !n.is_finite()
494                    || s["min"].as_f64().is_some_and(|m| n < m)
495                    || s["max"].as_f64().is_some_and(|m| n > m)
496                {
497                    return Err(format!("{key} outside finite numeric bounds"));
498                }
499                *v = json!(n);
500            }
501            "reference_selection" => {
502                fn reference(v: &Value) -> bool {
503                    v.is_string()
504                        || v.as_object()
505                            .is_some_and(|o| o.get("name").is_some_and(Value::is_string))
506                }
507                if !reference(v) && !v.as_array().is_some_and(|a| a.iter().all(reference)) {
508                    return Err(format!("{key} must contain reference names"));
509                }
510            }
511            "string" if !v.is_string() => return Err(format!("{key} must be string")),
512            "boolean" if !v.is_boolean() => return Err(format!("{key} must be boolean")),
513            _ => {}
514        }
515    }
516    Ok(())
517}