@johnhenry/wsh 0.46.1 → 0.48.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.
@@ -62,6 +62,22 @@ export const OBJECTS_DEFAULT_LIMITS = Object.freeze({
62
62
  maxKeys: 200,
63
63
  /** Requests accepted per second, per attached peer. */
64
64
  maxRequestsPerSecond: 50,
65
+ /** Handles per channel (on roots that opted in): more are refused, nothing is evicted. */
66
+ maxHandles: 64,
67
+ /** Callbacks (stubs of far-side functions) per channel: more are refused. */
68
+ maxCallbacks: 16,
69
+ /** Calls of one callback per second; the rest are dropped and counted. */
70
+ maxCallbacksPerSecond: 20,
71
+ /** Bytes of the arguments of one callback call; a bigger one is dropped and counted. */
72
+ maxCallbackBytes: 16 * 1024,
73
+ /** Event subscriptions per channel. */
74
+ maxSubscriptions: 16,
75
+ /** Events delivered per second, per subscription; the rest are dropped and counted. */
76
+ maxEventsPerSecond: 20,
77
+ /** Bytes of one delivered event; a bigger one is dropped and counted. */
78
+ maxEventBytes: 16 * 1024,
79
+ /** Events waiting for the transport (credit), per channel; more are dropped and counted. */
80
+ maxQueuedEvents: 100,
65
81
  /** How long a call that returns a promise is waited for. */
66
82
  callTimeoutMs: 30_000,
67
83
  });
@@ -83,6 +99,11 @@ export const NEEDS_LISTING = Object.freeze([
83
99
  ]);
84
100
 
85
101
  const KEY_MAX = 256;
102
+ const CALLBACK_SUFFIX = '(callback)';
103
+ const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
104
+ /** On a root with handles: members that lead from a node back up to the document or window graph. Refused until an allow-list entry names them, nodes opt-in or not. */
105
+ const GRAPH_MEMBERS = Object.freeze(['ownerDocument', 'defaultView', 'parentNode', 'parentElement', 'getRootNode', 'contentWindow', 'contentDocument', 'self', 'window', 'top', 'parent', 'frames', 'opener', 'globalThis']);
106
+ const EVENT_TYPE_RE = /^[A-Za-z0-9_$:.-]{1,128}$/;
86
107
 
87
108
  function checkKey(key) {
88
109
  if (typeof key !== 'string' || key === '' || key.length > KEY_MAX) throw invalid(`a path segment must be a string of 1 to ${KEY_MAX} characters`);
@@ -97,9 +118,18 @@ function checkKey(key) {
97
118
  function compileList(list, kind) {
98
119
  if (list === undefined || list === null) return [];
99
120
  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('.');
121
+ return list.map((original) => {
122
+ if (typeof original !== 'string' || original === '') throw new TypeError(`exposeObjects: allow.${kind} entries must be non-empty strings`);
123
+ // A call entry that ends in `(callback)` says the call accepts functions as arguments (they arrive as stubs the page can call, one-way).
124
+ let entry = original;
125
+ let callbacks = false;
126
+ if (entry.endsWith(CALLBACK_SUFFIX)) {
127
+ if (kind !== 'call') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: only a call entry can accept callbacks`);
128
+ entry = entry.slice(0, -CALLBACK_SUFFIX.length);
129
+ callbacks = true;
130
+ }
131
+ if (entry.includes(CALLBACK_SUFFIX)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: "(callback)" ends an entry`);
132
+ const segs = Object.assign(entry.split('.'), { callbacks });
103
133
  for (const s of segs) {
104
134
  if (s === '') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} has an empty segment`);
105
135
  if (ALWAYS_REFUSED.has(s)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} names "${s}", which is never reachable`);
@@ -336,12 +366,18 @@ function isPromiseLike(v) {
336
366
  * @param {() => number} [options.now]
337
367
  */
338
368
  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)');
369
+ const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, handles = {}, random = null, now = () => Date.now() } = options;
370
+ if (mode === 'handles') throw new TypeError("exposeObjects: handles are chosen per root, not for the host: use handles: { window: {} } (and nodes: true on a root that may hand out nodes)");
371
+ if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values' (handles are chosen per root with handles: { ROOT: {} })");
372
+ if (typeof allow === 'string') throw new TypeError('exposeObjects: allow must be { get, call, set, on }: a wide-open string is not accepted, and the allow-lists apply to handles too');
343
373
  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)`);
374
+ for (const k of Object.keys(allow)) if (!['get', 'call', 'set', 'on'].includes(k)) throw new TypeError(`exposeObjects: allow.${k} is not an operation (get, call, set, on)`);
375
+ // The extra fields of an event a subscriber may ask for, by event type (`'*'`: any type): names of properties read from the event, copied as plain data.
376
+ if (!eventFields || typeof eventFields !== 'object' || Array.isArray(eventFields)) throw new TypeError('exposeObjects: eventFields must be { [type]: [field names] }');
377
+ for (const [type, names] of Object.entries(eventFields)) {
378
+ if (!Array.isArray(names) || !names.every((n) => typeof n === 'string' && /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(n))) throw new TypeError(`exposeObjects: eventFields[${JSON.stringify(type)}] must be an array of property names`);
379
+ for (const n of names) if (ALWAYS_REFUSED.has(n)) throw new TypeError(`exposeObjects: eventFields[${JSON.stringify(type)}] names "${n}", which is never reachable`);
380
+ }
345
381
  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
382
  const rootNames = Object.keys(roots);
347
383
  if (rootNames.length === 0) throw new TypeError('exposeObjects: at least one root is needed');
@@ -350,40 +386,85 @@ export function createObjectsServer(options = {}) {
350
386
  if (roots[name] === null || (typeof roots[name] !== 'object' && typeof roots[name] !== 'function')) throw new TypeError(`exposeObjects: root "${name}" must be an object`);
351
387
  }
352
388
  if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('exposeObjects: authorize must be a function (who, op) => boolean');
389
+ // Handles: per root, explicit. `nodes: true` is the root's own opt-in to hand out DOM nodes, windows and documents: control of the page.
390
+ if (!handles || typeof handles !== 'object' || Array.isArray(handles)) throw new TypeError('exposeObjects: handles must be { ROOT: { nodes? } }');
391
+ const handleRoots = new Map();
392
+ for (const [name, cfg] of Object.entries(handles)) {
393
+ if (!rootNames.includes(name)) throw new TypeError(`exposeObjects: handles names ${JSON.stringify(name)}, which is no such root`);
394
+ if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) throw new TypeError(`exposeObjects: handles.${name} must be an object ({ nodes?: boolean })`);
395
+ if (cfg.nodes !== undefined && typeof cfg.nodes !== 'boolean') throw new TypeError(`exposeObjects: handles.${name}.nodes must be true or false`);
396
+ if (cfg.wideEntries !== undefined && typeof cfg.wideEntries !== 'boolean') throw new TypeError(`exposeObjects: handles.${name}.wideEntries must be true or false`);
397
+ handleRoots.set(name, { nodes: cfg.nodes === true, wideEntries: cfg.wideEntries === true });
398
+ }
399
+ if (handleRoots.size && typeof random !== 'function') throw new TypeError('exposeObjects: handles need a random source (random: (n) => Uint8Array of n random bytes, from crypto.getRandomValues)');
353
400
  const limits = { ...OBJECTS_DEFAULT_LIMITS };
354
401
  for (const [k, v] of Object.entries(limitOptions)) {
355
402
  if (!(k in OBJECTS_DEFAULT_LIMITS)) throw new TypeError(`exposeObjects: unknown limit ${JSON.stringify(k)} (${Object.keys(OBJECTS_DEFAULT_LIMITS).join(', ')})`);
356
403
  if (!Number.isSafeInteger(v) || v < 1) throw new TypeError(`exposeObjects: limits.${k} must be a positive integer`);
357
404
  limits[k] = v;
358
405
  }
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];
406
+ // `on` entries are `path@type` (`'window.app.bus@ready'`): the source and the event type, both named exactly (no wildcard in either); each is compiled as a path with its type attached.
407
+ const compileOn = (list) => {
408
+ if (list === undefined || list === null) return [];
409
+ if (!Array.isArray(list)) throw new TypeError('exposeObjects: allow.on must be an array of "path@type" entries');
410
+ return list.map((entry) => {
411
+ const at = typeof entry === 'string' ? entry.indexOf('@') : -1;
412
+ const type = at < 0 ? '' : entry.slice(at + 1);
413
+ if (at <= 0) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)} must be "path@type"`);
414
+ if (/[*?]/.test(type)) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)}: list the event types one by one; a wildcard type would hand over every event of the source`);
415
+ if (!EVENT_TYPE_RE.test(type)) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)}: the event type must be a name of letters, digits and _ $ : . - (up to 128)`);
416
+ if (/\*/.test(entry.slice(0, at))) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)}: an event source is named exactly, with no wildcard in the path`);
417
+ const segs = compileList([entry.slice(0, at)], 'on')[0];
418
+ return Object.assign(segs, { type });
419
+ });
420
+ };
421
+ const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set'), on: compileOn(allow.on) };
422
+ const every = [...lists.get, ...lists.call, ...lists.set, ...lists.on];
423
+ // With handles, a wildcard in `call` or `set` lets a caller hold and reuse every object under it: the root says so (`wideEntries: true`) or lists the paths.
424
+ for (const [name, mode] of handleRoots) {
425
+ if (mode.wideEntries) continue;
426
+ for (const kind of ['call', 'set']) {
427
+ const wide = lists[kind].find((p) => (p[0] === name || p[0] === '*' || p[0] === '**') && p.some((s) => s === '*' || s === '**'));
428
+ if (wide) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(wide.join('.'))} is wide on the handles root "${name}": list the paths, or acknowledge it with handles: { ${name}: { wideEntries: true } }`);
429
+ }
430
+ }
361
431
 
