@snaptrude/plugin-client 0.9.14 → 0.9.15
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 +17 -0
- package/dist/api/index.d.ts +20 -0
- package/dist/api/index.d.ts.map +1 -0
- 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 +13 -0
- package/dist/host-api.d.ts.map +1 -0
- package/dist/index.cjs +411 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +366 -0
- package/dist/index.js.map +1 -0
- package/dist/plugin-worker.d.ts +86 -0
- package/dist/plugin-worker.d.ts.map +1 -0
- package/dist/rpc-proxy.d.ts +28 -0
- package/dist/rpc-proxy.d.ts.map +1 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @snaptrude/plugin-client
|
|
2
2
|
|
|
3
|
+
## 0.9.15
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [4bfe118]
|
|
8
|
+
- Updated dependencies [80c1a2b]
|
|
9
|
+
- Updated dependencies [0e3df96]
|
|
10
|
+
- Updated dependencies [d84ea44]
|
|
11
|
+
- @snaptrude/plugin-core@0.9.15
|
|
12
|
+
|
|
3
13
|
## 0.9.14
|
|
4
14
|
|
|
5
15
|
### Patch Changes
|
|
@@ -52,6 +62,13 @@
|
|
|
52
62
|
|
|
53
63
|
- Version bump to track plugin-core 0.9.9 (program.metadata, program.labels, program.departments.setTargetCount, custom program sheets on program.spreadsheet, core.tags.listForComponents). No client code change — every namespace is served by the generic RPC proxy, so new plugin-core methods dispatch automatically once plugin-core is rebuilt.
|
|
54
64
|
|
|
65
|
+
## 0.9.8
|
|
66
|
+
|
|
67
|
+
### Patch Changes
|
|
68
|
+
|
|
69
|
+
- Updated dependencies [7fd374e]
|
|
70
|
+
- @snaptrude/plugin-core@0.9.8
|
|
71
|
+
|
|
55
72
|
## 0.9.7
|
|
56
73
|
|
|
57
74
|
### Patch Changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { PluginApi, PluginCoreApi, PluginDesignApi, PluginEntityApi, PluginProgramApi, PluginPresentationApi, PluginAnalysisApi, PluginWorkspaceApi } from "@snaptrude/plugin-core";
|
|
2
|
+
export declare class ClientPluginApi extends PluginApi {
|
|
3
|
+
private static instance;
|
|
4
|
+
/**
|
|
5
|
+
* Every namespace is fully remote under the all-handle model: math/geom now
|
|
6
|
+
* cross to the host (values are opaque handles), so there is no in-worker
|
|
7
|
+
* compute left. All dispatch through a single generic RPC Proxy. Units live
|
|
8
|
+
* under `core.units`, so they ride the `core` proxy.
|
|
9
|
+
*/
|
|
10
|
+
core: PluginCoreApi;
|
|
11
|
+
design: PluginDesignApi;
|
|
12
|
+
entity: PluginEntityApi;
|
|
13
|
+
program: PluginProgramApi;
|
|
14
|
+
presentation: PluginPresentationApi;
|
|
15
|
+
analysis: PluginAnalysisApi;
|
|
16
|
+
workspace: PluginWorkspaceApi;
|
|
17
|
+
private constructor();
|
|
18
|
+
static getInstance(): ClientPluginApi;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,aAAa,EACb,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EACnB,MAAM,wBAAwB,CAAA;AAG/B,qBAAa,eAAgB,SAAQ,SAAS;IAC5C,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAiB;IAExC;;;;;OAKG;IACI,IAAI,EAAE,aAAa,CAAA;IACnB,MAAM,EAAE,eAAe,CAAA;IACvB,MAAM,EAAE,eAAe,CAAA;IACvB,OAAO,EAAE,gBAAgB,CAAA;IACzB,YAAY,EAAE,qBAAqB,CAAA;IACnC,QAAQ,EAAE,iBAAiB,CAAA;IAC3B,SAAS,EAAE,kBAAkB,CAAA;IAEpC,OAAO;IAYP,MAAM,CAAC,WAAW,IAAI,eAAe;CAMtC"}
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Snaptrude plugin events.
|
|
3
|
+
*
|
|
4
|
+
* Plugins can react to changes in the host app. Events are delivered through
|
|
5
|
+
* the host event bus — a separate channel from the request/response
|
|
6
|
+
* `snaptrude.*` API — and carry a small structured-clone-safe payload, never
|
|
7
|
+
* live model data.
|
|
8
|
+
*
|
|
9
|
+
* Subscribe from a {@link PluginWorker} subclass with `this.subscribe(...)`.
|
|
10
|
+
*
|
|
11
|
+
* NOTE: events are a subscription surface, not `call()` RPC methods, so they do
|
|
12
|
+
* NOT appear in the discovery manifest (which enumerates callable methods
|
|
13
|
+
* only). This module is the typed, discoverable declaration of the surface.
|
|
14
|
+
*/
|
|
15
|
+
/** Every event a plugin can subscribe to. */
|
|
16
|
+
export declare const PLUGIN_EVENTS: readonly ["selection:changed", "tool:activated", "project:saved", "view:changed", "model:changed"];
|
|
17
|
+
/** Union of subscribable event names. */
|
|
18
|
+
export type PluginEventName = (typeof PLUGIN_EVENTS)[number];
|
|
19
|
+
/**
|
|
20
|
+
* Payload for `model:changed` — fired (debounced) whenever the project model is
|
|
21
|
+
* mutated, by a user edit OR a plugin edit. Deliberately minimal: it signals
|
|
22
|
+
* *that* the model changed, never *what* changed. Re-query the API for details.
|
|
23
|
+
*/
|
|
24
|
+
export interface ModelChangedEvent {
|
|
25
|
+
/** Origin of the change. Currently always `"command"` (the edit chokepoint). */
|
|
26
|
+
source: string;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=events.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,6CAA6C;AAC7C,eAAO,MAAM,aAAa,oGAMhB,CAAA;AAEV,yCAAyC;AACzC,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAA;AAE5D;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,gFAAgF;IAChF,MAAM,EAAE,MAAM,CAAA;CACf"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Handle } from "@snaptrude/plugin-core";
|
|
2
|
+
/**
|
|
3
|
+
* Return THE `Handle` instance for this id — the existing live wrapper when
|
|
4
|
+
* present, else a fresh one wired for auto-release.
|
|
5
|
+
*/
|
|
6
|
+
export declare function intern(id: string): Handle<string>;
|
|
7
|
+
/** TEST SEAM ONLY: replace the release transport (pass `undefined` to restore). */
|
|
8
|
+
export declare function __setReleaseTransport(transport?: (batch: string[]) => Promise<void>): void;
|
|
9
|
+
/** Exported for tests and for an eager flush before a plugin self-completes. */
|
|
10
|
+
export declare function flushReleaseQueue(): Promise<void>;
|
|
11
|
+
/**
|
|
12
|
+
* Recursively re-wrap a host result: `{ __h: "<id>" }` tags (produced by
|
|
13
|
+
* `Handle.toJSON` through the host's JSON-round-trip serialization) become
|
|
14
|
+
* interned `Handle` instances. Arrays and plain records are walked; all other
|
|
15
|
+
* values pass through untouched.
|
|
16
|
+
*/
|
|
17
|
+
export declare function rewrapResult(value: unknown): unknown;
|
|
18
|
+
/**
|
|
19
|
+
* Recursively unwrap outgoing args: `Handle` instances become their wire id
|
|
20
|
+
* strings. Uses a memo Map (not a bail-out set) so shared/diamond references
|
|
21
|
+
* get the SAME converted subtree — a bail-out would leak un-unwrapped Handle
|
|
22
|
+
* instances through the second reference. Cycles are handled by memoizing the
|
|
23
|
+
* output object before recursing. Non-plain objects pass through untouched
|
|
24
|
+
* (structured clone imposes plain-data args anyway).
|
|
25
|
+
*/
|
|
26
|
+
export declare function unwrapArgs(value: unknown, memo?: Map<object, unknown>): unknown;
|
|
27
|
+
//# sourceMappingURL=handle-runtime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-runtime.d.ts","sourceRoot":"","sources":["../src/handle-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AAqC/C;;;GAGG;AACH,wBAAgB,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAwBjD;AAqBD,mFAAmF;AACnF,wBAAgB,qBAAqB,CACnC,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,GAC7C,IAAI,CASN;AAED,gFAAgF;AAChF,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,CAgCvD;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAYpD;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,uBAA6B,GAAG,OAAO,CAqBrF"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import * as Comlink from "comlink";
|
|
2
|
+
import type { PluginApiMethod, PluginApiCallPayload, PluginApiCallWrappedResult, PluginApiCallResult } from "@snaptrude/plugin-core";
|
|
3
|
+
export interface HostApi {
|
|
4
|
+
call<M extends PluginApiMethod>(payload: PluginApiCallPayload<M>): Promise<PluginApiCallWrappedResult<M>>;
|
|
5
|
+
}
|
|
6
|
+
export interface HostApiWrapped {
|
|
7
|
+
call<M extends PluginApiMethod>(payload: PluginApiCallPayload<M>): Promise<PluginApiCallResult<M>>;
|
|
8
|
+
}
|
|
9
|
+
export declare function createHostApi(endpoint?: Comlink.Endpoint): HostApi;
|
|
10
|
+
/** TEST SEAM ONLY: replace the Comlink host instance (pass `undefined` to reset). */
|
|
11
|
+
export declare function __setHostApiInstance(instance?: HostApi): void;
|
|
12
|
+
export declare function getHostApi(): HostApiWrapped;
|
|
13
|
+
//# sourceMappingURL=host-api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host-api.d.ts","sourceRoot":"","sources":["../src/host-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,KAAK,EACV,eAAe,EACf,oBAAoB,EACpB,0BAA0B,EAC1B,mBAAmB,EACpB,MAAM,wBAAwB,CAAA;AAI/B,MAAM,WAAW,OAAO;IACtB,IAAI,CAAC,CAAC,SAAS,eAAe,EAC5B,OAAO,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAC/B,OAAO,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,CAAA;CAC1C;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,CAAC,CAAC,SAAS,eAAe,EAC5B,OAAO,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAC/B,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAA;CACnC;AAED,wBAAgB,aAAa,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,QAAQ,GAAG,OAAO,CAIlE;AAID,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,QAAQ,CAAC,EAAE,OAAO,GAAG,IAAI,CAE7D;AAED,wBAAgB,UAAU,IAAI,cAAc,CA0C3C"}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
CODE_META: () => import_plugin_core4.CODE_META,
|
|
34
|
+
ClientPluginApi: () => ClientPluginApi,
|
|
35
|
+
PLUGIN_ERROR_CODES: () => import_plugin_core4.PLUGIN_ERROR_CODES,
|
|
36
|
+
PLUGIN_EVENTS: () => PLUGIN_EVENTS,
|
|
37
|
+
PluginError: () => import_plugin_core4.PluginError,
|
|
38
|
+
PluginExecutionError: () => import_plugin_core4.PluginExecutionError,
|
|
39
|
+
PluginHandleError: () => import_plugin_core4.PluginHandleError,
|
|
40
|
+
PluginInternalError: () => import_plugin_core4.PluginInternalError,
|
|
41
|
+
PluginLifecycleError: () => import_plugin_core4.PluginLifecycleError,
|
|
42
|
+
PluginNotFoundError: () => import_plugin_core4.PluginNotFoundError,
|
|
43
|
+
PluginPermissionError: () => import_plugin_core4.PluginPermissionError,
|
|
44
|
+
PluginQuotaError: () => import_plugin_core4.PluginQuotaError,
|
|
45
|
+
PluginTimeoutError: () => import_plugin_core4.PluginTimeoutError,
|
|
46
|
+
PluginTransportError: () => import_plugin_core4.PluginTransportError,
|
|
47
|
+
PluginValidationError: () => import_plugin_core4.PluginValidationError,
|
|
48
|
+
PluginWorker: () => PluginWorker,
|
|
49
|
+
__setHostApiInstance: () => __setHostApiInstance,
|
|
50
|
+
__setReleaseTransport: () => __setReleaseTransport,
|
|
51
|
+
createHostApi: () => createHostApi,
|
|
52
|
+
flushReleaseQueue: () => flushReleaseQueue,
|
|
53
|
+
fromEnvelope: () => import_plugin_core4.fromEnvelope,
|
|
54
|
+
getHostApi: () => getHostApi,
|
|
55
|
+
intern: () => intern,
|
|
56
|
+
isErrorEnvelope: () => import_plugin_core4.isErrorEnvelope,
|
|
57
|
+
isPluginErrorCode: () => import_plugin_core4.isPluginErrorCode,
|
|
58
|
+
rewrapResult: () => rewrapResult,
|
|
59
|
+
snaptrude: () => snaptrude,
|
|
60
|
+
unwrapArgs: () => unwrapArgs
|
|
61
|
+
});
|
|
62
|
+
module.exports = __toCommonJS(index_exports);
|
|
63
|
+
|
|
64
|
+
// src/api/index.ts
|
|
65
|
+
var import_plugin_core3 = require("@snaptrude/plugin-core");
|
|
66
|
+
|
|
67
|
+
// src/host-api.ts
|
|
68
|
+
var Comlink = __toESM(require("comlink"), 1);
|
|
69
|
+
var import_plugin_core2 = require("@snaptrude/plugin-core");
|
|
70
|
+
|
|
71
|
+
// src/handle-runtime.ts
|
|
72
|
+
var import_plugin_core = require("@snaptrude/plugin-core");
|
|
73
|
+
var interned = /* @__PURE__ */ new Map();
|
|
74
|
+
var RELEASE_FLUSH_SIZE = 64;
|
|
75
|
+
var RELEASE_FLUSH_MS = 250;
|
|
76
|
+
var MAX_FLUSH_FAILURES = 5;
|
|
77
|
+
var releaseQueue = /* @__PURE__ */ new Set();
|
|
78
|
+
var flushTimer = null;
|
|
79
|
+
var consecutiveFlushFailures = 0;
|
|
80
|
+
var finalizer = new FinalizationRegistry((id) => {
|
|
81
|
+
if (interned.get(id)?.deref()) return;
|
|
82
|
+
interned.delete(id);
|
|
83
|
+
enqueueRelease(id);
|
|
84
|
+
});
|
|
85
|
+
function intern(id) {
|
|
86
|
+
releaseQueue.delete(id);
|
|
87
|
+
const existing = interned.get(id)?.deref();
|
|
88
|
+
if (existing) return existing;
|
|
89
|
+
const handle = new import_plugin_core.Handle(id);
|
|
90
|
+
handle[Symbol.asyncDispose] = async () => {
|
|
91
|
+
if (interned.get(id)?.deref() === handle) interned.delete(id);
|
|
92
|
+
enqueueRelease(id);
|
|
93
|
+
};
|
|
94
|
+
interned.set(id, new WeakRef(handle));
|
|
95
|
+
finalizer.register(handle, id);
|
|
96
|
+
return handle;
|
|
97
|
+
}
|
|
98
|
+
function enqueueRelease(id) {
|
|
99
|
+
releaseQueue.add(id);
|
|
100
|
+
if (releaseQueue.size >= RELEASE_FLUSH_SIZE) {
|
|
101
|
+
void flushReleaseQueue();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
flushTimer ?? (flushTimer = setTimeout(() => {
|
|
105
|
+
void flushReleaseQueue();
|
|
106
|
+
}, RELEASE_FLUSH_MS));
|
|
107
|
+
}
|
|
108
|
+
var releaseTransport = async (batch) => {
|
|
109
|
+
await getHostApi().call({
|
|
110
|
+
method: "core.handles.release",
|
|
111
|
+
args: [batch]
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
function __setReleaseTransport(transport) {
|
|
115
|
+
releaseTransport = transport ?? (async (batch) => {
|
|
116
|
+
await getHostApi().call({
|
|
117
|
+
method: "core.handles.release",
|
|
118
|
+
args: [batch]
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
async function flushReleaseQueue() {
|
|
123
|
+
if (flushTimer) {
|
|
124
|
+
clearTimeout(flushTimer);
|
|
125
|
+
flushTimer = null;
|
|
126
|
+
}
|
|
127
|
+
if (releaseQueue.size === 0) return;
|
|
128
|
+
const batch = [...releaseQueue];
|
|
129
|
+
releaseQueue.clear();
|
|
130
|
+
try {
|
|
131
|
+
await releaseTransport(batch);
|
|
132
|
+
consecutiveFlushFailures = 0;
|
|
133
|
+
} catch (err) {
|
|
134
|
+
consecutiveFlushFailures += 1;
|
|
135
|
+
if (consecutiveFlushFailures >= MAX_FLUSH_FAILURES) {
|
|
136
|
+
console.warn(
|
|
137
|
+
`[snaptrude] dropping ${batch.length} handle release(s) after ${consecutiveFlushFailures} failed flushes`,
|
|
138
|
+
err
|
|
139
|
+
);
|
|
140
|
+
consecutiveFlushFailures = 0;
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
for (const id of batch) {
|
|
144
|
+
if (!interned.get(id)?.deref()) releaseQueue.add(id);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function rewrapResult(value) {
|
|
149
|
+
if (Array.isArray(value)) return value.map(rewrapResult);
|
|
150
|
+
if (value && typeof value === "object") {
|
|
151
|
+
const record = value;
|
|
152
|
+
const keys = Object.keys(record);
|
|
153
|
+
if (keys.length === 1 && keys[0] === "__h" && typeof record.__h === "string") {
|
|
154
|
+
return intern(record.__h);
|
|
155
|
+
}
|
|
156
|
+
for (const key of keys) record[key] = rewrapResult(record[key]);
|
|
157
|
+
return record;
|
|
158
|
+
}
|
|
159
|
+
return value;
|
|
160
|
+
}
|
|
161
|
+
function unwrapArgs(value, memo = /* @__PURE__ */ new Map()) {
|
|
162
|
+
if (value instanceof import_plugin_core.Handle) return value.id;
|
|
163
|
+
if (value === null || typeof value !== "object") return value;
|
|
164
|
+
const hit = memo.get(value);
|
|
165
|
+
if (hit !== void 0) return hit;
|
|
166
|
+
if (Array.isArray(value)) {
|
|
167
|
+
const out2 = [];
|
|
168
|
+
memo.set(value, out2);
|
|
169
|
+
for (const item of value) out2.push(unwrapArgs(item, memo));
|
|
170
|
+
return out2;
|
|
171
|
+
}
|
|
172
|
+
const proto = Object.getPrototypeOf(value);
|
|
173
|
+
if (proto !== Object.prototype && proto !== null) return value;
|
|
174
|
+
const out = {};
|
|
175
|
+
memo.set(value, out);
|
|
176
|
+
for (const [key, item] of Object.entries(value)) out[key] = unwrapArgs(item, memo);
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// src/host-api.ts
|
|
181
|
+
function createHostApi(endpoint) {
|
|
182
|
+
return Comlink.wrap(
|
|
183
|
+
endpoint ?? globalThis
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
var _instance = null;
|
|
187
|
+
function __setHostApiInstance(instance) {
|
|
188
|
+
_instance = instance ?? null;
|
|
189
|
+
}
|
|
190
|
+
function getHostApi() {
|
|
191
|
+
if (!_instance) {
|
|
192
|
+
_instance = createHostApi();
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
call: async (payload) => {
|
|
196
|
+
if (!_instance) {
|
|
197
|
+
throw new Error("Host API not initialized");
|
|
198
|
+
}
|
|
199
|
+
let result;
|
|
200
|
+
try {
|
|
201
|
+
result = await _instance.call(payload);
|
|
202
|
+
} catch (transportErr) {
|
|
203
|
+
if (import_plugin_core2.PluginError.is(transportErr)) throw transportErr;
|
|
204
|
+
throw rehydrate(
|
|
205
|
+
(0, import_plugin_core2.makeClientEnvelope)(
|
|
206
|
+
"TRANSPORT_LOST",
|
|
207
|
+
transportErr instanceof Error ? transportErr.message : String(transportErr),
|
|
208
|
+
{ methodPath: payload.method }
|
|
209
|
+
)
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
if (result.success) {
|
|
213
|
+
return rewrapResult(result.data);
|
|
214
|
+
}
|
|
215
|
+
throw rehydrate(
|
|
216
|
+
result.errorInfo ?? (0, import_plugin_core2.makeClientEnvelope)("UNKNOWN", result.error ?? "Unknown host error", {
|
|
217
|
+
methodPath: payload.method
|
|
218
|
+
})
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function rehydrate(envelope) {
|
|
224
|
+
const error = (0, import_plugin_core2.fromEnvelope)(envelope);
|
|
225
|
+
Error.captureStackTrace?.(error, rehydrate);
|
|
226
|
+
return error;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// src/rpc-proxy.ts
|
|
230
|
+
function createRpcNamespace(basePath) {
|
|
231
|
+
const build = (path) => new Proxy(NOOP, {
|
|
232
|
+
get(_target, prop) {
|
|
233
|
+
if (typeof prop !== "string" || prop === "then") return void 0;
|
|
234
|
+
return build(`${path}.${prop}`);
|
|
235
|
+
},
|
|
236
|
+
apply(_target, _thisArg, argArray) {
|
|
237
|
+
const payload = {
|
|
238
|
+
method: path,
|
|
239
|
+
// Handle instances anywhere in the tuple become their wire id strings.
|
|
240
|
+
args: argArray.map((arg) => unwrapArgs(arg))
|
|
241
|
+
};
|
|
242
|
+
return getHostApi().call(payload);
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
return build(basePath);
|
|
246
|
+
}
|
|
247
|
+
var NOOP = () => {
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
// src/api/index.ts
|
|
251
|
+
var ClientPluginApi = class _ClientPluginApi extends import_plugin_core3.PluginApi {
|
|
252
|
+
constructor() {
|
|
253
|
+
super();
|
|
254
|
+
this.core = createRpcNamespace("core");
|
|
255
|
+
this.design = createRpcNamespace("design");
|
|
256
|
+
this.entity = createRpcNamespace("entity");
|
|
257
|
+
this.program = createRpcNamespace("program");
|
|
258
|
+
this.presentation = createRpcNamespace("presentation");
|
|
259
|
+
this.analysis = createRpcNamespace("analysis");
|
|
260
|
+
this.workspace = createRpcNamespace("workspace");
|
|
261
|
+
}
|
|
262
|
+
static getInstance() {
|
|
263
|
+
if (!_ClientPluginApi.instance) {
|
|
264
|
+
_ClientPluginApi.instance = new _ClientPluginApi();
|
|
265
|
+
}
|
|
266
|
+
return _ClientPluginApi.instance;
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
// src/plugin-worker.ts
|
|
271
|
+
var Comlink2 = __toESM(require("comlink"), 1);
|
|
272
|
+
var PluginWorker = class {
|
|
273
|
+
constructor() {
|
|
274
|
+
this.hostAPI = Comlink2.wrap(
|
|
275
|
+
self
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
sendToUI(action, payload) {
|
|
279
|
+
;
|
|
280
|
+
this.hostAPI.ui.sendToUI({ action, payload });
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Show a transient notification toast in the Snaptrude editor.
|
|
284
|
+
*
|
|
285
|
+
* @param message - Text to display.
|
|
286
|
+
* @param type - Severity; `"error"`/`"warning"` linger a little longer than
|
|
287
|
+
* `"info"`. Defaults to `"info"`.
|
|
288
|
+
*/
|
|
289
|
+
notify(message, type = "info") {
|
|
290
|
+
;
|
|
291
|
+
this.hostAPI.ui.showNotification(message, type);
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Signal the host that this plugin has finished its work and should be
|
|
295
|
+
* stopped. Use this in headless (UI-less) plugins that run a task and
|
|
296
|
+
* self-terminate.
|
|
297
|
+
*/
|
|
298
|
+
complete() {
|
|
299
|
+
;
|
|
300
|
+
this.hostAPI.lifecycle.complete();
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Subscribe to a host event (e.g. `"model:changed"`, fired debounced on any
|
|
304
|
+
* user- or plugin-initiated model edit). The callback runs in this worker
|
|
305
|
+
* each time the event fires; its argument is a small structured-clone-safe
|
|
306
|
+
* payload (see the event's payload type, e.g. `ModelChangedEvent`).
|
|
307
|
+
*
|
|
308
|
+
* Fire-and-forget: subscribe once (typically in `init()`). Subscriptions live
|
|
309
|
+
* for the plugin's lifetime and are cleared automatically when the plugin is
|
|
310
|
+
* stopped — there is no `unsubscribe` yet.
|
|
311
|
+
*
|
|
312
|
+
* @example
|
|
313
|
+
* ```ts
|
|
314
|
+
* import type { ModelChangedEvent } from "@snaptrude/plugin-client";
|
|
315
|
+
*
|
|
316
|
+
* async init() {
|
|
317
|
+
* this.subscribe("model:changed", (e) => {
|
|
318
|
+
* const { source } = e as ModelChangedEvent;
|
|
319
|
+
* console.log("model changed via", source);
|
|
320
|
+
* });
|
|
321
|
+
* }
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
subscribe(event, callback) {
|
|
325
|
+
;
|
|
326
|
+
this.hostAPI.events.on(
|
|
327
|
+
event,
|
|
328
|
+
Comlink2.proxy(callback)
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
async init() {
|
|
332
|
+
console.log(this.pluginId, "init() called");
|
|
333
|
+
console.log(this.pluginId, "Initialization complete");
|
|
334
|
+
}
|
|
335
|
+
async destroy() {
|
|
336
|
+
console.log(this.pluginId, "destroy() called \u2014 cleaning up");
|
|
337
|
+
}
|
|
338
|
+
async ping() {
|
|
339
|
+
return "pong";
|
|
340
|
+
}
|
|
341
|
+
async onUIMessage(_message) {
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Expose the worker API via Comlink and start listening.
|
|
345
|
+
* Call this once after constructing the plugin instance.
|
|
346
|
+
*
|
|
347
|
+
* The host calls `init(config)` with `{ pluginId }`,
|
|
348
|
+
* which is captured here to set `this.pluginId` before the
|
|
349
|
+
* subclass's `init()` runs.
|
|
350
|
+
*/
|
|
351
|
+
start() {
|
|
352
|
+
Comlink2.expose(
|
|
353
|
+
{
|
|
354
|
+
init: (config) => {
|
|
355
|
+
this.pluginId = config.pluginId;
|
|
356
|
+
return this.init();
|
|
357
|
+
},
|
|
358
|
+
destroy: () => this.destroy(),
|
|
359
|
+
ping: () => this.ping(),
|
|
360
|
+
onUIMessage: (message) => this.onUIMessage(message)
|
|
361
|
+
},
|
|
362
|
+
self
|
|
363
|
+
);
|
|
364
|
+
console.log("Worker loaded, API exposed via Comlink");
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
// src/events.ts
|
|
369
|
+
var PLUGIN_EVENTS = [
|
|
370
|
+
"selection:changed",
|
|
371
|
+
"tool:activated",
|
|
372
|
+
"project:saved",
|
|
373
|
+
"view:changed",
|
|
374
|
+
"model:changed"
|
|
375
|
+
];
|
|
376
|
+
|
|
377
|
+
// src/index.ts
|
|
378
|
+
var import_plugin_core4 = require("@snaptrude/plugin-core");
|
|
379
|
+
var snaptrude = ClientPluginApi.getInstance();
|
|
380
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
381
|
+
0 && (module.exports = {
|
|
382
|
+
CODE_META,
|
|
383
|
+
ClientPluginApi,
|
|
384
|
+
PLUGIN_ERROR_CODES,
|
|
385
|
+
PLUGIN_EVENTS,
|
|
386
|
+
PluginError,
|
|
387
|
+
PluginExecutionError,
|
|
388
|
+
PluginHandleError,
|
|
389
|
+
PluginInternalError,
|
|
390
|
+
PluginLifecycleError,
|
|
391
|
+
PluginNotFoundError,
|
|
392
|
+
PluginPermissionError,
|
|
393
|
+
PluginQuotaError,
|
|
394
|
+
PluginTimeoutError,
|
|
395
|
+
PluginTransportError,
|
|
396
|
+
PluginValidationError,
|
|
397
|
+
PluginWorker,
|
|
398
|
+
__setHostApiInstance,
|
|
399
|
+
__setReleaseTransport,
|
|
400
|
+
createHostApi,
|
|
401
|
+
flushReleaseQueue,
|
|
402
|
+
fromEnvelope,
|
|
403
|
+
getHostApi,
|
|
404
|
+
intern,
|
|
405
|
+
isErrorEnvelope,
|
|
406
|
+
isPluginErrorCode,
|
|
407
|
+
rewrapResult,
|
|
408
|
+
snaptrude,
|
|
409
|
+
unwrapArgs
|
|
410
|
+
});
|
|
411
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/api/index.ts","../src/host-api.ts","../src/handle-runtime.ts","../src/rpc-proxy.ts","../src/plugin-worker.ts","../src/events.ts"],"sourcesContent":["import { ClientPluginApi } from \"./api\"\n\nexport * from \"./api\"\nexport * from \"./host-api\"\nexport * from \"./plugin-worker\"\nexport * from \"./events\"\nexport {\n flushReleaseQueue,\n intern,\n rewrapResult,\n unwrapArgs,\n __setReleaseTransport,\n} from \"./handle-runtime\"\n\n// Error surface — plugins branch on `PluginError.is(e)` + `e.code`.\nexport {\n PluginError,\n PluginValidationError,\n PluginNotFoundError,\n PluginPermissionError,\n PluginHandleError,\n PluginQuotaError,\n PluginTimeoutError,\n PluginTransportError,\n PluginLifecycleError,\n PluginExecutionError,\n PluginInternalError,\n fromEnvelope,\n isErrorEnvelope,\n isPluginErrorCode,\n PLUGIN_ERROR_CODES,\n CODE_META,\n} from \"@snaptrude/plugin-core\"\nexport type {\n ErrorEnvelope,\n PluginErrorCode,\n WirePluginErrorCode,\n PluginErrorCategory,\n} from \"@snaptrude/plugin-core\"\n\n/**\n * The Snaptrude plugin client API.\n *\n * The main entry point for plugins to interact with the Snaptrude platform.\n */\nexport const snaptrude = ClientPluginApi.getInstance()\n","import {\n PluginApi,\n PluginCoreApi,\n PluginDesignApi,\n PluginEntityApi,\n PluginProgramApi,\n PluginPresentationApi,\n PluginAnalysisApi,\n PluginWorkspaceApi,\n} from \"@snaptrude/plugin-core\"\nimport { createRpcNamespace } from \"../rpc-proxy\"\n\nexport class ClientPluginApi extends PluginApi {\n private static instance: ClientPluginApi\n\n /**\n * Every namespace is fully remote under the all-handle model: math/geom now\n * cross to the host (values are opaque handles), so there is no in-worker\n * compute left. All dispatch through a single generic RPC Proxy. Units live\n * under `core.units`, so they ride the `core` proxy.\n */\n public core: PluginCoreApi\n public design: PluginDesignApi\n public entity: PluginEntityApi\n public program: PluginProgramApi\n public presentation: PluginPresentationApi\n public analysis: PluginAnalysisApi\n public workspace: PluginWorkspaceApi\n\n private constructor() {\n super()\n this.core = createRpcNamespace<PluginCoreApi>(\"core\")\n this.design = createRpcNamespace<PluginDesignApi>(\"design\")\n this.entity = createRpcNamespace<PluginEntityApi>(\"entity\")\n this.program = createRpcNamespace<PluginProgramApi>(\"program\")\n this.presentation =\n createRpcNamespace<PluginPresentationApi>(\"presentation\")\n this.analysis = createRpcNamespace<PluginAnalysisApi>(\"analysis\")\n this.workspace = createRpcNamespace<PluginWorkspaceApi>(\"workspace\")\n }\n\n static getInstance(): ClientPluginApi {\n if (!ClientPluginApi.instance) {\n ClientPluginApi.instance = new ClientPluginApi()\n }\n return ClientPluginApi.instance\n }\n}\n","import * as Comlink from \"comlink\"\nimport type {\n PluginApiMethod,\n PluginApiCallPayload,\n PluginApiCallWrappedResult,\n PluginApiCallResult,\n} from \"@snaptrude/plugin-core\"\nimport { PluginError, fromEnvelope, makeClientEnvelope } from \"@snaptrude/plugin-core\"\nimport { rewrapResult } from \"./handle-runtime\"\n\nexport interface HostApi {\n call<M extends PluginApiMethod>(\n payload: PluginApiCallPayload<M>\n ): Promise<PluginApiCallWrappedResult<M>>\n}\n\nexport interface HostApiWrapped {\n call<M extends PluginApiMethod>(\n payload: PluginApiCallPayload<M>\n ): Promise<PluginApiCallResult<M>>\n}\n\nexport function createHostApi(endpoint?: Comlink.Endpoint): HostApi {\n return Comlink.wrap<HostApi>(\n endpoint ?? (globalThis as unknown as Comlink.Endpoint)\n ) as unknown as HostApi\n}\n\nlet _instance: HostApi | null = null\n\n/** TEST SEAM ONLY: replace the Comlink host instance (pass `undefined` to reset). */\nexport function __setHostApiInstance(instance?: HostApi): void {\n _instance = instance ?? null\n}\n\nexport function getHostApi(): HostApiWrapped {\n if (!_instance) {\n _instance = createHostApi()\n }\n return {\n call: async <M extends PluginApiMethod>(payload: PluginApiCallPayload<M>): Promise<PluginApiCallResult<M>> => {\n if (!_instance) {\n throw new Error(\"Host API not initialized\")\n }\n\n let result: PluginApiCallWrappedResult<M>\n try {\n result = await _instance.call(payload)\n } catch (transportErr) {\n // Comlink-level rejection: port closed, worker terminated, clone\n // failure. Never a routed failure — the router always RETURNS its\n // envelope — so normalize to a typed transport error.\n if (PluginError.is(transportErr)) throw transportErr\n throw rehydrate(\n makeClientEnvelope(\n \"TRANSPORT_LOST\",\n transportErr instanceof Error ? transportErr.message : String(transportErr),\n { methodPath: payload.method }\n )\n )\n }\n\n if (result.success) {\n // Re-wrap tagged handles ({__h: id} → interned Handle instances).\n return rewrapResult(result.data) as PluginApiCallResult<M>\n }\n\n // Structured envelope when the host provides one; legacy hosts (string\n // `error` only) degrade to UNKNOWN with the message preserved.\n throw rehydrate(\n result.errorInfo ??\n makeClientEnvelope(\"UNKNOWN\", result.error ?? \"Unknown host error\", {\n methodPath: payload.method,\n })\n )\n }\n }\n}\n\n/**\n * Envelope → typed `PluginError`, with the stack trimmed to the plugin's call\n * site (V8 only; harmless no-op elsewhere) instead of transport internals.\n */\nfunction rehydrate(envelope: Parameters<typeof fromEnvelope>[0]): PluginError {\n const error = fromEnvelope(envelope)\n ;(Error as { captureStackTrace?: (target: object, ctor: Function) => void })\n .captureStackTrace?.(error, rehydrate)\n return error\n}\n","import { Handle } from \"@snaptrude/plugin-core\"\nimport { getHostApi } from \"./host-api\"\n\n/**\n * Worker-side handle lifecycle runtime (P1):\n *\n * - **Interning** — one live `Handle` instance per id, so `===`, `Set`, and\n * `Map` keys keep working exactly as they did when handles were raw strings\n * (the host identity-dedups resource/topology handles, so the same id\n * arrives repeatedly).\n * - **FinalizationRegistry backstop** — when the plugin drops every reference\n * to a handle, its host registry entry is eventually released without any\n * author action. Eventual, not timely: deterministic release\n * (`core.handles.release` / scopes / `await using`) remains the primary tool.\n * - **Batched release queue** — finalizer hits and `Symbol.asyncDispose` calls\n * collapse into one `core.handles.release([...])` RPC per flush.\n */\n\nconst interned = new Map<string, WeakRef<Handle<string>>>()\n\nconst RELEASE_FLUSH_SIZE = 64\nconst RELEASE_FLUSH_MS = 250\nconst MAX_FLUSH_FAILURES = 5\n\nconst releaseQueue = new Set<string>()\nlet flushTimer: ReturnType<typeof setTimeout> | null = null\nlet consecutiveFlushFailures = 0\n\nconst finalizer = new FinalizationRegistry<string>((id) => {\n // A NEW wrapper for the same id may have been interned after the collected\n // one died (deduped topology re-enumeration) — releasing then would free a\n // handle the plugin still holds. Only release when no live wrapper remains.\n if (interned.get(id)?.deref()) return\n interned.delete(id)\n enqueueRelease(id)\n})\n\n/**\n * Return THE `Handle` instance for this id — the existing live wrapper when\n * present, else a fresh one wired for auto-release.\n */\nexport function intern(id: string): Handle<string> {\n // The host just (re-)vended this id, so it is live host-side. Cancel any\n // PENDING auto-release for it — covers the finalizer-already-ran window\n // (old wrapper collected, id queued, same id re-vended before the flush;\n // without this the flush would release a handle the plugin holds live).\n releaseQueue.delete(id)\n\n const existing = interned.get(id)?.deref()\n if (existing) return existing\n\n const handle = new Handle<string>(id)\n // Instance-level override shadows the class's no-op placeholder. Explicit\n // dispose also UN-interns the wrapper: (a) the flush-failure retry filter\n // skips ids with a live interned wrapper, so a still-interned explicit\n // dispose would never be retried; (b) if the host re-vends the id later,\n // a fresh wrapper is minted instead of resurrecting the disposed one.\n ;(handle as { [Symbol.asyncDispose]?: () => Promise<void> })[Symbol.asyncDispose] =\n async () => {\n if (interned.get(id)?.deref() === handle) interned.delete(id)\n enqueueRelease(id)\n }\n interned.set(id, new WeakRef(handle))\n finalizer.register(handle, id)\n return handle\n}\n\nfunction enqueueRelease(id: string): void {\n releaseQueue.add(id)\n if (releaseQueue.size >= RELEASE_FLUSH_SIZE) {\n void flushReleaseQueue()\n return\n }\n flushTimer ??= setTimeout(() => {\n void flushReleaseQueue()\n }, RELEASE_FLUSH_MS)\n}\n\n/** How a release batch reaches the host. Swappable for tests (`__setReleaseTransport`). */\nlet releaseTransport = async (batch: string[]): Promise<void> => {\n await getHostApi().call({\n method: \"core.handles.release\",\n args: [batch],\n } as never)\n}\n\n/** TEST SEAM ONLY: replace the release transport (pass `undefined` to restore). */\nexport function __setReleaseTransport(\n transport?: (batch: string[]) => Promise<void>\n): void {\n releaseTransport =\n transport ??\n (async (batch: string[]) => {\n await getHostApi().call({\n method: \"core.handles.release\",\n args: [batch],\n } as never)\n })\n}\n\n/** Exported for tests and for an eager flush before a plugin self-completes. */\nexport async function flushReleaseQueue(): Promise<void> {\n if (flushTimer) {\n clearTimeout(flushTimer)\n flushTimer = null\n }\n if (releaseQueue.size === 0) return\n const batch = [...releaseQueue]\n releaseQueue.clear()\n try {\n await releaseTransport(batch)\n consecutiveFlushFailures = 0\n } catch (err) {\n // Transient failure (rate limit, timeout): re-queue so the entries are not\n // permanently leaked host-side; the next enqueue/flush retries. Ids the\n // plugin re-acquired in the meantime were already purged by intern() and\n // must not be re-added. If the host is simply gone, the plugin is stopping\n // and registry teardown reclaims everything anyway.\n consecutiveFlushFailures += 1\n if (consecutiveFlushFailures >= MAX_FLUSH_FAILURES) {\n // Persistent failure: retrying forever would just spin. Drop the batch\n // loudly — host teardown reclaims the entries when the plugin stops.\n console.warn(\n `[snaptrude] dropping ${batch.length} handle release(s) after ${consecutiveFlushFailures} failed flushes`,\n err\n )\n consecutiveFlushFailures = 0\n return\n }\n for (const id of batch) {\n if (!interned.get(id)?.deref()) releaseQueue.add(id)\n }\n }\n}\n\n/**\n * Recursively re-wrap a host result: `{ __h: \"<id>\" }` tags (produced by\n * `Handle.toJSON` through the host's JSON-round-trip serialization) become\n * interned `Handle` instances. Arrays and plain records are walked; all other\n * values pass through untouched.\n */\nexport function rewrapResult(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(rewrapResult)\n if (value && typeof value === \"object\") {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record)\n if (keys.length === 1 && keys[0] === \"__h\" && typeof record.__h === \"string\") {\n return intern(record.__h)\n }\n for (const key of keys) record[key] = rewrapResult(record[key])\n return record\n }\n return value\n}\n\n/**\n * Recursively unwrap outgoing args: `Handle` instances become their wire id\n * strings. Uses a memo Map (not a bail-out set) so shared/diamond references\n * get the SAME converted subtree — a bail-out would leak un-unwrapped Handle\n * instances through the second reference. Cycles are handled by memoizing the\n * output object before recursing. Non-plain objects pass through untouched\n * (structured clone imposes plain-data args anyway).\n */\nexport function unwrapArgs(value: unknown, memo = new Map<object, unknown>()): unknown {\n if (value instanceof Handle) return value.id\n if (value === null || typeof value !== \"object\") return value\n\n const hit = memo.get(value)\n if (hit !== undefined) return hit\n\n if (Array.isArray(value)) {\n const out: unknown[] = []\n memo.set(value, out)\n for (const item of value) out.push(unwrapArgs(item, memo))\n return out\n }\n\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return value\n\n const out: Record<string, unknown> = {}\n memo.set(value, out)\n for (const [key, item] of Object.entries(value)) out[key] = unwrapArgs(item, memo)\n return out\n}\n","import type {\n PluginApiCallPayload,\n PluginApiMethod,\n} from \"@snaptrude/plugin-core\"\nimport { getHostApi } from \"./host-api\"\nimport { unwrapArgs } from \"./handle-runtime\"\n\n/**\n * Build a namespace object whose nested property access maps to a\n * dot-separated host RPC method path, and whose every call dispatches that\n * path through the host bridge.\n *\n * The host exposes the entire plugin API behind a single generic `call()`\n * (see the host `bridge.ts`), and the method string is exactly the property\n * path — so one Proxy replaces every hand-written per-method RPC wrapper for\n * every namespace (`core.*`, `design.*`, `entity.*`):\n *\n * The POSITIONAL transport forwards the whole argument tuple; the host router\n * spreads it back into the resolved method (`fn(...args)`):\n *\n * ```ts\n * snaptrude.core.math.vec3.new(1, 2, 3)\n * // → getHostApi().call({ method: \"core.math.vec3.new\", args: [1, 2, 3] })\n * ```\n *\n * Typed at the call site, e.g. `createRpcNamespace<PluginEntityApi>(\"entity\")`.\n * The Proxy is structurally cast to the abstract API type — argument and\n * return types are enforced by that type, while dispatch is dynamic.\n *\n * Every namespace uses this — including `core.math.*` and `core.geom.*`: under\n * the all-handle model there is no in-worker compute; math and geometry are\n * host calls like everything else.\n */\nexport function createRpcNamespace<T extends object>(basePath: string): T {\n const build = (path: string): unknown =>\n new Proxy(NOOP, {\n get(_target, prop) {\n // Symbols and `then` must not resolve to a callable proxy, otherwise\n // the namespace would look thenable and break Promise resolution if it\n // ever reached an `await`.\n if (typeof prop !== \"string\" || prop === \"then\") return undefined\n return build(`${path}.${prop}`)\n },\n apply(_target, _thisArg, argArray: unknown[]) {\n const payload = {\n method: path,\n // Handle instances anywhere in the tuple become their wire id strings.\n args: argArray.map((arg) => unwrapArgs(arg)),\n } as unknown as PluginApiCallPayload<PluginApiMethod>\n return getHostApi().call(payload)\n },\n })\n\n return build(basePath) as T\n}\n\n/** Proxy target must be callable for the `apply` trap; identity is irrelevant. */\nconst NOOP = (): void => {}\n","import * as Comlink from \"comlink\"\nimport type { PluginEventName } from \"./events\"\n\nexport interface UIMessage {\n action: string\n payload: unknown\n}\n\ninterface PluginConfig {\n pluginId: string\n}\n\n/**\n * Base class for Snaptrude plugin workers.\n *\n * Handles Comlink wiring, host communication, and the standard lifecycle\n * methods (`init`, `destroy`, `ping`, `onUIMessage`). Subclass this and\n * override only the methods you need — then call `start()` to expose the\n * worker API.\n *\n * The plugin ID is received automatically from the host during\n * initialization — no need to pass it manually.\n *\n * @example\n * ```ts\n * import { PluginWorker } from \"@snaptrude/plugin-client\";\n *\n * class MyPlugin extends PluginWorker {\n * async onUIMessage(message: UIMessage) {\n * // handle messages from the UI panel\n * }\n * }\n *\n * new MyPlugin().start();\n * ```\n */\nexport abstract class PluginWorker {\n protected pluginId!: string\n private hostAPI: Comlink.Remote<Record<string, unknown>>\n\n constructor() {\n this.hostAPI = Comlink.wrap<Record<string, unknown>>(\n self as unknown as Comlink.Endpoint,\n )\n }\n\n protected sendToUI(action: string, payload: unknown): void {\n ;(this.hostAPI as Record<string, any>).ui.sendToUI({ action, payload })\n }\n\n /**\n * Show a transient notification toast in the Snaptrude editor.\n *\n * @param message - Text to display.\n * @param type - Severity; `\"error\"`/`\"warning\"` linger a little longer than\n * `\"info\"`. Defaults to `\"info\"`.\n */\n protected notify(\n message: string,\n type: \"info\" | \"warning\" | \"error\" = \"info\",\n ): void {\n ;(this.hostAPI as Record<string, any>).ui.showNotification(message, type)\n }\n\n /**\n * Signal the host that this plugin has finished its work and should be\n * stopped. Use this in headless (UI-less) plugins that run a task and\n * self-terminate.\n */\n protected complete(): void {\n ;(this.hostAPI as Record<string, any>).lifecycle.complete()\n }\n\n /**\n * Subscribe to a host event (e.g. `\"model:changed\"`, fired debounced on any\n * user- or plugin-initiated model edit). The callback runs in this worker\n * each time the event fires; its argument is a small structured-clone-safe\n * payload (see the event's payload type, e.g. `ModelChangedEvent`).\n *\n * Fire-and-forget: subscribe once (typically in `init()`). Subscriptions live\n * for the plugin's lifetime and are cleared automatically when the plugin is\n * stopped — there is no `unsubscribe` yet.\n *\n * @example\n * ```ts\n * import type { ModelChangedEvent } from \"@snaptrude/plugin-client\";\n *\n * async init() {\n * this.subscribe(\"model:changed\", (e) => {\n * const { source } = e as ModelChangedEvent;\n * console.log(\"model changed via\", source);\n * });\n * }\n * ```\n */\n protected subscribe(\n event: PluginEventName,\n callback: (payload?: unknown) => void,\n ): void {\n ;(this.hostAPI as Record<string, any>).events.on(\n event,\n Comlink.proxy(callback),\n )\n }\n\n async init(): Promise<void> {\n console.log(this.pluginId, \"init() called\")\n console.log(this.pluginId, \"Initialization complete\")\n }\n\n async destroy(): Promise<void> {\n console.log(this.pluginId, \"destroy() called — cleaning up\")\n }\n\n async ping(): Promise<string> {\n return \"pong\"\n }\n\n async onUIMessage(_message: UIMessage): Promise<void> {\n // Override in subclass to handle UI messages\n }\n\n /**\n * Expose the worker API via Comlink and start listening.\n * Call this once after constructing the plugin instance.\n *\n * The host calls `init(config)` with `{ pluginId }`,\n * which is captured here to set `this.pluginId` before the\n * subclass's `init()` runs.\n */\n start(): void {\n Comlink.expose(\n {\n init: (config: PluginConfig) => {\n this.pluginId = config.pluginId\n return this.init()\n },\n destroy: () => this.destroy(),\n ping: () => this.ping(),\n onUIMessage: (message: UIMessage) => this.onUIMessage(message),\n },\n self as unknown as Comlink.Endpoint,\n )\n console.log(\"Worker loaded, API exposed via Comlink\")\n }\n}\n","/**\n * Snaptrude plugin events.\n *\n * Plugins can react to changes in the host app. Events are delivered through\n * the host event bus — a separate channel from the request/response\n * `snaptrude.*` API — and carry a small structured-clone-safe payload, never\n * live model data.\n *\n * Subscribe from a {@link PluginWorker} subclass with `this.subscribe(...)`.\n *\n * NOTE: events are a subscription surface, not `call()` RPC methods, so they do\n * NOT appear in the discovery manifest (which enumerates callable methods\n * only). This module is the typed, discoverable declaration of the surface.\n */\n\n/** Every event a plugin can subscribe to. */\nexport const PLUGIN_EVENTS = [\n \"selection:changed\",\n \"tool:activated\",\n \"project:saved\",\n \"view:changed\",\n \"model:changed\",\n] as const\n\n/** Union of subscribable event names. */\nexport type PluginEventName = (typeof PLUGIN_EVENTS)[number]\n\n/**\n * Payload for `model:changed` — fired (debounced) whenever the project model is\n * mutated, by a user edit OR a plugin edit. Deliberately minimal: it signals\n * *that* the model changed, never *what* changed. Re-query the API for details.\n */\nexport interface ModelChangedEvent {\n /** Origin of the change. Currently always `\"command\"` (the edit chokepoint). */\n source: string\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,sBASO;;;ACTP,cAAyB;AAOzB,IAAAC,sBAA8D;;;ACP9D,yBAAuB;AAkBvB,IAAM,WAAW,oBAAI,IAAqC;AAE1D,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAE3B,IAAM,eAAe,oBAAI,IAAY;AACrC,IAAI,aAAmD;AACvD,IAAI,2BAA2B;AAE/B,IAAM,YAAY,IAAI,qBAA6B,CAAC,OAAO;AAIzD,MAAI,SAAS,IAAI,EA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1
|
+
import { ClientPluginApi } from "./api";
|
|
2
|
+
export * from "./api";
|
|
3
|
+
export * from "./host-api";
|
|
4
|
+
export * from "./plugin-worker";
|
|
5
|
+
export * from "./events";
|
|
6
|
+
export { flushReleaseQueue, intern, rewrapResult, unwrapArgs, __setReleaseTransport, } from "./handle-runtime";
|
|
7
|
+
export { PluginError, PluginValidationError, PluginNotFoundError, PluginPermissionError, PluginHandleError, PluginQuotaError, PluginTimeoutError, PluginTransportError, PluginLifecycleError, PluginExecutionError, PluginInternalError, fromEnvelope, isErrorEnvelope, isPluginErrorCode, PLUGIN_ERROR_CODES, CODE_META, } from "@snaptrude/plugin-core";
|
|
8
|
+
export type { ErrorEnvelope, PluginErrorCode, WirePluginErrorCode, PluginErrorCategory, } from "@snaptrude/plugin-core";
|
|
9
|
+
/**
|
|
10
|
+
* The Snaptrude plugin client API.
|
|
11
|
+
*
|
|
12
|
+
* The main entry point for plugins to interact with the Snaptrude platform.
|
|
13
|
+
*/
|
|
14
|
+
export declare const snaptrude: ClientPluginApi;
|
|
15
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,OAAO,CAAA;AAEvC,cAAc,OAAO,CAAA;AACrB,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA;AAC/B,cAAc,UAAU,CAAA;AACxB,OAAO,EACL,iBAAiB,EACjB,MAAM,EACN,YAAY,EACZ,UAAU,EACV,qBAAqB,GACtB,MAAM,kBAAkB,CAAA;AAGzB,OAAO,EACL,WAAW,EACX,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,iBAAiB,EACjB,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,YAAY,EACZ,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EAClB,SAAS,GACV,MAAM,wBAAwB,CAAA;AAC/B,YAAY,EACV,aAAa,EACb,eAAe,EACf,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,wBAAwB,CAAA;AAE/B;;;;GAIG;AACH,eAAO,MAAM,SAAS,iBAAgC,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
// src/api/index.ts
|
|
2
|
+
import {
|
|
3
|
+
PluginApi
|
|
4
|
+
} from "@snaptrude/plugin-core";
|
|
5
|
+
|
|
6
|
+
// src/host-api.ts
|
|
7
|
+
import * as Comlink from "comlink";
|
|
8
|
+
import { PluginError, fromEnvelope, makeClientEnvelope } from "@snaptrude/plugin-core";
|
|
9
|
+
|
|
10
|
+
// src/handle-runtime.ts
|
|
11
|
+
import { Handle } from "@snaptrude/plugin-core";
|
|
12
|
+
var interned = /* @__PURE__ */ new Map();
|
|
13
|
+
var RELEASE_FLUSH_SIZE = 64;
|
|
14
|
+
var RELEASE_FLUSH_MS = 250;
|
|
15
|
+
var MAX_FLUSH_FAILURES = 5;
|
|
16
|
+
var releaseQueue = /* @__PURE__ */ new Set();
|
|
17
|
+
var flushTimer = null;
|
|
18
|
+
var consecutiveFlushFailures = 0;
|
|
19
|
+
var finalizer = new FinalizationRegistry((id) => {
|
|
20
|
+
if (interned.get(id)?.deref()) return;
|
|
21
|
+
interned.delete(id);
|
|
22
|
+
enqueueRelease(id);
|
|
23
|
+
});
|
|
24
|
+
function intern(id) {
|
|
25
|
+
releaseQueue.delete(id);
|
|
26
|
+
const existing = interned.get(id)?.deref();
|
|
27
|
+
if (existing) return existing;
|
|
28
|
+
const handle = new Handle(id);
|
|
29
|
+
handle[Symbol.asyncDispose] = async () => {
|
|
30
|
+
if (interned.get(id)?.deref() === handle) interned.delete(id);
|
|
31
|
+
enqueueRelease(id);
|
|
32
|
+
};
|
|
33
|
+
interned.set(id, new WeakRef(handle));
|
|
34
|
+
finalizer.register(handle, id);
|
|
35
|
+
return handle;
|
|
36
|
+
}
|
|
37
|
+
function enqueueRelease(id) {
|
|
38
|
+
releaseQueue.add(id);
|
|
39
|
+
if (releaseQueue.size >= RELEASE_FLUSH_SIZE) {
|
|
40
|
+
void flushReleaseQueue();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
flushTimer ?? (flushTimer = setTimeout(() => {
|
|
44
|
+
void flushReleaseQueue();
|
|
45
|
+
}, RELEASE_FLUSH_MS));
|
|
46
|
+
}
|
|
47
|
+
var releaseTransport = async (batch) => {
|
|
48
|
+
await getHostApi().call({
|
|
49
|
+
method: "core.handles.release",
|
|
50
|
+
args: [batch]
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
function __setReleaseTransport(transport) {
|
|
54
|
+
releaseTransport = transport ?? (async (batch) => {
|
|
55
|
+
await getHostApi().call({
|
|
56
|
+
method: "core.handles.release",
|
|
57
|
+
args: [batch]
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
async function flushReleaseQueue() {
|
|
62
|
+
if (flushTimer) {
|
|
63
|
+
clearTimeout(flushTimer);
|
|
64
|
+
flushTimer = null;
|
|
65
|
+
}
|
|
66
|
+
if (releaseQueue.size === 0) return;
|
|
67
|
+
const batch = [...releaseQueue];
|
|
68
|
+
releaseQueue.clear();
|
|
69
|
+
try {
|
|
70
|
+
await releaseTransport(batch);
|
|
71
|
+
consecutiveFlushFailures = 0;
|
|
72
|
+
} catch (err) {
|
|
73
|
+
consecutiveFlushFailures += 1;
|
|
74
|
+
if (consecutiveFlushFailures >= MAX_FLUSH_FAILURES) {
|
|
75
|
+
console.warn(
|
|
76
|
+
`[snaptrude] dropping ${batch.length} handle release(s) after ${consecutiveFlushFailures} failed flushes`,
|
|
77
|
+
err
|
|
78
|
+
);
|
|
79
|
+
consecutiveFlushFailures = 0;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
for (const id of batch) {
|
|
83
|
+
if (!interned.get(id)?.deref()) releaseQueue.add(id);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function rewrapResult(value) {
|
|
88
|
+
if (Array.isArray(value)) return value.map(rewrapResult);
|
|
89
|
+
if (value && typeof value === "object") {
|
|
90
|
+
const record = value;
|
|
91
|
+
const keys = Object.keys(record);
|
|
92
|
+
if (keys.length === 1 && keys[0] === "__h" && typeof record.__h === "string") {
|
|
93
|
+
return intern(record.__h);
|
|
94
|
+
}
|
|
95
|
+
for (const key of keys) record[key] = rewrapResult(record[key]);
|
|
96
|
+
return record;
|
|
97
|
+
}
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
function unwrapArgs(value, memo = /* @__PURE__ */ new Map()) {
|
|
101
|
+
if (value instanceof Handle) return value.id;
|
|
102
|
+
if (value === null || typeof value !== "object") return value;
|
|
103
|
+
const hit = memo.get(value);
|
|
104
|
+
if (hit !== void 0) return hit;
|
|
105
|
+
if (Array.isArray(value)) {
|
|
106
|
+
const out2 = [];
|
|
107
|
+
memo.set(value, out2);
|
|
108
|
+
for (const item of value) out2.push(unwrapArgs(item, memo));
|
|
109
|
+
return out2;
|
|
110
|
+
}
|
|
111
|
+
const proto = Object.getPrototypeOf(value);
|
|
112
|
+
if (proto !== Object.prototype && proto !== null) return value;
|
|
113
|
+
const out = {};
|
|
114
|
+
memo.set(value, out);
|
|
115
|
+
for (const [key, item] of Object.entries(value)) out[key] = unwrapArgs(item, memo);
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/host-api.ts
|
|
120
|
+
function createHostApi(endpoint) {
|
|
121
|
+
return Comlink.wrap(
|
|
122
|
+
endpoint ?? globalThis
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
var _instance = null;
|
|
126
|
+
function __setHostApiInstance(instance) {
|
|
127
|
+
_instance = instance ?? null;
|
|
128
|
+
}
|
|
129
|
+
function getHostApi() {
|
|
130
|
+
if (!_instance) {
|
|
131
|
+
_instance = createHostApi();
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
call: async (payload) => {
|
|
135
|
+
if (!_instance) {
|
|
136
|
+
throw new Error("Host API not initialized");
|
|
137
|
+
}
|
|
138
|
+
let result;
|
|
139
|
+
try {
|
|
140
|
+
result = await _instance.call(payload);
|
|
141
|
+
} catch (transportErr) {
|
|
142
|
+
if (PluginError.is(transportErr)) throw transportErr;
|
|
143
|
+
throw rehydrate(
|
|
144
|
+
makeClientEnvelope(
|
|
145
|
+
"TRANSPORT_LOST",
|
|
146
|
+
transportErr instanceof Error ? transportErr.message : String(transportErr),
|
|
147
|
+
{ methodPath: payload.method }
|
|
148
|
+
)
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
if (result.success) {
|
|
152
|
+
return rewrapResult(result.data);
|
|
153
|
+
}
|
|
154
|
+
throw rehydrate(
|
|
155
|
+
result.errorInfo ?? makeClientEnvelope("UNKNOWN", result.error ?? "Unknown host error", {
|
|
156
|
+
methodPath: payload.method
|
|
157
|
+
})
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function rehydrate(envelope) {
|
|
163
|
+
const error = fromEnvelope(envelope);
|
|
164
|
+
Error.captureStackTrace?.(error, rehydrate);
|
|
165
|
+
return error;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// src/rpc-proxy.ts
|
|
169
|
+
function createRpcNamespace(basePath) {
|
|
170
|
+
const build = (path) => new Proxy(NOOP, {
|
|
171
|
+
get(_target, prop) {
|
|
172
|
+
if (typeof prop !== "string" || prop === "then") return void 0;
|
|
173
|
+
return build(`${path}.${prop}`);
|
|
174
|
+
},
|
|
175
|
+
apply(_target, _thisArg, argArray) {
|
|
176
|
+
const payload = {
|
|
177
|
+
method: path,
|
|
178
|
+
// Handle instances anywhere in the tuple become their wire id strings.
|
|
179
|
+
args: argArray.map((arg) => unwrapArgs(arg))
|
|
180
|
+
};
|
|
181
|
+
return getHostApi().call(payload);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
return build(basePath);
|
|
185
|
+
}
|
|
186
|
+
var NOOP = () => {
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// src/api/index.ts
|
|
190
|
+
var ClientPluginApi = class _ClientPluginApi extends PluginApi {
|
|
191
|
+
constructor() {
|
|
192
|
+
super();
|
|
193
|
+
this.core = createRpcNamespace("core");
|
|
194
|
+
this.design = createRpcNamespace("design");
|
|
195
|
+
this.entity = createRpcNamespace("entity");
|
|
196
|
+
this.program = createRpcNamespace("program");
|
|
197
|
+
this.presentation = createRpcNamespace("presentation");
|
|
198
|
+
this.analysis = createRpcNamespace("analysis");
|
|
199
|
+
this.workspace = createRpcNamespace("workspace");
|
|
200
|
+
}
|
|
201
|
+
static getInstance() {
|
|
202
|
+
if (!_ClientPluginApi.instance) {
|
|
203
|
+
_ClientPluginApi.instance = new _ClientPluginApi();
|
|
204
|
+
}
|
|
205
|
+
return _ClientPluginApi.instance;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
// src/plugin-worker.ts
|
|
210
|
+
import * as Comlink2 from "comlink";
|
|
211
|
+
var PluginWorker = class {
|
|
212
|
+
constructor() {
|
|
213
|
+
this.hostAPI = Comlink2.wrap(
|
|
214
|
+
self
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
sendToUI(action, payload) {
|
|
218
|
+
;
|
|
219
|
+
this.hostAPI.ui.sendToUI({ action, payload });
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Show a transient notification toast in the Snaptrude editor.
|
|
223
|
+
*
|
|
224
|
+
* @param message - Text to display.
|
|
225
|
+
* @param type - Severity; `"error"`/`"warning"` linger a little longer than
|
|
226
|
+
* `"info"`. Defaults to `"info"`.
|
|
227
|
+
*/
|
|
228
|
+
notify(message, type = "info") {
|
|
229
|
+
;
|
|
230
|
+
this.hostAPI.ui.showNotification(message, type);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Signal the host that this plugin has finished its work and should be
|
|
234
|
+
* stopped. Use this in headless (UI-less) plugins that run a task and
|
|
235
|
+
* self-terminate.
|
|
236
|
+
*/
|
|
237
|
+
complete() {
|
|
238
|
+
;
|
|
239
|
+
this.hostAPI.lifecycle.complete();
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Subscribe to a host event (e.g. `"model:changed"`, fired debounced on any
|
|
243
|
+
* user- or plugin-initiated model edit). The callback runs in this worker
|
|
244
|
+
* each time the event fires; its argument is a small structured-clone-safe
|
|
245
|
+
* payload (see the event's payload type, e.g. `ModelChangedEvent`).
|
|
246
|
+
*
|
|
247
|
+
* Fire-and-forget: subscribe once (typically in `init()`). Subscriptions live
|
|
248
|
+
* for the plugin's lifetime and are cleared automatically when the plugin is
|
|
249
|
+
* stopped — there is no `unsubscribe` yet.
|
|
250
|
+
*
|
|
251
|
+
* @example
|
|
252
|
+
* ```ts
|
|
253
|
+
* import type { ModelChangedEvent } from "@snaptrude/plugin-client";
|
|
254
|
+
*
|
|
255
|
+
* async init() {
|
|
256
|
+
* this.subscribe("model:changed", (e) => {
|
|
257
|
+
* const { source } = e as ModelChangedEvent;
|
|
258
|
+
* console.log("model changed via", source);
|
|
259
|
+
* });
|
|
260
|
+
* }
|
|
261
|
+
* ```
|
|
262
|
+
*/
|
|
263
|
+
subscribe(event, callback) {
|
|
264
|
+
;
|
|
265
|
+
this.hostAPI.events.on(
|
|
266
|
+
event,
|
|
267
|
+
Comlink2.proxy(callback)
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
async init() {
|
|
271
|
+
console.log(this.pluginId, "init() called");
|
|
272
|
+
console.log(this.pluginId, "Initialization complete");
|
|
273
|
+
}
|
|
274
|
+
async destroy() {
|
|
275
|
+
console.log(this.pluginId, "destroy() called \u2014 cleaning up");
|
|
276
|
+
}
|
|
277
|
+
async ping() {
|
|
278
|
+
return "pong";
|
|
279
|
+
}
|
|
280
|
+
async onUIMessage(_message) {
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Expose the worker API via Comlink and start listening.
|
|
284
|
+
* Call this once after constructing the plugin instance.
|
|
285
|
+
*
|
|
286
|
+
* The host calls `init(config)` with `{ pluginId }`,
|
|
287
|
+
* which is captured here to set `this.pluginId` before the
|
|
288
|
+
* subclass's `init()` runs.
|
|
289
|
+
*/
|
|
290
|
+
start() {
|
|
291
|
+
Comlink2.expose(
|
|
292
|
+
{
|
|
293
|
+
init: (config) => {
|
|
294
|
+
this.pluginId = config.pluginId;
|
|
295
|
+
return this.init();
|
|
296
|
+
},
|
|
297
|
+
destroy: () => this.destroy(),
|
|
298
|
+
ping: () => this.ping(),
|
|
299
|
+
onUIMessage: (message) => this.onUIMessage(message)
|
|
300
|
+
},
|
|
301
|
+
self
|
|
302
|
+
);
|
|
303
|
+
console.log("Worker loaded, API exposed via Comlink");
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
// src/events.ts
|
|
308
|
+
var PLUGIN_EVENTS = [
|
|
309
|
+
"selection:changed",
|
|
310
|
+
"tool:activated",
|
|
311
|
+
"project:saved",
|
|
312
|
+
"view:changed",
|
|
313
|
+
"model:changed"
|
|
314
|
+
];
|
|
315
|
+
|
|
316
|
+
// src/index.ts
|
|
317
|
+
import {
|
|
318
|
+
PluginError as PluginError2,
|
|
319
|
+
PluginValidationError,
|
|
320
|
+
PluginNotFoundError,
|
|
321
|
+
PluginPermissionError,
|
|
322
|
+
PluginHandleError,
|
|
323
|
+
PluginQuotaError,
|
|
324
|
+
PluginTimeoutError,
|
|
325
|
+
PluginTransportError,
|
|
326
|
+
PluginLifecycleError,
|
|
327
|
+
PluginExecutionError,
|
|
328
|
+
PluginInternalError,
|
|
329
|
+
fromEnvelope as fromEnvelope2,
|
|
330
|
+
isErrorEnvelope,
|
|
331
|
+
isPluginErrorCode,
|
|
332
|
+
PLUGIN_ERROR_CODES,
|
|
333
|
+
CODE_META
|
|
334
|
+
} from "@snaptrude/plugin-core";
|
|
335
|
+
var snaptrude = ClientPluginApi.getInstance();
|
|
336
|
+
export {
|
|
337
|
+
CODE_META,
|
|
338
|
+
ClientPluginApi,
|
|
339
|
+
PLUGIN_ERROR_CODES,
|
|
340
|
+
PLUGIN_EVENTS,
|
|
341
|
+
PluginError2 as PluginError,
|
|
342
|
+
PluginExecutionError,
|
|
343
|
+
PluginHandleError,
|
|
344
|
+
PluginInternalError,
|
|
345
|
+
PluginLifecycleError,
|
|
346
|
+
PluginNotFoundError,
|
|
347
|
+
PluginPermissionError,
|
|
348
|
+
PluginQuotaError,
|
|
349
|
+
PluginTimeoutError,
|
|
350
|
+
PluginTransportError,
|
|
351
|
+
PluginValidationError,
|
|
352
|
+
PluginWorker,
|
|
353
|
+
__setHostApiInstance,
|
|
354
|
+
__setReleaseTransport,
|
|
355
|
+
createHostApi,
|
|
356
|
+
flushReleaseQueue,
|
|
357
|
+
fromEnvelope2 as fromEnvelope,
|
|
358
|
+
getHostApi,
|
|
359
|
+
intern,
|
|
360
|
+
isErrorEnvelope,
|
|
361
|
+
isPluginErrorCode,
|
|
362
|
+
rewrapResult,
|
|
363
|
+
snaptrude,
|
|
364
|
+
unwrapArgs
|
|
365
|
+
};
|
|
366
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/api/index.ts","../src/host-api.ts","../src/handle-runtime.ts","../src/rpc-proxy.ts","../src/plugin-worker.ts","../src/events.ts","../src/index.ts"],"sourcesContent":["import {\n PluginApi,\n PluginCoreApi,\n PluginDesignApi,\n PluginEntityApi,\n PluginProgramApi,\n PluginPresentationApi,\n PluginAnalysisApi,\n PluginWorkspaceApi,\n} from \"@snaptrude/plugin-core\"\nimport { createRpcNamespace } from \"../rpc-proxy\"\n\nexport class ClientPluginApi extends PluginApi {\n private static instance: ClientPluginApi\n\n /**\n * Every namespace is fully remote under the all-handle model: math/geom now\n * cross to the host (values are opaque handles), so there is no in-worker\n * compute left. All dispatch through a single generic RPC Proxy. Units live\n * under `core.units`, so they ride the `core` proxy.\n */\n public core: PluginCoreApi\n public design: PluginDesignApi\n public entity: PluginEntityApi\n public program: PluginProgramApi\n public presentation: PluginPresentationApi\n public analysis: PluginAnalysisApi\n public workspace: PluginWorkspaceApi\n\n private constructor() {\n super()\n this.core = createRpcNamespace<PluginCoreApi>(\"core\")\n this.design = createRpcNamespace<PluginDesignApi>(\"design\")\n this.entity = createRpcNamespace<PluginEntityApi>(\"entity\")\n this.program = createRpcNamespace<PluginProgramApi>(\"program\")\n this.presentation =\n createRpcNamespace<PluginPresentationApi>(\"presentation\")\n this.analysis = createRpcNamespace<PluginAnalysisApi>(\"analysis\")\n this.workspace = createRpcNamespace<PluginWorkspaceApi>(\"workspace\")\n }\n\n static getInstance(): ClientPluginApi {\n if (!ClientPluginApi.instance) {\n ClientPluginApi.instance = new ClientPluginApi()\n }\n return ClientPluginApi.instance\n }\n}\n","import * as Comlink from \"comlink\"\nimport type {\n PluginApiMethod,\n PluginApiCallPayload,\n PluginApiCallWrappedResult,\n PluginApiCallResult,\n} from \"@snaptrude/plugin-core\"\nimport { PluginError, fromEnvelope, makeClientEnvelope } from \"@snaptrude/plugin-core\"\nimport { rewrapResult } from \"./handle-runtime\"\n\nexport interface HostApi {\n call<M extends PluginApiMethod>(\n payload: PluginApiCallPayload<M>\n ): Promise<PluginApiCallWrappedResult<M>>\n}\n\nexport interface HostApiWrapped {\n call<M extends PluginApiMethod>(\n payload: PluginApiCallPayload<M>\n ): Promise<PluginApiCallResult<M>>\n}\n\nexport function createHostApi(endpoint?: Comlink.Endpoint): HostApi {\n return Comlink.wrap<HostApi>(\n endpoint ?? (globalThis as unknown as Comlink.Endpoint)\n ) as unknown as HostApi\n}\n\nlet _instance: HostApi | null = null\n\n/** TEST SEAM ONLY: replace the Comlink host instance (pass `undefined` to reset). */\nexport function __setHostApiInstance(instance?: HostApi): void {\n _instance = instance ?? null\n}\n\nexport function getHostApi(): HostApiWrapped {\n if (!_instance) {\n _instance = createHostApi()\n }\n return {\n call: async <M extends PluginApiMethod>(payload: PluginApiCallPayload<M>): Promise<PluginApiCallResult<M>> => {\n if (!_instance) {\n throw new Error(\"Host API not initialized\")\n }\n\n let result: PluginApiCallWrappedResult<M>\n try {\n result = await _instance.call(payload)\n } catch (transportErr) {\n // Comlink-level rejection: port closed, worker terminated, clone\n // failure. Never a routed failure — the router always RETURNS its\n // envelope — so normalize to a typed transport error.\n if (PluginError.is(transportErr)) throw transportErr\n throw rehydrate(\n makeClientEnvelope(\n \"TRANSPORT_LOST\",\n transportErr instanceof Error ? transportErr.message : String(transportErr),\n { methodPath: payload.method }\n )\n )\n }\n\n if (result.success) {\n // Re-wrap tagged handles ({__h: id} → interned Handle instances).\n return rewrapResult(result.data) as PluginApiCallResult<M>\n }\n\n // Structured envelope when the host provides one; legacy hosts (string\n // `error` only) degrade to UNKNOWN with the message preserved.\n throw rehydrate(\n result.errorInfo ??\n makeClientEnvelope(\"UNKNOWN\", result.error ?? \"Unknown host error\", {\n methodPath: payload.method,\n })\n )\n }\n }\n}\n\n/**\n * Envelope → typed `PluginError`, with the stack trimmed to the plugin's call\n * site (V8 only; harmless no-op elsewhere) instead of transport internals.\n */\nfunction rehydrate(envelope: Parameters<typeof fromEnvelope>[0]): PluginError {\n const error = fromEnvelope(envelope)\n ;(Error as { captureStackTrace?: (target: object, ctor: Function) => void })\n .captureStackTrace?.(error, rehydrate)\n return error\n}\n","import { Handle } from \"@snaptrude/plugin-core\"\nimport { getHostApi } from \"./host-api\"\n\n/**\n * Worker-side handle lifecycle runtime (P1):\n *\n * - **Interning** — one live `Handle` instance per id, so `===`, `Set`, and\n * `Map` keys keep working exactly as they did when handles were raw strings\n * (the host identity-dedups resource/topology handles, so the same id\n * arrives repeatedly).\n * - **FinalizationRegistry backstop** — when the plugin drops every reference\n * to a handle, its host registry entry is eventually released without any\n * author action. Eventual, not timely: deterministic release\n * (`core.handles.release` / scopes / `await using`) remains the primary tool.\n * - **Batched release queue** — finalizer hits and `Symbol.asyncDispose` calls\n * collapse into one `core.handles.release([...])` RPC per flush.\n */\n\nconst interned = new Map<string, WeakRef<Handle<string>>>()\n\nconst RELEASE_FLUSH_SIZE = 64\nconst RELEASE_FLUSH_MS = 250\nconst MAX_FLUSH_FAILURES = 5\n\nconst releaseQueue = new Set<string>()\nlet flushTimer: ReturnType<typeof setTimeout> | null = null\nlet consecutiveFlushFailures = 0\n\nconst finalizer = new FinalizationRegistry<string>((id) => {\n // A NEW wrapper for the same id may have been interned after the collected\n // one died (deduped topology re-enumeration) — releasing then would free a\n // handle the plugin still holds. Only release when no live wrapper remains.\n if (interned.get(id)?.deref()) return\n interned.delete(id)\n enqueueRelease(id)\n})\n\n/**\n * Return THE `Handle` instance for this id — the existing live wrapper when\n * present, else a fresh one wired for auto-release.\n */\nexport function intern(id: string): Handle<string> {\n // The host just (re-)vended this id, so it is live host-side. Cancel any\n // PENDING auto-release for it — covers the finalizer-already-ran window\n // (old wrapper collected, id queued, same id re-vended before the flush;\n // without this the flush would release a handle the plugin holds live).\n releaseQueue.delete(id)\n\n const existing = interned.get(id)?.deref()\n if (existing) return existing\n\n const handle = new Handle<string>(id)\n // Instance-level override shadows the class's no-op placeholder. Explicit\n // dispose also UN-interns the wrapper: (a) the flush-failure retry filter\n // skips ids with a live interned wrapper, so a still-interned explicit\n // dispose would never be retried; (b) if the host re-vends the id later,\n // a fresh wrapper is minted instead of resurrecting the disposed one.\n ;(handle as { [Symbol.asyncDispose]?: () => Promise<void> })[Symbol.asyncDispose] =\n async () => {\n if (interned.get(id)?.deref() === handle) interned.delete(id)\n enqueueRelease(id)\n }\n interned.set(id, new WeakRef(handle))\n finalizer.register(handle, id)\n return handle\n}\n\nfunction enqueueRelease(id: string): void {\n releaseQueue.add(id)\n if (releaseQueue.size >= RELEASE_FLUSH_SIZE) {\n void flushReleaseQueue()\n return\n }\n flushTimer ??= setTimeout(() => {\n void flushReleaseQueue()\n }, RELEASE_FLUSH_MS)\n}\n\n/** How a release batch reaches the host. Swappable for tests (`__setReleaseTransport`). */\nlet releaseTransport = async (batch: string[]): Promise<void> => {\n await getHostApi().call({\n method: \"core.handles.release\",\n args: [batch],\n } as never)\n}\n\n/** TEST SEAM ONLY: replace the release transport (pass `undefined` to restore). */\nexport function __setReleaseTransport(\n transport?: (batch: string[]) => Promise<void>\n): void {\n releaseTransport =\n transport ??\n (async (batch: string[]) => {\n await getHostApi().call({\n method: \"core.handles.release\",\n args: [batch],\n } as never)\n })\n}\n\n/** Exported for tests and for an eager flush before a plugin self-completes. */\nexport async function flushReleaseQueue(): Promise<void> {\n if (flushTimer) {\n clearTimeout(flushTimer)\n flushTimer = null\n }\n if (releaseQueue.size === 0) return\n const batch = [...releaseQueue]\n releaseQueue.clear()\n try {\n await releaseTransport(batch)\n consecutiveFlushFailures = 0\n } catch (err) {\n // Transient failure (rate limit, timeout): re-queue so the entries are not\n // permanently leaked host-side; the next enqueue/flush retries. Ids the\n // plugin re-acquired in the meantime were already purged by intern() and\n // must not be re-added. If the host is simply gone, the plugin is stopping\n // and registry teardown reclaims everything anyway.\n consecutiveFlushFailures += 1\n if (consecutiveFlushFailures >= MAX_FLUSH_FAILURES) {\n // Persistent failure: retrying forever would just spin. Drop the batch\n // loudly — host teardown reclaims the entries when the plugin stops.\n console.warn(\n `[snaptrude] dropping ${batch.length} handle release(s) after ${consecutiveFlushFailures} failed flushes`,\n err\n )\n consecutiveFlushFailures = 0\n return\n }\n for (const id of batch) {\n if (!interned.get(id)?.deref()) releaseQueue.add(id)\n }\n }\n}\n\n/**\n * Recursively re-wrap a host result: `{ __h: \"<id>\" }` tags (produced by\n * `Handle.toJSON` through the host's JSON-round-trip serialization) become\n * interned `Handle` instances. Arrays and plain records are walked; all other\n * values pass through untouched.\n */\nexport function rewrapResult(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(rewrapResult)\n if (value && typeof value === \"object\") {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record)\n if (keys.length === 1 && keys[0] === \"__h\" && typeof record.__h === \"string\") {\n return intern(record.__h)\n }\n for (const key of keys) record[key] = rewrapResult(record[key])\n return record\n }\n return value\n}\n\n/**\n * Recursively unwrap outgoing args: `Handle` instances become their wire id\n * strings. Uses a memo Map (not a bail-out set) so shared/diamond references\n * get the SAME converted subtree — a bail-out would leak un-unwrapped Handle\n * instances through the second reference. Cycles are handled by memoizing the\n * output object before recursing. Non-plain objects pass through untouched\n * (structured clone imposes plain-data args anyway).\n */\nexport function unwrapArgs(value: unknown, memo = new Map<object, unknown>()): unknown {\n if (value instanceof Handle) return value.id\n if (value === null || typeof value !== \"object\") return value\n\n const hit = memo.get(value)\n if (hit !== undefined) return hit\n\n if (Array.isArray(value)) {\n const out: unknown[] = []\n memo.set(value, out)\n for (const item of value) out.push(unwrapArgs(item, memo))\n return out\n }\n\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return value\n\n const out: Record<string, unknown> = {}\n memo.set(value, out)\n for (const [key, item] of Object.entries(value)) out[key] = unwrapArgs(item, memo)\n return out\n}\n","import type {\n PluginApiCallPayload,\n PluginApiMethod,\n} from \"@snaptrude/plugin-core\"\nimport { getHostApi } from \"./host-api\"\nimport { unwrapArgs } from \"./handle-runtime\"\n\n/**\n * Build a namespace object whose nested property access maps to a\n * dot-separated host RPC method path, and whose every call dispatches that\n * path through the host bridge.\n *\n * The host exposes the entire plugin API behind a single generic `call()`\n * (see the host `bridge.ts`), and the method string is exactly the property\n * path — so one Proxy replaces every hand-written per-method RPC wrapper for\n * every namespace (`core.*`, `design.*`, `entity.*`):\n *\n * The POSITIONAL transport forwards the whole argument tuple; the host router\n * spreads it back into the resolved method (`fn(...args)`):\n *\n * ```ts\n * snaptrude.core.math.vec3.new(1, 2, 3)\n * // → getHostApi().call({ method: \"core.math.vec3.new\", args: [1, 2, 3] })\n * ```\n *\n * Typed at the call site, e.g. `createRpcNamespace<PluginEntityApi>(\"entity\")`.\n * The Proxy is structurally cast to the abstract API type — argument and\n * return types are enforced by that type, while dispatch is dynamic.\n *\n * Every namespace uses this — including `core.math.*` and `core.geom.*`: under\n * the all-handle model there is no in-worker compute; math and geometry are\n * host calls like everything else.\n */\nexport function createRpcNamespace<T extends object>(basePath: string): T {\n const build = (path: string): unknown =>\n new Proxy(NOOP, {\n get(_target, prop) {\n // Symbols and `then` must not resolve to a callable proxy, otherwise\n // the namespace would look thenable and break Promise resolution if it\n // ever reached an `await`.\n if (typeof prop !== \"string\" || prop === \"then\") return undefined\n return build(`${path}.${prop}`)\n },\n apply(_target, _thisArg, argArray: unknown[]) {\n const payload = {\n method: path,\n // Handle instances anywhere in the tuple become their wire id strings.\n args: argArray.map((arg) => unwrapArgs(arg)),\n } as unknown as PluginApiCallPayload<PluginApiMethod>\n return getHostApi().call(payload)\n },\n })\n\n return build(basePath) as T\n}\n\n/** Proxy target must be callable for the `apply` trap; identity is irrelevant. */\nconst NOOP = (): void => {}\n","import * as Comlink from \"comlink\"\nimport type { PluginEventName } from \"./events\"\n\nexport interface UIMessage {\n action: string\n payload: unknown\n}\n\ninterface PluginConfig {\n pluginId: string\n}\n\n/**\n * Base class for Snaptrude plugin workers.\n *\n * Handles Comlink wiring, host communication, and the standard lifecycle\n * methods (`init`, `destroy`, `ping`, `onUIMessage`). Subclass this and\n * override only the methods you need — then call `start()` to expose the\n * worker API.\n *\n * The plugin ID is received automatically from the host during\n * initialization — no need to pass it manually.\n *\n * @example\n * ```ts\n * import { PluginWorker } from \"@snaptrude/plugin-client\";\n *\n * class MyPlugin extends PluginWorker {\n * async onUIMessage(message: UIMessage) {\n * // handle messages from the UI panel\n * }\n * }\n *\n * new MyPlugin().start();\n * ```\n */\nexport abstract class PluginWorker {\n protected pluginId!: string\n private hostAPI: Comlink.Remote<Record<string, unknown>>\n\n constructor() {\n this.hostAPI = Comlink.wrap<Record<string, unknown>>(\n self as unknown as Comlink.Endpoint,\n )\n }\n\n protected sendToUI(action: string, payload: unknown): void {\n ;(this.hostAPI as Record<string, any>).ui.sendToUI({ action, payload })\n }\n\n /**\n * Show a transient notification toast in the Snaptrude editor.\n *\n * @param message - Text to display.\n * @param type - Severity; `\"error\"`/`\"warning\"` linger a little longer than\n * `\"info\"`. Defaults to `\"info\"`.\n */\n protected notify(\n message: string,\n type: \"info\" | \"warning\" | \"error\" = \"info\",\n ): void {\n ;(this.hostAPI as Record<string, any>).ui.showNotification(message, type)\n }\n\n /**\n * Signal the host that this plugin has finished its work and should be\n * stopped. Use this in headless (UI-less) plugins that run a task and\n * self-terminate.\n */\n protected complete(): void {\n ;(this.hostAPI as Record<string, any>).lifecycle.complete()\n }\n\n /**\n * Subscribe to a host event (e.g. `\"model:changed\"`, fired debounced on any\n * user- or plugin-initiated model edit). The callback runs in this worker\n * each time the event fires; its argument is a small structured-clone-safe\n * payload (see the event's payload type, e.g. `ModelChangedEvent`).\n *\n * Fire-and-forget: subscribe once (typically in `init()`). Subscriptions live\n * for the plugin's lifetime and are cleared automatically when the plugin is\n * stopped — there is no `unsubscribe` yet.\n *\n * @example\n * ```ts\n * import type { ModelChangedEvent } from \"@snaptrude/plugin-client\";\n *\n * async init() {\n * this.subscribe(\"model:changed\", (e) => {\n * const { source } = e as ModelChangedEvent;\n * console.log(\"model changed via\", source);\n * });\n * }\n * ```\n */\n protected subscribe(\n event: PluginEventName,\n callback: (payload?: unknown) => void,\n ): void {\n ;(this.hostAPI as Record<string, any>).events.on(\n event,\n Comlink.proxy(callback),\n )\n }\n\n async init(): Promise<void> {\n console.log(this.pluginId, \"init() called\")\n console.log(this.pluginId, \"Initialization complete\")\n }\n\n async destroy(): Promise<void> {\n console.log(this.pluginId, \"destroy() called — cleaning up\")\n }\n\n async ping(): Promise<string> {\n return \"pong\"\n }\n\n async onUIMessage(_message: UIMessage): Promise<void> {\n // Override in subclass to handle UI messages\n }\n\n /**\n * Expose the worker API via Comlink and start listening.\n * Call this once after constructing the plugin instance.\n *\n * The host calls `init(config)` with `{ pluginId }`,\n * which is captured here to set `this.pluginId` before the\n * subclass's `init()` runs.\n */\n start(): void {\n Comlink.expose(\n {\n init: (config: PluginConfig) => {\n this.pluginId = config.pluginId\n return this.init()\n },\n destroy: () => this.destroy(),\n ping: () => this.ping(),\n onUIMessage: (message: UIMessage) => this.onUIMessage(message),\n },\n self as unknown as Comlink.Endpoint,\n )\n console.log(\"Worker loaded, API exposed via Comlink\")\n }\n}\n","/**\n * Snaptrude plugin events.\n *\n * Plugins can react to changes in the host app. Events are delivered through\n * the host event bus — a separate channel from the request/response\n * `snaptrude.*` API — and carry a small structured-clone-safe payload, never\n * live model data.\n *\n * Subscribe from a {@link PluginWorker} subclass with `this.subscribe(...)`.\n *\n * NOTE: events are a subscription surface, not `call()` RPC methods, so they do\n * NOT appear in the discovery manifest (which enumerates callable methods\n * only). This module is the typed, discoverable declaration of the surface.\n */\n\n/** Every event a plugin can subscribe to. */\nexport const PLUGIN_EVENTS = [\n \"selection:changed\",\n \"tool:activated\",\n \"project:saved\",\n \"view:changed\",\n \"model:changed\",\n] as const\n\n/** Union of subscribable event names. */\nexport type PluginEventName = (typeof PLUGIN_EVENTS)[number]\n\n/**\n * Payload for `model:changed` — fired (debounced) whenever the project model is\n * mutated, by a user edit OR a plugin edit. Deliberately minimal: it signals\n * *that* the model changed, never *what* changed. Re-query the API for details.\n */\nexport interface ModelChangedEvent {\n /** Origin of the change. Currently always `\"command\"` (the edit chokepoint). */\n source: string\n}\n","import { ClientPluginApi } from \"./api\"\n\nexport * from \"./api\"\nexport * from \"./host-api\"\nexport * from \"./plugin-worker\"\nexport * from \"./events\"\nexport {\n flushReleaseQueue,\n intern,\n rewrapResult,\n unwrapArgs,\n __setReleaseTransport,\n} from \"./handle-runtime\"\n\n// Error surface — plugins branch on `PluginError.is(e)` + `e.code`.\nexport {\n PluginError,\n PluginValidationError,\n PluginNotFoundError,\n PluginPermissionError,\n PluginHandleError,\n PluginQuotaError,\n PluginTimeoutError,\n PluginTransportError,\n PluginLifecycleError,\n PluginExecutionError,\n PluginInternalError,\n fromEnvelope,\n isErrorEnvelope,\n isPluginErrorCode,\n PLUGIN_ERROR_CODES,\n CODE_META,\n} from \"@snaptrude/plugin-core\"\nexport type {\n ErrorEnvelope,\n PluginErrorCode,\n WirePluginErrorCode,\n PluginErrorCategory,\n} from \"@snaptrude/plugin-core\"\n\n/**\n * The Snaptrude plugin client API.\n *\n * The main entry point for plugins to interact with the Snaptrude platform.\n */\nexport const snaptrude = ClientPluginApi.getInstance()\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAQK;;;ACTP,YAAY,aAAa;AAOzB,SAAS,aAAa,cAAc,0BAA0B;;;ACP9D,SAAS,cAAc;AAkBvB,IAAM,WAAW,oBAAI,IAAqC;AAE1D,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAE3B,IAAM,eAAe,oBAAI,IAAY;AACrC,IAAI,aAAmD;AACvD,IAAI,2BAA2B;AAE/B,IAAM,YAAY,IAAI,qBAA6B,CAAC,OAAO;AAIzD,MAAI,SAAS,IAAI,EAAE,GAAG,MAAM,EAAG;AAC/B,WAAS,OAAO,EAAE;AAClB,iBAAe,EAAE;AACnB,CAAC;AAMM,SAAS,OAAO,IAA4B;AAKjD,eAAa,OAAO,EAAE;AAEtB,QAAM,WAAW,SAAS,IAAI,EAAE,GAAG,MAAM;AACzC,MAAI,SAAU,QAAO;AAErB,QAAM,SAAS,IAAI,OAAe,EAAE;AAMnC,EAAC,OAA2D,OAAO,YAAY,IAC9E,YAAY;AACV,QAAI,SAAS,IAAI,EAAE,GAAG,MAAM,MAAM,OAAQ,UAAS,OAAO,EAAE;AAC5D,mBAAe,EAAE;AAAA,EACnB;AACF,WAAS,IAAI,IAAI,IAAI,QAAQ,MAAM,CAAC;AACpC,YAAU,SAAS,QAAQ,EAAE;AAC7B,SAAO;AACT;AAEA,SAAS,eAAe,IAAkB;AACxC,eAAa,IAAI,EAAE;AACnB,MAAI,aAAa,QAAQ,oBAAoB;AAC3C,S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Y,UAAoC;AAAA,EAEtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,QAAc;AACZ,IAAQ;AAAA,MACN;AAAA,QACE,MAAM,CAAC,WAAyB;AAC9B,eAAK,WAAW,OAAO;AACvB,iBAAO,KAAK,KAAK;AAAA,QACnB;AAAA,QACA,SAAS,MAAM,KAAK,QAAQ;AAAA,QAC5B,MAAM,MAAM,KAAK,KAAK;AAAA,QACtB,aAAa,CAAC,YAAuB,KAAK,YAAY,OAAO;AAAA,MAC/D;AAAA,MACA;AAAA,IACF;AACA,YAAQ,IAAI,wCAAwC;AAAA,EACtD;AACF;;;ACjIO,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACPA;AAAA,EACE,eAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAaA,IAAM,YAAY,gBAAgB,YAAY;","names":["out","Comlink","PluginError","fromEnvelope"]}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { PluginEventName } from "./events";
|
|
2
|
+
export interface UIMessage {
|
|
3
|
+
action: string;
|
|
4
|
+
payload: unknown;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Base class for Snaptrude plugin workers.
|
|
8
|
+
*
|
|
9
|
+
* Handles Comlink wiring, host communication, and the standard lifecycle
|
|
10
|
+
* methods (`init`, `destroy`, `ping`, `onUIMessage`). Subclass this and
|
|
11
|
+
* override only the methods you need — then call `start()` to expose the
|
|
12
|
+
* worker API.
|
|
13
|
+
*
|
|
14
|
+
* The plugin ID is received automatically from the host during
|
|
15
|
+
* initialization — no need to pass it manually.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { PluginWorker } from "@snaptrude/plugin-client";
|
|
20
|
+
*
|
|
21
|
+
* class MyPlugin extends PluginWorker {
|
|
22
|
+
* async onUIMessage(message: UIMessage) {
|
|
23
|
+
* // handle messages from the UI panel
|
|
24
|
+
* }
|
|
25
|
+
* }
|
|
26
|
+
*
|
|
27
|
+
* new MyPlugin().start();
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export declare abstract class PluginWorker {
|
|
31
|
+
protected pluginId: string;
|
|
32
|
+
private hostAPI;
|
|
33
|
+
constructor();
|
|
34
|
+
protected sendToUI(action: string, payload: unknown): void;
|
|
35
|
+
/**
|
|
36
|
+
* Show a transient notification toast in the Snaptrude editor.
|
|
37
|
+
*
|
|
38
|
+
* @param message - Text to display.
|
|
39
|
+
* @param type - Severity; `"error"`/`"warning"` linger a little longer than
|
|
40
|
+
* `"info"`. Defaults to `"info"`.
|
|
41
|
+
*/
|
|
42
|
+
protected notify(message: string, type?: "info" | "warning" | "error"): void;
|
|
43
|
+
/**
|
|
44
|
+
* Signal the host that this plugin has finished its work and should be
|
|
45
|
+
* stopped. Use this in headless (UI-less) plugins that run a task and
|
|
46
|
+
* self-terminate.
|
|
47
|
+
*/
|
|
48
|
+
protected complete(): void;
|
|
49
|
+
/**
|
|
50
|
+
* Subscribe to a host event (e.g. `"model:changed"`, fired debounced on any
|
|
51
|
+
* user- or plugin-initiated model edit). The callback runs in this worker
|
|
52
|
+
* each time the event fires; its argument is a small structured-clone-safe
|
|
53
|
+
* payload (see the event's payload type, e.g. `ModelChangedEvent`).
|
|
54
|
+
*
|
|
55
|
+
* Fire-and-forget: subscribe once (typically in `init()`). Subscriptions live
|
|
56
|
+
* for the plugin's lifetime and are cleared automatically when the plugin is
|
|
57
|
+
* stopped — there is no `unsubscribe` yet.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* import type { ModelChangedEvent } from "@snaptrude/plugin-client";
|
|
62
|
+
*
|
|
63
|
+
* async init() {
|
|
64
|
+
* this.subscribe("model:changed", (e) => {
|
|
65
|
+
* const { source } = e as ModelChangedEvent;
|
|
66
|
+
* console.log("model changed via", source);
|
|
67
|
+
* });
|
|
68
|
+
* }
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
protected subscribe(event: PluginEventName, callback: (payload?: unknown) => void): void;
|
|
72
|
+
init(): Promise<void>;
|
|
73
|
+
destroy(): Promise<void>;
|
|
74
|
+
ping(): Promise<string>;
|
|
75
|
+
onUIMessage(_message: UIMessage): Promise<void>;
|
|
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
|
+
}
|
|
86
|
+
//# sourceMappingURL=plugin-worker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-worker.d.ts","sourceRoot":"","sources":["../src/plugin-worker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAE/C,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,OAAO,CAAA;CACjB;AAMD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,8BAAsB,YAAY;IAChC,SAAS,CAAC,QAAQ,EAAG,MAAM,CAAA;IAC3B,OAAO,CAAC,OAAO,CAAyC;;IAQxD,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAI1D;;;;;;OAMG;IACH,SAAS,CAAC,MAAM,CACd,OAAO,EAAE,MAAM,EACf,IAAI,GAAE,MAAM,GAAG,SAAS,GAAG,OAAgB,GAC1C,IAAI;IAIP;;;;OAIG;IACH,SAAS,CAAC,QAAQ,IAAI,IAAI;IAI1B;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,SAAS,CAAC,SAAS,CACjB,KAAK,EAAE,eAAe,EACtB,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,OAAO,KAAK,IAAI,GACpC,IAAI;IAOD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAKrB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAIxB,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC;IAIvB,WAAW,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrD;;;;;;;OAOG;IACH,KAAK,IAAI,IAAI;CAed"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build a namespace object whose nested property access maps to a
|
|
3
|
+
* dot-separated host RPC method path, and whose every call dispatches that
|
|
4
|
+
* path through the host bridge.
|
|
5
|
+
*
|
|
6
|
+
* The host exposes the entire plugin API behind a single generic `call()`
|
|
7
|
+
* (see the host `bridge.ts`), and the method string is exactly the property
|
|
8
|
+
* path — so one Proxy replaces every hand-written per-method RPC wrapper for
|
|
9
|
+
* every namespace (`core.*`, `design.*`, `entity.*`):
|
|
10
|
+
*
|
|
11
|
+
* The POSITIONAL transport forwards the whole argument tuple; the host router
|
|
12
|
+
* spreads it back into the resolved method (`fn(...args)`):
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* snaptrude.core.math.vec3.new(1, 2, 3)
|
|
16
|
+
* // → getHostApi().call({ method: "core.math.vec3.new", args: [1, 2, 3] })
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* Typed at the call site, e.g. `createRpcNamespace<PluginEntityApi>("entity")`.
|
|
20
|
+
* The Proxy is structurally cast to the abstract API type — argument and
|
|
21
|
+
* return types are enforced by that type, while dispatch is dynamic.
|
|
22
|
+
*
|
|
23
|
+
* Every namespace uses this — including `core.math.*` and `core.geom.*`: under
|
|
24
|
+
* the all-handle model there is no in-worker compute; math and geometry are
|
|
25
|
+
* host calls like everything else.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createRpcNamespace<T extends object>(basePath: string): T;
|
|
28
|
+
//# sourceMappingURL=rpc-proxy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpc-proxy.d.ts","sourceRoot":"","sources":["../src/rpc-proxy.ts"],"names":[],"mappings":"AAOA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,CAqBxE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@snaptrude/plugin-client",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.15",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
],
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"comlink": "^4.4.2",
|
|
26
|
-
"@snaptrude/plugin-core": "0.9.
|
|
26
|
+
"@snaptrude/plugin-core": "0.9.15"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"tsup": "^8.5.1",
|