@rainbow-robotics/plugin-ui 0.1.2-dev.8 → 1.0.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/README.md +236 -75
- package/build-dist.mjs +55 -17
- package/dist/host-ui.d.ts +49 -0
- package/dist/host-ui.d.ts.map +1 -0
- package/dist/host-ui.js +33 -0
- package/dist/host-ui.js.map +7 -0
- package/dist/manifest.d.ts +20 -4
- package/dist/manifest.d.ts.map +1 -1
- package/dist/manifest.js +1 -1
- package/dist/manifest.js.map +2 -2
- package/dist/pluginData.d.ts +62 -0
- package/dist/pluginData.d.ts.map +1 -0
- package/dist/react.d.ts +3436 -36
- package/dist/react.js +5 -54
- package/dist/react.js.map +2 -2
- package/dist/sdk.d.ts +38 -2
- package/dist/sdk.d.ts.map +1 -1
- package/dist/sdk.js +29 -4
- package/dist/sdk.js.map +2 -2
- package/dist/viteHost.d.ts +46 -0
- package/dist/viteHost.d.ts.map +1 -0
- package/dist/viteHost.js +262 -0
- package/dist/viteHost.js.map +7 -0
- package/dist/ws.d.ts +53 -0
- package/dist/ws.d.ts.map +1 -1
- package/dist/ws.js +141 -0
- package/dist/ws.js.map +7 -0
- package/package.json +45 -21
- package/src/host-ui.ts +80 -0
- package/src/host.tsx +229 -308
- package/src/index.d.ts +1 -0
- package/src/manifest.ts +25 -4
- package/src/pluginData.tsx +232 -0
- package/src/react.tsx +9 -127
- package/src/sdk.ts +81 -13
- package/src/viteHost.ts +309 -0
- package/src/ws.ts +127 -20
- package/build-browser.mjs +0 -84
- package/dist/connect.d.ts +0 -11
- package/dist/connect.d.ts.map +0 -1
- package/dist/connect.js +0 -34
- package/dist/connect.js.map +0 -7
- package/dist/elements.d.ts +0 -195
- package/dist/elements.d.ts.map +0 -1
- package/dist/elements.js +0 -115
- package/dist/elements.js.map +0 -7
- package/dist/react.d.ts.map +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/chunks/chunk-37HVFFJB.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/chunks/chunk-4MGSRUAS.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/chunks/chunk-Q6XGCIPE.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/connect.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/elements.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/react.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/sdk.js +0 -1
- package/dist-browser/vendor/react-dom-client.js +0 -1
- package/dist-browser/vendor/react-jsx-dev-runtime.js +0 -1
- package/dist-browser/vendor/react-jsx-runtime.js +0 -1
- package/dist-browser/vendor/react-runtime.js +0 -65
- package/dist-browser/vendor/react.js +0 -1
- package/src/connect.ts +0 -62
- package/src/elements.ts +0 -257
package/src/viteHost.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vite plugins for a HOST app previewing locally-developed plugins.
|
|
3
|
+
* Host-agnostic — paths are parameters.
|
|
4
|
+
*
|
|
5
|
+
* import {
|
|
6
|
+
* pluginPreviewRuntimePlugin,
|
|
7
|
+
* pluginPreviewAssetsPlugin,
|
|
8
|
+
* isPluginPreviewMode,
|
|
9
|
+
* } from "@rainbow-robotics/plugin-ui/vite-host";
|
|
10
|
+
*
|
|
11
|
+
* A built plugin's bare imports (react, rb-components, plugin-ui/*) resolve via
|
|
12
|
+
* the import map this file injects, to the host's already-loaded instances.
|
|
13
|
+
* See ./host.tsx.
|
|
14
|
+
*/
|
|
15
|
+
import type { Plugin } from "vite";
|
|
16
|
+
import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";
|
|
17
|
+
import { createRequire } from "node:module";
|
|
18
|
+
import { extname, resolve } from "node:path";
|
|
19
|
+
|
|
20
|
+
const require = createRequire(import.meta.url);
|
|
21
|
+
|
|
22
|
+
export const defaultPreviewAssetPrefixes = [
|
|
23
|
+
"/imgs/",
|
|
24
|
+
"/fonts/",
|
|
25
|
+
"/models/",
|
|
26
|
+
"/sounds/",
|
|
27
|
+
"/data/",
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
export const contentTypeByExt: Record<string, string> = {
|
|
31
|
+
".avif": "image/avif",
|
|
32
|
+
".css": "text/css; charset=utf-8",
|
|
33
|
+
".gif": "image/gif",
|
|
34
|
+
".glb": "model/gltf-binary",
|
|
35
|
+
".jpeg": "image/jpeg",
|
|
36
|
+
".jpg": "image/jpeg",
|
|
37
|
+
".js": "text/javascript; charset=utf-8",
|
|
38
|
+
".json": "application/json; charset=utf-8",
|
|
39
|
+
".mp3": "audio/mpeg",
|
|
40
|
+
".png": "image/png",
|
|
41
|
+
".svg": "image/svg+xml",
|
|
42
|
+
".wasm": "application/wasm",
|
|
43
|
+
".webp": "image/webp",
|
|
44
|
+
".woff": "font/woff",
|
|
45
|
+
".woff2": "font/woff2",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export const isPluginPreviewMode = (mode: string) => mode === "plugin-preview";
|
|
49
|
+
|
|
50
|
+
/* -------------------------------------------------------------------------- */
|
|
51
|
+
/* Shared-runtime import map (plugins reuse the host's loaded instances) */
|
|
52
|
+
/* -------------------------------------------------------------------------- */
|
|
53
|
+
|
|
54
|
+
const SHARED_BASE = "/plugin-shared";
|
|
55
|
+
|
|
56
|
+
// Each shared specifier → the named exports its shim re-exports from
|
|
57
|
+
// window.__RB_SHARED__[specifier] (set by the host, e.g. nexus/src/pluginShared).
|
|
58
|
+
//
|
|
59
|
+
// `names`: hardcoded list (small, stable modules).
|
|
60
|
+
// `parseNamesFrom`: parse the export names out of a source file's text — used
|
|
61
|
+
// for react.tsx, which re-exports the whole rb-components barrel (100+ names).
|
|
62
|
+
// We text-parse rather than import it: the barrel is .ts source, which plain
|
|
63
|
+
// Node can't execute.
|
|
64
|
+
const SHARED_MODULES: Record<
|
|
65
|
+
string,
|
|
66
|
+
{
|
|
67
|
+
file: string;
|
|
68
|
+
names?: string[];
|
|
69
|
+
parseNamesFrom?: { specifier: string; extraNames?: string[] };
|
|
70
|
+
hasDefault?: boolean;
|
|
71
|
+
}
|
|
72
|
+
> = {
|
|
73
|
+
react: {
|
|
74
|
+
file: "react",
|
|
75
|
+
hasDefault: true,
|
|
76
|
+
names: [
|
|
77
|
+
"Children", "Component", "Fragment", "Profiler", "PureComponent",
|
|
78
|
+
"StrictMode", "Suspense", "cloneElement", "createContext",
|
|
79
|
+
"createElement", "createRef", "forwardRef", "isValidElement", "lazy",
|
|
80
|
+
"memo", "startTransition", "useCallback", "useContext", "useDebugValue",
|
|
81
|
+
"useDeferredValue", "useEffect", "useId", "useImperativeHandle",
|
|
82
|
+
"useInsertionEffect", "useLayoutEffect", "useMemo", "useReducer",
|
|
83
|
+
"useRef", "useState", "useSyncExternalStore", "useTransition", "version",
|
|
84
|
+
],
|
|
85
|
+
},
|
|
86
|
+
"react/jsx-runtime": {
|
|
87
|
+
file: "react_jsx-runtime",
|
|
88
|
+
names: ["Fragment", "jsx", "jsxs"],
|
|
89
|
+
},
|
|
90
|
+
"react/jsx-dev-runtime": {
|
|
91
|
+
file: "react_jsx-dev-runtime",
|
|
92
|
+
names: ["Fragment", "jsxDEV"],
|
|
93
|
+
},
|
|
94
|
+
"react-dom": {
|
|
95
|
+
file: "react-dom",
|
|
96
|
+
hasDefault: true,
|
|
97
|
+
names: [
|
|
98
|
+
"__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED",
|
|
99
|
+
"createPortal",
|
|
100
|
+
"createRoot",
|
|
101
|
+
"findDOMNode",
|
|
102
|
+
"flushSync",
|
|
103
|
+
"hydrate",
|
|
104
|
+
"hydrateRoot",
|
|
105
|
+
"render",
|
|
106
|
+
"unmountComponentAtNode",
|
|
107
|
+
"unstable_batchedUpdates",
|
|
108
|
+
"unstable_renderSubtreeIntoContainer",
|
|
109
|
+
"version",
|
|
110
|
+
],
|
|
111
|
+
},
|
|
112
|
+
"react-dom/client": {
|
|
113
|
+
file: "react-dom_client",
|
|
114
|
+
names: ["createRoot", "hydrateRoot"],
|
|
115
|
+
},
|
|
116
|
+
"@rainbow-robotics/plugin-ui/react": {
|
|
117
|
+
file: "plugin-ui_react",
|
|
118
|
+
// react.tsx re-exports the full rb-components barrel (export *) plus the sdk
|
|
119
|
+
// hooks.
|
|
120
|
+
parseNamesFrom: {
|
|
121
|
+
specifier: "@repo/rb-components/new_components",
|
|
122
|
+
extraNames: ["useRb", "useRbFormData", "useRbSave"],
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
"@rainbow-robotics/plugin-ui/sdk": {
|
|
126
|
+
file: "plugin-ui_sdk",
|
|
127
|
+
names: ["RbContext", "useRb", "useRbFormData", "useRbSave"],
|
|
128
|
+
},
|
|
129
|
+
"@rainbow-robotics/plugin-ui/host-ui": {
|
|
130
|
+
file: "plugin-ui_host-ui",
|
|
131
|
+
names: [
|
|
132
|
+
"alert",
|
|
133
|
+
"confirm",
|
|
134
|
+
"getHostServices",
|
|
135
|
+
"prompt",
|
|
136
|
+
"setHostServices",
|
|
137
|
+
"toast",
|
|
138
|
+
],
|
|
139
|
+
},
|
|
140
|
+
"@rainbow-robotics/plugin-ui/ws": {
|
|
141
|
+
file: "plugin-ui_ws",
|
|
142
|
+
names: ["RbWs", "createLazyRbSdk"],
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// Parses `export { a, b as c, ... }` value names out of a source file's text
|
|
147
|
+
// (skips `export type { ... }` blocks and individual `type X` entries within
|
|
148
|
+
// a mixed block — types don't exist as runtime module properties). Static
|
|
149
|
+
// text parsing, not module execution, so it works for .ts source files with
|
|
150
|
+
// no loader and has no ESM-resolution footguns.
|
|
151
|
+
function parseExportedValueNames(source: string): string[] {
|
|
152
|
+
const names = new Set<string>();
|
|
153
|
+
const blockRe = /export\s+(type\s+)?\{([^}]*)\}/g;
|
|
154
|
+
let match: RegExpExecArray | null;
|
|
155
|
+
while ((match = blockRe.exec(source))) {
|
|
156
|
+
if (match[1]) continue; // whole `export type { ... }` block
|
|
157
|
+
for (const rawEntry of match[2].split(",")) {
|
|
158
|
+
const entry = rawEntry.trim();
|
|
159
|
+
if (!entry || entry.startsWith("type ")) continue;
|
|
160
|
+
const asMatch = entry.match(/^\S+\s+as\s+(\S+)$/);
|
|
161
|
+
names.add(asMatch ? asMatch[1] : entry);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return [...names];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const nameCache = new Map<string, string[]>();
|
|
168
|
+
|
|
169
|
+
function resolveNames(spec: string): string[] {
|
|
170
|
+
const mod = SHARED_MODULES[spec];
|
|
171
|
+
if (mod.names) return mod.names;
|
|
172
|
+
if (!mod.parseNamesFrom) {
|
|
173
|
+
throw new Error(`[plugin-ui] ${spec} has neither "names" nor "parseNamesFrom"`);
|
|
174
|
+
}
|
|
175
|
+
if (!nameCache.has(spec)) {
|
|
176
|
+
const { specifier, extraNames = [] } = mod.parseNamesFrom;
|
|
177
|
+
const sourcePath = require.resolve(specifier);
|
|
178
|
+
const parsed = parseExportedValueNames(readFileSync(sourcePath, "utf8"));
|
|
179
|
+
nameCache.set(spec, [...new Set([...parsed, ...extraNames])]);
|
|
180
|
+
}
|
|
181
|
+
return nameCache.get(spec)!;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function shimSource(spec: string): string {
|
|
185
|
+
const mod = SHARED_MODULES[spec];
|
|
186
|
+
const names = resolveNames(spec);
|
|
187
|
+
const g = `(globalThis.__RB_SHARED__||{})[${JSON.stringify(spec)}]`;
|
|
188
|
+
return (
|
|
189
|
+
`const m = ${g};\n` +
|
|
190
|
+
`if (!m) throw new Error("[plugin-ui] host shared module not registered: ${spec}");\n` +
|
|
191
|
+
`export const { ${names.join(", ")} } = m;\n` +
|
|
192
|
+
(mod.hasDefault ? `export default (m.default ?? m);\n` : "")
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const fileToSpec = Object.fromEntries(
|
|
197
|
+
Object.entries(SHARED_MODULES).map(([spec, { file }]) => [file, spec]),
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
function importMapScript(): string {
|
|
201
|
+
const imports: Record<string, string> = {};
|
|
202
|
+
for (const [spec, { file }] of Object.entries(SHARED_MODULES)) {
|
|
203
|
+
imports[spec] = `${SHARED_BASE}/${file}.js`;
|
|
204
|
+
}
|
|
205
|
+
return `<script type="importmap">${JSON.stringify({ imports })}</script>`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Serves the shared-runtime shim modules at /plugin-shared/*.js and injects the
|
|
210
|
+
* import map so a dynamically-imported plugin's bare `import "react"` /
|
|
211
|
+
* `import "@rainbow-robotics/plugin-ui/react"` etc. resolve to the host's OWN
|
|
212
|
+
* instances (via window.__RB_SHARED__). Applied in all modes — any nexus build
|
|
213
|
+
* that can host plugins needs it.
|
|
214
|
+
*/
|
|
215
|
+
export const pluginSharedRuntimePlugin = (): Plugin => ({
|
|
216
|
+
name: "plugin-ui-shared-runtime",
|
|
217
|
+
transformIndexHtml(html) {
|
|
218
|
+
return html.replace("</head>", ` ${importMapScript()}\n </head>`);
|
|
219
|
+
},
|
|
220
|
+
configureServer(server) {
|
|
221
|
+
server.middlewares.use((req, res, next) => {
|
|
222
|
+
const url = req.url?.split("?")[0];
|
|
223
|
+
if (!url?.startsWith(`${SHARED_BASE}/`)) return next();
|
|
224
|
+
const file = url.slice(`${SHARED_BASE}/`.length).replace(/\.js$/, "");
|
|
225
|
+
const spec = fileToSpec[file];
|
|
226
|
+
if (!spec) return next();
|
|
227
|
+
res.setHeader("Content-Type", "text/javascript; charset=utf-8");
|
|
228
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
229
|
+
res.end(shimSource(spec));
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
generateBundle() {
|
|
233
|
+
for (const [spec, { file }] of Object.entries(SHARED_MODULES)) {
|
|
234
|
+
this.emitFile({
|
|
235
|
+
type: "asset",
|
|
236
|
+
fileName: `plugin-shared/${file}.js`,
|
|
237
|
+
source: shimSource(spec),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
/** Inject the preview-host runtime flags into index.html (plugin-preview only). */
|
|
244
|
+
export const pluginPreviewRuntimePlugin = (): Plugin => ({
|
|
245
|
+
name: "plugin-ui-preview-runtime",
|
|
246
|
+
apply: (_config, { mode }) => isPluginPreviewMode(mode),
|
|
247
|
+
transformIndexHtml(html) {
|
|
248
|
+
return html.replace(
|
|
249
|
+
"</head>",
|
|
250
|
+
[
|
|
251
|
+
" <script>",
|
|
252
|
+
" window.__RB_PLUGIN_PREVIEW_HOST__ = true;",
|
|
253
|
+
" window.__RB_ASSETS_BASE_URL__ = window.location.origin;",
|
|
254
|
+
" </script>",
|
|
255
|
+
" </head>",
|
|
256
|
+
].join("\n"),
|
|
257
|
+
);
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
/** Serve the host's static assets (imgs/fonts/...) in plugin-preview dev mode. */
|
|
262
|
+
export const pluginPreviewAssetsPlugin = (opts: {
|
|
263
|
+
assetsDir: string;
|
|
264
|
+
prefixes?: string[];
|
|
265
|
+
}): Plugin => {
|
|
266
|
+
const { assetsDir, prefixes = defaultPreviewAssetPrefixes } = opts;
|
|
267
|
+
return {
|
|
268
|
+
name: "plugin-ui-preview-assets",
|
|
269
|
+
apply: (_config, { command, mode }) =>
|
|
270
|
+
command === "serve" && isPluginPreviewMode(mode),
|
|
271
|
+
configureServer(server) {
|
|
272
|
+
server.middlewares.use((req, res, next) => {
|
|
273
|
+
const url = req.url?.split("?")[0];
|
|
274
|
+
if (!url || !prefixes.some((prefix) => url.startsWith(prefix)))
|
|
275
|
+
return next();
|
|
276
|
+
|
|
277
|
+
const decodedUrl = decodeURIComponent(url);
|
|
278
|
+
const filePath = resolve(assetsDir, `.${decodedUrl}`);
|
|
279
|
+
if (!filePath.startsWith(assetsDir)) return next();
|
|
280
|
+
if (!existsSync(filePath) || !statSync(filePath).isFile()) return next();
|
|
281
|
+
|
|
282
|
+
const contentType = contentTypeByExt[extname(filePath)];
|
|
283
|
+
if (contentType) res.setHeader("Content-Type", contentType);
|
|
284
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
285
|
+
createReadStream(filePath).pipe(res);
|
|
286
|
+
});
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* All host-side plugin-ui Vite plugins in one call. Each self-gates by mode, so
|
|
293
|
+
* a host just spreads this into its `plugins` array.
|
|
294
|
+
*
|
|
295
|
+
* plugins: [muscatVitePlugin({ previewAssetsDir: resolve(here, "../assets/public") })]
|
|
296
|
+
*/
|
|
297
|
+
export const muscatVitePlugin = (opts: {
|
|
298
|
+
/** Host static assets dir served in plugin-preview dev mode. */
|
|
299
|
+
previewAssetsDir: string;
|
|
300
|
+
/** Override preview asset URL prefixes. */
|
|
301
|
+
previewAssetPrefixes?: string[];
|
|
302
|
+
}): Plugin[] => [
|
|
303
|
+
pluginSharedRuntimePlugin(),
|
|
304
|
+
pluginPreviewRuntimePlugin(),
|
|
305
|
+
pluginPreviewAssetsPlugin({
|
|
306
|
+
assetsDir: opts.previewAssetsDir,
|
|
307
|
+
prefixes: opts.previewAssetPrefixes,
|
|
308
|
+
}),
|
|
309
|
+
];
|
package/src/ws.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Socket.IO communication client for plugin frontends.
|
|
3
3
|
*
|
|
4
4
|
* Topics are automatically namespaced to prevent cross-plugin collisions:
|
|
5
|
-
* "sensor/data" → "
|
|
5
|
+
* "sensor/data" → "{pluginId}/sensor/data"
|
|
6
6
|
* "/broadcast/x" → "broadcast/x" (leading slash = absolute)
|
|
7
7
|
*
|
|
8
8
|
* Browser ←→ Python backend protocol:
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* server emits : msg, serve_call
|
|
11
11
|
*/
|
|
12
12
|
import { io, type Socket } from "socket.io-client";
|
|
13
|
+
// Type-only — no runtime coupling to host-ui.ts.
|
|
14
|
+
import type { PluginUIServices } from "./host-ui";
|
|
13
15
|
|
|
14
16
|
export interface WsHandle {
|
|
15
17
|
undeclare(): void;
|
|
@@ -19,38 +21,67 @@ export type WsSubscriber = WsHandle;
|
|
|
19
21
|
export type WsQueryable = WsHandle;
|
|
20
22
|
|
|
21
23
|
function resolveTopic(pluginId: string, topic: string): string {
|
|
22
|
-
return topic.startsWith("/") ? topic.slice(1) :
|
|
24
|
+
return topic.startsWith("/") ? topic.slice(1) : `${pluginId}/${topic}`;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
export class RbWs {
|
|
26
28
|
private readonly _socket: Socket;
|
|
27
29
|
private readonly _pluginId: string;
|
|
28
|
-
private readonly _subHandlers = new Map<
|
|
29
|
-
|
|
30
|
+
private readonly _subHandlers = new Map<
|
|
31
|
+
string,
|
|
32
|
+
Set<(payload: unknown) => void>
|
|
33
|
+
>();
|
|
34
|
+
private readonly _serveHandlers = new Map<
|
|
35
|
+
string,
|
|
36
|
+
(payload?: unknown) => unknown | Promise<unknown>
|
|
37
|
+
>();
|
|
30
38
|
|
|
31
39
|
private constructor(socket: Socket, pluginId: string) {
|
|
32
40
|
this._socket = socket;
|
|
33
41
|
this._pluginId = pluginId;
|
|
34
42
|
|
|
35
43
|
// Deliver incoming pub/sub messages to registered handlers
|
|
36
|
-
socket.on(
|
|
37
|
-
|
|
38
|
-
|
|
44
|
+
socket.on(
|
|
45
|
+
"msg",
|
|
46
|
+
({ topic, payload }: { topic: string; payload: unknown }) => {
|
|
47
|
+
this._subHandlers.get(topic)?.forEach((h) => h(payload));
|
|
48
|
+
},
|
|
49
|
+
);
|
|
39
50
|
|
|
40
51
|
// Python calls a browser-side serve handler
|
|
41
|
-
socket.on(
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
52
|
+
socket.on(
|
|
53
|
+
"serve_call",
|
|
54
|
+
async ({
|
|
55
|
+
id,
|
|
56
|
+
topic,
|
|
57
|
+
payload,
|
|
58
|
+
}: {
|
|
59
|
+
id: string;
|
|
60
|
+
topic: string;
|
|
61
|
+
payload: unknown;
|
|
62
|
+
}) => {
|
|
63
|
+
const handler = this._serveHandlers.get(topic);
|
|
64
|
+
const result = handler ? await handler(payload) : undefined;
|
|
65
|
+
socket.emit("serve_reply", { id, payload: result });
|
|
66
|
+
},
|
|
67
|
+
);
|
|
46
68
|
}
|
|
47
69
|
|
|
48
70
|
static connect(url: string, pluginId: string): Promise<RbWs> {
|
|
49
71
|
return new Promise((resolve, reject) => {
|
|
50
72
|
const socket = io(url, { transports: ["websocket"] });
|
|
51
|
-
const onConnect = () => {
|
|
52
|
-
|
|
53
|
-
|
|
73
|
+
const onConnect = () => {
|
|
74
|
+
cleanup();
|
|
75
|
+
resolve(new RbWs(socket, pluginId));
|
|
76
|
+
};
|
|
77
|
+
const onError = (err: Error) => {
|
|
78
|
+
cleanup();
|
|
79
|
+
reject(err);
|
|
80
|
+
};
|
|
81
|
+
const cleanup = () => {
|
|
82
|
+
socket.off("connect", onConnect);
|
|
83
|
+
socket.off("connect_error", onError);
|
|
84
|
+
};
|
|
54
85
|
socket.once("connect", onConnect);
|
|
55
86
|
socket.once("connect_error", onError);
|
|
56
87
|
});
|
|
@@ -66,7 +97,10 @@ export class RbWs {
|
|
|
66
97
|
}
|
|
67
98
|
|
|
68
99
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
69
|
-
async sub<P = any>(
|
|
100
|
+
async sub<P = any>(
|
|
101
|
+
topic: string,
|
|
102
|
+
handler: (payload: P) => void,
|
|
103
|
+
): Promise<WsSubscriber> {
|
|
70
104
|
const key = this._key(topic);
|
|
71
105
|
if (!this._subHandlers.has(key)) {
|
|
72
106
|
this._subHandlers.set(key, new Set());
|
|
@@ -89,12 +123,40 @@ export class RbWs {
|
|
|
89
123
|
|
|
90
124
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
91
125
|
async action<R = any, P = any>(topic: string, payload?: P): Promise<R> {
|
|
92
|
-
|
|
126
|
+
const key = this._key(topic);
|
|
127
|
+
return new Promise((resolve, reject) => {
|
|
93
128
|
this._socket
|
|
94
129
|
.timeout(10_000)
|
|
95
|
-
.emit(
|
|
96
|
-
|
|
97
|
-
|
|
130
|
+
.emit(
|
|
131
|
+
"action",
|
|
132
|
+
{ topic: key, payload },
|
|
133
|
+
(err: Error | null, result: R) => {
|
|
134
|
+
if (err) {
|
|
135
|
+
// socket.io ack timeout — the bridge itself never answered.
|
|
136
|
+
reject(new Error(`action "${key}": no ack from bridge (${err.message})`));
|
|
137
|
+
} else if (
|
|
138
|
+
result &&
|
|
139
|
+
typeof result === "object" &&
|
|
140
|
+
"error" in result &&
|
|
141
|
+
typeof result.error === "string"
|
|
142
|
+
) {
|
|
143
|
+
// Backend handler returned an error payload — surface it verbatim.
|
|
144
|
+
reject(new Error(result.error));
|
|
145
|
+
} else if (result === undefined || result === null) {
|
|
146
|
+
// The bridge acked but with no payload: the backend handler is
|
|
147
|
+
// registered yet didn't reply in time (hung inside the handler,
|
|
148
|
+
// e.g. a blocked SDK call) or returned nothing. Distinct from a
|
|
149
|
+
// "No handler registered" error, which comes back as result.error.
|
|
150
|
+
reject(
|
|
151
|
+
new Error(
|
|
152
|
+
`action "${key}": no reply from plugin backend — the handler was reached but didn't return in time (check the backend's stdout on the robot).`,
|
|
153
|
+
),
|
|
154
|
+
);
|
|
155
|
+
} else {
|
|
156
|
+
resolve(result);
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
);
|
|
98
160
|
});
|
|
99
161
|
}
|
|
100
162
|
|
|
@@ -118,3 +180,48 @@ export class RbWs {
|
|
|
118
180
|
this._socket.disconnect();
|
|
119
181
|
}
|
|
120
182
|
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Builds an rb-sdk-shaped object (pub/sub/action/serve + the passed-through
|
|
186
|
+
* toast/alert/confirm/prompt) that lazily awaits a not-yet-connected `RbWs` —
|
|
187
|
+
* so callers don't block their first render on the WebSocket handshake (there
|
|
188
|
+
* may be no backend reachable yet). Shared by both host mount paths (see
|
|
189
|
+
* ./host.tsx and muscat-plugin-kit's dev bootstrap), which otherwise
|
|
190
|
+
* duplicate this wiring.
|
|
191
|
+
*/
|
|
192
|
+
export function createLazyRbSdk(
|
|
193
|
+
wsPromise: Promise<RbWs>,
|
|
194
|
+
services: PluginUIServices,
|
|
195
|
+
// Per-mount, host-provided (unlike `services`, which is a global singleton):
|
|
196
|
+
// initial `data` and the `onSave` registration the host reads back. Plain
|
|
197
|
+
// values/closures, so they cross the dev React-instance boundary safely.
|
|
198
|
+
mount?: {
|
|
199
|
+
data?: unknown;
|
|
200
|
+
onSave?: (getPayload: () => unknown) => () => void;
|
|
201
|
+
},
|
|
202
|
+
) {
|
|
203
|
+
return {
|
|
204
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
205
|
+
pub: async (topic: string, payload: any) =>
|
|
206
|
+
(await wsPromise).pub(topic, payload),
|
|
207
|
+
sub: async (
|
|
208
|
+
topic: string,
|
|
209
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
210
|
+
handler: (payload: any) => void,
|
|
211
|
+
) => (await wsPromise).sub(topic, handler),
|
|
212
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
213
|
+
action: async (topic: string, payload?: any) =>
|
|
214
|
+
(await wsPromise).action(topic, payload),
|
|
215
|
+
serve: async (
|
|
216
|
+
topic: string,
|
|
217
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
218
|
+
handler: (payload?: any) => any,
|
|
219
|
+
) => (await wsPromise).serve(topic, handler),
|
|
220
|
+
toast: services.toast,
|
|
221
|
+
alert: services.alert,
|
|
222
|
+
confirm: services.confirm,
|
|
223
|
+
prompt: services.prompt,
|
|
224
|
+
data: mount?.data,
|
|
225
|
+
onSave: mount?.onSave ?? (() => () => {}),
|
|
226
|
+
};
|
|
227
|
+
}
|
package/build-browser.mjs
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
// Builds @rainbow-robotics/plugin-ui as browser ESM for the sandbox import map.
|
|
2
|
-
// Output: dist-browser/@rainbow-robotics/plugin-ui/{connect,react,sdk,elements}.js
|
|
3
|
-
// dist-browser/vendor/react-runtime.js
|
|
4
|
-
//
|
|
5
|
-
// Consumed by:
|
|
6
|
-
// - nexus (vite plugin emits dist-browser/ → dist/plugin-runtime/)
|
|
7
|
-
// - preview-host (serves dist-browser/ at /plugin-runtime/)
|
|
8
|
-
//
|
|
9
|
-
// Run: node libraries/plugin-ui/build-browser.mjs
|
|
10
|
-
import { build } from "esbuild";
|
|
11
|
-
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
12
|
-
import { dirname, resolve } from "node:path";
|
|
13
|
-
import { fileURLToPath } from "node:url";
|
|
14
|
-
|
|
15
|
-
const here = dirname(fileURLToPath(import.meta.url));
|
|
16
|
-
const src = resolve(here, "src");
|
|
17
|
-
const out = resolve(here, "dist-browser");
|
|
18
|
-
const repoRoot = resolve(here, "../..");
|
|
19
|
-
|
|
20
|
-
const define = { "process.env.NODE_ENV": JSON.stringify("production") };
|
|
21
|
-
const shared = {
|
|
22
|
-
bundle: true,
|
|
23
|
-
format: "esm",
|
|
24
|
-
platform: "browser",
|
|
25
|
-
target: "es2020",
|
|
26
|
-
minify: true,
|
|
27
|
-
sourcemap: false,
|
|
28
|
-
define,
|
|
29
|
-
logLevel: "warning",
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
rmSync(out, { recursive: true, force: true });
|
|
33
|
-
mkdirSync(resolve(out, "@rainbow-robotics/plugin-ui"), { recursive: true });
|
|
34
|
-
mkdirSync(resolve(out, "vendor"), { recursive: true });
|
|
35
|
-
|
|
36
|
-
// Plugin-UI entry points (react / react-dom provided by vendor bundle below)
|
|
37
|
-
await build({
|
|
38
|
-
...shared,
|
|
39
|
-
entryPoints: {
|
|
40
|
-
connect: resolve(src, "connect.ts"),
|
|
41
|
-
react: resolve(src, "react.tsx"),
|
|
42
|
-
sdk: resolve(src, "sdk.ts"),
|
|
43
|
-
elements: resolve(src, "elements.ts"),
|
|
44
|
-
},
|
|
45
|
-
outdir: resolve(out, "@rainbow-robotics/plugin-ui"),
|
|
46
|
-
entryNames: "[name]",
|
|
47
|
-
chunkNames: "chunks/[name]-[hash]",
|
|
48
|
-
splitting: true,
|
|
49
|
-
external: ["react", "react-dom/client"],
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
// Single vendor bundle: React + ReactDOM (sandbox loads this once via import map)
|
|
53
|
-
const reactShim = `
|
|
54
|
-
import React from "react";
|
|
55
|
-
import * as ReactClient from "react-dom/client";
|
|
56
|
-
import * as JsxRuntime from "react/jsx-runtime";
|
|
57
|
-
import * as JsxDevRuntime from "react/jsx-dev-runtime";
|
|
58
|
-
export default React;
|
|
59
|
-
export const { Children, Fragment, Profiler, StrictMode, Suspense,
|
|
60
|
-
cloneElement, createContext, createElement, createRef, forwardRef,
|
|
61
|
-
isValidElement, lazy, memo, startTransition, useCallback, useContext,
|
|
62
|
-
useDebugValue, useDeferredValue, useEffect, useId, useImperativeHandle,
|
|
63
|
-
useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef,
|
|
64
|
-
useState, useSyncExternalStore, useTransition, version } = React;
|
|
65
|
-
export const { createRoot, hydrateRoot } = ReactClient;
|
|
66
|
-
export const { jsx, jsxs } = JsxRuntime;
|
|
67
|
-
export const { jsxDEV } = JsxDevRuntime;
|
|
68
|
-
`;
|
|
69
|
-
|
|
70
|
-
await build({
|
|
71
|
-
...shared,
|
|
72
|
-
stdin: { contents: reactShim, resolveDir: repoRoot, loader: "js" },
|
|
73
|
-
outfile: resolve(out, "vendor", "react-runtime.js"),
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
// Aliases so all standard React specifiers map to the single vendor file
|
|
77
|
-
for (const name of ["react", "react-jsx-runtime", "react-jsx-dev-runtime", "react-dom-client"]) {
|
|
78
|
-
writeFileSync(
|
|
79
|
-
resolve(out, "vendor", `${name}.js`),
|
|
80
|
-
'export * from "./react-runtime.js"; export { default } from "./react-runtime.js";\n',
|
|
81
|
-
);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
console.log("[plugin-ui] dist-browser ready →", out);
|
package/dist/connect.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { type ComponentType } from "react";
|
|
2
|
-
/**
|
|
3
|
-
* Mount a plugin. Call this once from the sandbox entry (content.tsx).
|
|
4
|
-
*
|
|
5
|
-
* @example
|
|
6
|
-
* import { connect } from "@rainbow-robotics/plugin-ui/connect";
|
|
7
|
-
* import App from "./App";
|
|
8
|
-
* connect(App);
|
|
9
|
-
*/
|
|
10
|
-
export declare function connect(App: ComponentType): void;
|
|
11
|
-
//# sourceMappingURL=connect.d.ts.map
|
package/dist/connect.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAUA,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAe1D;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,GAAG,EAAE,aAAa,GAAG,IAAI,CA4BhD"}
|
package/dist/connect.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { RemoteMutationObserver } from "@remote-dom/core/elements";
|
|
2
|
-
import { ThreadWindow } from "@quilted/threads";
|
|
3
|
-
import { createElement } from "react";
|
|
4
|
-
import { createRoot } from "react-dom/client";
|
|
5
|
-
import { defineElements } from "./elements";
|
|
6
|
-
import { RbContext } from "./sdk";
|
|
7
|
-
import { RbWs } from "./ws";
|
|
8
|
-
function connect(App) {
|
|
9
|
-
defineElements();
|
|
10
|
-
const host = ThreadWindow.parent.import({
|
|
11
|
-
targetOrigin: "*"
|
|
12
|
-
});
|
|
13
|
-
void host.connect().then(async ({ connection, toast, socketUrl, pluginId }) => {
|
|
14
|
-
const ws = await RbWs.connect(socketUrl, pluginId);
|
|
15
|
-
const rb = {
|
|
16
|
-
pub: (topic, payload) => ws.pub(topic, payload),
|
|
17
|
-
sub: (topic, handler) => ws.sub(topic, handler),
|
|
18
|
-
action: (topic, payload) => ws.action(topic, payload),
|
|
19
|
-
serve: (topic, handler) => ws.serve(topic, handler),
|
|
20
|
-
toast: (message, type) => toast(message, type)
|
|
21
|
-
};
|
|
22
|
-
const root = document.createElement("remote-root");
|
|
23
|
-
document.body.append(root);
|
|
24
|
-
const observer = new RemoteMutationObserver(connection);
|
|
25
|
-
observer.observe(root);
|
|
26
|
-
createRoot(root).render(
|
|
27
|
-
createElement(RbContext.Provider, { value: rb }, createElement(App))
|
|
28
|
-
);
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
export {
|
|
32
|
-
connect
|
|
33
|
-
};
|
|
34
|
-
//# sourceMappingURL=connect.js.map
|
package/dist/connect.js.map
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/connect.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Sandbox bootstrap \u2014 runs *inside* the plugin iframe.\n *\n * The sandbox initiates the handshake: imports the host's `connect()` and calls\n * it. The host responds with the RemoteConnection, toast(), and Socket.IO config\n * (socketUrl + pluginId). We open a Socket.IO connection and wire up the rb object.\n */\nimport { RemoteMutationObserver } from \"@remote-dom/core/elements\";\nimport type { RemoteConnection } from \"@remote-dom/core\";\nimport { ThreadWindow } from \"@quilted/threads\";\nimport { createElement, type ComponentType } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { defineElements } from \"./elements\";\nimport { RbContext, type RbSdk } from \"./sdk\";\nimport { RbWs } from \"./ws\";\n\ninterface HostExports {\n connect: () => Promise<{\n connection: RemoteConnection;\n toast: (message: string, type?: string) => void;\n socketUrl: string;\n pluginId: string;\n }>;\n}\n\n/**\n * Mount a plugin. Call this once from the sandbox entry (content.tsx).\n *\n * @example\n * import { connect } from \"@rainbow-robotics/plugin-ui/connect\";\n * import App from \"./App\";\n * connect(App);\n */\nexport function connect(App: ComponentType): void {\n defineElements();\n\n const host = ThreadWindow.parent.import<HostExports>({\n targetOrigin: \"*\",\n });\n\n void host.connect().then(async ({ connection, toast, socketUrl, pluginId }) => {\n const ws = await RbWs.connect(socketUrl, pluginId);\n\n const rb: RbSdk = {\n pub: (topic, payload) => ws.pub(topic, payload),\n sub: (topic, handler) => ws.sub(topic, handler),\n action: (topic, payload) => ws.action(topic, payload),\n serve: (topic, handler) => ws.serve(topic, handler),\n toast: (message, type) => toast(message, type),\n };\n\n const root = document.createElement(\"remote-root\");\n document.body.append(root);\n\n const observer = new RemoteMutationObserver(connection);\n observer.observe(root);\n\n createRoot(root).render(\n createElement(RbContext.Provider, { value: rb }, createElement(App)),\n );\n });\n}\n"],
|
|
5
|
-
"mappings": "AAOA,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,qBAAyC;AAClD,SAAS,kBAAkB;AAC3B,SAAS,sBAAsB;AAC/B,SAAS,iBAA6B;AACtC,SAAS,YAAY;AAmBd,SAAS,QAAQ,KAA0B;AAChD,iBAAe;AAEf,QAAM,OAAO,aAAa,OAAO,OAAoB;AAAA,IACnD,cAAc;AAAA,EAChB,CAAC;AAED,OAAK,KAAK,QAAQ,EAAE,KAAK,OAAO,EAAE,YAAY,OAAO,WAAW,SAAS,MAAM;AAC7E,UAAM,KAAK,MAAM,KAAK,QAAQ,WAAW,QAAQ;AAEjD,UAAM,KAAY;AAAA,MAChB,KAAQ,CAAC,OAAO,YAAY,GAAG,IAAI,OAAO,OAAO;AAAA,MACjD,KAAQ,CAAC,OAAO,YAAY,GAAG,IAAI,OAAO,OAAO;AAAA,MACjD,QAAQ,CAAC,OAAO,YAAY,GAAG,OAAO,OAAO,OAAO;AAAA,MACpD,OAAQ,CAAC,OAAO,YAAY,GAAG,MAAM,OAAO,OAAO;AAAA,MACnD,OAAQ,CAAC,SAAS,SAAU,MAAM,SAAS,IAAI;AAAA,IACjD;AAEA,UAAM,OAAO,SAAS,cAAc,aAAa;AACjD,aAAS,KAAK,OAAO,IAAI;AAEzB,UAAM,WAAW,IAAI,uBAAuB,UAAU;AACtD,aAAS,QAAQ,IAAI;AAErB,eAAW,IAAI,EAAE;AAAA,MACf,cAAc,UAAU,UAAU,EAAE,OAAO,GAAG,GAAG,cAAc,GAAG,CAAC;AAAA,IACrE;AAAA,EACF,CAAC;AACH;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|