362
432
  /** 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 }) {
433
+ async function check(kind, root, segs, ctx, { terminal, type, callbacks = 0 }) {
434
+ const who = ctx.who;
364
435
  const gone = guard?.();
365
436
  if (gone) throw refuse('gone', `refused: ${gone}`);
437
+ // 0. what the caller's key may do on this root, if the transport says (`ctx.permit(root, op)`, asked afresh: an expiry holds at call time)
438
+ permitted(ctx, root, kind === 'get' && !terminal ? 'walk' : kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind);
366
439
  const rel = segs.slice(1).map(bareName);
367
440
  const own = lists[kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind];
368
441
  // 1. the allow-list: the operation's own list for the operation itself, any list for walking toward something
369
442
  if (terminal) {
370
443
  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 });
444
+ if (callbacks > 0 && !own.some((p) => matchPath(p, segs) && p.callbacks)) throw refuse('not-allowed', `refused: ${segs.join('.')} does not accept callbacks (its allow-list entry would end in "${CALLBACK_SUFFIX}")`, { path: segs.join('.'), op: kind });
445
+ if (kind === 'on' && !own.some((p) => matchPath(p, segs) && p.type === type)) throw refuse('not-allowed', `refused: the event type "${type}" of ${segs.join('.')} is not in the allow-list`, { path: segs.join('.'), op: kind, type });
371
446
  } else if (!every.some((p) => prefixPath(p, segs))) {
372
447
  throw refuse('not-allowed', `refused: ${segs.join('.')} is not on the way to anything the allow-list names`, { path: segs.join('.') });
373
448
  }
374
449
  // 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) {
450
+ // On a root with handles, the members that lead back up to the document or window graph need naming as well.
451
+ for (const seq of handleRoots.has(root) ? [...NEEDS_LISTING, ...GRAPH_MEMBERS.map((n) => [n])] : NEEDS_LISTING) {
376
452
  if (!containsSequence(rel, seq)) continue;
377
453
  const listed = terminal ? own.some((p) => matchPath(p, segs) && patternNames(p, seq)) : every.some((p) => prefixPath(p, segs) && patternNames(p, seq));
378
454
  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
455
  }
380
456
  if (terminal && authorize) {
381
457
  let ok = false;
382
- try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.') })) === true; } catch { ok = false; }
458
+ try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}), ...(callbacks ? { callbacks } : {}) })) === true; } catch { ok = false; }
383
459
  if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
384
460
  }
385
461
  }
386
462
 
463
+ function permitted(ctx, root, op) {
464
+ if (typeof ctx.permit !== 'function' || ctx.permit(root, op) === true) return;
465
+ throw refuse('not-permitted', `refused: this key's capabilities do not allow ${op === 'walk' ? 'reading' : op} on ${root}`, { root, op });
466
+ }
467
+
387
468
  const readKey = (holder, key) => {
388
469
  if (holder === null || holder === undefined) throw new ObjectsError(OBJECTS_ERROR.FAILED, `cannot read "${key}" of ${holder === null ? 'null' : 'undefined'}`, { reason: 'bad-path' });
389
470
  return Reflect.get(Object(holder), key, holder);
@@ -414,12 +495,13 @@ export function createObjectsServer(options = {}) {
414
495
  }
415
496
 
416
497
  async function resolve(params, ctx) {
417
- const root = requireRoot(params);
498
+ const start = startOf(params, ctx);
499
+ const { root } = start;
418
500
  const ops = params.ops;
419
501
  if (!Array.isArray(ops)) throw invalid('ops must be an array');
420
502
  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];
503
+ let cur = start.cur;
504
+ let segs = start.segs;
423
505
  for (let i = 0; i < ops.length; i++) {
424
506
  const op = ops[i];
425
507
  const last = i === ops.length - 1;
@@ -431,29 +513,99 @@ export function createObjectsServer(options = {}) {
431
513
  const next = [...segs, key];
432
514
  if (kind === 'get') {
433
515
  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 });
516
+ await check('get', root, next, ctx, { terminal: last });
435
517
  try { cur = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
436
518
  segs = next;
437
519
  continue;
438
520
  }
439
521
  // call / construct
440
522
  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 });
523
+ // Functions of the far side, passed as arguments: `callbacks: [[index, id], ...]`, with null in `args` at those places.
524
+ const spec = op.callbacks === undefined ? [] : op.callbacks;
525
+ if (!Array.isArray(spec) || spec.length > limits.maxArgs || !spec.every((c) => Array.isArray(c) && c.length === 2 && Number.isSafeInteger(c[0]) && c[0] >= 0 && Number.isSafeInteger(c[1]) && c[1] >= 1)) throw invalid('callbacks must be [[argument index, id], ...]');
526
+ await check(kind, root, next, ctx, { terminal: true, callbacks: spec.length });
442
527
  const args = op.args === undefined ? [] : op.args;
443
528
  if (!Array.isArray(args)) throw invalid('args must be an array');
444
529
  if (args.length > limits.maxArgs) throw limitError('maxArgs', limits.maxArgs, `${args.length} arguments`);
530
+ if (spec.some(([i]) => i >= args.length || args[i] !== null) || new Set(spec.map(([i]) => i)).size !== spec.length) throw invalid('a callback takes the place of an argument, once');
445
531
  const clean = fromWire(args, limits);
532
+ const made = [];
533
+ try {
534
+ for (const [index, id] of spec) { const had = ctx.session.callbacks.has(id); const stub = makeCallback(ctx.session, id); if (!had) made.push(id); clean[index] = stub; }
535
+ } catch (e) { for (const id of made) killCallback(ctx.session, id); throw e; }
446
536
  if (kind === 'call' && isTimerCallee(key) && typeof clean[0] === 'string') throw refuse('always-refused', `refused: ${key} with a string would evaluate it`);
447
537
  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' });
538
+ try { fn = readKey(cur, key); } catch (e) { for (const id of made) killCallback(ctx.session, id); throw wrapThrown(e, `reading ${next.join('.')}`); }
539
+ if (typeof fn !== 'function') { for (const id of made) killCallback(ctx.session, id); throw new ObjectsError(OBJECTS_ERROR.FAILED, `${next.join('.')} is not a function`, { reason: 'not-a-function' }); }
450
540
  try {
451
541
  const out = kind === 'call' ? Reflect.apply(fn, cur, clean) : Reflect.construct(fn, clean);
452
542
  cur = kind === 'call' ? await settle(out, ctx) : out;
453
- } catch (e) { throw wrapThrown(e, next.join('.')); }
543
+ } catch (e) { for (const id of made) killCallback(ctx.session, id); throw wrapThrown(e, next.join('.')); }
454
544
  segs = [...segs, `${key}()`];
455
545
  }
456
- return toWire(cur, { maxDepth: limits.maxDepth, maxBytes: ctx.maxBytes ?? limits.maxValueBytes });
546
+ return finishValue(cur, root, segs, ctx);
547
+ }
548
+
549
+ // ── Handles ───────────────────────────────────────────────────────────────────────────────────────────────────────
550
+ // On a root that opted in (`handles: { ROOT: { nodes? } }`), a function or an object that is not plain data comes back as an opaque handle instead of a
551
+ // named non-value. A handle stands at the PATH that produced it (`a.b` for a get, `a.f()` for a call), and every operation through it is judged by the
552
+ // allow-lists for that path extended by the member: it never widens what the path grants. The table is per channel, bounded, never evicts.
553
+
554
+ /** Prototype-chain names of what reaches the document or window graph. */
555
+ const GRAPH_CLASSES = new Set(['Node', 'Window', 'WorkerGlobalScope', 'Document']);
556
+ function reachesGraph(value) {
557
+ try {
558
+ let proto = Object.getPrototypeOf(value);
559
+ for (let hops = 0; proto && hops < 16; hops++, proto = Object.getPrototypeOf(proto)) {
560
+ const d = Object.getOwnPropertyDescriptor(proto, 'constructor');
561
+ const name = d && 'value' in d && typeof d.value === 'function' ? Object.getOwnPropertyDescriptor(d.value, 'name')?.value : undefined;
562
+ if (GRAPH_CLASSES.has(name)) return true;
563
+ }
564
+ const tag = Object.prototype.toString.call(value);
565
+ return tag === '[object Window]' || tag === '[object global]' || tag === '[object Document]' || tag === '[object HTMLDocument]';
566
+ } catch { return true; }
567
+ }
568
+
569
+ function finishValue(cur, root, segs, ctx) {
570
+ const wire = toWire(cur, { maxDepth: limits.maxDepth, maxBytes: ctx.maxBytes ?? limits.maxValueBytes });
571
+ const mode = handleRoots.get(root);
572
+ if (!mode || !('u' in wire) || (wire.u !== 'function' && wire.u !== 'object') || !ctx.session) return wire;
573
+ if (wire.u === 'object' && reachesGraph(cur) && !mode.nodes) return wire; // a node, a window, a document: named, not a handle, without the root's own opt-in
574
+ if (wire.u === 'function' && reachesGraph(cur) && !mode.nodes) return wire;
575
+ const { session } = ctx;
576
+ if (session.handles.size >= limits.maxHandles) throw limitError('maxHandles', limits.maxHandles, 'too many handles on this channel: release some (nothing is evicted)');
577
+ const id = newHandleId();
578
+ session.handles.set(id, { root, segs: segs.slice(), value: cur });
579
+ return { h: id, kind: wire.u, ...(wire.type ? { type: wire.type } : {}), ...previewOf(cur, root, segs, ctx) };
580
+ }
581
+
582
+ function newHandleId() {
583
+ const bytes = random(16);
584
+ let out = '';
585
+ let acc = 0;
586
+ let bits = 0;
587
+ for (const b of bytes) { acc = (acc << 8) | b; bits += 8; while (bits >= 6) { bits -= 6; out += B64URL[(acc >> bits) & 63]; } }
588
+ if (bits > 0) out += B64URL[(acc << (6 - bits)) & 63];
589
+ return out;
590
+ }
591
+
592
+ /** A preview is what a `get` on the same path could reveal: the names of a few own members, and only where the get-list names the path. */
593
+ function previewOf(value, root, segs, ctx) {
594
+ if (!lists.get.some((p) => matchPath(p, segs))) return {};
595
+ if (typeof ctx.permit === 'function' && ctx.permit(root, 'get') !== true) return {};
596
+ const rel = segs.slice(1).map(bareName);
597
+ for (const seq of [...NEEDS_LISTING, ...GRAPH_MEMBERS.map((n) => [n])]) if (containsSequence(rel, seq) && !lists.get.some((p) => matchPath(p, segs) && patternNames(p, seq))) return {};
598
+ try {
599
+ // Exactly the names describe() would list: the ones the allow-lists could walk to from here.
600
+ const keys = Object.keys(value).filter((k) => !ALWAYS_REFUSED.has(k) && !k.includes('.') && k.length <= 64 && every.some((p) => prefixPath(p, [...segs, k]))).slice(0, 8);
601
+ return { preview: { keys } };
602
+ } catch { return {}; }
603
+ }
604
+
605
+ async function releaseHandle(params, ctx) {
606
+ const { session } = ctx;
607
+ if (typeof params.handle !== 'string' || !session.handles.delete(params.handle)) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
608
+ return { ok: true };
457
609
  }
