@johnhenry/wsh 0.45.0 → 0.46.1

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.
@@ -0,0 +1,805 @@
1
+ /**
2
+ * The remote-object core (#190), `values` mode: path resolution, serialisation rules, limits and allow-list evaluation, with NO knowledge of
3
+ * wsh. It needs only a duplex seam, `Peer`:
4
+ *
5
+ * peer.onRequest(method, handler) handler(params, { signal, progress?, who? }) -> result | Promise (throws ObjectsError to refuse)
6
+ * peer.onNotification?(method, fn) optional
7
+ * peer.request(method, params, { signal, onProgress }) -> Promise (the client side)
8
+ * peer.notify(method, params)
9
+ * peer.onClose the core assigns a function; the peer calls it once, with a reason, when it ends
10
+ * peer.maxMessageBytes the largest message the transport carries (the core keeps its answers under it)
11
+ * who the per-call identity `{ username, fingerprint }`: `ctx.who` of a request, or the one given to `attach`
12
+ *
13
+ * A wsh `RpcChannel` is exactly this shape, so `exposeObjects` (in `objects.mjs`) is a few lines; `createDuplexPeer({ send })` below is the same
14
+ * over a bare `send(obj)` / `receive(obj)` pair (a worker's `postMessage`, a test), and `test/objects.test.mjs` runs one suite over both.
15
+ *
16
+ * What makes the allow-list mean what it says is that NOTHING BUT CLONEABLE VALUES CROSSES: a result is plain data (primitives, bytes, arrays and
17
+ * plain objects, bounded), a function, a DOM node, a class instance or a symbol is reported by name (`NonValue`) and is never a handle, so a
18
+ * result can never be walked somewhere else. Where this module does call user code, it is the path the caller named and the allow-list let through:
19
+ * - a `get` of an accessor property runs its getter, and a `set` runs a setter. Getters with side effects are still gets, and an allow-list
20
+ * entry for one allows its side effects. The serialiser itself never calls a getter, `toJSON` or anything else of the value it copies;
21
+ * - a Proxy that the embedder made a root runs its own traps when it is read.
22
+ *
23
+ * Paths are `root.seg.seg`; an allow-list entry is such a path with `*` (one segment) or `**` (any number, also none) for a segment. After a call the
24
+ * chain continues on the RESULT, whose path is the callee with `()`: `window.app.getCart().items`. Nothing is allowed by default.
25
+ */
26
+
27
+ export const OBJECTS_PROTOCOL = 'wsh-objects';
28
+
29
+ /** Error codes, JSON-RPC's where one fits (`reason` in `data` says which rule). */
30
+ export const OBJECTS_ERROR = Object.freeze({ INVALID: -32602, LIMIT: -32002, REFUSED: -32003, FAILED: -32000 });
31
+
32
+ export class ObjectsError extends Error {
33
+ /**
34
+ * @param {number} code
35
+ * @param {string} message
36
+ * @param {{ reason?: string, [k: string]: unknown }} [data]
37
+ */
38
+ constructor(code, message, data) {
39
+ super(message);
40
+ this.name = 'ObjectsError';
41
+ this.code = code;
42
+ this.data = data;
43
+ /** The rule that refused: `always-refused`, `not-allowed`, `needs-listing`, `authorize`, `limit`, `bad-request`, `no-such-root`, ... */
44
+ this.reason = data?.reason;
45
+ }
46
+ }
47
+ const refuse = (reason, message, extra) => new ObjectsError(OBJECTS_ERROR.REFUSED, message, { reason, ...extra });
48
+ const invalid = (message) => new ObjectsError(OBJECTS_ERROR.INVALID, message, { reason: 'bad-request' });
49
+ const limitError = (name, max, what) => new ObjectsError(OBJECTS_ERROR.LIMIT, `refused: ${name} (${max}): ${what}`, { reason: 'limit', limit: name, max });
50
+
51
+ /** The bounds, each refused by name. */
52
+ export const OBJECTS_DEFAULT_LIMITS = Object.freeze({
53
+ /** Operations (get / call / construct) in one `resolve` request. */
54
+ maxOps: 32,
55
+ /** Arguments of one call. */
56
+ maxArgs: 16,
57
+ /** How deep a returned or sent value may nest. */
58
+ maxDepth: 8,
59
+ /** Bytes of one returned value, and of one sent value. */
60
+ maxValueBytes: 256 * 1024,
61
+ /** Keys one `describe` lists. */
62
+ maxKeys: 200,
63
+ /** Requests accepted per second, per attached peer. */
64
+ maxRequestsPerSecond: 50,
65
+ /** How long a call that returns a promise is waited for. */
66
+ callTimeoutMs: 30_000,
67
+ });
68
+
69
+ // ── The rules that hold for every allow-list ────────────────────────────────────────────────────────────────────────
70
+
71
+ /** A path segment that is never walked, read, called or set: it climbs to a prototype or hands out a code evaluator. */
72
+ const ALWAYS_REFUSED = new Set([
73
+ '__proto__', 'prototype', 'constructor', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__',
74
+ 'eval', 'Function', 'import', 'execScript',
75
+ ]);
76
+ /** `fn.call`, `fn.apply` and `fn.bind` re-aim a function: refused on a function (an object may have a method of that name). */
77
+ const FUNCTION_REFLECTION = new Set(['call', 'apply', 'bind']);
78
+ /** Timers take a string to evaluate: refused with a string argument. */
79
+ const STRING_TIMERS = new Set(['setTimeout', 'setInterval', 'setImmediate']);
80
+ /** Refused until a pattern NAMES them (a literal sequence of segments, not a wildcard): a path that contains one of these sequences. */
81
+ export const NEEDS_LISTING = Object.freeze([
82
+ ['document', 'cookie'], ['localStorage'], ['sessionStorage'], ['indexedDB'], ['navigator', 'credentials'], ['fetch'], ['XMLHttpRequest'], ['postMessage'], ['open'],
83
+ ]);
84
+
85
+ const KEY_MAX = 256;
86
+
87
+ function checkKey(key) {
88
+ if (typeof key !== 'string' || key === '' || key.length > KEY_MAX) throw invalid(`a path segment must be a string of 1 to ${KEY_MAX} characters`);
89
+ if (key.includes('.')) throw invalid(`a path segment cannot contain "." (${JSON.stringify(key.slice(0, 40))})`);
90
+ if (ALWAYS_REFUSED.has(key)) throw refuse('always-refused', `refused: "${key}" is never reachable (it climbs to a prototype or evaluates code)`);
91
+ return key;
92
+ }
93
+
94
+ // ── Allow-lists ─────────────────────────────────────────────────────────────────────────────────────────────────────
95
+
96
+ /** Compile one list of entries (`'window.app.**'`) into arrays of segments, refusing an entry that could never be right. */
97
+ function compileList(list, kind) {
98
+ if (list === undefined || list === null) return [];
99
+ if (!Array.isArray(list)) throw new TypeError(`exposeObjects: allow.${kind} must be an array of path patterns`);
100
+ return list.map((entry) => {
101
+ if (typeof entry !== 'string' || entry === '') throw new TypeError(`exposeObjects: allow.${kind} entries must be non-empty strings`);
102
+ const segs = entry.split('.');
103
+ for (const s of segs) {
104
+ if (s === '') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} has an empty segment`);
105
+ if (ALWAYS_REFUSED.has(s)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} names "${s}", which is never reachable`);
106
+ if (/\*/.test(s) && s !== '*' && s !== '**') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)}: a wildcard must be a whole segment ("*" or "**")`);
107
+ }
108
+ return segs;
109
+ });
110
+ }
111
+
112
+ /** Does the pattern match the whole path? `*` is one segment, `**` any number (also none). */
113
+ export function matchPath(pattern, path) {
114
+ const rec = (i, j) => {
115
+ if (i === pattern.length) return j === path.length;
116
+ if (pattern[i] === '**') return rec(i + 1, j) || (j < path.length && rec(i, j + 1));
117
+ return j < path.length && (pattern[i] === '*' || pattern[i] === path[j]) && rec(i + 1, j + 1);
118
+ };
119
+ return rec(0, 0);
120
+ }
121
+
122
+ /** Could the path be extended into a match? (Walking toward something allowed.) */
123
+ function prefixPath(pattern, path) {
124
+ const rec = (i, j) => {
125
+ if (j === path.length) return true;
126
+ if (i === pattern.length) return false;
127
+ if (pattern[i] === '**') return rec(i + 1, j) || rec(i, j + 1);
128
+ return (pattern[i] === '*' || pattern[i] === path[j]) && rec(i + 1, j + 1);
129
+ };
130
+ return rec(0, 0);
131
+ }
132
+
133
+ const containsSequence = (segs, seq) => {
134
+ for (let i = 0; i + seq.length <= segs.length; i++) if (seq.every((s, k) => segs[i + k] === s)) return true;
135
+ return false;
136
+ };
137
+ /** The segments of a pattern, as literal text, contain `seq` consecutively. */
138
+ const patternNames = (pattern, seq) => containsSequence(pattern, seq);
139
+
140
+ const bareName = (seg) => (seg.endsWith('()') ? seg.slice(0, -2) : seg);
141
+
142
+ // ── Serialisation: only cloneable values cross ──────────────────────────────────────────────────────────────────────
143
+
144
+ function utf8Length(s) {
145
+ let n = 0;
146
+ for (let i = 0; i < s.length; i++) {
147
+ const c = s.charCodeAt(i);
148
+ if (c < 0x80) n += 1;
149
+ else if (c < 0x800) n += 2;
150
+ else if (c >= 0xd800 && c <= 0xdbff) { n += 4; i++; } else n += 3;
151
+ }
152
+ return n;
153
+ }
154
+
155
+ const TYPE_MAX = 64;
156
+ const TEXT_MAX = 200;
157
+ const clip = (s, n) => (s.length > n ? `${s.slice(0, n)}...` : s);
158
+ const isPrintable = (s) => typeof s === 'string' && /^[\x20-\x7e]*$/.test(s);
159
+
160
+ /** The class name of an object, read without running any code of it (own data properties only). */
161
+ function typeName(value) {
162
+ try {
163
+ let proto = Object.getPrototypeOf(value);
164
+ for (let hops = 0; proto && hops < 8; hops++, proto = Object.getPrototypeOf(proto)) {
165
+ const d = Object.getOwnPropertyDescriptor(proto, 'constructor');
166
+ const name = d && 'value' in d && typeof d.value === 'function' ? Object.getOwnPropertyDescriptor(d.value, 'name')?.value : undefined;
167
+ if (typeof name === 'string' && isPrintable(name) && name) return clip(name, TYPE_MAX);
168
+ }
169
+ } catch { /* an exotic object: unnamed */ }
170
+ return undefined;
171
+ }
172
+
173
+ /**
174
+ * Describe a value that cannot be cloned: `{ u: kind, type?, text? }`. `kind` is `function`, `symbol`, `bigint`, `number` (an integer too large for the
175
+ * wire), `Date`, `RegExp`, `Error` or `object`; `type` the class name; `text` a short, safe rendering (a date's ISO string, an error's message).
176
+ */
177
+ function nonValue(value) {
178
+ const t = typeof value;
179
+ if (t === 'undefined') return { u: 'undefined' };
180
+ if (t === 'function') {
181
+ const name = (() => { try { const n = Object.getOwnPropertyDescriptor(value, 'name')?.value; return typeof n === 'string' && isPrintable(n) && n ? clip(n, TYPE_MAX) : undefined; } catch { return undefined; } })();
182
+ return { u: 'function', ...(name ? { type: name } : {}) };
183
+ }
184
+ if (t === 'symbol') return { u: 'symbol' };
185
+ if (t === 'bigint') return { u: 'bigint', text: clip(String(value), TEXT_MAX) };
186
+ if (t === 'number') return { u: 'number', text: String(value) };
187
+ const tag = Object.prototype.toString.call(value);
188
+ const type = typeName(value);
189
+ if (tag === '[object Date]') { let text; try { text = Number.isFinite(value.getTime()) ? value.toISOString() : 'Invalid Date'; } catch { text = undefined; } return { u: 'Date', ...(text ? { text } : {}) }; }
190
+ if (tag === '[object RegExp]') { let text; try { text = clip(String(RegExp.prototype.toString.call(value)), TEXT_MAX); } catch { text = undefined; } return { u: 'RegExp', ...(text ? { text } : {}) }; }
191
+ if (tag === '[object Error]' || tag === '[object DOMException]') {
192
+ let text;
193
+ try { const d = Object.getOwnPropertyDescriptor(value, 'message'); text = d && typeof d.value === 'string' ? clip(d.value, TEXT_MAX) : undefined; } catch { /* unreadable */ }
194
+ return { u: 'Error', ...(type ? { type } : {}), ...(text ? { text } : {}) };
195
+ }
196
+ return { u: 'object', ...(type ? { type } : {}) };
197
+ }
198
+
199
+ const isBytes = (v) => v instanceof ArrayBuffer || ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === '[object ArrayBuffer]';
200
+ const isPlainObject = (v) => {
201
+ if (v === null || typeof v !== 'object') return false;
202
+ const proto = Object.getPrototypeOf(v);
203
+ return proto === null || proto === Object.prototype || (Object.getPrototypeOf(proto) === null && Object.prototype.toString.call(v) === '[object Object]' && typeName(v) === 'Object');
204
+ };
205
+ const bytesOf = (v) => {
206
+ if (v instanceof Uint8Array) return v.slice();
207
+ if (ArrayBuffer.isView(v)) return new Uint8Array(v.buffer, v.byteOffset, v.byteLength).slice();
208
+ return new Uint8Array(v).slice();
209
+ };
210
+
211
+ /**
212
+ * A value as plain data, or a named non-value, within `{ maxDepth, maxBytes }`. Returns `{ v }` or `{ u, ... }` (+ `truncated: true` when `cut` replaced a
213
+ * subtree with null because it was deeper than `depth`). Throws an `ObjectsError` naming `maxValueBytes` or `maxDepth`.
214
+ *
215
+ * Inside an object or array the rule is JSON's: a member that cannot be cloned (a function, a DOM node, a class instance, a symbol, an accessor
216
+ * property, `undefined`, a circular reference) is left out of an object and is `null` in an array. The keys `__proto__`, `constructor` and
217
+ * `prototype` are never copied. Nothing of the value is called: no getter, no `toJSON`.
218
+ */
219
+ export function toWire(value, { maxDepth = OBJECTS_DEFAULT_LIMITS.maxDepth, maxBytes = OBJECTS_DEFAULT_LIMITS.maxValueBytes, cut = false } = {}) {
220
+ let bytes = 0;
221
+ let truncated = false;
222
+ const spend = (n) => { bytes += n; if (bytes > maxBytes) throw limitError('maxValueBytes', maxBytes, 'the value is larger than that'); };
223
+ const ancestors = new Set();
224
+
225
+ /** `NOTHING` for a member to leave out. */
226
+ const NOTHING = Symbol('nothing');
227
+ function copy(v, depth) {
228
+ switch (typeof v) {
229
+ case 'boolean': spend(1); return v;
230
+ case 'string': spend(utf8Length(v) + 3); return v;
231
+ case 'number':
232
+ // An integer past 2^64 does not survive the wire's integer encoding: name it instead.
233
+ if (Number.isFinite(v) && Number.isInteger(v) && Math.abs(v) >= 2 ** 63) return NOTHING;
234
+ spend(9); return v;
235
+ case 'undefined': case 'function': case 'symbol': case 'bigint': return NOTHING;
236
+ default: break;
237
+ }
238
+ if (v === null) { spend(1); return null; }
239
+ if (isBytes(v)) { const b = bytesOf(v); spend(b.byteLength + 5); return b; }
240
+ const isArr = Array.isArray(v);
241
+ if (!isArr && !isPlainObject(v)) return NOTHING;
242
+ if (ancestors.has(v)) return NOTHING;
243
+ if (depth >= maxDepth) {
244
+ if (cut) { truncated = true; return null; }
245
+ throw limitError('maxDepth', maxDepth, 'the value nests deeper than that');
246
+ }
247
+ ancestors.add(v);
248
+ try {
249
+ if (isArr) {
250
+ const out = [];
251
+ const length = Math.min(v.length, maxBytes);
252
+ spend(5);
253
+ for (let i = 0; i < length; i++) {
254
+ const d = Object.getOwnPropertyDescriptor(v, i);
255
+ const item = d && 'value' in d ? copy(d.value, depth + 1) : NOTHING;
256
+ if (item === NOTHING) { spend(1); out.push(null); } else out.push(item);
257
+ }
258
+ return out;
259
+ }
260
+ const out = {};
261
+ spend(5);
262
+ for (const key of Object.keys(v)) {
263
+ if (ALWAYS_REFUSED.has(key)) continue;
264
+ const d = Object.getOwnPropertyDescriptor(v, key);
265
+ if (!d || !('value' in d)) continue; // an accessor is never called by a copy
266
+ const item = copy(d.value, depth + 1);
267
+ if (item === NOTHING) continue;
268
+ spend(utf8Length(key) + 3);
269
+ out[key] = item;
270
+ }
271
+ return out;
272
+ } finally { ancestors.delete(v); }
273
+ }
274
+
275
+ const top = copy(value, 0);
276
+ if (top === NOTHING) return nonValue(value);
277
+ return { v: top, ...(truncated ? { truncated: true } : {}) };
278
+ }
279
+
280
+ /** What a value sent TO this side may be: plain data only, copied; anything else is refused. */
281
+ export function fromWire(value, { maxDepth = OBJECTS_DEFAULT_LIMITS.maxDepth, maxBytes = OBJECTS_DEFAULT_LIMITS.maxValueBytes } = {}) {
282
+ let bytes = 0;
283
+ const spend = (n) => { bytes += n; if (bytes > maxBytes) throw limitError('maxValueBytes', maxBytes, 'a sent value is larger than that'); };
284
+ function copy(v, depth) {
285
+ switch (typeof v) {
286
+ case 'boolean': spend(1); return v;
287
+ case 'string': spend(utf8Length(v) + 3); return v;
288
+ case 'number': spend(9); return v;
289
+ default: break;
290
+ }
291
+ if (v === null) { spend(1); return null; }
292
+ if (v instanceof Uint8Array) { spend(v.byteLength + 5); return v.slice(); }
293
+ if (depth >= maxDepth) throw limitError('maxDepth', maxDepth, 'a sent value nests deeper than that');
294
+ if (Array.isArray(v)) { spend(5); return v.map((x) => copy(x, depth + 1)); }
295
+ if (typeof v === 'object') {
296
+ // Anything but a plain object is refused, whatever its prototype turns out to be after decoding.
297
+ const proto = Object.getPrototypeOf(v);
298
+ if (proto !== Object.prototype && proto !== null) throw invalid('an argument must be plain data (an object with a prototype of its own was sent)');
299
+ const out = {};
300
+ spend(5);
301
+ for (const key of Object.keys(v)) {
302
+ if (ALWAYS_REFUSED.has(key)) throw refuse('always-refused', `refused: a sent object has the key "${key}", which is never accepted`);
303
+ spend(utf8Length(key) + 3);
304
+ out[key] = copy(v[key], depth + 1);
305
+ }
306
+ return out;
307
+ }
308
+ throw invalid(`an argument of type ${typeof v} cannot be sent: only plain data crosses`);
309
+ }
310
+ return copy(value, 0);
311
+ }
312
+
313
+ // ── The server ──────────────────────────────────────────────────────────────────────────────────────────────────────
314
+
315
+ const isTimerCallee = (key) => STRING_TIMERS.has(bareName(key));
316
+
317
+ function isPromiseLike(v) {
318
+ return v !== null && typeof v === 'object' && Object.prototype.toString.call(v) === '[object Promise]';
319
+ }
320
+
321
+ /**
322
+ * The server half: roots, allow-lists and limits, attachable to any peer.
323
+ *
324
+ * @param {object} options
325
+ * @param {Record<string, unknown>} options.roots - the objects that can be reached, by name. Nothing else is.
326
+ * @param {'values'} [options.mode='values']
327
+ * @param {{ get?: string[], call?: string[], set?: string[] }} [options.allow] - path patterns by operation, from a root (`'window.document.title'`,
328
+ * `'window.app.**'`). Nothing is allowed by default. `call` covers `construct`. An entry for a path that needs listing
329
+ * (`NEEDS_LISTING`) must name it.
330
+ * @param {(who: object, op: { kind: string, root: string, path: string[], text: string }) => boolean | Promise<boolean>} [options.authorize]
331
+ * asked for every operation the allow-list let through; anything but `true` refuses.
332
+ * @param {Partial<typeof OBJECTS_DEFAULT_LIMITS>} [options.limits]
333
+ * @param {() => string | null} [options.guard] - why nothing may be served any more (the window left), else null
334
+ * @param {{ setTimeout(fn: () => void, ms: number): any, clearTimeout(id: any): void } | null} [options.timers] - for `callTimeoutMs`; without them a call that
335
+ * returns a promise is waited for until it settles or the request is cancelled (this module reaches for no global)
336
+ * @param {() => number} [options.now]
337
+ */
338
+ export function createObjectsServer(options = {}) {
339
+ const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, now = () => Date.now() } = options;
340
+ if (mode === 'handles') throw new TypeError("exposeObjects: mode 'handles' is not built: only 'values' exists (handles, events and callbacks are a later step of #190)");
341
+ if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values'");
342
+ if (typeof allow === 'string') throw new TypeError('exposeObjects: allow must be { get, call, set } (the wide-open form belongs to mode handles, which is not built)');
343
+ if (!allow || typeof allow !== 'object' || Array.isArray(allow)) throw new TypeError('exposeObjects: allow must be { get, call, set }');
344
+ for (const k of Object.keys(allow)) if (!['get', 'call', 'set'].includes(k)) throw new TypeError(`exposeObjects: allow.${k} is not an operation (get, call, set)`);
345
+ if (!roots || typeof roots !== 'object' || Array.isArray(roots)) throw new TypeError('exposeObjects: roots must be an object of { name: object }: the named roots are all that is reachable');
346
+ const rootNames = Object.keys(roots);
347
+ if (rootNames.length === 0) throw new TypeError('exposeObjects: at least one root is needed');
348
+ for (const name of rootNames) {
349
+ if (!/^[A-Za-z_$][A-Za-z0-9_$-]{0,63}$/.test(name) || ALWAYS_REFUSED.has(name)) throw new TypeError(`exposeObjects: root name ${JSON.stringify(name)} is not allowed`);
350
+ if (roots[name] === null || (typeof roots[name] !== 'object' && typeof roots[name] !== 'function')) throw new TypeError(`exposeObjects: root "${name}" must be an object`);
351
+ }
352
+ if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('exposeObjects: authorize must be a function (who, op) => boolean');
353
+ const limits = { ...OBJECTS_DEFAULT_LIMITS };
354
+ for (const [k, v] of Object.entries(limitOptions)) {
355
+ if (!(k in OBJECTS_DEFAULT_LIMITS)) throw new TypeError(`exposeObjects: unknown limit ${JSON.stringify(k)} (${Object.keys(OBJECTS_DEFAULT_LIMITS).join(', ')})`);
356
+ if (!Number.isSafeInteger(v) || v < 1) throw new TypeError(`exposeObjects: limits.${k} must be a positive integer`);
357
+ limits[k] = v;
358
+ }
359
+ const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set') };
360
+ const every = [...lists.get, ...lists.call, ...lists.set];
361
+
362
+ /** The checks every operation passes, in order. `terminal` ones need the operation's own list; the rest need only to walk toward something allowed. */
363
+ async function check(kind, root, segs, who, { terminal }) {
364
+ const gone = guard?.();
365
+ if (gone) throw refuse('gone', `refused: ${gone}`);
366
+ const rel = segs.slice(1).map(bareName);
367
+ const own = lists[kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind];
368
+ // 1. the allow-list: the operation's own list for the operation itself, any list for walking toward something
369
+ if (terminal) {
370
+ if (!own.some((p) => matchPath(p, segs))) throw refuse('not-allowed', `refused: ${kind} of ${segs.join('.')} is not in the allow-list`, { path: segs.join('.'), op: kind });
371
+ } else if (!every.some((p) => prefixPath(p, segs))) {
372
+ throw refuse('not-allowed', `refused: ${segs.join('.')} is not on the way to anything the allow-list names`, { path: segs.join('.') });
373
+ }
374
+ // 2. what a wildcard does not cover: the operation itself needs an entry that names it; walking toward one needs only that some entry that names it goes that way
375
+ for (const seq of NEEDS_LISTING) {
376
+ if (!containsSequence(rel, seq)) continue;
377
+ const listed = terminal ? own.some((p) => matchPath(p, segs) && patternNames(p, seq)) : every.some((p) => prefixPath(p, segs) && patternNames(p, seq));
378
+ if (!listed) throw refuse('needs-listing', `refused: "${rel.join('.')}" is refused until an allow-list entry names ${seq.join('.')} (a wildcard does not)`, { path: segs.join('.') });
379
+ }
380
+ if (terminal && authorize) {
381
+ let ok = false;
382
+ try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.') })) === true; } catch { ok = false; }
383
+ if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
384
+ }
385
+ }
386
+
387
+ const readKey = (holder, key) => {
388
+ if (holder === null || holder === undefined) throw new ObjectsError(OBJECTS_ERROR.FAILED, `cannot read "${key}" of ${holder === null ? 'null' : 'undefined'}`, { reason: 'bad-path' });
389
+ return Reflect.get(Object(holder), key, holder);
390
+ };
391
+ const wrapThrown = (e, where) => {
392
+ if (e instanceof ObjectsError) return e;
393
+ let message;
394
+ try { message = clip(String(e?.message ?? e ?? ''), TEXT_MAX); } catch { message = ''; }
395
+ return new ObjectsError(OBJECTS_ERROR.FAILED, `${where} threw: ${message || 'an error'}`, { reason: 'threw' });
396
+ };
397
+
398
+ /** A call that returns a promise is waited for, until it settles, the request is cancelled, or `callTimeoutMs` (when timers were given). */
399
+ async function settle(value, ctx) {
400
+ if (!isPromiseLike(value)) return value;
401
+ let timer = null;
402
+ const waits = [value];
403
+ if (timers) {
404
+ const timeout = new Promise((_, reject) => { timer = timers.setTimeout(() => reject(limitError('callTimeoutMs', limits.callTimeoutMs, 'the call did not settle in time')), limits.callTimeoutMs); });
405
+ timeout.catch(() => {});
406
+ waits.push(timeout);
407
+ }
408
+ if (ctx.signal) {
409
+ const aborted = new Promise((_, reject) => ctx.signal.addEventListener('abort', () => reject(new ObjectsError(OBJECTS_ERROR.FAILED, 'the request was cancelled', { reason: 'cancelled' })), { once: true }));
410
+ aborted.catch(() => {});
411
+ waits.push(aborted);
412
+ }
413
+ try { return await Promise.race(waits); } finally { if (timer !== null) timers.clearTimeout(timer); }
414
+ }
415
+
416
+ async function resolve(params, ctx) {
417
+ const root = requireRoot(params);
418
+ const ops = params.ops;
419
+ if (!Array.isArray(ops)) throw invalid('ops must be an array');
420
+ if (ops.length > limits.maxOps) throw limitError('maxOps', limits.maxOps, `${ops.length} operations in one request`);
421
+ let cur = roots[root];
422
+ let segs = [root];
423
+ for (let i = 0; i < ops.length; i++) {
424
+ const op = ops[i];
425
+ const last = i === ops.length - 1;
426
+ if (op === null || typeof op !== 'object' || Array.isArray(op)) throw invalid('an operation must be an object');
427
+ const names = ['get', 'call', 'construct'].filter((k) => Object.hasOwn(op, k));
428
+ if (names.length !== 1) throw invalid('an operation names exactly one of get, call, construct');
429
+ const kind = names[0];
430
+ const key = checkKey(op[kind]);
431
+ const next = [...segs, key];
432
+ if (kind === 'get') {
433
+ if (typeof cur === 'function' && FUNCTION_REFLECTION.has(key)) throw refuse('always-refused', `refused: "${key}" of a function re-aims it and is never reachable`);
434
+ await check('get', root, next, ctx.who, { terminal: last });
435
+ try { cur = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
436
+ segs = next;
437
+ continue;
438
+ }
439
+ // call / construct
440
+ if (kind === 'call' && typeof cur === 'function' && FUNCTION_REFLECTION.has(key)) throw refuse('always-refused', `refused: "${key}" of a function re-aims it and is never reachable`);
441
+ await check(kind, root, next, ctx.who, { terminal: true });
442
+ const args = op.args === undefined ? [] : op.args;
443
+ if (!Array.isArray(args)) throw invalid('args must be an array');
444
+ if (args.length > limits.maxArgs) throw limitError('maxArgs', limits.maxArgs, `${args.length} arguments`);
445
+ const clean = fromWire(args, limits);
446
+ if (kind === 'call' && isTimerCallee(key) && typeof clean[0] === 'string') throw refuse('always-refused', `refused: ${key} with a string would evaluate it`);
447
+ let fn;
448
+ try { fn = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
449
+ if (typeof fn !== 'function') throw new ObjectsError(OBJECTS_ERROR.FAILED, `${next.join('.')} is not a function`, { reason: 'not-a-function' });
450
+ try {
451
+ const out = kind === 'call' ? Reflect.apply(fn, cur, clean) : Reflect.construct(fn, clean);
452
+ cur = kind === 'call' ? await settle(out, ctx) : out;
453
+ } catch (e) { throw wrapThrown(e, next.join('.')); }
454
+ segs = [...segs, `${key}()`];
455
+ }
456
+ return toWire(cur, { maxDepth: limits.maxDepth, maxBytes: ctx.maxBytes ?? limits.maxValueBytes });
457
+ }
458
+
459
+ function requireRoot(params) {
460
+ if (params === null || typeof params !== 'object') throw invalid('params must be an object');
461
+ const root = params.root;
462
+ if (typeof root !== 'string' || !Object.hasOwn(roots, root)) throw new ObjectsError(OBJECTS_ERROR.INVALID, `no such root: ${JSON.stringify(typeof root === 'string' ? clip(root, 64) : root)}`, { reason: 'no-such-root' });
463
+ return root;
464
+ }
465
+
466
+ /** Walk `path` (an array of keys) as traversal only; the holder and its path. */
467
+ async function walk(root, path, who) {
468
+ if (!Array.isArray(path)) throw invalid('path must be an array');
469
+ if (path.length > limits.maxOps) throw limitError('maxOps', limits.maxOps, `a path of ${path.length} segments`);
470
+ let cur = roots[root];
471
+ let segs = [root];
472
+ for (const raw of path) {
473
+ const key = checkKey(raw);
474
+ if (typeof cur === 'function' && FUNCTION_REFLECTION.has(key)) throw refuse('always-refused', `refused: "${key}" of a function re-aims it and is never reachable`);
475
+ const next = [...segs, key];
476
+ await check('get', root, next, who, { terminal: false });
477
+ try { cur = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
478
+ segs = next;
479
+ }
480
+ return { cur, segs };
481
+ }
482
+
483
+ async function setValue(params, ctx) {
484
+ const root = requireRoot(params);
485
+ const path = params.path;
486
+ if (!Array.isArray(path) || path.length === 0) throw invalid('set needs a path of at least one segment');
487
+ const { cur: parent, segs } = await walk(root, path.slice(0, -1), ctx.who);
488
+ const key = checkKey(path[path.length - 1]);
489
+ const target = [...segs, key];
490
+ await check('set', root, target, ctx.who, { terminal: true });
491
+ if (parent === null || (typeof parent !== 'object' && typeof parent !== 'function')) throw new ObjectsError(OBJECTS_ERROR.FAILED, `cannot set "${key}" on ${segs.join('.')}: it is not an object`, { reason: 'bad-path' });
492
+ const value = fromWire(params.value, limits);
493
+ let ok;
494
+ try { ok = Reflect.set(parent, key, value, parent); } catch (e) { throw wrapThrown(e, `setting ${target.join('.')}`); }
495
+ if (!ok) throw new ObjectsError(OBJECTS_ERROR.FAILED, `${target.join('.')} refused the assignment (read-only or frozen)`, { reason: 'refused-by-object' });
496
+ return { ok: true };
497
+ }
498
+
499
+ function kindOf(v) {
500
+ if (v === null) return 'null';
501
+ const t = typeof v;
502
+ return t === 'object' ? (Array.isArray(v) ? 'array' : 'object') : t;
503
+ }
504
+
505
+ async function describe(params, ctx) {
506
+ const root = requireRoot(params);
507
+ const { cur, segs } = await walk(root, params.path ?? [], ctx.who);
508
+ await check('describe', root, segs, ctx.who, { terminal: false });
509
+ if (cur === null || (typeof cur !== 'object' && typeof cur !== 'function')) return { type: kindOf(cur), keys: [] };
510
+ const keys = [];
511
+ const seen = new Set();
512
+ let object = cur;
513
+ let own = true;
514
+ for (let hops = 0; object && hops < 6 && keys.length < limits.maxKeys; hops++, object = Object.getPrototypeOf(object), own = false) {
515
+ if (object === Object.prototype || object === Function.prototype) break;
516
+ let names;
517
+ try { names = Reflect.ownKeys(object); } catch { break; }
518
+ for (const name of names) {
519
+ if (typeof name !== 'string' || seen.has(name) || ALWAYS_REFUSED.has(name) || name.includes('.')) continue;
520
+ seen.add(name);
521
+ const child = [...segs, name];
522
+ if (!every.some((p) => prefixPath(p, child))) continue; // a name the caller could not walk to is not told
523
+ let d;
524
+ try { d = Object.getOwnPropertyDescriptor(object, name); } catch { continue; }
525
+ keys.push({ key: name, type: d && 'value' in d ? kindOf(d.value) : 'accessor', own });
526
+ if (keys.length >= limits.maxKeys) break;
527
+ }
528
+ }
529
+ return { type: kindOf(cur), keys, ...(keys.length >= limits.maxKeys ? { truncated: true } : {}) };
530
+ }
531
+
532
+ async function snapshot(params, ctx) {
533
+ const root = requireRoot(params);
534
+ const { cur, segs } = await walk(root, params.path ?? [], ctx.who);
535
+ await check('snapshot', root, segs, ctx.who, { terminal: true });
536
+ const depth = params.depth === undefined ? limits.maxDepth : Number.isSafeInteger(params.depth) && params.depth >= 0 ? Math.min(params.depth, limits.maxDepth) : (() => { throw invalid('depth must be a whole number'); })();
537
+ const ceiling = ctx.maxBytes ?? limits.maxValueBytes;
538
+ const wanted = params.maxBytes === undefined ? ceiling : Number.isSafeInteger(params.maxBytes) && params.maxBytes > 0 ? Math.min(params.maxBytes, ceiling) : (() => { throw invalid('maxBytes must be a positive whole number'); })();
539
+ return toWire(cur, { maxDepth: depth, maxBytes: wanted, cut: true });
540
+ }
541
+
542
+ /** Register the protocol's methods on a peer. `who` is the identity of every call unless the transport gives one per call. */
543
+ function attach(peer, { who } = {}) {
544
+ if (typeof peer?.onRequest !== 'function') throw new TypeError('attach: the peer needs onRequest(method, handler)');
545
+ const stamps = [];
546
+ const method = (name, fn) => peer.onRequest(name, async (params, ctx = {}) => {
547
+ const t = now();
548
+ while (stamps.length && t - stamps[0] >= 1000) stamps.shift();
549
+ if (stamps.length >= limits.maxRequestsPerSecond) throw limitError('maxRequestsPerSecond', limits.maxRequestsPerSecond, 'too many requests in a second');
550
+ stamps.push(t);
551
+ // A value is kept under what the transport carries in one message, with room for the envelope.
552
+ const maxBytes = Math.min(limits.maxValueBytes, Math.max(1024, (peer.maxMessageBytes ?? Infinity) - 4096));
553
+ const call = { ...ctx, signal: ctx.signal, who: ctx.who ?? who, maxBytes };
554
+ if (params === null || typeof params !== 'object' || Array.isArray(params)) throw invalid('params must be an object');
555
+ try { return await fn(params, call); } catch (e) { if (e instanceof ObjectsError) throw e; throw wrapThrown(e, name); }
556
+ });
557
+ method('roots', async () => ({ roots: rootNames.slice() }));
558
+ method('resolve', resolve);
559
+ method('set', setValue);
560
+ method('describe', describe);
561
+ method('snapshot', snapshot);
562
+ return { limits };
563
+ }
564
+
565
+ return { attach, limits: Object.freeze({ ...limits }), rootNames: rootNames.slice() };
566
+ }
567
+
568
+ // ── A bare duplex as a peer ─────────────────────────────────────────────────────────────────────────────────────────
569
+
570
+ /**
571
+ * A `Peer` over `send(message)` and `receive(message)` (JSON-RPC-shaped plain objects: requests `{ id, method, params }`, responses
572
+ * `{ id, result }` / `{ id, error }`, notifications `{ method, params }`, and `$/cancel` and `$/progress`). For a transport that is not wsh.
573
+ * @param {{ send(message: object): void, maxMessageBytes?: number }} options
574
+ */
575
+ export function createDuplexPeer({ send, maxMessageBytes = 1024 * 1024 } = {}) {
576
+ if (typeof send !== 'function') throw new TypeError('createDuplexPeer: send(message) is required');
577
+ let nextId = 1;
578
+ let closed = false;
579
+ const pending = new Map();
580
+ const inflight = new Map();
581
+ const handlers = new Map();
582
+ const notifications = new Map();
583
+ const peer = {
584
+ maxMessageBytes,
585
+ onClose: null,
586
+ get closed() { return closed; },
587
+ onRequest(method, handler) { handlers.set(method, handler); },
588
+ onNotification(method, handler) { notifications.set(method, handler); },
589
+ notify(method, params) { if (!closed) send({ method, ...(params !== undefined ? { params } : {}) }); },
590
+ request(method, params, { signal, onProgress } = {}) {
591
+ if (closed) return Promise.reject(new ObjectsError(OBJECTS_ERROR.FAILED, 'the connection is closed', { reason: 'closed' }));
592
+ const id = nextId++;
593
+ return new Promise((resolve, reject) => {
594
+ const settle = () => { pending.delete(id); signal?.removeEventListener?.('abort', onAbort); };
595
+ const onAbort = () => { if (!pending.has(id)) return; settle(); send({ method: '$/cancel', params: { id } }); reject(new ObjectsError(OBJECTS_ERROR.FAILED, 'the request was cancelled', { reason: 'cancelled' })); };
596
+ pending.set(id, { resolve: (v) => { settle(); resolve(v); }, reject: (e) => { settle(); reject(e); }, onProgress });
597
+ if (signal?.aborted) { onAbort(); return; }
598
+ signal?.addEventListener?.('abort', onAbort, { once: true });
599
+ send({ id, method, ...(params !== undefined ? { params } : {}) });
600
+ });
601
+ },
602
+ receive(message) {
603
+ if (closed || message === null || typeof message !== 'object') return;
604
+ if (typeof message.method === 'string') {
605
+ if (message.id === undefined) {
606
+ if (message.method === '$/cancel') { inflight.get(message.params?.id)?.abort(new ObjectsError(OBJECTS_ERROR.FAILED, 'cancelled', { reason: 'cancelled' })); return; }
607
+ if (message.method === '$/progress') { pending.get(message.params?.id)?.onProgress?.(message.params.chunk); return; }
608
+ try { notifications.get(message.method)?.(message.params); } catch { /* a notification has no one to tell */ }
609
+ return;
610
+ }
611
+ const handler = handlers.get(message.method);
612
+ const id = message.id;
613
+ if (!handler) { send({ id, error: { code: -32601, message: `method not found: ${message.method}` } }); return; }
614
+ const ctl = new AbortController();
615
+ inflight.set(id, ctl);
616
+ const ctx = { signal: ctl.signal, progress: (chunk) => send({ method: '$/progress', params: { id, chunk } }) };
617
+ Promise.resolve().then(() => handler(message.params, ctx)).then(
618
+ (result) => { if (ctl.signal.aborted) return; send({ id, result: result === undefined ? null : result }); },
619
+ (e) => { if (ctl.signal.aborted) return; send({ id, error: { code: e?.code ?? OBJECTS_ERROR.FAILED, message: String(e?.message ?? e), ...(e?.data ? { data: e.data } : {}) } }); },
620
+ ).finally(() => inflight.delete(id));
621
+ return;
622
+ }
623
+ const p = pending.get(message.id);
624
+ if (!p) return;
625
+ if (message.error) p.reject(new ObjectsError(message.error.code ?? OBJECTS_ERROR.FAILED, String(message.error.message ?? 'error'), message.error.data));
626
+ else p.resolve(message.result);
627
+ },
628
+ close(reason = 'closed') {
629
+ if (closed) return;
630
+ closed = true;
631
+ for (const p of [...pending.values()]) p.reject(new ObjectsError(OBJECTS_ERROR.FAILED, `the connection closed (${reason})`, { reason: 'closed' }));
632
+ pending.clear();
633
+ for (const ctl of inflight.values()) ctl.abort(new ObjectsError(OBJECTS_ERROR.FAILED, 'closed', { reason: 'closed' }));
634
+ try { peer.onClose?.(reason); } catch { /* ignore */ }
635
+ },
636
+ };
637
+ return peer;
638
+ }
639
+
640
+ // ── The client: lazy references ─────────────────────────────────────────────────────────────────────────────────────
641
+
642
+ const BRAND = Symbol.for('wsh.objects.ref');
643
+ const SESSION = Symbol.for('wsh.objects.session');
644
+
645
+ /** What a remote value that cannot be cloned arrives as: named, never a handle. */
646
+ export class NonValue {
647
+ /** @param {{ u: string, type?: string, text?: string }} wire */
648
+ constructor(wire) {
649
+ this.kind = wire.u;
650
+ if (wire.type !== undefined) this.type = wire.type;
651
+ if (wire.text !== undefined) this.text = wire.text;
652
+ Object.freeze(this);
653
+ }
654
+
655
+ toString() { return `[remote ${this.kind}${this.type ? ` ${this.type}` : ''}${this.text ? `: ${this.text}` : ''}]`; }
656
+ }
657
+
658
+ const decodeResult = (res) => {
659
+ if (res && typeof res === 'object' && 'u' in res) return res.u === 'undefined' ? undefined : new NonValue(res);
660
+ return res?.v;
661
+ };
662
+
663
+ function asObjectsError(e, session) {
664
+ if (e instanceof ObjectsError) return e;
665
+ const closing = session?.closing ? ` (${session.closing})` : '';
666
+ const message = `${String(e?.message ?? e)}${/closed|cancel/i.test(String(e?.message)) ? closing : ''}`;
667
+ return new ObjectsError(Number.isInteger(e?.code) ? e.code : OBJECTS_ERROR.FAILED, message, e?.data);
668
+ }
669
+
670
+ const stateOf = (ref) => {
671
+ const state = ref !== null && (typeof ref === 'function' || typeof ref === 'object') ? ref[BRAND] : undefined;
672
+ if (!state) throw new TypeError('expected a remote reference (what openObjects() returns, and what you reach from it)');
673
+ return state;
674
+ };
675
+
676
+ /** A function (a callback, or a remote reference, which is a function to the engine) cannot be sent: only plain data crosses, and a reference is a path, not a value. */
677
+ function plainArgs(args) {
678
+ let visits = 0;
679
+ const walk = (v, depth) => {
680
+ if (typeof v === 'function') throw new TypeError('a function or a remote reference cannot be sent as an argument: only plain data crosses (a reference is a path: await it to get its value first)');
681
+ if (v === null || typeof v !== 'object' || depth > 8 || ++visits > 2000) return;
682
+ if (ArrayBuffer.isView(v)) return;
683
+ for (const k of Object.keys(v)) walk(v[k], depth + 1);
684
+ };
685
+ walk(args, 0);
686
+ return args;
687
+ }
688
+
689
+ function makeRef(session, root, ops) {
690
+ const state = { session, root, ops };
691
+ const readOnly = (what) => () => { throw new TypeError(what); };
692
+ const handler = {
693
+ get(_target, key) {
694
+ if (key === BRAND) return state;
695
+ if (typeof key === 'symbol') return undefined; // Symbol.toPrimitive, Symbol.asyncIterator, inspect hooks: not remote properties
696
+ if (key === 'then') {
697
+ // `await ref` sends the whole chain in ONE request. A remote property really named "then" is reached with get(ref, 'then').
698
+ return (onFulfilled, onRejected) => send(state).then(onFulfilled, onRejected);
699
+ }
700
+ return makeRef(session, root, [...ops, { get: key }]);
701
+ },
702
+ set(_t, key) { throw new TypeError(`cannot assign to ${String(key)} of a remote reference with "=": assignment cannot be awaited or report a refusal. Use await set(ref, ${JSON.stringify(String(key))}, value)`); },
703
+ defineProperty: readOnly('a remote reference cannot be defined on: use set(ref, key, value)'),
704
+ deleteProperty: readOnly('a remote reference cannot be deleted from'),
705
+ setPrototypeOf: readOnly('the prototype of a remote reference cannot be set'),
706
+ apply(_t, _this, args) {
707
+ const last = ops[ops.length - 1];
708
+ if (!last || !('get' in last)) throw new TypeError('only a method reached by name can be called (win.app.cart.add(x)); call a path, not a result');
709
+ return makeRef(session, root, [...ops.slice(0, -1), { call: last.get, args: plainArgs(args) }]);
710
+ },
711
+ construct(_t, args) {
712
+ const last = ops[ops.length - 1];
713
+ if (!last || !('get' in last)) throw new TypeError('only a constructor reached by name can be constructed (new win.app.Cart())');
714
+ return makeRef(session, root, [...ops.slice(0, -1), { construct: last.get, args: plainArgs(args) }]);
715
+ },
716
+ };
717
+ // A function as the target so the proxy can be called and constructed.
718
+ return new Proxy(function remote() {}, handler);
719
+ }
720
+
721
+ async function send(state, { signal } = {}) {
722
+ const { session, root, ops } = state;
723
+ try {
724
+ return decodeResult(await session.peer.request('resolve', { root, ops }, { signal, ...(session.timeoutMs ? { timeoutMs: session.timeoutMs } : {}) }));
725
+ } catch (e) { throw asObjectsError(e, session); }
726
+ }
727
+
728
+ /** A reference that is a pure path (no call in it): what `set`, `describe` and `snapshot` take. */
729
+ function pathOf(ref, what) {
730
+ const state = stateOf(ref);
731
+ const keys = [];
732
+ for (const op of state.ops) {
733
+ if (!('get' in op)) throw new TypeError(`${what} needs a plain path (a reference with no call in it): await the call first, or name the path`);
734
+ keys.push(op.get);
735
+ }
736
+ return { state, keys };
737
+ }
738
+
739
+ /** Read a property of a reference (also one named `then`, which `ref.then` cannot reach), or with no key, the reference itself. */
740
+ export function get(ref, ...keys) {
741
+ const state = stateOf(ref);
742
+ return send({ ...state, ops: [...state.ops, ...keys.map((k) => ({ get: String(k) }))] });
743
+ }
744
+
745
+ /** Assign a property of a remote object: `await set(win.document, 'title', 'Paid')`. Not `=`: an assignment cannot be awaited or report a refusal. */
746
+ export async function set(ref, key, value) {
747
+ const { state, keys } = pathOf(ref, 'set');
748
+ plainArgs([value]);
749
+ try { await state.session.peer.request('set', { root: state.root, path: [...keys, String(key)], value }); } catch (e) { throw asObjectsError(e, state.session); }
750
+ }
751
+
752
+ /** Call a method reached by name with these (plain-data) arguments: `await call(win.app.cart.add, { sku: 'A1' })`; for a method named `then`, `call(ref, ...)`. */
753
+ export function call(ref, ...args) {
754
+ const state = stateOf(ref);
755
+ const last = state.ops[state.ops.length - 1];
756
+ if (!last || !('get' in last)) throw new TypeError('call needs a method reached by name');
757
+ return send({ ...state, ops: [...state.ops.slice(0, -1), { call: last.get, args: plainArgs(args) }] });
758
+ }
759
+
760
+ /** `new` a constructor reached by name: `await construct(win.app.Cart, 'A')`. */
761
+ export function construct(ref, ...args) {
762
+ const state = stateOf(ref);
763
+ const last = state.ops[state.ops.length - 1];
764
+ if (!last || !('get' in last)) throw new TypeError('construct needs a constructor reached by name');
765
+ return send({ ...state, ops: [...state.ops.slice(0, -1), { construct: last.get, args: plainArgs(args) }] });
766
+ }
767
+
768
+ /** A bounded deep copy: `await snapshot(win.app.state, { depth: 3, maxBytes: 256_000 })`. Subtrees deeper than `depth` are `null`. */
769
+ export async function snapshot(ref, { depth, maxBytes, signal } = {}) {
770
+ const { state, keys } = pathOf(ref, 'snapshot');
771
+ try {
772
+ return decodeResult(await state.session.peer.request('snapshot', { root: state.root, path: keys, ...(depth !== undefined ? { depth } : {}), ...(maxBytes !== undefined ? { maxBytes } : {}) }, { signal }));
773
+ } catch (e) { throw asObjectsError(e, state.session); }
774
+ }
775
+
776
+ /** The shape of an object, for a REPL or completion: `{ type, keys: [{ key, type, own }] }`. Only names the allow-list could walk to are told. */
777
+ export async function describe(ref, { signal } = {}) {
778
+ const { state, keys } = pathOf(ref, 'describe');
779
+ try { return await state.session.peer.request('describe', { root: state.root, path: keys }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
780
+ }
781
+
782
+ /**
783
+ * The client half over any peer: asks for the roots and returns them as lazy references, `{ window }`.
784
+ * @param {object} peer
785
+ * @param {{ timeoutMs?: number }} [options]
786
+ */
787
+ export async function createObjectsClient(peer, { timeoutMs } = {}) {
788
+ if (typeof peer?.request !== 'function') throw new TypeError('createObjectsClient: the peer needs request(method, params)');
789
+ const session = { peer, closing: null, timeoutMs };
790
+ peer.onNotification?.('closing', (params) => { session.closing = typeof params?.reason === 'string' ? clip(params.reason, TEXT_MAX) : 'closing'; });
791
+ let roots;
792
+ try { roots = (await peer.request('roots', {}))?.roots; } catch (e) { throw asObjectsError(e, session); }
793
+ if (!Array.isArray(roots)) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the host did not list its roots', { reason: 'bad-reply' });
794
+ const page = {};
795
+ for (const name of roots) if (typeof name === 'string' && !ALWAYS_REFUSED.has(name)) page[name] = makeRef(session, name, []);
796
+ Object.defineProperty(page, SESSION, { value: session });
797
+ return Object.freeze(page);
798
+ }
799
+
800
+ /** End the connection behind what `openObjects()` returned. */
801
+ export async function closeObjects(page) {
802
+ const session = page?.[SESSION];
803
+ if (!session) throw new TypeError('closeObjects: expected what openObjects() returned');
804
+ await session.peer.close?.('closed by the caller');
805
+ }