@snaptrude/plugin-client 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/api/index.d.ts +2 -1
- package/dist/api/index.d.ts.map +1 -1
- package/dist/events.d.ts +28 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/handle-runtime.d.ts +27 -0
- package/dist/handle-runtime.d.ts.map +1 -0
- package/dist/host-api.d.ts.map +1 -1
- package/dist/index.cjs +201 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +171 -3
- package/dist/index.js.map +1 -1
- package/dist/plugin-worker.d.ts +32 -0
- package/dist/plugin-worker.d.ts.map +1 -1
- package/dist/rpc-proxy.d.ts.map +1 -1
- package/package.json +10 -3
- package/upgrade-notes/0.4.0-to-0.5.0.md +53 -0
- package/upgrade-notes/0.5.0-to-0.6.0.md +38 -0
- package/upgrade-notes/0.6.0-to-0.7.0.md +38 -0
- package/upgrade-notes/0.7.0-to-0.7.1.md +28 -0
- package/upgrade-notes/0.7.1-to-0.8.0.md +44 -0
- package/upgrade-notes/0.8.0-to-0.9.0.md +61 -0
- package/upgrade-notes/index.json +42 -0
- package/AGENTS.md +0 -86
- package/CLAUDE.md +0 -11
- package/src/api/index.ts +0 -45
- package/src/host-api.ts +0 -87
- package/src/index.ts +0 -38
- package/src/plugin-worker.ts +0 -99
- package/src/rpc-proxy.ts +0 -56
- package/test/host-api-errors.test.mjs +0 -101
- package/tsconfig.json +0 -17
- package/tsup.config.ts +0 -12
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
---
|
|
2
|
+
from: 0.7.1
|
|
3
|
+
to: 0.8.0
|
|
4
|
+
breaking: true
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Summary
|
|
8
|
+
|
|
9
|
+
0.8.0 turns handles into real objects with a managed lifecycle, adds the 0.8 API wave (export, element editing, camera, storey management, visibility, dimensions, locale, events), and fixes several host behaviors that silently produced wrong geometry or wrong data. Most plugin code compiles and runs unchanged — the breaking surface is code that treats handles as plain strings, plus the behavior corrections below.
|
|
10
|
+
|
|
11
|
+
## Breaking changes
|
|
12
|
+
|
|
13
|
+
- **`Handle` is now a class, not a string.** Public type names are unchanged (`Vec3Handle`, `ProfileHandle`, `BrepHandle`, …) and every API keeps accepting the values it returns, but a handle is no longer a `string` at runtime:
|
|
14
|
+
- `typeof handle` is now `"object"`, not `"string"`. Remove `typeof x === "string"` checks on handles.
|
|
15
|
+
- `JSON.stringify(handle)` now emits the wire tag `{"__h":"<id>"}` instead of a bare id string. Code that persists or logs stringified structures containing handles sees a new shape. To keep the old output use `handle.toString()` / `` `${handle}` `` / `handle.id`.
|
|
16
|
+
- String operations (`.startsWith`, concatenation, using a handle as an object key) must go through `handle.id` (the bare wire id) — template literals and `toString()` still produce the bare id.
|
|
17
|
+
- Compare handles with `a.equals(b)` (or `a.id === b.id`), not `a === b`. Identity `===` still works for handles returned by the same call chain (the client interns wrappers per id), but `.equals()` is the guaranteed form.
|
|
18
|
+
- Entity-style kinds are NOT affected: component/material/underlay/terrain/importJob ids remain branded strings.
|
|
19
|
+
- **`program.site` footprints are now world Snaptrude units, not metres.** Site parcel footprints were the only plan-geometry read scaled to scene metres (×0.254), so they could not be overlaid on `planPoints` / space footprints. They now return world XZ plan coordinates in Snaptrude units — the same plan space as every other plan read. Code that scaled site footprints by 1/0.254 to compensate must drop that correction. Areas and the geographic reads (`listGeoPolygons`, `getContext`) are unchanged.
|
|
20
|
+
- **`design.create.beam` / `design.create.column` build real geometry where they previously built degenerate solids.** Horizontal beams (the documented canonical call) used to build a zero-height flat sheet sunk below ground; they now build a true beam via tool-parity footprint synthesis (section X extent = width, Z extent = depth, body hangs below the authoring plane by its depth). Columns are built to exactly the requested height — the silent slab-thickness deduction is gone (previously every API column was one slab short, and heights below slab thickness built inverted). Degenerate inputs (zero/diagonal/in-plane directions, zero height) now throw VALIDATION errors instead of silently producing corrupt geometry. Direction vectors are normalized, so magnitude no longer scales dimensions.
|
|
21
|
+
- **`design.query.list*` no longer lists engine-internal shells.** After an instance-mode copy, the replaced originals (parked at infinity) and disposed phantoms no longer appear in `listSpaces` and the other list reads — previously one copy silently doubled space counts and schedules. If code relied on seeing the parked originals, it must stop; they were never user-visible geometry.
|
|
22
|
+
|
|
23
|
+
## New APIs
|
|
24
|
+
|
|
25
|
+
- **`core.handles.*` — handle lifecycle.** `release(handles[])` (batched, arena-agnostic, silent no-op on unknown/already-released ids), `releaseAll(kind?)`, mint-recording scopes `beginScope()` → `endScope(scope, retain?)` (token-addressed close; `retain` promotes handles to the enclosing scope), and `stats()`. The client also runs a GC-backed auto-release queue (FinalizationRegistry), so handles you drop are reclaimed host-side without explicit code; use explicit `release`/scopes for deterministic cleanup in long-running or handle-heavy plugins.
|
|
26
|
+
- **The 0.8 API wave.** Model/presentation export (`core.io.export`, `presentation.export`), element editing widenings on `design.update`/`design.edit`, `core.camera.*`, storey management, `design.visibility.*`, dimensions, locale/user reads (`core.user`), `design.types.list`, presentation annotate — see the 0.8.0 changelog for the full list.
|
|
27
|
+
- **Events.** `this.subscribe("model:changed", handler)` on `PluginWorker` — debounced model-change notifications delivered to the plugin worker (fires for user and plugin edits alike); see the Plugin Development guide.
|
|
28
|
+
|
|
29
|
+
## Behavior changes
|
|
30
|
+
|
|
31
|
+
- `core.geom.delete.profile` / `core.geom.delete.contour` are deprecated aliases of `core.handles.release` — they keep working, but migrate to `core.handles.release([handle])`.
|
|
32
|
+
- `design.create.copy` with `count > 1` no longer freezes the canvas after the call resolves (the post-commit properties-panel storm is fixed); results are unchanged.
|
|
33
|
+
- `design.delete.entities` deletes instance copies before their source meshes within a batch, so mixed batches no longer fail midway with invalidated handles.
|
|
34
|
+
- `design.update.wall` rebuilds (thickness/type changes) replace the wall — always re-bind to the returned `affected[0]` handle; the old handle dies with the rebuilt mesh.
|
|
35
|
+
|
|
36
|
+
## No action needed
|
|
37
|
+
|
|
38
|
+
Plugin code that only passes handles back into API calls (the overwhelmingly common pattern) compiles and runs unchanged against 0.8.0 — template literals and `toString()` still produce the bare id, and every API accepts the values it returns. Action is needed only for the handle-as-string patterns and behavior corrections above; the migration is:
|
|
39
|
+
|
|
40
|
+
1. Bump `@snaptrude/plugin-client` to `0.8.0` and reinstall.
|
|
41
|
+
2. Grep for `typeof` checks, string methods, `===` comparisons, object/Map keys, and `JSON.stringify` on handle values; route them through `handle.id` / `handle.equals()`.
|
|
42
|
+
3. Replace `core.geom.delete.*` calls with `core.handles.release([...])`.
|
|
43
|
+
4. Drop any 1/0.254 compensation on `program.site` footprints, and re-bind wall handles from `design.update.wall`'s `affected`.
|
|
44
|
+
5. Rebuild; existing additive API usage needs no changes.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
---
|
|
2
|
+
from: 0.8.0
|
|
3
|
+
to: 0.9.0
|
|
4
|
+
breaking: false
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Summary
|
|
8
|
+
|
|
9
|
+
0.9.0 reorganizes the namespace map: the `entity` top-level is retired (storeys move under `core`, reference lines and buildable envelopes join the `design` family), two straggler renames land (`core.zoom` → `core.camera`, `getTagsForComponent` → `listForComponent`), and a new `workspace` top-level plus `core.mode` and a façade heatmap API are introduced. Nothing breaks: every deprecated path keeps working — each delegates to the same implementation as its canonical replacement — so existing plugins compile and run unchanged. Migrate names at your own pace; new code should use the canonical paths.
|
|
10
|
+
|
|
11
|
+
## Breaking changes
|
|
12
|
+
|
|
13
|
+
None. All 0.9.0 moves are deprecate-in-place aliases; no signatures or result shapes changed on existing paths.
|
|
14
|
+
|
|
15
|
+
## Moved paths (deprecated → canonical)
|
|
16
|
+
|
|
17
|
+
- `entity.story.get` → `core.storeys.get`
|
|
18
|
+
- `entity.story.getAll` → `core.storeys.list` — the canonical result names the field `storeys` where `getAll` named it `stories`; the records are identical
|
|
19
|
+
- `entity.story.create` → `core.storeys.create`
|
|
20
|
+
- `entity.story.update` → `core.storeys.update`
|
|
21
|
+
- `entity.story.delete` → `core.storeys.delete`
|
|
22
|
+
- `entity.story.duplicate` → `core.storeys.copy`
|
|
23
|
+
- `entity.story.setActive` → `core.storeys.setActive`
|
|
24
|
+
- `entity.referenceLine.createMulti` → `design.create.referenceLines` — adds optional styling args and returns a `ComponentHandle[]` where `createMulti` returned `{ referenceLineIds }`
|
|
25
|
+
- `entity.referenceLine.get` → `design.query.referenceLines.get`
|
|
26
|
+
- `entity.referenceLine.getAll` → `design.query.listReferenceLines` — returns a filterable `ComponentHandle[]` where `getAll` returned `{ referenceLineIds }`
|
|
27
|
+
- `entity.referenceLine.delete` → `design.delete.entities`
|
|
28
|
+
- `entity.buildableEnvelope.create` → `design.create.buildableEnvelope`
|
|
29
|
+
- `entity.buildableEnvelope.update` → `design.update.buildableEnvelope`
|
|
30
|
+
- `core.zoom.extents` → `core.camera.zoomExtents`
|
|
31
|
+
- `core.zoom.selection` → `core.camera.zoomSelection`
|
|
32
|
+
- `core.tags.getTagsForComponent` → `core.tags.listForComponent`
|
|
33
|
+
|
|
34
|
+
## New APIs
|
|
35
|
+
|
|
36
|
+
- **`workspace.*` — dashboard-level operations.** `workspace.projects.{list, get, create, copy, rename}` (`copy` is the dashboard's Save As) and `workspace.teams.{list, get, listMembers}` — project and team operations that previously had no plugin surface. Mutators are write-gated like every other mutating API.
|
|
37
|
+
- **`core.mode.{list, get, set}` — application mode.** Read and switch between `design`, `bim`, `present`, and `program`. `set("program")` throws `PRECONDITION_FAILED` (Program opens in a paired browser tab the plugin worker cannot drive).
|
|
38
|
+
- **`analysis.heatmaps.renderSurfaceGrid`** — oriented-plane (façade) heatmap grids: `renderGrid` plus a plane-normal argument, for vertical and tilted surfaces.
|
|
39
|
+
- **`analysis.heatmaps` named overlays** — render calls accept `options.name` to register up to 16 concurrent overlays (unnamed renders keep the old replace-in-place behaviour via a shared default), and the new `analysis.heatmaps.overlays` sub-API manages them: `list()`, `show(name)` / `hide(name)` / `remove(name)`, `removeAll()`; exactly one overlay is visible at a time (legend follows it), and `reset()` clears them all. Overlays are in-session only and every overlay clears on any scene-mutating edit.
|
|
40
|
+
- **`analysis.heatmaps.renderField(cells, options?)`** — arbitrary cell geometry: planar polygon rings (host-triangulated) or pre-tessellated `vertices`/`indices` meshes, one value each. Every heatmap render call now also accepts `options.scale`: discrete `bands` (2–64, default 11 — unchanged default), binary `threshold` (pass/fail with a labelled two-swatch legend), or exact-match `categorical` classes.
|
|
41
|
+
- **Heatmap hover tooltips** — pass `hover: true` in any `analysis.heatmaps` render call to get a per-cell tooltip while that overlay is visible, showing the cell's `value` (+ unit) and optional `meta` payload; grid/surface-grid cells now accept `meta` like field cells.
|
|
42
|
+
- **`design.query.geometry.getTriangulatedMeshes(components, options?)`** — triangulated render meshes as plain world-space arrays (`{ meshes: [{ id, positions, indices, materialIds? }] }`, no kernel handles), in plan units; optional per-triangle material names via `includeMaterialIds: true` (`null` = unpainted/default); capped at 500 000 triangles per call (over-cap throws `VALIDATION` with the actual total — split the component list and batch).
|
|
43
|
+
- **`presentation.shapes` — plugin-owned keyed shapes on Present sheets.** `upsert(key, shape, { sheetId? })` creates-or-updates one stable shape per key (deterministic id, returns `{ shapeId, created }`), so rerunning an analysis updates the sheet instead of duplicating; plus `remove(key)`, `removeAll()`, and `list()`. The `shape` spec is a `type: "text" | "note" | "arrow" | "geo"` union taking the same options as the matching `presentation.annotate` call.
|
|
44
|
+
- **`program.site.getTimezone()`** — the IANA timezone id (e.g. `"Asia/Kolkata"`) of the project's geo-location, or `null` when the project is not geo-located on terrain.
|
|
45
|
+
- **`analysis.weather.getSeries(args)`** — hourly weather rows (dry-bulb, humidity, wind, radiation, sky cover) for a date range from the project's resolved EPW station, with full source metadata (station, WMO, distance, checksum) and per-field quality flags. Throws typed `PRECONDITION_FAILED` / `NOT_GEOLOCATED` on non-geo-located projects.
|
|
46
|
+
- **`analysis.solar.sampleGrid(args)`** — per-point solar sampling at arbitrary world positions: direct-sun visibility, shade fraction, sky-view factor, and direct/diffuse/total irradiance (W/m² instant or kWh/m² over a range), GPU-raytraced against the full model + terrain context. Pro-gated and write-gated like `analysis.illuminance`.
|
|
47
|
+
- **`analysis.daylight.compute(args)` + `poll({ runId, cursor? })`** — IES LM-83 annual daylight metrics as numbers (no textures): per-sensor records and per-space/storey/project aggregates with a full provenance echo (weather file, thresholds, grid, resolved optics, blind operation). `metrics: ["ASE"]` runs synchronously as before; runs including `"sDA"` now compute real sDA300/50% (Radiance) with LM-83 dynamic blind operation (2% rule, 5% diffuse closed-blind default — the API operates the blinds; sDA without blinds is not LM-83-compliant) and are asynchronous: `compute` returns `{ status: "running", runId }` immediately, and the new `analysis.daylight.poll` fetches results until `status === "complete"`. Optional `optics` arg overrides surface optics per material (keyed by material name as shown in Snaptrude) or per category, over LM-83/convention defaults (wall 0.5 / ceiling 0.7 / floor 0.2 / furniture 0.5 / glazing Tvis 0.65 / context 0.2); glazing takes visible transmittance (Tvis), converted to Radiance transmissivity backend-side. Sensor records gain `da300Percent`/`sdaPass`, aggregates gain `sdaPercent`; ASE fields are present when ASE is requested.
|
|
48
|
+
- **`program.site.getWeather()`** — the project's resolved weather source (station metadata + any pinned override), without fetching rows.
|
|
49
|
+
- **`core.io.import` accepts `.epw` weather files** — upload into the project weather catalog (deduped by checksum) and optionally pin as the project's weather override; `analysis.weather`/`solar`/`daylight` then resolve to the pinned file.
|
|
50
|
+
- **`design.query.geometry.getTriangulatedMeshes` `includeFaceIndices`** — per-triangle B-rep face ids (`faceIds`, honest `null` when a component has no face mapping), enabling face-level post-processing on the triangulated output.
|
|
51
|
+
- **`design.query.spaces.getEnclosure(space)`** — geometric v1 enclosure read: the surfaces bounding a space and its adjacent spaces, derived from live geometry.
|
|
52
|
+
- **`program.spreadsheet.datasets.{set, list}` + plugin-sourced bindings** — store named plugin datasets (upsert; 10 000-row / 2 MB caps) and bind them to ranges with `bindings.create(name, { dataset: "plugin", name }, target)`; re-running `datasets.set` auto-refreshes every binding bound to that dataset. The takeoff source (`{ dataset: "takeoff" }`) is unchanged.
|
|
53
|
+
- **`program.spreadsheet.addImage(sheetName, image, options?)`** — floating images in workbook sheets from PNG/JPEG/SVG data URIs (2 MB cap): cell-anchored, optional explicit size (intrinsic by default), and a stable `name` replaces the picture on rerun. For images on Present-mode sheets use `presentation.shapes` instead.
|
|
54
|
+
- **`program.spreadsheet.addChart` contract enum** — the ratified `chartType` names (`"column"`, `"bar"`) now work on the wire; the legacy internal names (`"columnClustered"`, `"barClustered"`) remain accepted.
|
|
55
|
+
- **`core.geom.create.brepFrom*` — constructive solid modeling.** A full family of brep constructors that mint `BrepHandle`s at authored coordinates: `brepFromFaces(faces)` (plain `{x, y, z}` face loops — host validates welding, planarity, edge coherence and fixes global orientation), `brepFromExtrusion(contour, direction, amount)` (prisms along any direction, holes and arc profiles included), `brepFromLoft(bottomContour, topContour)` (tapered solids; lofts that would produce non-planar side faces are rejected), `brepFromMesh(positions, faces)` (indexed vertex + face-index input), and the booleans `brepFromUnion` / `brepFromSubtraction` (`a` minus `b`) / `brepFromIntersection` — the production OpenCascade lane; scene-derived `getBrep` handles are accepted as read-only boolean inputs, and empty or disjoint results throw typed `VALIDATION` errors. All minted breps are inspectable through `core.geom.query.brep.*` before committing.
|
|
56
|
+
- **`design.create.massFromBrep(brep, label?)`** — commit a mass from any `core.geom.create` brep constructor's handle (scene-derived `getBrep` breps stay read-only → `PRECONDITION_FAILED`): generic mass at the authored coordinates, single undo step, collab-synced. Together with the constructors this closes the loop — author faces / extrude / loft / boolean, then place the result in the scene.
|
|
57
|
+
- **`presentation.placedViews` — layout control over placed views.** Inspect and edit the LAYOUT of view shapes already placed on Present sheets (content refresh stays on `sheets.updatePlacedView`): `list(sheetId?)` / `get(shapeId)` return sheet, sheet-local position, size, architectural scale (`null` for 3D), rotation, crop and link state; `move(shapeId, position, { sheetId? })` repositions or reparents across sheets; `scale(shapeId, factor)` is a uniform corner-drag-equivalent resize; `setScale(shapeId, scale)` sets a standard architectural scale (2D views only); `setCrop(shapeId, crop | null)` crops with native tldraw fractions, keeping the visible region page-anchored — and the crop survives `updatePlacedView` refreshes. Identity is the shape id `sheets.place` returns.
|
|
58
|
+
|
|
59
|
+
## No action needed
|
|
60
|
+
|
|
61
|
+
All 0.9.0 changes are additive. Deprecated paths remain until at least the next major version, and removal is gated on call metrics showing zero live traffic plus a consumer sweep. To modernize a plugin: rename calls per the moved-paths list above (only `core.storeys.list` and the two reference-line list/create reads have different result shapes from their predecessors — everything else is a pure rename).
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"package": "@snaptrude/plugin-client",
|
|
3
|
+
"latest": "0.9.0",
|
|
4
|
+
"spans": [
|
|
5
|
+
{
|
|
6
|
+
"from": "0.4.0",
|
|
7
|
+
"to": "0.5.0",
|
|
8
|
+
"file": "0.4.0-to-0.5.0.md",
|
|
9
|
+
"breaking": false
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"from": "0.5.0",
|
|
13
|
+
"to": "0.6.0",
|
|
14
|
+
"file": "0.5.0-to-0.6.0.md",
|
|
15
|
+
"breaking": false
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"from": "0.6.0",
|
|
19
|
+
"to": "0.7.0",
|
|
20
|
+
"file": "0.6.0-to-0.7.0.md",
|
|
21
|
+
"breaking": true
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"from": "0.7.0",
|
|
25
|
+
"to": "0.7.1",
|
|
26
|
+
"file": "0.7.0-to-0.7.1.md",
|
|
27
|
+
"breaking": false
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"from": "0.7.1",
|
|
31
|
+
"to": "0.8.0",
|
|
32
|
+
"file": "0.7.1-to-0.8.0.md",
|
|
33
|
+
"breaking": true
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"from": "0.8.0",
|
|
37
|
+
"to": "0.9.0",
|
|
38
|
+
"file": "0.8.0-to-0.9.0.md",
|
|
39
|
+
"breaking": false
|
|
40
|
+
}
|
|
41
|
+
]
|
|
42
|
+
}
|
package/AGENTS.md
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
# Plugin Client — Agent Guide
|
|
2
|
-
|
|
3
|
-
This package implements the plugin-core API for the **worker side** (plugin runtime).
|
|
4
|
-
Plugins import `snaptrude` from this package to interact with the Snaptrude host.
|
|
5
|
-
|
|
6
|
-
## Relationship to plugin-core
|
|
7
|
-
|
|
8
|
-
> Source of truth: [`packages/plugin-core/AGENTS.md`](../plugin-core/AGENTS.md)
|
|
9
|
-
|
|
10
|
-
This package implements the API surface defined in `@snaptrude/plugin-core`. Only the
|
|
11
|
-
root `PluginApi` class is extended; every namespace under it is satisfied structurally
|
|
12
|
-
by a generic RPC proxy (see below). When plugin-core changes its top-level shape,
|
|
13
|
-
this package must be updated to match.
|
|
14
|
-
|
|
15
|
-
## What this package contains
|
|
16
|
-
|
|
17
|
-
- `src/api/index.ts` — `ClientPluginApi`: wires one generic RPC proxy per top-level namespace
|
|
18
|
-
- `src/rpc-proxy.ts` — `createRpcNamespace()`: Proxy mapping dotted property paths to host RPC calls
|
|
19
|
-
- `src/host-api.ts` — Comlink RPC wrapper (`HostApi.call()`); unwraps success/error results
|
|
20
|
-
- `src/plugin-worker.ts` — `PluginWorker` base class (lifecycle, UI messaging, Comlink exposure)
|
|
21
|
-
- `src/index.ts` — Exports the `snaptrude` singleton (`ClientPluginApi` instance)
|
|
22
|
-
|
|
23
|
-
## Quick commands
|
|
24
|
-
|
|
25
|
-
```bash
|
|
26
|
-
pnpm check-types # typecheck (no emit)
|
|
27
|
-
pnpm build # tsup build (ESM + CJS)
|
|
28
|
-
pnpm dev # tsup watch mode
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
## Implementation patterns
|
|
32
|
-
|
|
33
|
-
### Everything is a generic RPC proxy (async, remote)
|
|
34
|
-
|
|
35
|
-
Under the all-handle model there is no in-worker compute: `core.math.*` and
|
|
36
|
-
`core.geom.*` values are opaque handles, so **every** namespace — `core.*`
|
|
37
|
-
(including `core.units`), `design.*`, `entity.*`, `tools.*` — is a
|
|
38
|
-
`createRpcNamespace<PluginXApi>("x")` Proxy. There are no hand-written
|
|
39
|
-
per-method wrappers. Nested property access builds the dot-separated method
|
|
40
|
-
path; the call marshals `{ method, args }` to the host via Comlink
|
|
41
|
-
(`getHostApi().call()`):
|
|
42
|
-
|
|
43
|
-
```typescript
|
|
44
|
-
// src/api/index.ts — one proxy per top-level namespace
|
|
45
|
-
this.core = createRpcNamespace<PluginCoreApi>("core")
|
|
46
|
-
|
|
47
|
-
// Plugin code — positional args (whole tuple crosses the wire), values are handles:
|
|
48
|
-
const v = await snaptrude.core.math.vec3.new(1, 2, 3)
|
|
49
|
-
await snaptrude.entity.space.createRectangular(position, dimensions)
|
|
50
|
-
// → getHostApi().call({ method: "entity.space.createRectangular", args: [position, dimensions] })
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
The proxy is structurally cast to the abstract API type, so argument and return
|
|
54
|
-
types are enforced by plugin-core while dispatch stays dynamic. The `method`
|
|
55
|
-
string is exactly the property path and must match `PluginApiMethod`
|
|
56
|
-
(auto-inferred from the class hierarchy in `plugin-core/src/host-utils.ts`).
|
|
57
|
-
|
|
58
|
-
## When to update this package
|
|
59
|
-
|
|
60
|
-
- **plugin-core adds/removes/changes a method**: Usually nothing to do here — the
|
|
61
|
-
proxy dispatches dynamically and types flow from plugin-core. Rebuild plugin-core,
|
|
62
|
-
then run `pnpm check-types` here.
|
|
63
|
-
- **plugin-core adds a new top-level namespace on `PluginApi`**: Add a matching
|
|
64
|
-
`createRpcNamespace<PluginNewApi>("new")` property in `ClientPluginApi`
|
|
65
|
-
(`src/api/index.ts`). Nested modules under an existing namespace need no wiring.
|
|
66
|
-
|
|
67
|
-
After making changes, always run `pnpm check-types` to verify everything compiles.
|
|
68
|
-
|
|
69
|
-
## File mapping (plugin-core -> plugin-client)
|
|
70
|
-
|
|
71
|
-
There are no per-namespace files here anymore — the whole plugin-core API tree is
|
|
72
|
-
served by two files:
|
|
73
|
-
|
|
74
|
-
| plugin-core | plugin-client |
|
|
75
|
-
| --------------------------------------------- | -------------------------------------------------------------------- |
|
|
76
|
-
| `src/api/**` (all namespaces, e.g. `core.math.vec3`) | `src/api/index.ts` (`ClientPluginApi`, one `createRpcNamespace` each) |
|
|
77
|
-
| `src/host-utils.ts` (`PluginApiMethod` types) | `src/rpc-proxy.ts` + `src/host-api.ts` (dispatch + Comlink transport) |
|
|
78
|
-
|
|
79
|
-
## Downstream consumers
|
|
80
|
-
|
|
81
|
-
Changes to this package's **public exports** affect:
|
|
82
|
-
|
|
83
|
-
- Internal plugins under `plugins/`
|
|
84
|
-
- Example plugins under `examples/`
|
|
85
|
-
|
|
86
|
-
If you change or remove an export, search these directories for usage.
|
package/CLAUDE.md
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
# CLAUDE.md
|
|
2
|
-
|
|
3
|
-
> **All coding standards, checks, and guidance live in [`AGENTS.md`](AGENTS.md).**
|
|
4
|
-
> `CLAUDE.md` is a pointer only — add all new rules, patterns, and instructions to `AGENTS.md`.
|
|
5
|
-
|
|
6
|
-
See [AGENTS.md](AGENTS.md) for:
|
|
7
|
-
|
|
8
|
-
- Implementation pattern (generic RPC proxy — every namespace is async host RPC)
|
|
9
|
-
- File mapping from plugin-core to plugin-client
|
|
10
|
-
- When and how to update this package in response to plugin-core changes
|
|
11
|
-
- Downstream consumer notes
|
package/src/api/index.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
PluginApi,
|
|
3
|
-
PluginCoreApi,
|
|
4
|
-
PluginDesignApi,
|
|
5
|
-
PluginEntityApi,
|
|
6
|
-
PluginProgramApi,
|
|
7
|
-
PluginPresentationApi,
|
|
8
|
-
PluginAnalysisApi,
|
|
9
|
-
} from "@snaptrude/plugin-core"
|
|
10
|
-
import { createRpcNamespace } from "../rpc-proxy"
|
|
11
|
-
|
|
12
|
-
export class ClientPluginApi extends PluginApi {
|
|
13
|
-
private static instance: ClientPluginApi
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Every namespace is fully remote under the all-handle model: math/geom now
|
|
17
|
-
* cross to the host (values are opaque handles), so there is no in-worker
|
|
18
|
-
* compute left. All dispatch through a single generic RPC Proxy. Units live
|
|
19
|
-
* under `core.units`, so they ride the `core` proxy.
|
|
20
|
-
*/
|
|
21
|
-
public core: PluginCoreApi
|
|
22
|
-
public design: PluginDesignApi
|
|
23
|
-
public entity: PluginEntityApi
|
|
24
|
-
public program: PluginProgramApi
|
|
25
|
-
public presentation: PluginPresentationApi
|
|
26
|
-
public analysis: PluginAnalysisApi
|
|
27
|
-
|
|
28
|
-
private constructor() {
|
|
29
|
-
super()
|
|
30
|
-
this.core = createRpcNamespace<PluginCoreApi>("core")
|
|
31
|
-
this.design = createRpcNamespace<PluginDesignApi>("design")
|
|
32
|
-
this.entity = createRpcNamespace<PluginEntityApi>("entity")
|
|
33
|
-
this.program = createRpcNamespace<PluginProgramApi>("program")
|
|
34
|
-
this.presentation =
|
|
35
|
-
createRpcNamespace<PluginPresentationApi>("presentation")
|
|
36
|
-
this.analysis = createRpcNamespace<PluginAnalysisApi>("analysis")
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
static getInstance(): ClientPluginApi {
|
|
40
|
-
if (!ClientPluginApi.instance) {
|
|
41
|
-
ClientPluginApi.instance = new ClientPluginApi()
|
|
42
|
-
}
|
|
43
|
-
return ClientPluginApi.instance
|
|
44
|
-
}
|
|
45
|
-
}
|
package/src/host-api.ts
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import * as Comlink from "comlink"
|
|
2
|
-
import type {
|
|
3
|
-
PluginApiMethod,
|
|
4
|
-
PluginApiCallPayload,
|
|
5
|
-
PluginApiCallWrappedResult,
|
|
6
|
-
PluginApiCallResult,
|
|
7
|
-
} from "@snaptrude/plugin-core"
|
|
8
|
-
import { PluginError, fromEnvelope, makeClientEnvelope } from "@snaptrude/plugin-core"
|
|
9
|
-
|
|
10
|
-
export interface HostApi {
|
|
11
|
-
call<M extends PluginApiMethod>(
|
|
12
|
-
payload: PluginApiCallPayload<M>
|
|
13
|
-
): Promise<PluginApiCallWrappedResult<M>>
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export interface HostApiWrapped {
|
|
17
|
-
call<M extends PluginApiMethod>(
|
|
18
|
-
payload: PluginApiCallPayload<M>
|
|
19
|
-
): Promise<PluginApiCallResult<M>>
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function createHostApi(endpoint?: Comlink.Endpoint): HostApi {
|
|
23
|
-
return Comlink.wrap<HostApi>(
|
|
24
|
-
endpoint ?? (globalThis as unknown as Comlink.Endpoint)
|
|
25
|
-
) as unknown as HostApi
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
let _instance: HostApi | null = null
|
|
29
|
-
|
|
30
|
-
/** TEST SEAM ONLY: replace the Comlink host instance (pass `undefined` to reset). */
|
|
31
|
-
export function __setHostApiInstance(instance?: HostApi): void {
|
|
32
|
-
_instance = instance ?? null
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function getHostApi(): HostApiWrapped {
|
|
36
|
-
if (!_instance) {
|
|
37
|
-
_instance = createHostApi()
|
|
38
|
-
}
|
|
39
|
-
return {
|
|
40
|
-
call: async <M extends PluginApiMethod>(payload: PluginApiCallPayload<M>): Promise<PluginApiCallResult<M>> => {
|
|
41
|
-
if (!_instance) {
|
|
42
|
-
throw new Error("Host API not initialized")
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
let result: PluginApiCallWrappedResult<M>
|
|
46
|
-
try {
|
|
47
|
-
result = await _instance.call(payload)
|
|
48
|
-
} catch (transportErr) {
|
|
49
|
-
// Comlink-level rejection: port closed, worker terminated, clone
|
|
50
|
-
// failure. Never a routed failure — the router always RETURNS its
|
|
51
|
-
// envelope — so normalize to a typed transport error.
|
|
52
|
-
if (PluginError.is(transportErr)) throw transportErr
|
|
53
|
-
throw rehydrate(
|
|
54
|
-
makeClientEnvelope(
|
|
55
|
-
"TRANSPORT_LOST",
|
|
56
|
-
transportErr instanceof Error ? transportErr.message : String(transportErr),
|
|
57
|
-
{ methodPath: payload.method }
|
|
58
|
-
)
|
|
59
|
-
)
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
if (result.success) {
|
|
63
|
-
return result.data
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Structured envelope when the host provides one; legacy hosts (string
|
|
67
|
-
// `error` only) degrade to UNKNOWN with the message preserved.
|
|
68
|
-
throw rehydrate(
|
|
69
|
-
result.errorInfo ??
|
|
70
|
-
makeClientEnvelope("UNKNOWN", result.error ?? "Unknown host error", {
|
|
71
|
-
methodPath: payload.method,
|
|
72
|
-
})
|
|
73
|
-
)
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Envelope → typed `PluginError`, with the stack trimmed to the plugin's call
|
|
80
|
-
* site (V8 only; harmless no-op elsewhere) instead of transport internals.
|
|
81
|
-
*/
|
|
82
|
-
function rehydrate(envelope: Parameters<typeof fromEnvelope>[0]): PluginError {
|
|
83
|
-
const error = fromEnvelope(envelope)
|
|
84
|
-
;(Error as { captureStackTrace?: (target: object, ctor: Function) => void })
|
|
85
|
-
.captureStackTrace?.(error, rehydrate)
|
|
86
|
-
return error
|
|
87
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { ClientPluginApi } from "./api"
|
|
2
|
-
|
|
3
|
-
export * from "./api"
|
|
4
|
-
export * from "./host-api"
|
|
5
|
-
export * from "./plugin-worker"
|
|
6
|
-
|
|
7
|
-
// Error surface — plugins branch on `PluginError.is(e)` + `e.code`.
|
|
8
|
-
export {
|
|
9
|
-
PluginError,
|
|
10
|
-
PluginValidationError,
|
|
11
|
-
PluginNotFoundError,
|
|
12
|
-
PluginPermissionError,
|
|
13
|
-
PluginHandleError,
|
|
14
|
-
PluginQuotaError,
|
|
15
|
-
PluginTimeoutError,
|
|
16
|
-
PluginTransportError,
|
|
17
|
-
PluginLifecycleError,
|
|
18
|
-
PluginExecutionError,
|
|
19
|
-
PluginInternalError,
|
|
20
|
-
fromEnvelope,
|
|
21
|
-
isErrorEnvelope,
|
|
22
|
-
isPluginErrorCode,
|
|
23
|
-
PLUGIN_ERROR_CODES,
|
|
24
|
-
CODE_META,
|
|
25
|
-
} from "@snaptrude/plugin-core"
|
|
26
|
-
export type {
|
|
27
|
-
ErrorEnvelope,
|
|
28
|
-
PluginErrorCode,
|
|
29
|
-
WirePluginErrorCode,
|
|
30
|
-
PluginErrorCategory,
|
|
31
|
-
} from "@snaptrude/plugin-core"
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* The Snaptrude plugin client API.
|
|
35
|
-
*
|
|
36
|
-
* The main entry point for plugins to interact with the Snaptrude platform.
|
|
37
|
-
*/
|
|
38
|
-
export const snaptrude = ClientPluginApi.getInstance()
|
package/src/plugin-worker.ts
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import * as Comlink from "comlink"
|
|
2
|
-
|
|
3
|
-
export interface UIMessage {
|
|
4
|
-
action: string
|
|
5
|
-
payload: unknown
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
interface PluginConfig {
|
|
9
|
-
pluginId: string
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Base class for Snaptrude plugin workers.
|
|
14
|
-
*
|
|
15
|
-
* Handles Comlink wiring, host communication, and the standard lifecycle
|
|
16
|
-
* methods (`init`, `destroy`, `ping`, `onUIMessage`). Subclass this and
|
|
17
|
-
* override only the methods you need — then call `start()` to expose the
|
|
18
|
-
* worker API.
|
|
19
|
-
*
|
|
20
|
-
* The plugin ID is received automatically from the host during
|
|
21
|
-
* initialization — no need to pass it manually.
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```ts
|
|
25
|
-
* import { PluginWorker } from "@snaptrude/plugin-client";
|
|
26
|
-
*
|
|
27
|
-
* class MyPlugin extends PluginWorker {
|
|
28
|
-
* async onUIMessage(message: UIMessage) {
|
|
29
|
-
* // handle messages from the UI panel
|
|
30
|
-
* }
|
|
31
|
-
* }
|
|
32
|
-
*
|
|
33
|
-
* new MyPlugin().start();
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
export abstract class PluginWorker {
|
|
37
|
-
protected pluginId!: string
|
|
38
|
-
private hostAPI: Comlink.Remote<Record<string, unknown>>
|
|
39
|
-
|
|
40
|
-
constructor() {
|
|
41
|
-
this.hostAPI = Comlink.wrap<Record<string, unknown>>(
|
|
42
|
-
self as unknown as Comlink.Endpoint
|
|
43
|
-
)
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
protected sendToUI(action: string, payload: unknown): void {
|
|
47
|
-
;(this.hostAPI as Record<string, any>).ui.sendToUI({ action, payload })
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Signal the host that this plugin has finished its work and should be
|
|
52
|
-
* stopped. Use this in headless (UI-less) plugins that run a task and
|
|
53
|
-
* self-terminate.
|
|
54
|
-
*/
|
|
55
|
-
protected complete(): void {
|
|
56
|
-
;(this.hostAPI as Record<string, any>).lifecycle.complete()
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
async init(): Promise<void> {
|
|
60
|
-
console.log(this.pluginId, "init() called")
|
|
61
|
-
console.log(this.pluginId, "Initialization complete")
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
async destroy(): Promise<void> {
|
|
65
|
-
console.log(this.pluginId, "destroy() called — cleaning up")
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
async ping(): Promise<string> {
|
|
69
|
-
return "pong"
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
async onUIMessage(_message: UIMessage): Promise<void> {
|
|
73
|
-
// Override in subclass to handle UI messages
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Expose the worker API via Comlink and start listening.
|
|
78
|
-
* Call this once after constructing the plugin instance.
|
|
79
|
-
*
|
|
80
|
-
* The host calls `init(config)` with `{ pluginId }`,
|
|
81
|
-
* which is captured here to set `this.pluginId` before the
|
|
82
|
-
* subclass's `init()` runs.
|
|
83
|
-
*/
|
|
84
|
-
start(): void {
|
|
85
|
-
Comlink.expose(
|
|
86
|
-
{
|
|
87
|
-
init: (config: PluginConfig) => {
|
|
88
|
-
this.pluginId = config.pluginId
|
|
89
|
-
return this.init()
|
|
90
|
-
},
|
|
91
|
-
destroy: () => this.destroy(),
|
|
92
|
-
ping: () => this.ping(),
|
|
93
|
-
onUIMessage: (message: UIMessage) => this.onUIMessage(message),
|
|
94
|
-
},
|
|
95
|
-
self as unknown as Comlink.Endpoint
|
|
96
|
-
)
|
|
97
|
-
console.log("Worker loaded, API exposed via Comlink")
|
|
98
|
-
}
|
|
99
|
-
}
|
package/src/rpc-proxy.ts
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
PluginApiCallPayload,
|
|
3
|
-
PluginApiMethod,
|
|
4
|
-
} from "@snaptrude/plugin-core"
|
|
5
|
-
import { getHostApi } from "./host-api"
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Build a namespace object whose nested property access maps to a
|
|
9
|
-
* dot-separated host RPC method path, and whose every call dispatches that
|
|
10
|
-
* path through the host bridge.
|
|
11
|
-
*
|
|
12
|
-
* The host exposes the entire plugin API behind a single generic `call()`
|
|
13
|
-
* (see the host `bridge.ts`), and the method string is exactly the property
|
|
14
|
-
* path — so one Proxy replaces every hand-written per-method RPC wrapper for
|
|
15
|
-
* every namespace (`core.*`, `design.*`, `entity.*`):
|
|
16
|
-
*
|
|
17
|
-
* The POSITIONAL transport forwards the whole argument tuple; the host router
|
|
18
|
-
* spreads it back into the resolved method (`fn(...args)`):
|
|
19
|
-
*
|
|
20
|
-
* ```ts
|
|
21
|
-
* snaptrude.core.math.vec3.new(1, 2, 3)
|
|
22
|
-
* // → getHostApi().call({ method: "core.math.vec3.new", args: [1, 2, 3] })
|
|
23
|
-
* ```
|
|
24
|
-
*
|
|
25
|
-
* Typed at the call site, e.g. `createRpcNamespace<PluginEntityApi>("entity")`.
|
|
26
|
-
* The Proxy is structurally cast to the abstract API type — argument and
|
|
27
|
-
* return types are enforced by that type, while dispatch is dynamic.
|
|
28
|
-
*
|
|
29
|
-
* Every namespace uses this — including `core.math.*` and `core.geom.*`: under
|
|
30
|
-
* the all-handle model there is no in-worker compute; math and geometry are
|
|
31
|
-
* host calls like everything else.
|
|
32
|
-
*/
|
|
33
|
-
export function createRpcNamespace<T extends object>(basePath: string): T {
|
|
34
|
-
const build = (path: string): unknown =>
|
|
35
|
-
new Proxy(NOOP, {
|
|
36
|
-
get(_target, prop) {
|
|
37
|
-
// Symbols and `then` must not resolve to a callable proxy, otherwise
|
|
38
|
-
// the namespace would look thenable and break Promise resolution if it
|
|
39
|
-
// ever reached an `await`.
|
|
40
|
-
if (typeof prop !== "string" || prop === "then") return undefined
|
|
41
|
-
return build(`${path}.${prop}`)
|
|
42
|
-
},
|
|
43
|
-
apply(_target, _thisArg, argArray: unknown[]) {
|
|
44
|
-
const payload = {
|
|
45
|
-
method: path,
|
|
46
|
-
args: argArray,
|
|
47
|
-
} as unknown as PluginApiCallPayload<PluginApiMethod>
|
|
48
|
-
return getHostApi().call(payload)
|
|
49
|
-
},
|
|
50
|
-
})
|
|
51
|
-
|
|
52
|
-
return build(basePath) as T
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** Proxy target must be callable for the `apply` trap; identity is irrelevant. */
|
|
56
|
-
const NOOP = (): void => {}
|