458
610
 
459
611
  function requireRoot(params) {
@@ -463,17 +615,31 @@ export function createObjectsServer(options = {}) {
463
615
  return root;
464
616
  }
465
617
 
466
- /** Walk `path` (an array of keys) as traversal only; the holder and its path. */
467
- async function walk(root, path, who) {
618
+ /**
619
+ * Where a request starts: a root, or a handle of this channel (`params.handle`), which stands at the path that produced it. A handle is looked
620
+ * up in THIS channel's table by its id: another channel, another key, or a made-up id finds nothing.
621
+ */
622
+ function startOf(params, ctx) {
623
+ if (params === null || typeof params !== 'object') throw invalid('params must be an object');
624
+ if (params.handle === undefined) { const root = requireRoot(params); return { root, cur: roots[root], segs: [root] }; }
625
+ const rec = typeof params.handle === 'string' ? ctx.session?.handles.get(params.handle) : undefined;
626
+ if (!rec) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
627
+ // The root's mode is checked again, and the key's permission for that root is asked afresh by `check` on every step.
628
+ return { root: rec.root, cur: rec.value, segs: rec.segs.slice() };
629
+ }
630
+
631
+ /** Walk `path` (an array of keys) as traversal only, from where the request starts; the holder and its path. */
632
+ async function walk(start, path, ctx) {
633
+ const root = start.root;
468
634
  if (!Array.isArray(path)) throw invalid('path must be an array');
469
635
  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];
636
+ let cur = start.cur;
637
+ let segs = start.segs;
472
638
  for (const raw of path) {
473
639
  const key = checkKey(raw);
474
640
  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
641
  const next = [...segs, key];
476
- await check('get', root, next, who, { terminal: false });
642
+ await check('get', root, next, ctx, { terminal: false });
477
643
  try { cur = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
478
644
  segs = next;
479
645
  }
@@ -481,13 +647,14 @@ export function createObjectsServer(options = {}) {
481
647
  }
482
648
 
483
649
  async function setValue(params, ctx) {
484
- const root = requireRoot(params);
650
+ const start = startOf(params, ctx);
651
+ const { root } = start;
485
652
  const path = params.path;
486
653
  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);
654
+ const { cur: parent, segs } = await walk(start, path.slice(0, -1), ctx);
488
655
  const key = checkKey(path[path.length - 1]);
489
656
  const target = [...segs, key];
490
- await check('set', root, target, ctx.who, { terminal: true });
657
+ await check('set', root, target, ctx, { terminal: true });
491
658
  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
659
  const value = fromWire(params.value, limits);
493
660
  let ok;
@@ -503,9 +670,10 @@ export function createObjectsServer(options = {}) {
503
670
  }
504
671
 
505
672
  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 });
673
+ const start = startOf(params, ctx);
674
+ const { root } = start;
675
+ const { cur, segs } = await walk(start, params.path ?? [], ctx);
676
+ await check('describe', root, segs, ctx, { terminal: false });
509
677
  if (cur === null || (typeof cur !== 'object' && typeof cur !== 'function')) return { type: kindOf(cur), keys: [] };
510
678
  const keys = [];
511
679
  const seen = new Set();
@@ -530,18 +698,176 @@ export function createObjectsServer(options = {}) {
530
698
  }
531
699
 
532
700
  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 });
