diff --git a/.github/workflows/solidcraft-plugin.yml b/.github/workflows/solidcraft-plugin.yml new file mode 100644 index 00000000..ee99a1bc --- /dev/null +++ b/.github/workflows/solidcraft-plugin.yml @@ -0,0 +1,60 @@ +# The TeamCraft plugin for SolidCraft (plugins/solidcraft): formatting, +# lints and tests on Linux, then the WebAssembly component, checked to import +# nothing but SolidCraft's plugin interface, kept as an artifact. Its own +# Cargo project – never part of the server or desktop build. +name: SolidCraft plugin + +on: + push: + branches: [main] + paths: ["plugins/solidcraft/**", ".github/workflows/solidcraft-plugin.yml"] + pull_request: + paths: ["plugins/solidcraft/**", ".github/workflows/solidcraft-plugin.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: solidcraft-plugin-${{ github.event_name }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + +jobs: + plugin: + name: SolidCraft plugin + runs-on: ubuntu-24.04 + timeout-minutes: 20 + defaults: + run: + working-directory: plugins/solidcraft + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown + components: clippy, rustfmt + - uses: Swatinem/rust-cache@v2 + with: + workspaces: plugins/solidcraft + - uses: taiki-e/install-action@v2 + with: + tool: wasm-tools + - name: Formatting + run: cargo fmt --check + - name: Clippy (tests on this computer) + run: cargo clippy --all-targets -- -D warnings + - name: Tests + run: cargo test + - name: Clippy (the component) + run: cargo clippy --release --target wasm32-unknown-unknown -- -D warnings + - name: Build the package + run: ./build.sh + - uses: actions/upload-artifact@v4 + with: + name: teamcraft-solidcraft-plugin + path: plugins/solidcraft/target/package/teamcraft + if-no-files-found: error diff --git a/CHANGELOG.md b/CHANGELOG.md index d1f45d35..96c4c184 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,11 @@ see the notices in the README. SolidCraft design's properties (and TeamCraft's ids and server under `teamcraft.pdm`) through `solidcraft-cli`; refused while the design is read-only or open in SolidCraft. +- **TeamCraft plugin for SolidCraft** (`plugins/solidcraft`). A WebAssembly + component for SolidCraft's plugin runtime: *TeamCraft status*, *Check for + TeamCraft* (part numbers, BOM rows, linked designs), *Link to TeamCraft + item* and *Unlink*; works offline on the open design. Built and tested by + the new workflow *SolidCraft plugin*. ## [0.2.11] - 2026-11-21 diff --git a/CLAUDE.md b/CLAUDE.md index c72c38f7..94374908 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -210,6 +210,9 @@ desktop/ TeamCraft Desktop (Tauri 2, own Cargo project – never part new-files.js + desktop/src/newfiles.rs = new items from local files, worklist *New on this computer* (#359); desktop/src/localserver.rs = *Try TeamCraft on this computer* (starts the bundled teamcraft-server local); tauri.local-server.conf.json = the *with local server* installers (externalBin teamcraft-server + postgresql/) +plugins/solidcraft TeamCraft plugin for SolidCraft: WebAssembly component (craft:plugin@0.2.0, wit/plugin.wit = SolidCraft's + interface, MIT), own Cargo project; src/logic.rs = status, check, link, unlink over SolidCraft's commands + (fake host in tests); build.sh → target/package/teamcraft; workflow solidcraft-plugin.yml ``` ## Conventions diff --git a/README.md b/README.md index 7365b011..30c618f1 100755 --- a/README.md +++ b/README.md @@ -322,7 +322,7 @@ end-to-end tests against a real PostgreSQL. - **SolidCraft and FieldCraft** – [SolidCraft](https://github.com/tangency-labs/solidcraft) designs (`.sc`, checked by content) and [FieldCraft](https://github.com/tangency-labs/fieldcraft) models (`.fieldcraft`) are recognised, SolidCraft's embedded picture is the preview image, linked designs are - file references with quantities, the desktop app exports designs to STEP with `solidcraft-cli`, and their STEP and 3MF + file references with quantities, the desktop app exports designs to STEP with `solidcraft-cli`, a TeamCraft plugin for SolidCraft shows and checks the design's TeamCraft item inside SolidCraft, and their STEP and 3MF exports previewed – design, export and analysis in one revision ([more](https://warr-ev.github.io/TeamCraft/reference/interop.html)). @@ -556,6 +556,7 @@ Third-party components (complete list with versions in `Cargo.lock` and | futures-core | desktop app: cancellable streamed uploads | MIT / Apache-2.0 | | Montserrat, Oswald | fonts | SIL OFL 1.1 | | libfuzzer-sys (libFuzzer) | fuzz targets in `fuzz/` only, never shipped | MIT / Apache-2.0 (libFuzzer: Apache-2.0 with LLVM exception) | +| wit-bindgen; SolidCraft's plugin interface (`plugins/solidcraft/wit/plugin.wit`, unchanged) | the TeamCraft plugin for SolidCraft in `plugins/solidcraft` only, never in the server or desktop app | Apache-2.0 WITH LLVM-exception / MIT / Apache-2.0; WIT file: MIT | SolidWorks, NX, Creo, CATIA, Inventor, Fusion, Revit and the other product names are trademarks of their respective diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index 1228fd22..b5be490d 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -706,6 +706,8 @@ real files and belong to section 3 once such files are at hand. - [x] Desktop: item number and revision written into the design properties (#369); left: automatically at check-out (a setting), link paths after a rename - [x] Desktop: designs open in SolidCraft (lock file) shown, warning at check-in (#370) - [ ] (research first) 3D preview from the `.sc` file alone (#371) +- [x] TeamCraft plugin for SolidCraft (`plugins/solidcraft`): status, check before check-in, link/unlink; left: tested + in a real SolidCraft, a release package, a *Check in* hand-over to the desktop app ### 5. Feature demand (backlog) diff --git a/docs/src/reference/interop.md b/docs/src/reference/interop.md index 29f188e4..c3aa435e 100755 --- a/docs/src/reference/interop.md +++ b/docs/src/reference/interop.md @@ -23,7 +23,32 @@ references it. The three projects share their approach – one Rust build, a desktop app and a command line, open formats – but not code: TeamCraft is licensed under the -MPL-2.0 and does not include SolidCraft or FieldCraft code. +MPL-2.0 and does not include SolidCraft or FieldCraft code (the plugin for SolidCraft below contains SolidCraft's interface definition, MIT). What TeamCraft reads from a `.sc` design, and the sources of those findings, are recorded in the research page [SolidCraft designs](../research/solidcraft-design.md). + +## TeamCraft plugin for SolidCraft + +`plugins/solidcraft` is a plugin for SolidCraft's plugin runtime (a +WebAssembly component, `craft:plugin@0.2.0`, built by the workflow +*SolidCraft plugin*, see its [README](https://github.com/WARR-eV/TeamCraft/tree/main/plugins/solidcraft)). +SolidCraft's plugins have no network access, so it works on the open design +only – with the TeamCraft object the desktop app's *Item data* writes +(`teamcraft.pdm`): + +* **TeamCraft status** – the item and revision of the design, the link to the + revision page, whether part number and revision still match; +* **Check for TeamCraft** – missing part numbers, a part number or revision + that differs from the linked item, BOM rows without a part number, one part + number with two descriptions, quantities SolidCraft cannot add up, linked + designs with an absolute path or the same file name twice; +* **Link to TeamCraft item** / **Unlink from TeamCraft** – write or remove the + item data from inside SolidCraft, for designs edited without the desktop + app. + +Install: copy the package folder `teamcraft` into SolidCraft's plugins folder +(*Preferences › Plugins › Show in folder*) and enable it. The plugin is +TeamCraft's own code (MPL-2.0); it contains SolidCraft's interface definition +`plugin.wit` unchanged under SolidCraft's MIT licence, which a component for +SolidCraft's runtime needs. diff --git a/docs/src/research/solidcraft-design.md b/docs/src/research/solidcraft-design.md index e7f80438..574fa83a 100644 --- a/docs/src/research/solidcraft-design.md +++ b/docs/src/research/solidcraft-design.md @@ -15,7 +15,11 @@ All findings come from SolidCraft's public documentation and its source code, licensed MIT OR Apache-2.0, as of SolidCraft 0.46.1 (commit `18c9760e3`, ). They were read as a specification; TeamCraft's readers are its own code and no SolidCraft code -is copied or vendored (see [FieldCraft and SolidCraft](../reference/interop.md)). +is copied or vendored (see [FieldCraft and SolidCraft](../reference/interop.md)). The +TeamCraft plugin for SolidCraft (`plugins/solidcraft`) is the one exception: +it contains SolidCraft's plugin interface definition `plugin.wit`, unchanged +and under its MIT licence, because a component for SolidCraft's runtime is +built against it. | Topic | Source | |-------------------------------------------|------------------------------------------------------------| diff --git a/plugins/solidcraft/Cargo.toml b/plugins/solidcraft/Cargo.toml new file mode 100644 index 00000000..ac7a62e3 --- /dev/null +++ b/plugins/solidcraft/Cargo.toml @@ -0,0 +1,28 @@ +# The TeamCraft plugin for SolidCraft – a WebAssembly component, built on its +# own (never part of the server or desktop build). See README.md. +[package] +name = "teamcraft-solidcraft-plugin" +version = "0.1.0" +edition = "2021" +license = "MPL-2.0" +description = "TeamCraft plugin for SolidCraft: TeamCraft item status, check before check-in, link a design to an item" +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +serde_json = "1" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wit-bindgen = "0.41" + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 +strip = true +panic = "abort" + +# Not a member of another workspace. +[workspace] diff --git a/plugins/solidcraft/README.md b/plugins/solidcraft/README.md new file mode 100644 index 00000000..fa0c6120 --- /dev/null +++ b/plugins/solidcraft/README.md @@ -0,0 +1,58 @@ +# TeamCraft plugin for SolidCraft + +A plugin for [SolidCraft](https://github.com/tangency-labs/solidcraft) +(open-source parametric CAD) that shows and checks a design's TeamCraft +data inside SolidCraft. It is a WebAssembly component for SolidCraft's +experimental plugin runtime (`craft:plugin@0.2.0`, capability +`commands@0.2`). + +SolidCraft's plugins have no network access, so the plugin never talks to a +TeamCraft server. It works with what is in the open design: its properties, +the TeamCraft object the desktop app writes (*Item data*, key +`teamcraft.pdm`: item number, revision, item and revision ids, server), the +bill of materials and the linked designs. Check-out, check-in and the +working folder stay in the TeamCraft desktop app. + +## Entries + +All four are on the *TeamCraft* ribbon group (Plugins tab) and in the +Plugins menu. + +| Entry | Effect | What it does | +|-------|--------|--------------| +| **status** – *TeamCraft status* | read | The TeamCraft item and revision the design belongs to, the page of the revision on the server, and whether the design's part number and revision still say the same. | +| **check** – *Check for TeamCraft* | read | What keeps the design from going into TeamCraft cleanly: no part number, a part number or revision that differs from the linked item, BOM rows without a part number, one part number with two descriptions, quantities SolidCraft cannot add up, linked designs with an absolute path or two linked designs with the same file name. `ready` is true when only notes are left. | +| **link** – *Link to TeamCraft item* | edit | Writes item number, revision and (optional) name into the design properties (*Part number*, *Revision*, *Description*) and TeamCraft's object – for designs edited without the desktop app. Ids written by the desktop app are kept while the item stays the same. One undo step; save the design afterwards. | +| **unlink** – *Unlink from TeamCraft* | edit | Removes TeamCraft's object; part number and revision stay. | + +SolidCraft commands it calls (declared in `plugin.json`, none of them reads +or writes files): `document.metadata`, `document.metadata.set`, +`document.metadata.remove`, `assembly.bom`, `component.links`. + +## Build + +```sh +rustup target add wasm32-unknown-unknown +cargo install wasm-tools +./build.sh # → target/package/teamcraft/ (plugin.json, plugin.wasm, SHA256SUMS) +cargo test # the entries against a fake design, on this computer +``` + +`build.sh` checks that the component imports nothing but `craft:plugin@0.2.0` +(no WASI). The GitHub workflow *SolidCraft plugin* builds and tests it and +keeps the package as an artifact. + +## Install + +Copy the folder `teamcraft` (the package; the folder name must be the plugin +id) into SolidCraft's plugins folder – *Preferences › Plugins › Show in +folder* – enable it there and review the approval SolidCraft shows. Installing +or enabling never runs plugin code; SolidCraft asks before the first run. + +## Licence and sources + +The plugin is TeamCraft's own code under the MPL-2.0. `wit/plugin.wit` is +SolidCraft's interface definition (`crates/craft-plugin/wit/plugin.wit` at +SolidCraft commit `94096b84f`), unchanged, under SolidCraft's MIT licence +(`wit/LICENSE-MIT`); it is needed to build a component for SolidCraft's +plugin runtime. Background: `docs/src/research/solidcraft-design.md`. diff --git a/plugins/solidcraft/build.sh b/plugins/solidcraft/build.sh new file mode 100755 index 00000000..f631004f --- /dev/null +++ b/plugins/solidcraft/build.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Builds the TeamCraft plugin for SolidCraft: the package folder +# target/package/teamcraft/ with plugin.json and plugin.wasm (a WebAssembly component). +# Needs the wasm32-unknown-unknown target (rustup target add +# wasm32-unknown-unknown) and wasm-tools (cargo install wasm-tools). +set -euo pipefail +cd "$(dirname "$0")" + +cargo build --release --target wasm32-unknown-unknown +core=target/wasm32-unknown-unknown/release/teamcraft_solidcraft_plugin.wasm +out=target/package/teamcraft +rm -rf "$out" +mkdir -p "$out" +# the core module + the component type wit-bindgen embedded → a component +wasm-tools component new "$core" -o "$out/plugin.wasm" +wasm-tools validate "$out/plugin.wasm" +# SolidCraft refuses WASI and anything outside craft:plugin@0.2.0 +imports=$(wasm-tools component wit "$out/plugin.wasm" | grep -E '^\s*import ' || true) +echo "Imports:" +echo "$imports" +if grep -vqE 'craft:plugin/[a-z-]+@0\.2\.0' <<<"$imports"; then + echo "error: the component imports something other than craft:plugin@0.2.0" >&2 + exit 1 +fi +cp plugin.json README.md "$out/" +cp ../../LICENSE "$out/LICENSE" +(cd "$out" && sha256sum plugin.json plugin.wasm > SHA256SUMS) +echo "Package: $out" diff --git a/plugins/solidcraft/plugin.json b/plugins/solidcraft/plugin.json new file mode 100644 index 00000000..ae9f94c5 --- /dev/null +++ b/plugins/solidcraft/plugin.json @@ -0,0 +1,53 @@ +{ + "id": "teamcraft", + "name": "TeamCraft", + "version": "0.1.0", + "description": "TeamCraft item of the design, a check before checking it in to TeamCraft, and linking a design to a TeamCraft item. Works offline on the open design.", + "capabilities": ["commands@0.2"], + "runtime": { + "module": "plugin.wasm", + "entries": [ + { + "name": "status", + "effect": "read", + "input_schema": {"type": "object", "properties": {}}, + "slots": [{"kind": "ribbon", "name": "TeamCraft"}] + }, + { + "name": "check", + "effect": "read", + "input_schema": {"type": "object", "properties": {}}, + "slots": [{"kind": "ribbon", "name": "TeamCraft"}] + }, + { + "name": "link", + "effect": "edit", + "input_schema": { + "type": "object", + "required": ["item_number", "revision"], + "properties": { + "item_number": {"type": "string", "title": "Item number", "maxLength": 256}, + "revision": {"type": "string", "title": "Revision", "maxLength": 256}, + "name": {"type": "string", "title": "Item name", "maxLength": 256}, + "server": {"type": "string", "title": "TeamCraft server (https://…)", "maxLength": 256} + } + }, + "slots": [{"kind": "ribbon", "name": "TeamCraft"}] + }, + { + "name": "unlink", + "effect": "edit", + "input_schema": {"type": "object", "properties": {}}, + "slots": [{"kind": "ribbon", "name": "TeamCraft"}] + } + ], + "commands": [ + "document.metadata", + "document.metadata.set", + "document.metadata.remove", + "assembly.bom", + "component.links" + ], + "limits": {"fuel": 50000000, "memory_mib": 64, "deadline_ms": 10000} + } +} diff --git a/plugins/solidcraft/src/lib.rs b/plugins/solidcraft/src/lib.rs new file mode 100644 index 00000000..bd9b1bbc --- /dev/null +++ b/plugins/solidcraft/src/lib.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MPL-2.0 +//! The TeamCraft plugin for SolidCraft: a WebAssembly component for +//! SolidCraft's plugin runtime (`craft:plugin@0.2.0`, world +//! `command-plugin`, capability `commands@0.2`). See `README.md`. +//! +//! [`logic`] holds what the entries do; this file only connects it to the +//! host: `commands.run` for SolidCraft's commands and the exported +//! `entry.execute`. The bindings exist only in the WebAssembly build, so the +//! logic's tests run on the build machine. + +pub mod logic; + +#[cfg(target_arch = "wasm32")] +mod component { + wit_bindgen::generate!({ + path: "wit", + world: "command-plugin", + }); + + use craft::plugin::types::{CommandFailure, FieldFailure, PluginError}; + use exports::craft::plugin::entry::Guest; + + use super::logic::{self, EntryError, Host}; + + /// SolidCraft's command surface through the host's `commands.run`. + struct Commands; + + impl Host for Commands { + fn run( + &mut self, + command: &str, + args: serde_json::Value, + ) -> Result { + let reply = craft::plugin::commands::run(command, &args.to_string()) + .map_err(|e| describe(&e))?; + serde_json::from_str(&reply) + .map_err(|e| format!("{command} answered with no JSON: {e}")) + } + } + + fn describe(e: &PluginError) -> String { + match e { + PluginError::PermissionDenied(s) + | PluginError::LimitExceeded(s) + | PluginError::Trap(s) + | PluginError::Unsupported(s) => s.clone(), + PluginError::CommandFailed(f) => format!("{}: {}", f.command, f.reason), + PluginError::InvalidManifest(f) | PluginError::InvalidInput(f) => { + format!("{}: {}", f.field, f.reason) + } + PluginError::Cancelled => "cancelled".into(), + } + } + + struct Plugin; + + impl Guest for Plugin { + fn execute(entry: String, params: String) -> Result { + let params: serde_json::Value = serde_json::from_str(¶ms).map_err(|e| { + PluginError::InvalidInput(FieldFailure { + field: "params".into(), + reason: e.to_string(), + }) + })?; + match logic::execute(&mut Commands, &entry, ¶ms) { + Ok(result) => Ok(result.to_string()), + Err(EntryError::Input { field, reason }) => { + Err(PluginError::InvalidInput(FieldFailure { field, reason })) + } + Err(EntryError::Command { command, reason }) => { + Err(PluginError::CommandFailed(CommandFailure { + command, + reason, + })) + } + Err(EntryError::Unsupported(text)) => Err(PluginError::Unsupported(text)), + } + } + } + + export!(Plugin); +} diff --git a/plugins/solidcraft/src/logic.rs b/plugins/solidcraft/src/logic.rs new file mode 100644 index 00000000..3f3eaea3 --- /dev/null +++ b/plugins/solidcraft/src/logic.rs @@ -0,0 +1,648 @@ +// SPDX-License-Identifier: MPL-2.0 +//! What the plugin's entries do, over SolidCraft's command surface – pure, so +//! the tests run on the build machine against a fake host ([`Host`]). +//! +//! The plugin has no network access (SolidCraft's plugin runtime refuses it), +//! so it works with what is in the open design: its properties, the object +//! TeamCraft keeps under [`KEY`] (written by the desktop app's *Item data* or +//! by [`link`]), the bill of materials and the linked designs. + +use serde_json::{json, Map, Value}; + +/// The reverse-DNS key of TeamCraft's object in a design's properties – the +/// same as the desktop app's (`desktop/src/scprops.rs`). +pub const KEY: &str = "teamcraft.pdm"; + +/// SolidCraft's commands, as the plugin calls them. +pub trait Host { + /// Runs `command` with `args` and returns its JSON result, or why it + /// failed. + fn run(&mut self, command: &str, args: Value) -> Result; +} + +/// Why an entry failed. +#[derive(Debug, PartialEq)] +pub enum EntryError { + /// The input is broken: which field, and why. + Input { field: String, reason: String }, + /// A SolidCraft command failed. + Command { command: String, reason: String }, + /// An entry this plugin does not have. + Unsupported(String), +} + +fn input(field: &str, reason: &str) -> EntryError { + EntryError::Input { + field: field.into(), + reason: reason.into(), + } +} + +fn call(host: &mut dyn Host, command: &str, args: Value) -> Result { + host.run(command, args) + .map_err(|reason| EntryError::Command { + command: command.into(), + reason, + }) +} + +/// The entries of the manifest (`plugin.json`). +pub const ENTRIES: [&str; 4] = ["status", "check", "link", "unlink"]; + +/// Runs the entry `entry` with its `params`. +pub fn execute(host: &mut dyn Host, entry: &str, params: &Value) -> Result { + match entry { + "status" => status(host), + "check" => check(host), + "link" => link(host, params), + "unlink" => unlink(host), + other => Err(EntryError::Unsupported(format!( + "The TeamCraft plugin has no entry `{other}`." + ))), + } +} + +/// The design's `metadata` as saved and SolidCraft's `properties` (its keys as text). +type Properties = (Map, Map); + +/// The design's properties: (`metadata` as saved, SolidCraft's `properties`). +fn properties(host: &mut dyn Host) -> Result { + let read = call(host, "document.metadata", json!({}))?; + let object = |name: &str| { + read.get(name) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default() + }; + Ok((object("metadata"), object("properties"))) +} + +fn text<'a>(map: &'a Map, key: &str) -> &'a str { + map.get(key) + .and_then(Value::as_str) + .map(str::trim) + .unwrap_or("") +} + +/// TeamCraft's object in the design, if there is one. +fn teamcraft(metadata: &Map) -> Option<&Map> { + metadata.get(KEY).and_then(Value::as_object) +} + +/// The TeamCraft page of the revision, from the server and the revision id. +fn revision_url(tc: &Map) -> Option { + let server = text(tc, "server").trim_end_matches('/'); + let id = text(tc, "revision_id"); + let web = server.starts_with("https://") || server.starts_with("http://"); + (web && !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')) + .then(|| format!("{server}/revisions/{id}")) +} + +/// *TeamCraft status*: which item and revision the design belongs to, and +/// whether its part number and revision still say the same. +pub fn status(host: &mut dyn Host) -> Result { + let (metadata, props) = properties(host)?; + let part_number = text(&props, "part_number"); + let revision = text(&props, "revision"); + let Some(tc) = teamcraft(&metadata) else { + return Ok(json!({ + "managed": false, + "part_number": part_number, + "revision": revision, + "message": "This design is not linked to a TeamCraft item. Check it out in the TeamCraft \ + desktop app and use *Item data*, or use *Link to TeamCraft item* here.", + })); + }; + let item = text(tc, "item_number"); + let rev = text(tc, "revision"); + let mut out = json!({ + "managed": true, + "item_number": item, + "revision": rev, + "server": text(tc, "server"), + "part_number_matches": part_number == item, + "revision_matches": revision == rev, + "message": format!("TeamCraft item {item}, revision {rev}."), + }); + if let Some(url) = revision_url(tc) { + out["url"] = json!(url); + } + if part_number != item || revision != rev { + out["message"] = json!(format!( + "TeamCraft item {item}, revision {rev} – but the design says part number \ + “{part_number}”, revision “{revision}”. Write the item data again or correct them." + )); + } + Ok(out) +} + +/// One finding of [`check`]. +fn finding(level: &str, message: String) -> Value { + json!({"level": level, "message": message}) +} + +/// Whether `path` is absolute (Unix, Windows drive or network path). +fn is_absolute(path: &str) -> bool { + let b = path.as_bytes(); + path.starts_with('/') + || path.starts_with("\\\\") + || (b.len() > 2 + && b[0].is_ascii_alphabetic() + && b[1] == b':' + && (b[2] == b'\\' || b[2] == b'/')) +} + +fn file_name(path: &str) -> &str { + path.rsplit(['/', '\\']).next().unwrap_or(path) +} + +/// *Check for TeamCraft*: what keeps the design from going into TeamCraft +/// cleanly – missing part numbers, a design that says another item than the +/// one it is linked to, BOM rows TeamCraft cannot match, linked designs it +/// cannot find by name. Reads only. +pub fn check(host: &mut dyn Host) -> Result { + let (metadata, props) = properties(host)?; + let mut findings = Vec::new(); + let part_number = text(&props, "part_number"); + if part_number.is_empty() { + findings.push(finding( + "warning", + "The design has no part number (Design Properties) – TeamCraft matches the item by it." + .into(), + )); + } + if text(&props, "description").is_empty() { + findings.push(finding( + "info", + "The design has no description – TeamCraft uses it as the item name of a new item." + .into(), + )); + } + match teamcraft(&metadata) { + None => findings.push(finding( + "info", + "Not linked to a TeamCraft item yet.".into(), + )), + Some(tc) => { + let item = text(tc, "item_number"); + if !part_number.is_empty() && part_number != item { + findings.push(finding( + "warning", + format!("The part number “{part_number}” is not the TeamCraft item {item} the design is linked to."), + )); + } + let rev = text(tc, "revision"); + if text(&props, "revision") != rev { + findings.push(finding( + "warning", + format!( + "The revision “{}” is not TeamCraft's revision {rev}.", + text(&props, "revision") + ), + )); + } + } + } + check_bom(host, &mut findings); + check_links(host, &mut findings); + let ready = findings.iter().all(|f| f["level"] == "info"); + let problems = findings.iter().filter(|f| f["level"] != "info").count(); + Ok(json!({ + "ready": ready, + "summary": if ready { + "Ready for TeamCraft.".to_string() + } else { + format!("{problems} thing(s) to fix before checking in to TeamCraft.") + }, + "findings": findings, + })) +} + +/// BOM rows TeamCraft cannot match: no part number, a quantity SolidCraft +/// cannot count, one part number with different descriptions. +fn check_bom(host: &mut dyn Host, findings: &mut Vec) { + // a part without components has no rows; a failure is no finding + let Ok(bom) = host.run("assembly.bom", json!({"levels": "all"})) else { + return; + }; + let rows = bom + .get("rows") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let mut seen: Map = Map::new(); + for row in &rows { + let item = match &row["item"] { + Value::String(s) => s.clone(), + Value::Number(n) => n.to_string(), + _ => "?".into(), + }; + let name = row["definition"].as_str().unwrap_or("").to_string(); + let number = row["part_number"].as_str().unwrap_or("").trim().to_string(); + let description = row["description"].as_str().unwrap_or("").trim().to_string(); + if row["bom_type"] == "reference" || row["bom_type"] == "phantom" { + continue; + } + if number.is_empty() { + findings.push(finding( + "warning", + format!("BOM item {item} ({name}) has no part number – TeamCraft's BOM import would create a new item for it."), + )); + } else if let Some(other) = seen.get(&number).and_then(Value::as_str) { + if other != description { + findings.push(finding( + "warning", + format!("Part number {number} has two descriptions: “{other}” and “{description}” (item {item})."), + )); + } + } else { + seen.insert(number.clone(), json!(description)); + } + if row.get("quantity_unknown").is_some() { + findings.push(finding( + "warning", + format!("BOM item {item} ({name}) has a quantity SolidCraft cannot add up."), + )); + } + if row.get("duplicate").is_some() { + findings.push(finding( + "warning", + format!("BOM item number {item} is used twice."), + )); + } + } +} + +/// Linked designs TeamCraft cannot match: an absolute path (outside the +/// working folder) or two links with the same file name in different +/// folders (TeamCraft finds references by file name). +fn check_links(host: &mut dyn Host, findings: &mut Vec) { + let Ok(links) = host.run("component.links", json!({})) else { + return; + }; + let links = links + .get("links") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let mut by_name: Map = Map::new(); + for link in &links { + let path = link["path"].as_str().unwrap_or(""); + let component = link["name"].as_str().unwrap_or("?"); + if path.is_empty() { + continue; + } + if is_absolute(path) { + findings.push(finding( + "warning", + format!("{component} links {path} by an absolute path – keep linked designs in the TeamCraft working folder and save the assembly there, so the link is relative."), + )); + } + let key = file_name(path).to_lowercase(); + match by_name.get(&key).and_then(Value::as_str) { + Some(other) if other != path => findings.push(finding( + "warning", + format!("Two linked designs are named {}: {other} and {path} – TeamCraft tells references apart by file name.", file_name(path)), + )), + Some(_) => {} + None => { + by_name.insert(key, json!(path)); + } + } + } +} + +/// Longest value written (SolidCraft's limit for a property's text is 4 KiB). +const MAX_FIELD: usize = 256; + +fn field(params: &Value, name: &str, required: bool) -> Result { + let value = match params.get(name) { + None | Some(Value::Null) => String::new(), + Some(Value::String(s)) => s.trim().to_string(), + Some(_) => return Err(input(name, "must be text")), + }; + if required && value.is_empty() { + return Err(input(name, "is required")); + } + if value.len() > MAX_FIELD || value.chars().any(char::is_control) { + return Err(input(name, "must be one line of at most 256 bytes")); + } + Ok(value) +} + +/// *Link to TeamCraft item*: writes the item number, revision and name into +/// the design's properties and TeamCraft's object, like the desktop app's +/// *Item data* – for designs edited without the desktop app. One undo step. +pub fn link(host: &mut dyn Host, params: &Value) -> Result { + let item_number = field(params, "item_number", true)?; + let revision = field(params, "revision", true)?; + let name = field(params, "name", false)?; + let server = field(params, "server", false)?; + if !server.is_empty() && !(server.starts_with("https://") || server.starts_with("http://")) { + return Err(input("server", "must start with https:// or http://")); + } + let (metadata, _) = properties(host)?; + // keep the ids the desktop app wrote when the item stays the same + let mut tc = teamcraft(&metadata) + .filter(|tc| text(tc, "item_number") == item_number) + .cloned() + .unwrap_or_default(); + if text(&tc, "revision") != revision { + tc.remove("revision_id"); + } + tc.insert("item_number".into(), json!(item_number)); + tc.insert("revision".into(), json!(revision)); + if !server.is_empty() { + tc.insert("server".into(), json!(server)); + } + let mut values = json!({ + "part_number": item_number, + "revision": revision, + KEY: tc, + }); + if !name.is_empty() { + values["description"] = json!(name); + } + call(host, "document.metadata.set", json!({"values": values}))?; + Ok(json!({ + "linked": true, + "item_number": item_number, + "revision": revision, + "message": format!("Linked to TeamCraft item {item_number}, revision {revision}. Save the design."), + })) +} + +/// *Unlink from TeamCraft*: removes TeamCraft's object; the part number and +/// revision stay as they are. +pub fn unlink(host: &mut dyn Host) -> Result { + let removed = call(host, "document.metadata.remove", json!({"key": KEY}))?; + let was = removed + .get("removed") + .and_then(Value::as_array) + .is_some_and(|r| !r.is_empty()); + Ok(json!({ + "unlinked": was, + "message": if was { + "The design is no longer linked to a TeamCraft item." + } else { + "The design was not linked to a TeamCraft item." + }, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A design in memory: its metadata, BOM rows and links; records calls. + #[derive(Default)] + struct Fake { + metadata: Map, + rows: Vec, + links: Vec, + calls: Vec<(String, Value)>, + } + + impl Host for Fake { + fn run(&mut self, command: &str, args: Value) -> Result { + self.calls.push((command.to_string(), args.clone())); + let props = |m: &Map| { + let mut p = Map::new(); + for k in [ + "project", + "part_number", + "revision", + "author", + "organization", + "description", + "license", + ] { + p.insert( + k.into(), + m.get(k) + .filter(|v| v.is_string()) + .cloned() + .unwrap_or(Value::Null), + ); + } + Value::Object(p) + }; + match command { + "document.metadata" => { + Ok(json!({"metadata": self.metadata, "properties": props(&self.metadata)})) + } + "document.metadata.set" => { + for (k, v) in args["values"].as_object().unwrap() { + self.metadata.insert(k.clone(), v.clone()); + } + Ok(json!({"metadata": self.metadata})) + } + "document.metadata.remove" => { + let key = args["key"].as_str().unwrap(); + let was = self.metadata.remove(key).is_some(); + Ok(json!({"removed": if was { vec![key] } else { vec![] }})) + } + "assembly.bom" if self.rows.is_empty() => { + Err("the design has no components".into()) + } + "assembly.bom" => Ok(json!({"rows": self.rows})), + "component.links" => Ok(json!({"links": self.links})), + other => Err(format!("unknown command {other}")), + } + } + } + + fn linked() -> Fake { + let metadata = json!({ + "part_number": "TC-1042", "revision": "B", "description": "Motor mount", + KEY: {"item_number": "TC-1042", "revision": "B", "item_id": "i-1", + "revision_id": "0b6f1c2e-aaaa-bbbb-cccc-1234567890ab", "server": "https://plm.example.org/"} + }); + Fake { + metadata: metadata.as_object().unwrap().clone(), + ..Fake::default() + } + } + + #[test] + fn status_of_a_linked_design_names_item_and_page() { + let s = status(&mut linked()).unwrap(); + assert_eq!(s["managed"], true); + assert_eq!(s["item_number"], "TC-1042"); + assert_eq!( + s["url"], + "https://plm.example.org/revisions/0b6f1c2e-aaaa-bbbb-cccc-1234567890ab" + ); + assert_eq!(s["part_number_matches"], true); + let mut changed = linked(); + changed.metadata.insert("revision".into(), json!("C")); + let s = status(&mut changed).unwrap(); + assert_eq!(s["revision_matches"], false); + assert!(s["message"].as_str().unwrap().contains("revision “C”")); + } + + #[test] + fn status_of_an_unlinked_design_says_how_to_link() { + let s = status(&mut Fake::default()).unwrap(); + assert_eq!(s["managed"], false); + assert!(s["message"].as_str().unwrap().contains("Item data")); + } + + #[test] + fn no_url_from_an_odd_server_or_id() { + let mut f = linked(); + f.metadata[KEY]["server"] = json!("javascript:alert(1)"); + assert!(status(&mut f).unwrap().get("url").is_none()); + let mut f = linked(); + f.metadata[KEY]["revision_id"] = json!("../admin"); + assert!(status(&mut f).unwrap().get("url").is_none()); + } + + #[test] + fn a_clean_part_is_ready() { + let c = check(&mut linked()).unwrap(); + assert_eq!(c["ready"], true, "{c}"); + assert_eq!(c["summary"], "Ready for TeamCraft."); + } + + #[test] + fn check_finds_what_teamcraft_cannot_match() { + let mut f = linked(); + f.metadata.insert("part_number".into(), json!("TC-9999")); + f.rows = vec![ + json!({"item": 1, "part_number": "TC-200", "description": "Frame", "definition": "Frame", "bom_type": "normal", "count": 1}), + json!({"item": "1.1", "part_number": "", "description": "", "definition": "Bolt", "bom_type": "normal", "count": 4}), + json!({"item": 2, "part_number": "TC-200", "description": "Frame welded", "definition": "Frame2", "bom_type": "normal", "count": 1}), + json!({"item": 3, "part_number": "", "definition": "Sketch body", "bom_type": "reference", "count": 1}), + json!({"item": 4, "part_number": "TC-300", "description": "Rail", "definition": "Rail", "bom_type": "normal", "quantity": null, "quantity_unknown": "mixed"}), + ]; + f.links = vec![ + json!({"component": 3, "name": "Plate", "path": "/home/kim/parts/plate.sc"}), + json!({"component": 4, "name": "Plate B", "path": "lib/plate.sc"}), + json!({"component": 5, "name": "Bolt", "path": "bolt.sc"}), + ]; + let c = check(&mut f).unwrap(); + assert_eq!(c["ready"], false); + let text: Vec = c["findings"] + .as_array() + .unwrap() + .iter() + .map(|f| f["message"].as_str().unwrap().to_string()) + .collect(); + let has = |s: &str| text.iter().any(|t| t.contains(s)); + assert!( + has("“TC-9999” is not the TeamCraft item TC-1042"), + "{text:?}" + ); + assert!(has("BOM item 1.1 (Bolt) has no part number"), "{text:?}"); + assert!(has("Part number TC-200 has two descriptions"), "{text:?}"); + assert!( + !has("Sketch body"), + "reference components are not BOM lines" + ); + assert!(has("BOM item 4 (Rail) has a quantity"), "{text:?}"); + assert!(has("by an absolute path"), "{text:?}"); + assert!(has("Two linked designs are named plate.sc"), "{text:?}"); + assert!( + c["summary"].as_str().unwrap().starts_with("6 thing(s)"), + "{c}" + ); + } + + #[test] + fn link_writes_one_change_and_keeps_known_ids() { + let mut f = linked(); + let r = link( + &mut f, + &json!({"item_number": "TC-1042", "revision": "C", "name": "Motor mount v2"}), + ) + .unwrap(); + assert_eq!(r["linked"], true); + let sets: Vec<_> = f + .calls + .iter() + .filter(|(c, _)| c == "document.metadata.set") + .collect(); + assert_eq!(sets.len(), 1, "one undo step"); + assert_eq!(f.metadata["part_number"], "TC-1042"); + assert_eq!(f.metadata["revision"], "C"); + assert_eq!(f.metadata["description"], "Motor mount v2"); + assert_eq!(f.metadata[KEY]["item_id"], "i-1", "same item: id kept"); + assert!( + f.metadata[KEY].get("revision_id").is_none(), + "another revision: its id is gone" + ); + assert_eq!(f.metadata[KEY]["server"], "https://plm.example.org/"); + // another item: TeamCraft's old ids are not carried over + link(&mut f, &json!({"item_number": "TC-2000", "revision": "A"})).unwrap(); + assert!(f.metadata[KEY].get("item_id").is_none()); + } + + #[test] + fn link_refuses_bad_input() { + let mut f = Fake::default(); + for (params, field) in [ + (json!({"revision": "A"}), "item_number"), + (json!({"item_number": "X", "revision": ""}), "revision"), + (json!({"item_number": 5, "revision": "A"}), "item_number"), + ( + json!({"item_number": "X\nY", "revision": "A"}), + "item_number", + ), + ( + json!({"item_number": "X", "revision": "A", "server": "ftp://x"}), + "server", + ), + ] { + match link(&mut f, ¶ms) { + Err(EntryError::Input { field: got, .. }) => assert_eq!(got, field, "{params}"), + other => panic!("{params}: {other:?}"), + } + } + assert!( + f.calls.iter().all(|(c, _)| c != "document.metadata.set"), + "nothing written" + ); + } + + #[test] + fn unlink_removes_only_teamcrafts_object() { + let mut f = linked(); + assert_eq!(unlink(&mut f).unwrap()["unlinked"], true); + assert!(f.metadata.get(KEY).is_none()); + assert_eq!(f.metadata["part_number"], "TC-1042"); + assert_eq!(unlink(&mut f).unwrap()["unlinked"], false); + } + + #[test] + fn unknown_entries_and_the_manifest_agree() { + assert!(matches!( + execute(&mut Fake::default(), "nope", &json!({})), + Err(EntryError::Unsupported(_)) + )); + let manifest: Value = serde_json::from_str(include_str!("../plugin.json")).unwrap(); + let declared: Vec<&str> = manifest["runtime"]["entries"] + .as_array() + .unwrap() + .iter() + .map(|e| e["name"].as_str().unwrap()) + .collect(); + assert_eq!(declared, ENTRIES); + let commands: Vec<&str> = manifest["runtime"]["commands"] + .as_array() + .unwrap() + .iter() + .map(|c| c.as_str().unwrap()) + .collect(); + for command in [ + "document.metadata", + "document.metadata.set", + "document.metadata.remove", + "assembly.bom", + "component.links", + ] { + assert!(commands.contains(&command), "{command} not declared"); + } + assert_eq!(manifest["id"], "teamcraft"); + } +} diff --git a/plugins/solidcraft/wit/LICENSE-MIT b/plugins/solidcraft/wit/LICENSE-MIT new file mode 100644 index 00000000..bd0e0f26 --- /dev/null +++ b/plugins/solidcraft/wit/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 SolidCraft contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/solidcraft/wit/plugin.wit b/plugins/solidcraft/wit/plugin.wit new file mode 100644 index 00000000..230ae357 --- /dev/null +++ b/plugins/solidcraft/wit/plugin.wit @@ -0,0 +1,173 @@ +package craft:plugin@0.2.0; + +// Capabilities are sets of the interfaces in this file. A plugin names the ones it needs in its +// manifest's `capabilities` list: +// - `commands@0.2`: types, commands, log, control, files, clock and entry (world `command-plugin`); +// - `formats@0.2`: types, log, control, clock, source, design and importer (world `importer-plugin`); +// - `evaluate@0.2`: with `formats`, evaluate, so an importer can check its result; +// - `storage@0.1`: with `commands`, the app's `storage.*` commands and the `storage` interface, so a +// plugin keeps its own data in the open design: its main document as JSON, its files as bytes. +// - `design@0.1`: with `commands`, design-state, for document identity/revision and read listeners. +// - `forms@0.1`: with `commands`, forms.open, to request a populated command form; +// programs receive an interactive-required refusal instead of a window. +// Later capabilities (ui, viewport) arrive as their own interfaces. While the version is +// 0.x, a minor version may break the one before it. 0.2 added `plugin-error.unsupported`. A host +// still runs plugins built against 0.1 (`../wit-0.1/plugin.wit`): it reads the version from the +// component's imports and exports, and shows their `invalid-input` as before. +// App commands and their schemas are data; this world never names app types. +interface types { + type json = string; + record command-failure { command: string, reason: string } + record field-failure { field: string, reason: string } + variant plugin-error { + permission-denied(string), + command-failed(command-failure), + limit-exceeded(string), + invalid-manifest(field-failure), + invalid-input(field-failure), + trap(string), + cancelled, + // The input is valid, but this plugin does not handle it: a file it can open in general + // but not this one (no solids, a newer file version, a feature it does not convert), or + // an option value it does not offer. The text says what it does not support, in the + // user's words. Use `invalid-input` for input that is broken. + unsupported(string), + } +} +// The app's command surface: the same commands, inputs and results its MCP clients get. +interface commands { + use types.{json, plugin-error}; + run: func(command: string, args: json) -> result; +} +// Additive forms@0.1 capability. Existing command components need not import this. +interface forms { + use types.{json, plugin-error}; + open: func(entry: string, params: json) -> result<_, plugin-error>; +} +// Additive read-only import: JSON {document_id: string, revision: string}, or null with no document. +// Both fields are opaque printable ASCII, bounded to 128 characters; compare them for equality. +// Importing this interface requires the manifest capability design@0.1. Older components omit it. +interface design-state { + use types.{json, plugin-error}; + get-token: func() -> result; +} +interface log { + enum level { debug, info, warn, error } + log: func(level: level, message: string); +} +interface control { + progress: func(fraction: f32, message: string); + cancelled: func() -> bool; +} +interface files { + use types.{plugin-error}; + read-file: func(grant: string, path: string) -> result, plugin-error>; + write-file: func(grant: string, path: string, data: list) -> result<_, plugin-error>; +} +interface clock { + now: func() -> u64; +} +// A plugin's own files in the open design (capability `storage@0.1`), as bytes: never as text. +// Files are named by a plain relative path; a cache file is one the plugin can make again, which +// a save may drop. Only the plugin's own run writes its files; anyone reads them. +interface storage { + use types.{plugin-error}; + // Writes the running plugin's file `name` (`cache`: as a cache file), its bytes as they are; + // `append` adds them to the file's end, to write a large file in parts. One name is one file: + // writing it as the other kind moves it. Returns the file's size. Part of the run's one undo step. + put-blob: func(name: string, data: list, cache: bool, append: bool) -> result; + // Up to `len` bytes (at most 1 MiB) of a plugin's file from `offset`; empty past its end. + // `plugin`: whose file, the running plugin's own when left out (inside a run, only its own). + get-blob: func(plugin: option, name: string, offset: u64, len: u32) -> result, plugin-error>; + // Up to `len` bytes (at most 1 MiB) of a plugin's main document, its saved JSON, from + // `offset`; empty past its end, or when it has none. + get-document: func(plugin: option, offset: u64, len: u32) -> result, plugin-error>; +} +// What the plugin exports: its manifest's entries, called by name. +interface entry { + use types.{json, plugin-error}; + execute: func(entry: string, params: json) -> result; +} +// The file an importer converts, read in chunks so each host call stays small. +interface source { + use types.{plugin-error}; + // The file being imported: its name, without folders, and its size in bytes. + record file-info { name: string, size: u64 } + // At most `len` bytes (up to 1 MiB) at `offset`; empty at the end of the file. `path` "" is the + // file being imported. Any other path is relative to that file's folder and needs the + // `input_folder` permission: an assembly reads its parts this way. + read: func(path: string, offset: u64, len: u32) -> result, plugin-error>; + // The size of a file, or none when there is no such file. + size: func(path: string) -> result, plugin-error>; + // The path as the folder spells it: `path` itself when it exists, else the one file whose name + // matches it ignoring case, else none. Needs `input_folder` for any path but "". + resolve: func(path: string) -> result, plugin-error>; +} +// Where an importer writes its result: a SolidCraft design file, in order, at most 1 MiB per call. +interface design { + use types.{plugin-error}; + write: func(bytes: list) -> result<_, plugin-error>; +} +// An importer checks its own result in the app (capability `evaluate@0.1`). It stages a design +// file it made; the app opens it in a private session, apart from every open design and every +// file, and runs read-only commands on it. Nothing here reaches the user's designs or files. +interface evaluate { + use types.{json, plugin-error}; + // Appends at most 1 MiB to the staged design (256 MiB in all). Staging after a run starts a + // new design. + stage: func(bytes: list) -> result<_, plugin-error>; + // Runs one command on the staged design, opening it on the first run. The app names the + // commands it allows (SolidCraft: document.inspect, inspect.measure, model.edges, model.faces + // and timeline.roll_to). A command that fails returns {"error": "..."}; a design the app + // can't open fails the call. + run: func(command: string, args: json) -> result; + // Discards the staged design and its session. + reset: func(); +} +// What an importer exports: its manifest's importer entries, called by name. +interface importer { + use types.{json, plugin-error}; + use source.{file-info}; + // Convert `file` with the entry's declared options. The design goes to `design.write`; the + // result is the loss report: what could not be carried over, as JSON. + import-file: func(entry: string, file: file-info, options: json) -> result; +} +world command-plugin { + import forms; + import commands; + import design-state; + import log; + import control; + import files; + import clock; + import storage; + export entry; +} +world importer-plugin { + import log; + import control; + import clock; + import source; + import design; + import evaluate; + export importer; +} + +// Optional, additive capability dialog@0.1. Existing worlds retain their exports. +interface dialog-provider { + use types.{json, plugin-error}; + // Values and reply are JSON objects. The host validates the entire reply before applying it. + update-fields: func(entry: string, values: json) -> result; +} +world dialog-plugin { + import commands; + import log; + import control; + import files; + import clock; + export dialog-provider; +} +world command-dialog-plugin { + include command-plugin; + export dialog-provider; +}