@nullplatform/ui-plugin-sdk 0.2.0 → 0.5.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/dist/protocol.js CHANGED
@@ -9,23 +9,62 @@
9
9
  export const PROTOCOL_VERSION = 1;
10
10
  export class BridgeError extends Error {
11
11
  code;
12
- constructor(message, code = 'BRIDGE_ERROR') {
12
+ status;
13
+ constructor(message, code = 'BRIDGE_ERROR', status) {
13
14
  super(message);
14
15
  this.name = 'BridgeError';
15
16
  this.code = code;
17
+ if (status !== undefined)
18
+ this.status = status;
16
19
  }
17
20
  }
21
+ /**
22
+ * A rejection that is not an `Error`. The hosts' API clients reject with plain objects —
23
+ * RTK Query with `{ status, data }`, others with the parsed body — and `String(value)` on
24
+ * one of those yields `[object Object]`, which is how a real 404 reached plugins as an
25
+ * unreadable string. Pulls out the status and the most specific message it can find.
26
+ */
27
+ function fromPlainObject(error) {
28
+ const status = typeof error.status === 'number' ? error.status : undefined;
29
+ const payload = error.data ?? error.body ?? error;
30
+ // A non-JSON response leaves the body as a plain string (RTK Query does this), and that
31
+ // string IS the reason — reading it only as an object would drop it.
32
+ const body = (typeof payload === 'object' && payload !== null ? payload : {});
33
+ const candidate = [
34
+ typeof payload === 'string' ? payload : undefined,
35
+ typeof body.message === 'string' ? body.message : undefined,
36
+ typeof body.error === 'string' ? body.error : undefined,
37
+ typeof error.message === 'string' ? error.message : undefined,
38
+ typeof error.error === 'string' ? error.error : undefined,
39
+ ].find((value) => value !== undefined && value !== '');
40
+ // A status alone still says more than `[object Object]`; with neither, let the caller
41
+ // fall back rather than inventing a message.
42
+ if (candidate === undefined && status === undefined)
43
+ return null;
44
+ const code = typeof error.code === 'string' ? error.code : status !== undefined ? `HTTP_${status}` : undefined;
45
+ return { message: candidate ?? `Request failed with status ${status}`, code, status };
46
+ }
18
47
  export function serializeError(error) {
19
48
  if (error instanceof BridgeError)
20
- return { message: error.message, code: error.code, stack: error.stack };
49
+ return { message: error.message, code: error.code, status: error.status, stack: error.stack };
21
50
  if (error instanceof Error) {
22
- const code = error.code;
23
- return { message: error.message, code: typeof code === 'string' ? code : undefined, stack: error.stack };
51
+ const { code, status } = error;
52
+ return {
53
+ message: error.message,
54
+ code: typeof code === 'string' ? code : undefined,
55
+ status: typeof status === 'number' ? status : undefined,
56
+ stack: error.stack,
57
+ };
58
+ }
59
+ if (typeof error === 'object' && error !== null) {
60
+ const extracted = fromPlainObject(error);
61
+ if (extracted)
62
+ return extracted;
24
63
  }
25
64
  return { message: String(error) };
26
65
  }
27
66
  export function deserializeError(error) {
28
- const bridgeError = new BridgeError(error.message, error.code);
67
+ const bridgeError = new BridgeError(error.message, error.code, error.status);
29
68
  if (error.stack)
30
69
  bridgeError.stack = error.stack;
31
70
  return bridgeError;
@@ -90,12 +129,14 @@ export function toCloneable(value, seen = new WeakSet()) {
90
129
  }
91
130
  if (typeof Node !== 'undefined' && value instanceof Node)
92
131
  return undefined;
93
- if (Array.isArray(value))
94
- return value.map((item) => toCloneable(item, seen));
95
132
  if (type === 'object') {
96
133
  if (seen.has(value))
97
134
  return undefined;
98
135
  seen.add(value);
136
+ }
137
+ if (Array.isArray(value))
138
+ return value.map((item) => toCloneable(item, seen));
139
+ if (type === 'object') {
99
140
  const out = {};
100
141
  for (const [key, item] of Object.entries(value)) {
101
142
  const cloned = toCloneable(item, seen);
@@ -110,3 +151,51 @@ let counter = 0;
110
151
  export function createIdGenerator(prefix) {
111
152
  return () => `${prefix}-${++counter}`;
112
153
  }
154
+ /** Bound work before traversing data received from an untrusted worker. */
155
+ export function assertWireValue(value) {
156
+ let nodes = 0, characters = 0;
157
+ const seen = new WeakSet();
158
+ const walk = (item, depth) => {
159
+ if (++nodes > 50000 || depth > 32)
160
+ throw new BridgeError('Message exceeds complexity limit', 'MESSAGE_LIMIT');
161
+ if (typeof item === 'string')
162
+ characters += item.length;
163
+ else if (item && typeof item === 'object') {
164
+ if (seen.has(item))
165
+ throw new BridgeError('Cyclic message', 'INVALID_MESSAGE');
166
+ seen.add(item);
167
+ for (const [key, child] of Object.entries(item)) {
168
+ if (['__proto__', 'constructor', 'prototype'].includes(key))
169
+ throw new BridgeError('Unsafe message key', 'INVALID_MESSAGE');
170
+ characters += key.length;
171
+ walk(child, depth + 1);
172
+ }
173
+ seen.delete(item);
174
+ }
175
+ else if (!['undefined', 'boolean', 'number'].includes(typeof item) && item !== null) {
176
+ throw new BridgeError('Message must contain plain data', 'INVALID_MESSAGE');
177
+ }
178
+ if (characters > 2 * 1024 * 1024)
179
+ throw new BridgeError('Message exceeds size limit', 'MESSAGE_LIMIT');
180
+ };
181
+ walk(value, 0);
182
+ }
183
+ /** Deadline also covers custom adapters/loaders that ignore cancellation. */
184
+ export function withDeadline(promise, timeoutMs = 30000, signal) {
185
+ return new Promise((resolve, reject) => {
186
+ const finish = (error, value) => {
187
+ clearTimeout(timer);
188
+ signal?.removeEventListener('abort', abort);
189
+ if (error)
190
+ reject(error);
191
+ else
192
+ resolve(value);
193
+ };
194
+ const abort = () => finish(new BridgeError('Operation cancelled', 'DISPOSED'));
195
+ const timer = setTimeout(() => finish(new BridgeError('Operation timed out', 'TIMEOUT')), timeoutMs);
196
+ signal?.addEventListener('abort', abort, { once: true });
197
+ if (signal?.aborted)
198
+ abort();
199
+ promise.then(value => finish(undefined, value), error => finish(error));
200
+ });
201
+ }
package/dist/worker.js CHANGED
@@ -3,19 +3,18 @@ import "./polyfill.js";
3
3
  * Worker-side runtime: receives the MessagePort from the sandbox bootstrap,
4
4
  * mounts widgets into remote-dom roots and relays mutations to the host.
5
5
  */
6
- import { createElement } from 'react';
6
+ import { Component, createElement } from 'react';
7
7
  import { createRoot } from 'react-dom/client';
8
8
  import { BatchingRemoteConnection } from '@remote-dom/core/elements';
9
9
  import { defineCatalogElements, ROOT_TAG } from './elements.js';
10
10
  import { bridge } from './bridge.js';
11
11
  import { PluginContextProvider, broadcastContext } from './context.js';
12
12
  import { PROTOCOL_VERSION, createIdGenerator, serializeError, serializeFunctions, } from './protocol.js';
13
- const functions = new Map();
14
13
  const nextFunctionId = createIdGenerator('fn');
15
14
  const mounts = new Map();
16
15
  let definition = null;
17
16
  let pluginId = 'unknown';
18
- function createConnection(port, mountId) {
17
+ function createConnection(port, mountId, functions) {
19
18
  const raw = {
20
19
  mutate(records) {
21
20
  const cloneable = serializeFunctions(records, nextFunctionId, functions);
@@ -27,6 +26,14 @@ function createConnection(port, mountId) {
27
26
  };
28
27
  return new BatchingRemoteConnection(raw);
29
28
  }
29
+ class WorkerErrorBoundary extends Component {
30
+ state = { failed: false };
31
+ static getDerivedStateFromError() { return { failed: true }; }
32
+ componentDidCatch(error) {
33
+ this.props.port.postMessage({ type: 'error', mountId: this.props.mountId, error: serializeError(error) });
34
+ }
35
+ render() { return this.state.failed ? null : this.props.children; }
36
+ }
30
37
  function mount(port, message) {
31
38
  if (!definition)
32
39
  throw new Error('defineUI() was not called before mount');
@@ -36,10 +43,11 @@ function mount(port, message) {
36
43
  defineCatalogElements();
37
44
  const element = document.createElement(ROOT_TAG);
38
45
  document.body.append(element);
39
- element.connect(createConnection(port, message.mountId));
46
+ const functions = new Map();
47
+ element.connect(createConnection(port, message.mountId, functions));
40
48
  const root = createRoot(element);
41
- root.render(createElement(PluginContextProvider, { initial: message.context }, createElement(Widget, { slot: message.slot, config: message.config })));
42
- mounts.set(message.mountId, { root, element });
49
+ root.render(createElement(PluginContextProvider, { initial: message.context }, createElement(WorkerErrorBoundary, { port, mountId: message.mountId }, createElement(Widget, { slot: message.slot, config: message.config }))));
50
+ mounts.set(message.mountId, { root, element, functions });
43
51
  }
44
52
  function unmount(mountId) {
45
53
  const current = mounts.get(mountId);
@@ -50,7 +58,7 @@ function unmount(mountId) {
50
58
  mounts.delete(mountId);
51
59
  }
52
60
  async function invokeFunction(port, message) {
53
- const fn = functions.get(message.fnId);
61
+ const fn = [...mounts.values()].map(mount => mount.functions.get(message.fnId)).find(Boolean);
54
62
  if (!fn) {
55
63
  port.postMessage({ type: 'fn-result', id: message.id, ok: false, error: { message: `Unknown function ${message.fnId}` } });
56
64
  return;
@@ -85,6 +93,11 @@ function handle(port, message) {
85
93
  case 'unmount':
86
94
  unmount(message.mountId);
87
95
  break;
96
+ case 'release-functions':
97
+ for (const mount of mounts.values())
98
+ for (const id of message.ids)
99
+ mount.functions.delete(id);
100
+ break;
88
101
  case 'context':
89
102
  broadcastContext(message.context);
90
103
  break;
@@ -106,6 +119,9 @@ function handle(port, message) {
106
119
  /** Connects this worker to the host through the port handed over by the sandbox. */
107
120
  export function connect(port) {
108
121
  bridge.attach(port);
122
+ globalThis.addEventListener('unhandledrejection', (event) => {
123
+ port.postMessage({ type: 'error', error: serializeError(event.reason) });
124
+ });
109
125
  port.onmessage = (event) => handle(port, event.data);
110
126
  port.start?.();
111
127
  port.postMessage({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullplatform/ui-plugin-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.5.0",
4
4
  "description": "SDK for nullplatform UI plugins: catalog components, bridge client and defineUI",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -32,7 +32,7 @@
32
32
  ],
33
33
  "scripts": {
34
34
  "build": "tsc -p tsconfig.json && tsc -p tsconfig.contract.cjs.json && node scripts/finish-build.mjs",
35
- "typecheck": "tsc -p tsconfig.json --noEmit",
35
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test-types.json",
36
36
  "test": "vitest run --passWithNoTests"
37
37
  },
38
38
  "dependencies": {