701
+ const start = startOf(params, ctx);
702
+ const { root } = start;
703
+ const { cur, segs } = await walk(start, params.path ?? [], ctx);
704
+ await check('snapshot', root, segs, ctx, { terminal: true });
536
705
  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
706
  const ceiling = ctx.maxBytes ?? limits.maxValueBytes;
538
707
  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
708
  return toWire(cur, { maxDepth: depth, maxBytes: wanted, cut: true });
540
709
  }
541
710
 
711
+ // ── Events ──────────────────────────────────────────────────────────────────────────────────────────────────────────
712
+ // A subscription is a listener on an EventTarget-style source (`addEventListener`) or an emitter-style one (`on` / `off`), named by an `allow.on` entry
713
+ // (`path@type`) of its own. What is delivered is plain data: an Event becomes `{ type, timeStamp, isTrusted }` plus the fields the host lists for its type
714
+ // (`eventFields`) and the subscriber asked for, each copied as plain data (a node is left out); an emitter's arguments become `{ type, args }`. Never the event,
715
+ // never a handle. A listener runs in the page's dispatch: it only copies, bounds, queues, and cannot throw into it.
716
+
717
+ const sourceMethods = (source) => {
718
+ const fn = (name) => { try { const f = Reflect.get(Object(source), name, source); return typeof f === 'function' ? f : null; } catch { return null; } };
719
+ if (fn('addEventListener') && fn('removeEventListener')) return { kind: 'target', add: 'addEventListener', remove: 'removeEventListener' };
720
+ if (fn('on') && fn('off')) return { kind: 'emitter', add: 'on', remove: 'off' };
721
+ if (fn('on') && fn('removeListener')) return { kind: 'emitter', add: 'on', remove: 'removeListener' };
722
+ return null;
723
+ };
724
+
725
+ /** An Event as plain data. */
726
+ function describeEvent(event, fields) {
727
+ const read = (name) => { try { return Reflect.get(Object(event), name, event); } catch { return undefined; } };
728
+ const out = { type: String(read('type') ?? ''), timeStamp: Number.isFinite(read('timeStamp')) ? read('timeStamp') : 0, isTrusted: read('isTrusted') === true };
729
+ for (const name of fields) {
730
+ const w = toWire(read(name), { maxDepth: 3, maxBytes: limits.maxEventBytes });
731
+ if ('v' in w && w.v !== undefined) out[name] = w.v;
732
+ }
733
+ return out;
734
+ }
735
+
736
+ async function pump(session) {
737
+ if (session.pumping) return;
738
+ session.pumping = true;
739
+ try {
740
+ while (session.queue.length && !session.closed) {
741
+ const { sub, cb, data, dropped } = session.queue.shift();
742
+ const message = cb ? { id: cb.id, seq: ++cb.seq, args: data, ...(dropped ? { dropped } : {}) } : { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
743
+ // The write waits for the transport (credit): events and callback calls behind it queue, to `maxQueuedEvents`, and beyond that are dropped and counted.
744
+ try { await session.peer.notify(cb ? 'callback' : 'event', message); } catch { /* the channel is going away */ }
745
+ }
746
+ } finally { session.pumping = false; }
747
+ }
748
+
749
+ // ── Callbacks ─────────────────────────────────────────────────────────────────────────────────────────────────────────
750
+ // A far-side function passed to a call whose entry ends in `(callback)` becomes a stub in the page. The stub is one-way: calling it copies its arguments as plain
751
+ // values (what cannot be cloned is null; never a handle), bounds them, queues a notification through the channel's credit, and returns undefined at once, so
752
+ // the page cannot be made to wait for the far side and learns nothing of it. After the channel ends, or after a release, a call is a no-op that is counted.
753
+
754
+ function makeCallback(session, id) {
755
+ // The same function sent again (an id the channel already has) is the same stub.
756
+ const existing = session.callbacks.get(id);
757
+ if (existing) return existing.stub;
758
+ if (session.callbacks.size >= limits.maxCallbacks) throw limitError('maxCallbacks', limits.maxCallbacks, 'too many callbacks on this channel: release some');
759
+ const cb = { id, seq: 0, stamps: [], dropped: 0, dead: false, stub: null };
760
+ cb.stub = function callback(...args) {
761
+ try { deliverCallback(session, cb, args); } catch { cb.dropped++; }
762
+ };
763
+ session.callbacks.set(id, cb);
764
+ return cb.stub;
765
+ }
766
+
767
+ function killCallback(session, id) {
768
+ const cb = session.callbacks.get(id);
769
+ if (cb) { cb.dead = true; session.callbacks.delete(id); }
770
+ return !!cb;
771
+ }
772
+
773
+ function deliverCallback(session, cb, args) {
774
+ if (session.closed || cb.dead || guard?.()) { session.deadCalls++; return; }
775
+ const t = now();
776
+ while (cb.stamps.length && t - cb.stamps[0] >= 1000) cb.stamps.shift();
777
+ // Rate and room first, copy after: a dropped call costs a counter.
778
+ if (cb.stamps.length >= limits.maxCallbacksPerSecond || session.queue.length >= limits.maxQueuedEvents) { cb.dropped++; return; }
779
+ let copy;
780
+ try {
781
+ copy = args.slice(0, limits.maxArgs).map((a) => { const w = toWire(a, { maxDepth: 4, maxBytes: limits.maxCallbackBytes }); return 'v' in w ? w.v : null; });
782
+ toWire(copy, { maxDepth: 6, maxBytes: limits.maxCallbackBytes });
783
+ } catch { cb.dropped++; return; }
784
+ cb.stamps.push(t);
785
+ session.queue.push({ cb, data: copy, dropped: cb.dropped });
786
+ cb.dropped = 0;
787
+ void pump(session);
788
+ }
789
+
790
+ async function releaseCallback(params, ctx) {
791
+ if (!killCallback(ctx.session, params.id)) throw invalid('no such callback');
792
+ return { ok: true };
793
+ }
794
+
795
+ function deliver(session, sub, args) {
796
+ if (session.closed) return;
797
+ try {
798
+ if (guard?.()) return;
799
+ const t = now();
800
+ while (sub.stamps.length && t - sub.stamps[0] >= 1000) sub.stamps.shift();
801
+ if (sub.stamps.length >= limits.maxEventsPerSecond) { sub.dropped++; return; }
802
+ // Room first, copy after: a dropped event costs a counter, not a read of the event or a copy of its fields.
803
+ if (session.queue.length >= limits.maxQueuedEvents) { sub.dropped++; return; }
804
+ let data;
805
+ if (sub.kind === 'target') data = describeEvent(args[0], sub.fields);
806
+ else {
807
+ // Emitter arguments: plain values; what cannot be cloned is null (the whole value keeps its position).
808
+ data = { type: sub.type, args: args.map((a) => { const w = toWire(a, { maxDepth: 4, maxBytes: limits.maxEventBytes }); return 'v' in w ? w.v : null; }) };
809
+ }
810
+ toWire(data, { maxDepth: 6, maxBytes: limits.maxEventBytes });
811
+ sub.stamps.push(t);
812
+ // The events dropped since the last accepted one are told with this one: "this many were lost before it".
813
+ session.queue.push({ sub, data, dropped: sub.dropped });
814
+ sub.dropped = 0;
815
+ void pump(session);
816
+ } catch { sub.dropped++; }
817
+ }
818
+
819
+ async function subscribe(params, ctx) {
820
+ const { session } = ctx;
821
+ const root = requireRoot(params);
822
+ const type = params.type;
823
+ if (typeof type !== 'string' || !EVENT_TYPE_RE.test(type)) throw invalid('an event type is a name of letters, digits and _ $ : . - (up to 128)');
824
+ const id = params.id;
825
+ if (!Number.isSafeInteger(id) || id < 1 || session.subs.has(id)) throw invalid('a subscription id is a whole number the channel has not used');
826
+ const asked = params.fields === undefined ? [] : params.fields;
827
+ if (!Array.isArray(asked) || asked.length > 16 || !asked.every((f) => typeof f === 'string')) throw invalid('fields must be an array of property names');
828
+ const offered = [...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])];
829
+ for (const f of asked) if (!offered.includes(f)) throw refuse('not-allowed', `refused: the field "${f}" of ${type} events is not offered by this host`, { field: f, type });
830
+ if (session.subs.size >= limits.maxSubscriptions) throw limitError('maxSubscriptions', limits.maxSubscriptions, 'too many event subscriptions on this channel');
831
+ const { cur: source, segs } = await walk({ root, cur: roots[root], segs: [root] }, params.path ?? [], ctx);
832
+ await check('on', root, segs, ctx, { terminal: true, type });
833
+ const kind = sourceMethods(source);
834
+ if (!kind) throw new ObjectsError(OBJECTS_ERROR.FAILED, `${segs.join('.')} is not an event source (it needs addEventListener, or on and off)`, { reason: 'not-an-event-source' });
835
+ const sub = { id, type, kind: kind.kind, fields: [...new Set(asked)], source, stamps: [], dropped: 0, seq: 0, remove: kind.remove, listener: null };
836
+ sub.listener = (...args) => deliver(session, sub, args);
837
+ try { Reflect.apply(Reflect.get(Object(source), kind.add, source), source, [type, sub.listener]); } catch (e) { throw wrapThrown(e, `${segs.join('.')}.${kind.add}`); }
838
+ session.subs.set(id, sub);
839
+ return { ok: true };
840
+ }
841
+
842
+ function removeSub(sub) {
843
+ try { Reflect.apply(Reflect.get(Object(sub.source), sub.remove, sub.source), sub.source, [sub.type, sub.listener]); } catch { /* the page's own source: nothing to tell */ }
844
+ }
845
+
846
+ async function unsubscribe(params, ctx) {
847
+ const sub = ctx.session.subs.get(params.id);
848
+ if (!sub) throw invalid('no such subscription');
849
+ ctx.session.subs.delete(params.id);
850
+ removeSub(sub);
851
+ ctx.session.queue = ctx.session.queue.filter((q) => q.sub !== sub);
852
+ return { ok: true, dropped: sub.dropped };
853
+ }
854
+
542
855
  /** Register the protocol's methods on a peer. `who` is the identity of every call unless the transport gives one per call. */
543
856
  function attach(peer, { who } = {}) {
544
857
  if (typeof peer?.onRequest !== 'function') throw new TypeError('attach: the peer needs onRequest(method, handler)');
858
+ const session = { peer, subs: new Map(), queue: [], pumping: false, closed: false, handles: new Map(), callbacks: new Map(), deadCalls: 0 };
859
+ // The end of the channel (the peer left, Stop, a navigation, a revoke) takes every listener out of the page's sources.
860
+ const prior = peer.onClose;
861
+ peer.onClose = (reason) => {
862
+ session.closed = true;
863
+ for (const sub of session.subs.values()) removeSub(sub);
864
+ session.subs.clear();
865
+ session.queue = [];
866
+ session.handles.clear(); // the end of the channel (leaving, Stop, navigation, revoke) releases every handle
867
+ for (const cb of session.callbacks.values()) cb.dead = true; // and kills every callback stub
868
+ session.callbacks.clear();
869
+ try { prior?.(reason); } catch { /* ignore */ }
870
+ };
545
871
  const stamps = [];
546
872
  const method = (name, fn) => peer.onRequest(name, async (params, ctx = {}) => {
547
873
  const t = now();
@@ -550,16 +876,25 @@ export function createObjectsServer(options = {}) {
550
876
  stamps.push(t);
551
877
  // A value is kept under what the transport carries in one message, with room for the envelope.
552
878
  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 };
879
+ const call = { ...ctx, signal: ctx.signal, who: ctx.who ?? who, maxBytes, session };
554
880
  if (params === null || typeof params !== 'object' || Array.isArray(params)) throw invalid('params must be an object');
555
881
  try { return await fn(params, call); } catch (e) { if (e instanceof ObjectsError) throw e; throw wrapThrown(e, name); }
556
882
  });
557
- method('roots', async () => ({ roots: rootNames.slice() }));
883
+ // A key that may use only some roots is told of those only.
884
+ // The host also says what it supports (additive: an older client ignores it), so a client does not send a function to a host that would drop it, nor misread a handle.
885
+ method('roots', async (_params, call) => ({
886
+ roots: rootNames.filter((name) => typeof call.permit !== 'function' || call.permit(name, 'walk') === true),
887
+ features: ['events', 'callbacks', ...(handleRoots.size ? ['handles'] : [])],
888
+ }));
558
889
  method('resolve', resolve);
559
890
  method('set', setValue);
560
891
  method('describe', describe);
561
892
  method('snapshot', snapshot);
562
- return { limits };
893
+ method('subscribe', subscribe);
894
+ method('unsubscribe', unsubscribe);
895
+ method('release', releaseHandle);
896
+ method('releaseCallback', releaseCallback);
897
+ return { limits, handleCount: () => session.handles.size, callbackCount: () => session.callbacks.size, deadCallbackCalls: () => session.deadCalls };
563
898
  }
564
899
 
565
900
  return { attach, limits: Object.freeze({ ...limits }), rootNames: rootNames.slice() };
@@ -655,11 +990,33 @@ export class NonValue {
655
990
  toString() { return `[remote ${this.kind}${this.type ? ` ${this.type}` : ''}${this.text ? `: ${this.text}` : ''}]`; }
656
991
  }
657
992
 
658
- const decodeResult = (res) => {
993
+ const decodeResult = (res, session) => {
994
+ if (res && typeof res === 'object' && typeof res.h === 'string' && session) {
995
+ if (!session.features?.includes('handles')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the host returned a handle but did not say it supports handles: it is not a host this client understands', { reason: 'unsupported' });
996
+ return new RemoteHandle(session, res);
997
+ }
659
998
  if (res && typeof res === 'object' && 'u' in res) return res.u === 'undefined' ? undefined : new NonValue(res);
660
999
  return res?.v;
661
1000
  };
662
1001
 
1002
+ const HANDLE_ID = new WeakMap();
1003
+
1004
+ /**
1005
+ * What a value that cannot be cloned arrives as on a root that opted in to handles: an opaque token. Nothing of it is enumerable (the id is not
1006
+ * there to copy), it is not thenable, and it is not an argument. `use(handle)` makes a reference that stands on it; `release(handle)` gives its place back.
1007
+ */
1008
+ export class RemoteHandle {
1009
+ constructor(session, wire) {
1010
+ HANDLE_ID.set(this, { session, id: wire.h });
1011
+ Object.defineProperty(this, 'kind', { value: wire.kind, enumerable: false });
1012
+ Object.defineProperty(this, 'type', { value: wire.type, enumerable: false });
1013
+ Object.defineProperty(this, 'preview', { value: wire.preview, enumerable: false });
1014
+ Object.freeze(this);
1015
+ }
1016
+
1017
+ toString() { return `[remote handle${this.type ? ` ${this.type}` : ''}]`; }
1018
+ }
1019
+
663
1020
  function asObjectsError(e, session) {
664
1021
  if (e instanceof ObjectsError) return e;
665
1022
  const closing = session?.closing ? ` (${session.closing})` : '';
@@ -678,6 +1035,7 @@ function plainArgs(args) {
678
1035
  let visits = 0;
679
1036
  const walk = (v, depth) => {
680
1037
  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)');
1038
+ if (v instanceof RemoteHandle) throw new TypeError('a handle cannot be sent as an argument: it means something only on its own session, and only plain data crosses');
681
1039
  if (v === null || typeof v !== 'object' || depth > 8 || ++visits > 2000) return;
682
1040
  if (ArrayBuffer.isView(v)) return;
683
1041
  for (const k of Object.keys(v)) walk(v[k], depth + 1);
@@ -686,8 +1044,11 @@ function plainArgs(args) {
686
1044
  return args;
687
1045
  }
688
1046
 
689
- function makeRef(session, root, ops) {
690
- const state = { session, root, ops };
1047
+ /** What a request names as its start: the handle this reference stands on, or its root. */
1048
+ const target = (state) => (state.handle !== undefined ? { handle: state.handle } : { root: state.root });
1049
+
1050
+ function makeRef(session, root, ops, handle) {
1051
+ const state = { session, root, ops, handle };
691
1052
  const readOnly = (what) => () => { throw new TypeError(what); };
692
1053
  const handler = {
693
1054
  get(_target, key) {
@@ -697,7 +1058,7 @@ function makeRef(session, root, ops) {
697
1058
  // `await ref` sends the whole chain in ONE request. A remote property really named "then" is reached with get(ref, 'then').
698
1059
  return (onFulfilled, onRejected) => send(state).then(onFulfilled, onRejected);
699
1060
  }
700
- return makeRef(session, root, [...ops, { get: key }]);
1061
+ return makeRef(session, root, [...ops, { get: key }], handle);
701
1062
  },
702
1063
  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
1064
  defineProperty: readOnly('a remote reference cannot be defined on: use set(ref, key, value)'),
@@ -706,22 +1067,52 @@ function makeRef(session, root, ops) {
706
1067
  apply(_t, _this, args) {
707
1068
  const last = ops[ops.length - 1];
708
1069
  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) }]);
1070
+ return makeRef(session, root, [...ops.slice(0, -1), { call: last.get, ...callArgs(args) }], handle);
710
1071
  },
711
1072
  construct(_t, args) {
712
1073
  const last = ops[ops.length - 1];
713
1074
  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) }]);
1075
+ return makeRef(session, root, [...ops.slice(0, -1), { construct: last.get, ...callArgs(args) }], handle);
715
1076
  },
716
1077
  };
717
1078
  // A function as the target so the proxy can be called and constructed.
718
1079
  return new Proxy(function remote() {}, handler);
719
1080
  }
720
1081
 
1082
+ /**
1083
+ * The arguments of a call: a function at the top level of the list (not a reference, not a handle) is a CALLBACK: its place is null on the wire, listed in `fns`
1084
+ * (until it is sent, when `send` gives it an id). A function deeper in an argument, a reference and a handle are refused where they are written.
1085
+ */
1086
+ function callArgs(args) {
1087
+ const fns = [];
1088
+ const copy = args.map((a, i) => {
1089
+ if (typeof a === 'function' && !a[BRAND]) { fns.push([i, a]); return null; }
1090
+ return a;
1091
+ });
1092
+ plainArgs(copy);
1093
+ return fns.length ? { args: copy, fns } : { args: copy };
1094
+ }
1095
+
1096
+ const CALLBACK_OF = new WeakMap();
1097
+
1098
+ /** The wire form of an op: its callbacks get ids (one per function per channel, the same id each time it is sent) and `fns` goes. */
1099
+ function wireOp(session, op) {
1100
+ if (!op.fns) return op;
1101
+ const { fns, ...rest } = op;
1102
+ return { ...rest, callbacks: fns.map(([i, fn]) => {
1103
+ let rec = CALLBACK_OF.get(fn);
1104
+ if (!rec || rec.session !== session || rec.released) { rec = { session, id: session.nextCb++, released: false }; CALLBACK_OF.set(fn, rec); session.callbacks.set(rec.id, fn); }
1105
+ return [i, rec.id];
1106
+ }) };
1107
+ }
1108
+
721
1109
  async function send(state, { signal } = {}) {
722
- const { session, root, ops } = state;
1110
+ const { session } = state;
723
1111
  try {
724
- return decodeResult(await session.peer.request('resolve', { root, ops }, { signal, ...(session.timeoutMs ? { timeoutMs: session.timeoutMs } : {}) }));
1112
+ // A function would reach a host that does not know callbacks as null: refuse to send it (a named error), unless the host said it supports them.
1113
+ if (state.ops.some((op) => op.fns) && !session.features?.includes('callbacks')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support callbacks (it did not say so): a function cannot be passed to it', { reason: 'unsupported' });
1114
+ const ops = state.ops.map((op) => wireOp(session, op));
1115
+ return decodeResult(await session.peer.request('resolve', { ...target(state), ops }, { signal, ...(session.timeoutMs ? { timeoutMs: session.timeoutMs } : {}) }), session);
725
1116
  } catch (e) { throw asObjectsError(e, session); }
726
1117
  }
727
1118
 
@@ -746,7 +1137,7 @@ export function get(ref, ...keys) {
746
1137
  export async function set(ref, key, value) {
747
1138
  const { state, keys } = pathOf(ref, 'set');
748
1139
  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); }
1140
+ try { await state.session.peer.request('set', { ...target(state), path: [...keys, String(key)], value }); } catch (e) { throw asObjectsError(e, state.session); }
750
1141
  }
751
1142
 
752
1143
  /** 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, ...)`. */
@@ -754,7 +1145,7 @@ export function call(ref, ...args) {
754
1145
  const state = stateOf(ref);
755
1146
  const last = state.ops[state.ops.length - 1];
756
1147
  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) }] });
1148
+ return send({ ...state, ops: [...state.ops.slice(0, -1), { call: last.get, ...callArgs(args) }] });
758
1149
  }
759
1150
 
760
1151
  /** `new` a constructor reached by name: `await construct(win.app.Cart, 'A')`. */
@@ -762,21 +1153,50 @@ export function construct(ref, ...args) {
762
1153
  const state = stateOf(ref);
763
1154
  const last = state.ops[state.ops.length - 1];
764
1155
  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) }] });
1156
+ return send({ ...state, ops: [...state.ops.slice(0, -1), { construct: last.get, ...callArgs(args) }] });
766
1157
  }
767
1158
 
768
1159
  /** A bounded deep copy: `await snapshot(win.app.state, { depth: 3, maxBytes: 256_000 })`. Subtrees deeper than `depth` are `null`. */
769
1160
  export async function snapshot(ref, { depth, maxBytes, signal } = {}) {
770
1161
  const { state, keys } = pathOf(ref, 'snapshot');
771
1162
  try {
772
- return decodeResult(await state.session.peer.request('snapshot', { root: state.root, path: keys, ...(depth !== undefined ? { depth } : {}), ...(maxBytes !== undefined ? { maxBytes } : {}) }, { signal }));
1163
+ return decodeResult(await state.session.peer.request('snapshot', { ...target(state), path: keys, ...(depth !== undefined ? { depth } : {}), ...(maxBytes !== undefined ? { maxBytes } : {}) }, { signal }));
773
1164
  } catch (e) { throw asObjectsError(e, state.session); }
774
1165
  }
775
1166
 
1167
+ /**
1168
+ * Listen for an event of a remote source named by the host's `allow.on`: `const stop = await on(win.app.bus, 'ready', (data, { seq, dropped }) => ...)`.
1169
+ * `data` is plain (an Event as `{ type, timeStamp, isTrusted, ...the fields you asked for }`, an emitter's as `{ type, args }`); `dropped` counts the events the
1170
+ * host dropped before this one (rate, size, or a slow channel). `fields` are extra event fields the host lists for the type. Resolves to the function that unsubscribes.
1171
+ */
1172
+ export async function on(ref, type, listener, { fields, onError } = {}) {
1173
+ const { state, keys } = pathOf(ref, 'on');
1174
+ if (typeof listener !== 'function') throw new TypeError('on needs a listener function: listener(data, { type, seq, dropped })');
1175
+ const { session } = state;
1176
+ if (state.handle !== undefined) throw new TypeError('events are not offered through a handle: name the source by its path');
1177
+ if (!session.features?.includes('events')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support events (it did not say so)', { reason: 'unsupported' });
1178
+ const id = session.nextSub++;
1179
+ // Registered before the request: an event can follow the answer at once.
1180
+ session.subs.set(id, { listener, onError, type });
1181
+ try {
1182
+ await session.peer.request('subscribe', { id, root: state.root, path: keys, type, ...(fields ? { fields } : {}) });
1183
+ } catch (e) { session.subs.delete(id); throw asObjectsError(e, session); }
1184
+ return async function off() {
1185
+ if (!session.subs.delete(id)) return;
1186
+ try { await session.peer.request('unsubscribe', { id }); } catch { /* the channel is already gone: the host removed the listener with it */ }
1187
+ };
1188
+ }
1189
+
1190
+ /** Stop a subscription: `await off(await on(...))`, the same as calling the function `on` returned. */
1191
+ export async function off(unsubscribe) {
1192
+ if (typeof unsubscribe !== 'function') throw new TypeError('off needs what on() returned');
1193
+ await unsubscribe();
1194
+ }
1195
+
776
1196
  /** 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
1197
  export async function describe(ref, { signal } = {}) {
778
1198
  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); }
1199
+ try { return await state.session.peer.request('describe', { ...target(state), path: keys }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
780
1200
  }
781
1201
 
782
1202
  /**
@@ -784,12 +1204,33 @@ export async function describe(ref, { signal } = {}) {
784
1204
  * @param {object} peer
785
1205
  * @param {{ timeoutMs?: number }} [options]
786
1206
  */
787
- export async function createObjectsClient(peer, { timeoutMs } = {}) {
1207
+ export async function createObjectsClient(peer, { timeoutMs, onCallbackError, onCallbackDropped } = {}) {
788
1208
  if (typeof peer?.request !== 'function') throw new TypeError('createObjectsClient: the peer needs request(method, params)');
789
- const session = { peer, closing: null, timeoutMs };
1209
+ const session = { peer, closing: null, timeoutMs, subs: new Map(), nextSub: 1, callbacks: new Map(), nextCb: 1 };
1210
+ // The page called a stub of one of our functions: run it here. Its errors and its return value stay here (the stub is one-way); `onCallbackDropped({ dropped })`
1211
+ // is told, before the call that follows them, how many calls the host dropped (rate, size, a slow channel).
1212
+ peer.onNotification?.('callback', (params) => {
1213
+ const fn = session.callbacks.get(params?.id);
1214
+ if (!fn || !Array.isArray(params.args)) return;
1215
+ if (Number.isSafeInteger(params.dropped) && params.dropped > 0) { try { onCallbackDropped?.({ dropped: params.dropped, fn }); } catch { /* ours */ } }
1216
+ try { fn(...params.args); } catch (e) { try { onCallbackError?.(e); } catch { /* ours */ } }
1217
+ });
1218
+ // An event the host delivers: to the listener that asked, in this process. A listener that throws is this side's business and goes to its `onError`: it never travels back.
1219
+ peer.onNotification?.('event', (params) => {
1220
+ const sub = session.subs.get(params?.id);
1221
+ if (!sub) return;
1222
+ try { sub.listener(params.data, { type: sub.type, seq: params.seq, dropped: Number.isSafeInteger(params.dropped) ? params.dropped : 0 }); } catch (e) {
1223
+ try { sub.onError?.(e); } catch { /* the error handler's own */ }
1224
+ }
1225
+ });
790
1226
  peer.onNotification?.('closing', (params) => { session.closing = typeof params?.reason === 'string' ? clip(params.reason, TEXT_MAX) : 'closing'; });
791
1227
  let roots;
792
- try { roots = (await peer.request('roots', {}))?.roots; } catch (e) { throw asObjectsError(e, session); }
1228
+ try {
1229
+ const answer = await peer.request('roots', {});
1230
+ roots = answer?.roots;
1231
+ // What the host says it supports; a host that says nothing (before 0.48.0) supports none of the three.
1232
+ session.features = Array.isArray(answer?.features) ? answer.features.filter((f) => typeof f === 'string') : [];
1233
+ } catch (e) { throw asObjectsError(e, session); }
793
1234
  if (!Array.isArray(roots)) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the host did not list its roots', { reason: 'bad-reply' });
794
1235
  const page = {};
795
1236
  for (const name of roots) if (typeof name === 'string' && !ALWAYS_REFUSED.has(name)) page[name] = makeRef(session, name, []);
@@ -798,6 +1239,31 @@ export async function createObjectsClient(peer, { timeoutMs } = {}) {
798
1239
  }
799
1240
 
800
1241
  /** End the connection behind what `openObjects()` returned. */
1242
+ /** A reference that stands on a handle: `await use(handle).items.length`. Its path is the one that produced the handle, extended by what you name. */
1243
+ export function use(handle) {
1244
+ const rec = handle instanceof RemoteHandle ? HANDLE_ID.get(handle) : undefined;
1245
+ if (!rec) throw new TypeError('use needs a handle (what awaiting a reference returns on a root that opted in to handles)');
1246
+ return makeRef(rec.session, null, [], rec.id);
1247
+ }
1248
+
1249
+ /** Give a handle's place back. Releasing a released handle does nothing. Everything is released when the channel ends. */
1250
+ export async function release(handle) {
1251
+ // A function that was passed as a callback: its stub in the page dies, and a call of it is a counted no-op.
1252
+ if (typeof handle === 'function' && CALLBACK_OF.has(handle)) {
1253
+ const cb = CALLBACK_OF.get(handle);
1254
+ if (cb.released) return;
1255
+ cb.released = true;
1256
+ cb.session.callbacks.delete(cb.id);
1257
+ try { await cb.session.peer.request('releaseCallback', { id: cb.id }); } catch (e) { throw asObjectsError(e, cb.session); }
1258
+ return;
1259
+ }
1260
+ const rec = handle instanceof RemoteHandle ? HANDLE_ID.get(handle) : undefined;
1261
+ if (!rec) throw new TypeError('release needs a handle, or a function that was passed as a callback');
1262
+ if (rec.released) return;
1263
+ rec.released = true;
1264
+ try { await rec.session.peer.request('release', { handle: rec.id }); } catch (e) { throw asObjectsError(e, rec.session); }
1265
+ }
1266
+
801
1267
  export async function closeObjects(page) {
802
1268
  const session = page?.[SESSION];
803
1269
  if (!session) throw new TypeError('closeObjects: expected what openObjects() returned');