@mica-js/widget 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,8 @@
1
- import { CANVAS_VERSION, applyCanvasCommand, assertCanvasBindings, parseCanvas, parsePayloadType } from "@mica-js/core/canvas";
1
+ import { CANVAS_VERSION, applyCanvasCommand, assertCanvasBindings, parseCanvas, parseDeliveryKind, parsePayloadType, validateCanvasBindings } from "@mica-js/core/canvas";
2
+ import { createRpc, defineRpcService } from "@mica-js/core/rpc";
3
+ import { Emitter } from "@mica-js/core/lifecycle";
4
+ import { loggerService } from "@mica-js/core/logging";
5
+ import { SandboxWorker } from "@mica-js/sandbox";
2
6
  //#region src/errors.ts
3
7
  /** Thrown when a widget reference resolves to a package that cannot be turned into a module. */
4
8
  var WidgetLoadError = class extends Error {
@@ -14,7 +18,7 @@ var WidgetLoadError = class extends Error {
14
18
  }
15
19
  };
16
20
  //#endregion
17
- //#region src/load-package.ts
21
+ //#region src/package/load.ts
18
22
  var PACKAGE_JSON = "package.json";
19
23
  var JSON_EXTENSION = ".json";
20
24
  var IMPLEMENTATION_EXTENSION = ".js";
@@ -163,9 +167,16 @@ function readPorts(value, packageId, path) {
163
167
  });
164
168
  const title = portText(descriptor, "title", key, packageId, path);
165
169
  const description = portText(descriptor, "description", key, packageId, path);
170
+ const declaredDelivery = descriptor["delivery"];
171
+ const delivery = declaredDelivery === void 0 ? void 0 : parseDeliveryKind(declaredDelivery);
172
+ if (declaredDelivery !== void 0 && delivery === void 0) throw new WidgetLoadError("schema/invalid-value", `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare "delivery" as "level" or "message".`, {
173
+ packageId,
174
+ path
175
+ });
166
176
  ports[key] = {
167
177
  direction,
168
178
  type,
179
+ ...delivery === void 0 ? {} : { delivery },
169
180
  ...title === void 0 ? {} : { title },
170
181
  ...description === void 0 ? {} : { description }
171
182
  };
@@ -255,7 +266,7 @@ async function sha256Hex(text, packageId) {
255
266
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
256
267
  }
257
268
  //#endregion
258
- //#region src/provider/static.ts
269
+ //#region src/package/static-provider.ts
259
270
  /** Provider over a fixed module table, used for builtin widgets and tests. */
260
271
  function createStaticWidgetProvider(modules) {
261
272
  const index = new Map(Object.entries(modules));
@@ -264,7 +275,7 @@ function createStaticWidgetProvider(modules) {
264
275
  } };
265
276
  }
266
277
  //#endregion
267
- //#region src/provider/package.ts
278
+ //#region src/package/package-provider.ts
268
279
  /**
269
280
  * Loads every package up front and indexes its widgets under `<packageId>:<widgetId>`.
270
281
  * Resolution never touches the file system again, and unknown references return `undefined`.
@@ -303,32 +314,649 @@ function withPathCache(files) {
303
314
  };
304
315
  }
305
316
  //#endregion
306
- //#region src/runtime/protocol.ts
317
+ //#region src/host-fs/errors.ts
318
+ var DEFAULT_MESSAGES = {
319
+ FileNotFound: "Host resource not found",
320
+ NoPermissions: "Host resource access denied",
321
+ NoFileSystem: "No host file system handles the URI scheme",
322
+ Unavailable: "Host file system is unavailable"
323
+ };
324
+ var ERROR_CODES = [
325
+ "FileNotFound",
326
+ "NoPermissions",
327
+ "NoFileSystem",
328
+ "Unavailable"
329
+ ];
330
+ function isHostFsErrorCode(value) {
331
+ return typeof value === "string" && ERROR_CODES.includes(value);
332
+ }
333
+ /** Rejection of `HostFs.read`: `code` classifies the failure, `uri` names the resource. */
334
+ var HostFsError = class extends Error {
335
+ code;
336
+ uri;
337
+ constructor(code, uri, message, options = {}) {
338
+ super(message ?? `${DEFAULT_MESSAGES[code]}: ${uri}`, options.cause === void 0 ? void 0 : { cause: options.cause });
339
+ this.name = "HostFsError";
340
+ this.code = code;
341
+ this.uri = uri;
342
+ }
343
+ };
344
+ /** Narrows an unknown rejection to a `HostFsError` created in this realm. */
345
+ function isHostFsError(value) {
346
+ return value instanceof HostFsError;
347
+ }
348
+ /** Copies the fields a thread hop must carry; the instance itself does not survive a structured clone. */
349
+ function toHostFsErrorPayload(error) {
350
+ return {
351
+ code: error.code,
352
+ uri: error.uri,
353
+ message: error.message
354
+ };
355
+ }
356
+ /** Rebuilds a `HostFsError` from its payload, rejecting codes outside the contract. */
357
+ function fromHostFsErrorPayload(payload) {
358
+ const code = payload.code;
359
+ if (!isHostFsErrorCode(code)) throw new TypeError(`Unknown HostFsError code: ${String(code)}`);
360
+ return new HostFsError(code, payload.uri, payload.message);
361
+ }
362
+ //#endregion
363
+ //#region src/host-fs/data-uri.ts
364
+ /**
365
+ * Decodes a self-contained `data:` URI to its bytes.
366
+ *
367
+ * `data:` resources never reach `HostFs`: the bytes travel with the reference, so the host decodes
368
+ * them locally. `;base64` payloads are decoded from base64; other payloads are percent-decoded,
369
+ * while characters that need no escaping are encoded as UTF-8. The URI fragment is ignored.
370
+ *
371
+ * @throws TypeError when the URI has no payload separator or the payload is not decodable.
372
+ */
373
+ function decodeDataUri(uri) {
374
+ const { base64, payload } = splitDataUri(uri);
375
+ return base64 ? decodeBase64(payload) : decodePercentPayload(payload);
376
+ }
377
+ /**
378
+ * Decodes a self-contained `data:` URI to its text payload.
379
+ *
380
+ * The decoded bytes are read as UTF-8, so a payload that carries binary or malformed UTF-8 is a
381
+ * decode failure rather than replacement characters.
382
+ *
383
+ * @throws TypeError when the URI has no payload separator, the payload is not decodable, or the
384
+ * bytes are not UTF-8.
385
+ */
386
+ function decodeDataUriText(uri) {
387
+ const bytes = decodeDataUri(uri);
388
+ try {
389
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
390
+ } catch (cause) {
391
+ throw new TypeError("Data URI payload is not valid UTF-8", { cause });
392
+ }
393
+ }
394
+ /** Splits the URI into its `;base64` flag and payload. */
395
+ function splitDataUri(uri) {
396
+ if (uri.slice(0, 5).toLowerCase() !== "data:") throw new TypeError("Not a data: URI");
397
+ const hash = uri.indexOf("#");
398
+ const body = hash < 0 ? uri : uri.slice(0, hash);
399
+ const comma = body.indexOf(",");
400
+ if (comma < 0) throw new TypeError("Data URI must separate its payload with a comma");
401
+ const metadata = body.slice(5, comma);
402
+ return {
403
+ base64: /;base64$/i.test(metadata),
404
+ payload: body.slice(comma + 1)
405
+ };
406
+ }
407
+ function decodeBase64(payload) {
408
+ let binary;
409
+ try {
410
+ binary = atob(payload);
411
+ } catch (cause) {
412
+ throw new TypeError("Data URI payload is not valid base64", { cause });
413
+ }
414
+ const bytes = new Uint8Array(binary.length);
415
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
416
+ return bytes;
417
+ }
418
+ function isHexDigit(value) {
419
+ return value !== void 0 && /^[0-9A-Fa-f]$/.test(value);
420
+ }
421
+ /**
422
+ * Percent-decodes a payload to bytes, so `%89PNG` keeps its binary value instead of being read as
423
+ * (invalid) UTF-8. Literal characters are UTF-8 encoded.
424
+ */
425
+ function decodePercentPayload(payload) {
426
+ const encoder = new TextEncoder();
427
+ const chunks = [];
428
+ let literal = 0;
429
+ let index = 0;
430
+ while (index < payload.length) {
431
+ if (payload[index] !== "%") {
432
+ index += 1;
433
+ continue;
434
+ }
435
+ const high = payload[index + 1];
436
+ const low = payload[index + 2];
437
+ if (!isHexDigit(high) || !isHexDigit(low)) throw new TypeError("Data URI payload is not valid percent-encoding");
438
+ if (index > literal) chunks.push(encoder.encode(payload.slice(literal, index)));
439
+ chunks.push(new Uint8Array([Number.parseInt(`${high}${low}`, 16)]));
440
+ index += 3;
441
+ literal = index;
442
+ }
443
+ if (literal < payload.length) chunks.push(encoder.encode(payload.slice(literal)));
444
+ let total = 0;
445
+ for (const chunk of chunks) total += chunk.length;
446
+ const bytes = new Uint8Array(total);
447
+ let offset = 0;
448
+ for (const chunk of chunks) {
449
+ bytes.set(chunk, offset);
450
+ offset += chunk.length;
451
+ }
452
+ return bytes;
453
+ }
454
+ //#endregion
455
+ //#region src/host-fs/uri.ts
456
+ var ABSOLUTE_URI = /^[A-Za-z][A-Za-z0-9+.-]*:/;
457
+ /** Whether `uri` carries a scheme, i.e. is absolute rather than a relative reference. */
458
+ function isAbsoluteHostUri(uri) {
459
+ return ABSOLUTE_URI.test(uri);
460
+ }
461
+ /** Splits a reference into path, query and fragment without interpreting leading slashes. */
462
+ function splitPath(value) {
463
+ const hash = value.indexOf("#");
464
+ const fragment = hash < 0 ? void 0 : value.slice(hash + 1);
465
+ const beforeFragment = hash < 0 ? value : value.slice(0, hash);
466
+ const question = beforeFragment.indexOf("?");
467
+ const query = question < 0 ? void 0 : beforeFragment.slice(question + 1);
468
+ return {
469
+ path: question < 0 ? beforeFragment : beforeFragment.slice(0, question),
470
+ query,
471
+ fragment
472
+ };
473
+ }
474
+ function parseUri(value) {
475
+ const schemeMatch = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(value);
476
+ const scheme = schemeMatch?.[1];
477
+ let rest = schemeMatch === null ? value : value.slice(schemeMatch[0].length);
478
+ let authority;
479
+ if (rest.startsWith("//")) {
480
+ const tail = rest.slice(2);
481
+ const end = tail.search(/[/?#]/);
482
+ authority = end < 0 ? tail : tail.slice(0, end);
483
+ rest = end < 0 ? "" : tail.slice(end);
484
+ }
485
+ const { path, query, fragment } = splitPath(rest);
486
+ return {
487
+ scheme,
488
+ authority,
489
+ path,
490
+ query,
491
+ fragment
492
+ };
493
+ }
494
+ function removeLastSegment(output) {
495
+ const slash = output.lastIndexOf("/");
496
+ return slash < 0 ? "" : output.slice(0, slash);
497
+ }
498
+ /** RFC 3986 §5.2.4: drops `.` and `..` segments without touching empty segments. */
499
+ function removeDotSegments(path) {
500
+ let input = path;
501
+ let output = "";
502
+ while (input.length > 0) if (input.startsWith("../")) input = input.slice(3);
503
+ else if (input.startsWith("./")) input = input.slice(2);
504
+ else if (input.startsWith("/./")) input = `/${input.slice(3)}`;
505
+ else if (input === "/.") input = "/";
506
+ else if (input.startsWith("/../")) {
507
+ input = `/${input.slice(4)}`;
508
+ output = removeLastSegment(output);
509
+ } else if (input === "/..") {
510
+ input = "/";
511
+ output = removeLastSegment(output);
512
+ } else if (input === "." || input === "..") input = "";
513
+ else {
514
+ const segment = /^\/?[^/]*/.exec(input)?.[0] ?? input;
515
+ output += segment;
516
+ input = input.slice(segment.length);
517
+ }
518
+ return output;
519
+ }
520
+ /** RFC 3986 §5.3: merges a relative path with the base path. */
521
+ function mergePath(base, referencePath) {
522
+ if (referencePath === "") return base.path;
523
+ if (base.authority !== void 0 && base.path === "") return `/${referencePath}`;
524
+ const slash = base.path.lastIndexOf("/");
525
+ return slash < 0 ? referencePath : `${base.path.slice(0, slash + 1)}${referencePath}`;
526
+ }
527
+ function compose(scheme, authority, path, query, fragment) {
528
+ let uri = `${scheme}:`;
529
+ if (authority !== void 0) uri += `//${authority}`;
530
+ uri += path;
531
+ if (query !== void 0) uri += `?${query}`;
532
+ if (fragment !== void 0) uri += `#${fragment}`;
533
+ return uri;
534
+ }
535
+ /**
536
+ * Resolves a document reference against the absolute URI of the document that contains it.
537
+ *
538
+ * - a reference with a scheme is an absolute URI and is returned unchanged;
539
+ * - a reference starting with `/` replaces the path and keeps the base scheme and authority;
540
+ * - any other reference is merged with the base directory and normalized.
541
+ *
542
+ * The result always keeps the scheme and authority of `baseUri`, so a `//host/path` reference
543
+ * stays inside the base authority instead of replacing it. Hosts pass a base URI whose path is
544
+ * not empty; a base with an authority and an empty path resolves relative references under that
545
+ * authority.
546
+ *
547
+ * @throws TypeError when `baseUri` is not an absolute URI.
548
+ */
549
+ function resolveHostUri(baseUri, reference) {
550
+ const base = parseUri(baseUri);
551
+ if (base.scheme === void 0) throw new TypeError(`Host URI base must be absolute: ${baseUri}`);
552
+ if (isAbsoluteHostUri(reference)) return reference;
553
+ const target = splitPath(reference);
554
+ const replacesPath = reference.startsWith("/");
555
+ const path = replacesPath ? removeDotSegments(target.path) : removeDotSegments(mergePath(base, target.path));
556
+ const query = !replacesPath && target.path === "" && target.query === void 0 ? base.query : target.query;
557
+ return compose(base.scheme, base.authority, path, query, target.fragment);
558
+ }
559
+ //#endregion
560
+ //#region src/guest/widget/protocol.ts
307
561
  /**
308
562
  * Guest event names. The sandbox reserves the `mica:` namespace for its own traffic: guest events
309
563
  * with that prefix never reach host listeners, and `sandbox.on('mica:...')` throws. Widget traffic
310
564
  * therefore lives in the `widget:` namespace.
311
565
  */
312
- var WIDGET_FRAME_EVENT = "widget:frame";
313
- var WIDGET_PUBLISH_EVENT = "widget:publish";
314
- var WIDGET_ERROR_EVENT = "widget:error";
566
+ var widgetFrameEvent = "widget:frame";
567
+ var widgetPublishEvent = "widget:publish";
568
+ var widgetErrorEvent = "widget:error";
315
569
  /** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */
316
- var WIDGET_ASSET_FAILED_EVENT = "widget:asset-failed";
570
+ var widgetAssetFailedEvent = "widget:asset-failed";
317
571
  /** Guest methods the host reaches through `sandbox.call()`. */
318
- var WIDGET_LOAD_METHOD = "load";
319
- var WIDGET_MOUNT_METHOD = "mount";
320
- var WIDGET_UNMOUNT_METHOD = "unmount";
321
- var WIDGET_RESIZE_METHOD = "resize";
322
- var WIDGET_SET_PROPERTIES_METHOD = "set-properties";
323
- var WIDGET_DELIVER_METHOD = "deliver";
324
- var WIDGET_POINTER_METHOD = "pointer";
572
+ var widgetLoadMethod = "load";
573
+ var widgetMountMethod = "mount";
574
+ var widgetUnmountMethod = "unmount";
575
+ var widgetResizeMethod = "resize";
576
+ var widgetSetPropertiesMethod = "set-properties";
577
+ /**
578
+ * Replaces the device endpoints one instance writes to and reads from (RFC 0018).
579
+ *
580
+ * The guest routes topic traffic itself when it holds a direct device channel, so it needs the same
581
+ * binding map the host validates against. A guest without that channel ignores the call.
582
+ */
583
+ var widgetSetBindingsMethod = "set-bindings";
584
+ var widgetDeliverMethod = "deliver";
585
+ var widgetPointerMethod = "pointer";
325
586
  /**
326
587
  * Releases every instance without terminating the guest. Widget modules stay evaluated, so the next
327
588
  * `load` reuses their factories and only fresh instances are created.
328
589
  */
329
- var WIDGET_RESET_RUNTIME_METHOD = "reset-runtime";
590
+ var widgetResetRuntimeMethod = "reset-runtime";
591
+ /**
592
+ * Wire names shared by the worker script and the host adapter. Both sides must agree on the exact
593
+ * strings, so they are defined once and registered with `register` / `getProxy`.
594
+ */
595
+ var widgetGuestService = defineRpcService("guest");
596
+ var widgetGuestControlService = defineRpcService("guest-control");
597
+ var widgetHostControlService = defineRpcService("host-control");
598
+ var widgetHostCapabilitiesService = defineRpcService("host-capabilities");
599
+ defineRpcService("guest");
600
+ //#endregion
601
+ //#region src/guest/audio/protocol.ts
602
+ /**
603
+ * Typed RPC contracts of the widget audio path (RFC 0016).
604
+ *
605
+ * Three endpoints carry the whole path:
606
+ *
607
+ * - the guest runtime talks to the `AudioWorklet` over a `MessagePort` it receives from the host;
608
+ * - the host talks to the same worklet over the `AudioWorkletNode` port;
609
+ * - the host pushes availability and the direct port into the guest over the sandbox RPC endpoint.
610
+ *
611
+ * `createRpc` serializes every call, so PCM stays on the worker ↔ worklet port and never passes
612
+ * through the render host.
613
+ */
614
+ /** Name the worklet registers its processor under. */
615
+ var widgetAudioWorkletProcessor = "mica-widget-audio";
616
+ defineRpcService("audio-worklet");
617
+ var widgetAudioControlService = defineRpcService("audio-control");
618
+ var widgetAudioGuestService = defineRpcService("audio-guest");
619
+ //#endregion
620
+ //#region \0mica-widget-audio-worklet-code:/home/runner/work/mica-js/mica-js/packages/widget/src/guest/audio/entry.ts
621
+ var entry_default$1 = "(function(){function e(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var t=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(t,n,r)=>{if(this.#t)return e(()=>{});let i={listener:t,thisArgs:n};this.#e.add(i);let a=e(()=>{this.#e.delete(i)});return r?.push(a),a};get hasListeners(){return this.#e.size>0}fire(e){if(!this.#t)for(let t of[...this.#e])t.listener.call(t.thisArgs,e)}dispose(){this.#t||(this.#t=!0,this.#e.clear())}};function n(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.kind===`close`)return!0;if(!Number.isSafeInteger(t.id)||t.id<=0)return!1;switch(t.kind){case`call`:case`listen`:return typeof t.service==`string`&&t.service.length>0&&typeof t.member==`string`&&t.member.length>0&&Array.isArray(t.args)&&(t.kind!==`listen`||t.args.length===0);case`unlisten`:return!0;case`result`:return Object.hasOwn(t,`value`);case`error`:case`subscription-error`:return typeof t.name==`string`&&typeof t.message==`string`;case`event`:return Array.isArray(t.args);default:return!1}}function r(e,t){return Object.assign(Error(t),{name:e})}function i(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw r(`MethodNotFound`,`Method is not exposed: ${t}`);for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(typeof e.value==`function`)return e.value;break}}throw r(`MethodNotFound`,`Method is not callable: ${t}`)}function a(a,l={}){let u=l,d=c(u.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new t,_=new t,v=0,y=0,b=!1;function x(e){let t=o(e);try{u.onError?.(t)}catch{}g.fire(t)}function S(){if(b)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function C(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function w(e,t){S(),a.postMessage(e,t?[...t]:void 0)}function T(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function E(e,t,n){return new Promise((i,a)=>{let s=t>0?setTimeout(()=>{T(e.id)?.reject(r(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:i,reject:a,timer:s});try{w(e,n)}catch(t){T(e.id)?.reject(o(t))}})}function D(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function O(e,t,n){if(b)return;let r=o(n);try{w({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),A()}}function k(){if(!b){b=!0,a.removeEventListener(`message`,M),a.removeEventListener(`close`,k),a.removeEventListener(`messageerror`,A);for(let e of p.keys())T(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())D(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function A(){if(!b){try{w({kind:`close`})}catch(e){x(e)}k()}}async function j(e){try{let t=f.get(e.service);if(!t)throw r(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,a=i(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw r(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let o=a.call(n,(...n)=>{if(!(b||h.get(e.id)!==i))try{w({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){D(e.id),O(`subscription-error`,e.id,t)}});if(typeof o!=`function`)throw r(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=o,h.get(e.id)!==i&&i.stop(),b||w({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw r(`InvalidCall`,`Event members require a subscription`);let i=await a.apply(n,e.args);b||w({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&D(e.id),O(`error`,e.id,t)}}function M(e){let t=e.data;if(!n(t))x(r(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=y){x(r(`RpcProtocolError`,`Request IDs must increase`));return}y=t.id,j(t);break;case`unlisten`:D(t.id);break;case`result`:T(t.id)?.resolve(t.value);break;case`error`:T(t.id)?.reject(r(t.name,t.message));break;case`subscription-error`:{let e=r(t.name,t.message),n=m.delete(t.id),i=T(t.id);i?i.reject(e):n&&x(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){x(e)}break;case`close`:k()}}return a.addEventListener(`message`,M),a.addEventListener(`close`,k),a.addEventListener(`messageerror`,A),a.start?.(),{register(t,n,i={}){S();let a=s(t);if(typeof n!=`object`||!n)throw TypeError(`RPC services must be objects`);if(f.has(a))throw Error(`Service already registered: ${a}`);let o={implementation:n,options:i};return f.set(a,o),e(()=>{if(f.get(a)===o){f.delete(a);for(let[e,t]of h)t.registration===o&&(D(e),O(`subscription-error`,e,r(`ServiceUnregistered`,`Service unregistered: ${a}`)))}})},getProxy(t,n={}){let r=s(t),i=c(n.timeoutMs??d),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(t,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?t=>{if(S(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=C();m.set(n,t),E({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!b)try{w({kind:`unlisten`,id:n})}catch(e){x(e)}x(e)});let a=e(()=>{if(m.delete(n)&&(T(n)?.resolve(void 0),!b))try{w({kind:`unlisten`,id:n})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(S(),E({kind:`call`,id:C(),service:r,member:o,args:e},i,n.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(t,n,r)=>b?(t.call(n,void 0),e(()=>{})):_.event(e=>{try{t.call(n,e)}catch(e){x(e)}},void 0,r),dispose:A}}function o(e){return e instanceof Error?e:Error(String(e))}function s(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function c(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function l(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}let u=l(`audio-worklet`),d=l(`audio-control`);l(`audio-guest`);function f(e){let t=1,n=1,r=e*e/4;for(let e=1;e<64&&(n*=r/(e*e),t+=n,!(n<=t*1e-15));e+=1);return t}function p(e){if(e===0)return 1;let t=Math.PI*e;return Math.sin(t)/t}function m(e){return e<=-1||e>=1?0:f(8*Math.sqrt(1-e*e))/f(8)}function h(e){let t=/* @__PURE__ */ new Float32Array(8192),n=.45*Math.min(1,1/e);for(let e=0;e<256;e+=1){let r=e/256,i=0;for(let a=0;a<32;a+=1){let o=a-15-r,s=2*n*p(2*n*o)*m(o/16);t[e*32+a]=s,i+=s}if(i!==0)for(let n=0;n<32;n+=1)t[e*32+n]=(t[e*32+n]??0)/i}return t}var g=class{sourceRate;targetRate;ratio;passthrough;delayFrames;#e;constructor(e,t){this.sourceRate=e,this.targetRate=t,this.ratio=e/t,this.passthrough=e===t,this.delayFrames=this.passthrough?0:16*Math.max(1,this.ratio),this.#e=this.passthrough?void 0:h(this.ratio)}get span(){return this.passthrough?{behind:0,ahead:0}:{behind:15,ahead:16}}sample(e,t){if(this.passthrough)return e(Math.round(t));let n=Math.floor(t),r=(t-n)*256,i=Math.min(255,Math.floor(r)),a=Math.min(1,r-i),o=this.#e;if(o===void 0)return e(n);let s=i*32,c=i+1>=256,l=c?0:(i+1)*32,u=c&&a>0?1:0,d=n-15,f=0;for(let t=0;t<32;t+=1){let n=d+t,r=o[s+t]??0,i=o[l+t]??0;f+=e(n)*r*(1-a)+e(n+u)*i*a}return f}};function _(e,t){let n=t===`s16`?e/32768:e;return Number.isFinite(n)?n>1?1:n<-1?-1:n:0}var v=class{capacity;channels;data;written=0;readFloor=0;constructor(e,t){this.capacity=e,this.channels=t,this.data=new Float32Array(e*t)}write(e,t,n){for(let r=0;r<t;r+=1){let t=(this.written+r)%this.capacity*this.channels;for(let i=0;i<this.channels;i+=1)this.data[t+i]=_(e[r*this.channels+i]??0,n)}this.written+=t}at(e,t){return e<this.readFloor||e>=this.written?0:this.data[e%this.capacity*this.channels+t]??0}},y=class{streamId;channels;format;capacityFrames;startFrames;buffer;resampler;volume;state=`buffering`;underruns=0;endRequested=!1;finished=!1;closed=!1;reportedState=`buffering`;position;consumed=0;#e=0;constructor(e,t){this.streamId=e.streamId,this.channels=e.channels,this.format=e.format,this.capacityFrames=e.capacityFrames,this.startFrames=e.startFrames,this.volume=e.volume,this.buffer=new v(e.capacityFrames,e.channels),this.resampler=new g(e.sampleRate,t),this.position=this.resampler.delayFrames}get bufferedFrames(){return Math.max(0,this.buffer.written-this.consumed)}write(e,t){return this.closed||t<=0||this.bufferedFrames+t>this.capacityFrames?!1:(this.buffer.write(e,t,this.format),!0)}clear(){this.consumed=this.buffer.written,this.buffer.readFloor=this.buffer.written,this.position=this.buffer.written+this.resampler.delayFrames,this.state=`buffering`,this.#e=0}render(e,t,n,r){if(this.closed||e.length===0)return;let{resampler:i,buffer:a}=this,o=i.span,s=i.delayFrames,c=this.endRequested?a.written-1:a.written-1-o.ahead,l=this.position-s,u=Math.ceil((c+1-l)/i.ratio),d=this.endRequested||u<t,f=Math.max(1,r-1);for(let o=0;o<t;o+=1){let t=this.position-s;if(this.state!==`playing`){if(a.written-Math.floor(t)<(this.endRequested?1:Math.max(this.startFrames,1)))break;a.readFloor=Math.max(a.readFloor,Math.floor(t)),this.state=`playing`,this.#e=r}if(Math.floor(t)>c){this.endRequested?(this.finished=!0,this.state=`ended`):(this.state=`buffering`,this.underruns+=1,this.#e=0);break}let l=n*this.volume;if(d){let e=Math.ceil((c+1-t)/i.ratio);e<=r&&(l*=Math.max(0,e-1)/f)}if(this.#e>0&&(l*=1-this.#e/r,--this.#e),this.channels===1){let n=i.sample(e=>a.at(e,0),t)*l;for(let t of e)t[o]=(t[o]??0)+n}else for(let n=0;n<this.channels;n+=1){let r=e[Math.min(n,e.length-1)];r&&(r[o]=(r[o]??0)+i.sample(e=>a.at(e,n),t)*l)}this.position+=i.ratio;let u=Math.min(a.written,Math.floor(this.position-s));u>this.consumed&&(this.consumed=u)}}};let b=Math.PI*2;var x=class{id;type;#e;#t=0;#n;#r=0;#i=0;#a;#o=0;#s=0;#c=0;#l=0;#u=!1;constructor(e,t,n){this.id=e,this.type=t.type,this.#e=n,this.#n=t.frequency,this.#a=t.volume}get frequency(){return this.#n}get volume(){return this.#a}get finished(){return this.#u}set(e){if(this.#u)return;let t=Math.max(.005,e.rampMs/1e3);e.frequency!==void 0&&this.#d(e.frequency,t),e.volume!==void 0&&this.#f(e.volume,t)}stop(e){if(this.#u)return;let t=Math.round(e/1e3*this.#e);t<=0?this.#u=!0:(this.#l=t,this.#c=t)}render(e,t,n){if(!(this.#u||e.length===0))for(let r=0;r<t;r+=1){this.#p();let t=this.#n/this.#e,i=this.#m(t)*this.#a*n;this.#c>0&&(i*=this.#c/this.#l,--this.#c);for(let t of e)t[r]=(t[r]??0)+i;if(this.#t+=t,this.#t>=1&&(this.#t-=Math.floor(this.#t)),this.#c===0&&this.#l>0){this.#u=!0;return}}}#d(e,t){let n=Math.max(1,Math.round(t*this.#e));this.#r=(e-this.#n)/n,this.#i=n,this.#r===0&&(this.#n=e)}#f(e,t){let n=Math.max(1,Math.round(t*this.#e));this.#o=(e-this.#a)/n,this.#s=n,this.#o===0&&(this.#a=e)}#p(){this.#i>0&&(this.#n+=this.#r,--this.#i),this.#s>0&&(this.#a+=this.#o,--this.#s)}#m(e){let t=this.#t;switch(this.type){case`sine`:return Math.sin(b*t);case`square`:return(t<.5?1:-1)+C(t,e)-C(S(t+.5),e);case`sawtooth`:return 2*t-1-C(t,e);case`triangle`:return 1-4*Math.abs(t-.5)}}};function S(e){return e>=1?e-1:e}function C(e,t){if(t<=0||t>=1)return 0;if(e<t){let n=e/t;return n+n-n*n-1}if(e>1-t){let n=(e-1)/t;return n*n+n+n+1}return 0}let w=[`sine`,`square`,`triangle`,`sawtooth`];var T=class{#e;#t;#n=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ new Map;#i=/* @__PURE__ */ new Set;#a=/* @__PURE__ */ new Set;#o;#s=!1;#c=!1;#l=0;#u=!1;constructor(e){this.#e=e.sampleRate,this.#t=Math.max(1,Math.round(.02*this.#e))}attachHostPort(e){if(this.#u||this.#o!==void 0)return;let t=a(e);this.#o=t,t.register(d,this.#d())}attachGuestPort(e,t){if(this.#u)return;this.detachGuestPort(e);let n=a(t),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,o=n.register(u,this.#f(e,{progress:r,ended:i}));this.#n.set(e,{id:e,port:t,endpoint:n,progress:r,ended:i,registration:o})}detachGuestPort(e){for(let[t,n]of[...this.#r])n.runtimeId===e&&this.#_(t,`disposed`);let t=this.#n.get(e);t&&(this.#n.delete(e),t.registration.dispose(),t.endpoint.dispose(),D(t.port))}process(e){let t=e[0];if(!t||t.length===0||this.#u)return!0;for(let e of t)e.fill(0);if(this.#c||this.#r.size===0)return!0;let n=t[0]?.length??0;if(n===0)return!0;let r=Math.max(1,Math.round(this.#e*.002));for(let e of[...this.#r.values()]){let i=this.#s?0:e.volume;for(let[r,a]of[...e.tones])a.render(t,n,i),a.finished&&(e.tones.delete(r),this.#b(e,{target:`tone`,id:r,reason:`stopped`}));for(let[a,o]of[...e.streams])o.render(t,n,i,r),o.finished?this.#v(e,a,`finished`):o.state!==o.reportedState&&(o.reportedState=o.state,this.#y(e,o))}if(this.#l+=n,this.#l>=this.#t){this.#l=0;for(let e of this.#r.values())for(let t of e.streams.values())this.#y(e,t)}return!0}dispose(){if(!this.#u){for(let e of[...this.#r.keys()])this.#_(e,`disposed`);for(let e of[...this.#n.keys()])this.detachGuestPort(e);this.#u=!0,this.#a.clear(),this.#o?.dispose(),this.#o=void 0}}#d(){return{openSession:e=>this.#p(e),closeSession:e=>this.#_(e,`stopped`),setSessionVolume:(e,t)=>{let n=this.#r.get(e);n&&typeof t==`number`&&Number.isFinite(t)&&(n.volume=Math.min(1,Math.max(0,t)))},setMuted:e=>{this.#s=e===!0},suspend:()=>{this.#c=!0},resume:()=>{this.#c=!1},attachGuestPort:(e,t)=>{typeof e==`string`&&e.length!==0&&E(t)&&this.attachGuestPort(e,t)},detachGuestPort:e=>{typeof e==`string`&&this.detachGuestPort(e)},onDidDiagnostic:e=>typeof e==`function`?(this.#a.add(e),()=>{this.#a.delete(e)}):()=>{}}}#f(e,t){return{createTone:(t,n)=>{this.#m(e,t,n)},setTone:(t,n,r)=>{let i=this.#g(e,t),a=i?.tones.get(n);i&&a&&(A(r)?a.set(r):this.#x(i.session,`worklet`,`A tone update was rejected`))},stopTone:(t,n,r)=>{let i=this.#g(e,t),a=i?.tones.get(n);if(!i||!a)return;let o=typeof r==`object`&&r&&Number.isFinite(r.fadeMs)?Math.min(1e4,Math.max(0,r.fadeMs)):0;a.stop(o),a.finished&&(i.tones.delete(n),this.#b(i,{target:`tone`,id:n,reason:`stopped`}))},createStream:(t,n)=>this.#h(e,t,n),writeStream:(t,n,r)=>{let i=this.#g(e,t),a=i?.streams.get(n);if(!i||!a)return!1;let o=M(r,a.channels,a.format);return o===void 0||o>a.capacityFrames?(this.#x(i.session,`worklet`,`A PCM block was rejected`),!1):a.write(r,o)?!0:(this.#x(i.session,`capacity`,`A PCM block beyond the stream capacity was dropped`),!1)},clearStream:(t,n)=>{let r=this.#g(e,t),i=r?.streams.get(n);r&&i&&(i.clear(),this.#y(r,i))},endStream:(t,n)=>{let r=this.#g(e,t),i=r?.streams.get(n);r&&i&&(i.endRequested=!0,i.consumed>=i.buffer.written&&this.#v(r,n,`finished`))},closeStream:(t,n)=>{let r=this.#g(e,t);r?.streams.has(n)&&this.#v(r,n,`stopped`)},onDidProgress:e=>typeof e==`function`?(t.progress.add(e),()=>{t.progress.delete(e)}):()=>{},onDidEnded:e=>typeof e==`function`?(t.ended.add(e),()=>{t.ended.delete(e)}):()=>{}}}#p(e){O(e)&&!this.#r.has(e.session)&&(this.#n.has(e.runtimeId)?this.#r.set(e.session,{session:e.session,runtimeId:e.runtimeId,instanceId:e.instanceId,maxVoices:Math.max(1,Math.floor(e.maxVoices)),maxStreams:Math.max(1,Math.floor(e.maxStreams)),volume:1,tones:/* @__PURE__ */ new Map,streams:/* @__PURE__ */ new Map}):this.#x(e.session,`worklet`,`A session arrived before its guest port`))}#m(e,t,n){let r=this.#g(e,t);if(r){if(!k(n))this.#x(r.session,`worklet`,`A tone command was rejected`);else if(!r.tones.has(n.voiceId))for(r.tones.set(n.voiceId,new x(n.voiceId,n,this.#e));r.tones.size>r.maxVoices;){let e=r.tones.keys().next().value;if(e===void 0||e===n.voiceId)break;r.tones.delete(e),this.#b(r,{target:`tone`,id:e,reason:`dropped`}),this.#x(r.session,`voices`,`A tone was dropped: the per-instance ceiling of ${r.maxVoices} is exhausted`)}}}#h(e,t,n){let r=this.#g(e,t);return r?j(n)?r.streams.has(n.streamId)?{accepted:!0}:r.streams.size>=r.maxStreams?(this.#x(r.session,`streams`,`A PCM stream was refused: the per-instance quota of ${r.maxStreams} is exhausted`),{accepted:!1}):(r.streams.set(n.streamId,new y(n,this.#e)),{accepted:!0}):(this.#x(r.session,`worklet`,`A stream-open command was rejected`),{accepted:!1}):{accepted:!1}}#g(e,t){if(typeof t!=`string`)return;let n=this.#r.get(t);if(!n)this.#x(t,`worklet`,`A guest call named an unknown session`);else if(n.runtimeId!==e)this.#x(t,`worklet`,`A guest call came from another runtime`);else return n}#_(e,t){let n=this.#r.get(e);if(n){for(let e of[...n.tones.keys()])n.tones.delete(e),this.#b(n,{target:`tone`,id:e,reason:t});for(let e of[...n.streams.keys()])this.#v(n,e,t);this.#r.delete(e);for(let t of[...this.#i])t.startsWith(`${e}\\u0000`)&&this.#i.delete(t)}}#v(e,t,n){let r=e.streams.get(t);r&&(r.closed=!0,r.state=n===`finished`?`ended`:`closed`,e.streams.delete(t),this.#y(e,r),this.#b(e,{target:`stream`,id:t,reason:n}))}#y(e,t){let n=this.#n.get(e.runtimeId);if(!n)return;let r={streamId:t.streamId,consumedFrames:t.consumed,underruns:t.underruns,state:t.state};for(let e of[...n.progress])try{e(r)}catch{}}#b(e,t){let n=this.#n.get(e.runtimeId);if(n)for(let e of[...n.ended])try{e(t)}catch{}}#x(e,t,n){let r=`${e}\\u0000${t}`;if(this.#i.has(r))return;this.#i.add(r);let i={session:e,code:t===`worklet`?`widget/audio-failed`:`widget/audio-limit`,category:t,message:n};for(let e of[...this.#a])try{e(i)}catch{}}};function E(e){return typeof e==`object`&&!!e&&typeof e.postMessage==`function`&&typeof e.addEventListener==`function`}function D(e){try{e.close?.()}catch{}}function O(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.session==`string`&&t.session.length>0&&typeof t.runtimeId==`string`&&t.runtimeId.length>0&&typeof t.instanceId==`string`&&typeof t.maxVoices==`number`&&Number.isFinite(t.maxVoices)&&typeof t.maxStreams==`number`&&Number.isFinite(t.maxStreams)}function k(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.frequency,r=t.volume;return typeof t.voiceId==`string`&&t.voiceId.length>0&&typeof t.type==`string`&&w.includes(t.type)&&typeof n==`number`&&Number.isFinite(n)&&n>0&&n<=24e3&&typeof r==`number`&&Number.isFinite(r)&&r>=0&&r<=1}function A(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.rampMs;if(typeof n!=`number`||!Number.isFinite(n)||n<0||n>1e4)return!1;let r=t.volume;if(r!==void 0&&(typeof r!=`number`||!Number.isFinite(r)||r<0||r>1))return!1;let i=t.frequency;return!(i!==void 0&&(typeof i!=`number`||!Number.isFinite(i)||i<=0||i>24e3))}function j(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.sampleRate,r=t.capacityFrames,i=t.startFrames,a=t.volume;return typeof t.streamId==`string`&&t.streamId.length>0&&typeof n==`number`&&Number.isInteger(n)&&n>=8e3&&n<=96e3&&(t.channels===1||t.channels===2)&&(t.format===`s16`||t.format===`f32`)&&typeof r==`number`&&Number.isInteger(r)&&r>=1&&r<=192e3&&typeof i==`number`&&Number.isInteger(i)&&i>=0&&i<=r&&typeof a==`number`&&Number.isFinite(a)}function M(e,t,n){if(e instanceof(n===`s16`?Int16Array:Float32Array)&&e.length!==0&&e.length%t===0)return e.length/t}var N=class extends AudioWorkletProcessor{#e;constructor(){super(),this.#e=new T({sampleRate}),this.#e.attachHostPort(this.port)}process(e,t){return this.#e.process(t)}};registerProcessor(`mica-widget-audio`,N)})();";
622
+ //#endregion
623
+ //#region src/host/audio/worklet.ts
624
+ var objectUrl;
625
+ /**
626
+ * Blob URL of the packaged `AudioWorkletProcessor` script.
627
+ *
628
+ * The script is bundled and minified into this module while the package is built, so an
629
+ * `AudioContext` can load it through `addModule()` without the package publishing a separate
630
+ * `*.worklet.js` asset. The URL is created once per page and reused by every host.
631
+ */
632
+ function widgetAudioWorkletUrl() {
633
+ objectUrl ??= URL.createObjectURL(new Blob([entry_default$1], { type: "text/javascript" }));
634
+ return objectUrl;
635
+ }
636
+ /**
637
+ * Loads the packaged processor into `context` and creates its node.
638
+ *
639
+ * Pass it as `getAudioWorklet` wherever a `WidgetHost` or `CanvasEditor` asks for one; hosts that
640
+ * provide no loader of their own use the same processor internally.
641
+ */
642
+ async function createWidgetAudioWorklet(context) {
643
+ if (typeof context.audioWorklet?.addModule !== "function") throw new Error("The AudioContext does not support AudioWorklet.addModule().");
644
+ await context.audioWorklet.addModule(widgetAudioWorkletUrl());
645
+ return new AudioWorkletNode(context, widgetAudioWorkletProcessor);
646
+ }
647
+ //#endregion
648
+ //#region src/host/audio/engine.ts
649
+ /**
650
+ * Host half of the audio path (RFC 0016).
651
+ *
652
+ * Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the
653
+ * worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.
654
+ * No audio node other than that worklet is created here: tones, mixing and volume all live inside
655
+ * the worklet.
656
+ */
657
+ var WidgetAudioEngine = class {
658
+ #context;
659
+ #destination;
660
+ #report;
661
+ #notify;
662
+ #limits;
663
+ #loadWorklet;
664
+ #createChannel;
665
+ #createWorkletNode;
666
+ #runtimeId = `r${Math.random().toString(36).slice(2, 10)}`;
667
+ #instances = /* @__PURE__ */ new Map();
668
+ #worklet;
669
+ #endpoint;
670
+ #control;
671
+ #booting;
672
+ #available;
673
+ #muted = false;
674
+ #suspended = false;
675
+ #sessionCounter = 0;
676
+ #disposed = false;
677
+ #lastState;
678
+ #detachStateListener;
679
+ /** Context state moved without an engine call; guests get the same ordered notification. */
680
+ #onContextStateChange = () => {
681
+ if (this.#disposed) return;
682
+ this.#syncState();
683
+ };
684
+ constructor(options) {
685
+ this.#context = options.context;
686
+ this.#destination = options.destination ?? options.context.destination;
687
+ this.#report = options.report;
688
+ this.#notify = options.notify;
689
+ this.#limits = {
690
+ maxVoices: Math.max(1, Math.floor(options.limits?.maxVoices ?? 8)),
691
+ maxStreams: Math.max(1, Math.floor(options.limits?.maxStreams ?? 4))
692
+ };
693
+ this.#loadWorklet = options.loadWorklet;
694
+ this.#createChannel = options.createChannel ?? (() => {
695
+ const channel = new MessageChannel();
696
+ return {
697
+ port1: channel.port1,
698
+ port2: channel.port2
699
+ };
700
+ });
701
+ this.#createWorkletNode = options.createWorkletNode ?? ((context, name) => {
702
+ const ctor = globalThis.AudioWorkletNode;
703
+ if (!ctor) throw new Error("AudioWorkletNode is not available");
704
+ return new ctor(context, name, {
705
+ numberOfInputs: 0,
706
+ numberOfOutputs: 1,
707
+ outputChannelCount: [2]
708
+ });
709
+ });
710
+ }
711
+ /**
712
+ * Current availability.
713
+ *
714
+ * `unavailable` means "no audio at all": the host configured none, the browser lacks
715
+ * `AudioWorklet`, or the worklet module failed to load.
716
+ */
717
+ get state() {
718
+ if (this.#disposed || this.#available === false) return "unavailable";
719
+ if (this.#available !== true || this.#suspended) return "suspended";
720
+ return this.#context.state === "running" ? "running" : "suspended";
721
+ }
722
+ /** Limits in force, so a caller can mirror them in its own UI. */
723
+ get limits() {
724
+ return this.#limits;
725
+ }
726
+ /**
727
+ * Opens the mount generation of one instance.
728
+ *
729
+ * Resolves once the worklet registered the session token, so the `mount` request that carries it
730
+ * can never arrive after the first guest call of that generation.
731
+ */
732
+ async open(instanceId) {
733
+ if (this.#disposed) return { state: "unavailable" };
734
+ if (!await this.#boot()) return { state: "unavailable" };
735
+ this.close(instanceId);
736
+ this.#sessionCounter += 1;
737
+ const session = `${this.#runtimeId}-${this.#sessionCounter}`;
738
+ this.#instances.set(instanceId, {
739
+ instanceId,
740
+ session
741
+ });
742
+ try {
743
+ await this.#control?.openSession({
744
+ session,
745
+ runtimeId: this.#runtimeId,
746
+ instanceId,
747
+ maxVoices: this.#limits.maxVoices,
748
+ maxStreams: this.#limits.maxStreams
749
+ });
750
+ } catch (error) {
751
+ this.#report("widget/audio-failed", instanceId, `The audio worklet rejected the session: ${describe(error)}`);
752
+ }
753
+ this.#syncState();
754
+ return {
755
+ state: this.state,
756
+ session
757
+ };
758
+ }
759
+ setMuted(muted) {
760
+ this.#muted = muted === true;
761
+ this.#call((control) => control.setMuted(this.#muted));
762
+ }
763
+ setInstanceVolume(instanceId, volume) {
764
+ if (typeof volume !== "number") throw new TypeError("WidgetHost.audio.setInstanceVolume expects a number");
765
+ if (!Number.isFinite(volume) || volume < 0 || volume > 1) throw new RangeError("WidgetHost.audio.setInstanceVolume expects a value in [0, 1]");
766
+ const instance = this.#instances.get(instanceId);
767
+ if (!instance) return;
768
+ this.#call((control) => control.setSessionVolume(instance.session, volume));
769
+ }
770
+ /** Freezes audio without touching the caller's `AudioContext`. */
771
+ suspend() {
772
+ if (this.#disposed || this.#suspended) return;
773
+ this.#suspended = true;
774
+ this.#call((control) => control.suspend());
775
+ this.#syncState();
776
+ }
777
+ resume() {
778
+ if (this.#disposed) return;
779
+ this.#suspended = false;
780
+ this.#call((control) => control.resume());
781
+ this.#syncState();
782
+ }
783
+ /**
784
+ * Closes the instance only when it still belongs to `session`.
785
+ *
786
+ * A mount attempt that lost its id may have opened its own audio generation after the host's
787
+ * cleanup sweep; closing by id alone would tear down the replacement instead.
788
+ */
789
+ closeSession(instanceId, session) {
790
+ const instance = this.#instances.get(instanceId);
791
+ if (!instance || instance.session !== session) return;
792
+ this.close(instanceId);
793
+ }
794
+ /** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */
795
+ close(instanceId) {
796
+ const instance = this.#instances.get(instanceId);
797
+ if (!instance) return;
798
+ this.#instances.delete(instanceId);
799
+ this.#call((control) => control.closeSession(instance.session));
800
+ }
801
+ /**
802
+ * Drops every instance and hands the worklet a fresh guest channel.
803
+ *
804
+ * Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs
805
+ * a port of its own.
806
+ */
807
+ reset() {
808
+ for (const instanceId of [...this.#instances.keys()]) this.close(instanceId);
809
+ if (this.#available === true && this.#control !== void 0) this.#restartRuntime();
810
+ }
811
+ dispose() {
812
+ if (this.#disposed) return;
813
+ for (const instanceId of [...this.#instances.keys()]) this.close(instanceId);
814
+ this.#call((control) => control.detachGuestPort(this.#runtimeId));
815
+ this.#disposed = true;
816
+ this.#detachStateListener?.();
817
+ this.#detachStateListener = void 0;
818
+ this.#endpoint?.dispose();
819
+ this.#endpoint = void 0;
820
+ this.#control = void 0;
821
+ const worklet = this.#worklet;
822
+ this.#worklet = void 0;
823
+ if (worklet !== void 0) {
824
+ closePort(worklet.port);
825
+ try {
826
+ worklet.disconnect?.();
827
+ } catch {}
828
+ }
829
+ }
830
+ /** Boots the worklet once; a failure is permanent for the lifetime of the engine. */
831
+ #boot() {
832
+ this.#booting ??= this.#start().catch((error) => {
833
+ this.#available = false;
834
+ if (!this.#disposed) this.#report("widget/audio-failed", "", `Widget audio is unavailable: ${describe(error)}`);
835
+ return false;
836
+ });
837
+ return this.#booting;
838
+ }
839
+ async #start() {
840
+ if (this.#loadWorklet === void 0 && typeof this.#context.audioWorklet?.addModule !== "function") {
841
+ this.#available = false;
842
+ return false;
843
+ }
844
+ this.#listenForContextState();
845
+ const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());
846
+ if (this.#disposed) {
847
+ closePort(worklet.port);
848
+ try {
849
+ worklet.disconnect?.();
850
+ } catch {}
851
+ return false;
852
+ }
853
+ this.#worklet = worklet;
854
+ const endpoint = createRpc(worklet.port);
855
+ this.#endpoint = endpoint;
856
+ const control = endpoint.getProxy(widgetAudioControlService, { transfer: (member, args) => member === "attachGuestPort" ? [args[1]] : [] });
857
+ this.#control = control;
858
+ control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));
859
+ worklet.connect(this.#destination);
860
+ await this.#attachRuntime();
861
+ this.#available = true;
862
+ return true;
863
+ }
864
+ /**
865
+ * Mirrors the context's own `statechange` onto mounted guests.
866
+ *
867
+ * The caller owns the `AudioContext`, so its state can move without the engine asking: autoplay
868
+ * policy keeping it suspended, the browser suspending a hidden page, or the caller calling
869
+ * `resume()`. Guests read `api.audio.state` and `onStateChange`, so those moves must be forwarded.
870
+ */
871
+ #listenForContextState() {
872
+ if (this.#detachStateListener) return;
873
+ const context = this.#context;
874
+ if (typeof context.addEventListener === "function") {
875
+ context.addEventListener("statechange", this.#onContextStateChange);
876
+ this.#detachStateListener = () => context.removeEventListener?.("statechange", this.#onContextStateChange);
877
+ return;
878
+ }
879
+ if (!("onstatechange" in context)) return;
880
+ const previous = context.onstatechange;
881
+ context.onstatechange = this.#onContextStateChange;
882
+ this.#detachStateListener = () => {
883
+ if (context.onstatechange === this.#onContextStateChange) context.onstatechange = previous;
884
+ };
885
+ }
886
+ /** Worklet → host diagnostics, attributed back to the instance that owns the session. */
887
+ #onDiagnostic(diagnostic) {
888
+ const owner = [...this.#instances.values()].find((entry) => entry.session === diagnostic.session);
889
+ if (!owner) return;
890
+ this.#report(diagnostic.code, owner.instanceId, diagnostic.message);
891
+ }
892
+ async #loadDefaultWorklet() {
893
+ await this.#context.audioWorklet?.addModule(widgetAudioWorkletUrl());
894
+ return this.#createWorkletNode(this.#context, widgetAudioWorkletProcessor);
895
+ }
896
+ async #restartRuntime() {
897
+ const control = this.#control;
898
+ if (control === void 0) return;
899
+ try {
900
+ await control.detachGuestPort(this.#runtimeId);
901
+ } catch {}
902
+ await this.#attachRuntime();
903
+ }
904
+ /** Transfers a fresh port to the worklet and hands the other end to the guest. */
905
+ async #attachRuntime() {
906
+ const control = this.#control;
907
+ if (control === void 0 || this.#disposed) return;
908
+ const channel = this.#createChannel();
909
+ try {
910
+ await control.attachGuestPort(this.#runtimeId, channel.port1);
911
+ } catch (error) {
912
+ closePort(channel.port1);
913
+ closePort(channel.port2);
914
+ this.#report("widget/audio-failed", "", `The audio worklet rejected the guest port: ${describe(error)}`);
915
+ return;
916
+ }
917
+ this.#notify.emitPort(channel.port2);
918
+ }
919
+ /** Fires one host → worklet call; a missing or closed worklet is not a widget failure. */
920
+ #call(run) {
921
+ const control = this.#control;
922
+ if (control === void 0 || this.#disposed) return;
923
+ try {
924
+ run(control).catch(() => void 0);
925
+ } catch {}
926
+ }
927
+ #syncState() {
928
+ const next = this.state;
929
+ if (next === this.#lastState) return;
930
+ this.#lastState = next;
931
+ this.#notify.emitState(next);
932
+ }
933
+ };
934
+ function closePort(port) {
935
+ try {
936
+ port.close();
937
+ } catch {}
938
+ }
939
+ function describe(error) {
940
+ if (error instanceof Error && error.message) return error.message;
941
+ return typeof error === "string" ? error : String(error);
942
+ }
943
+ //#endregion
944
+ //#region src/host/audio/noop.ts
945
+ /**
946
+ * Controls of a host that was created without `audio`.
947
+ *
948
+ * The state is `unavailable` and every setter is a no-op, so callers never have to branch on
949
+ * whether audio is configured.
950
+ */
951
+ var NO_AUDIO_CONTROLS = {
952
+ state: "unavailable",
953
+ setMuted() {},
954
+ setInstanceVolume() {},
955
+ suspend() {},
956
+ resume() {}
957
+ };
330
958
  //#endregion
331
- //#region src/runtime/props.ts
959
+ //#region src/guest/widget/props.ts
332
960
  function isPlainObject(value) {
333
961
  if (typeof value !== "object" || value === null) return false;
334
962
  const prototype = Object.getPrototypeOf(value);
@@ -393,61 +1021,176 @@ function collectAssetRefs(value, found = /* @__PURE__ */ new Map(), seen = /* @_
393
1021
  return found;
394
1022
  }
395
1023
  //#endregion
396
- //#region src/host/layers.ts
1024
+ //#region src/host/catalog.ts
1025
+ /** `symbol` + `port` pair as one map key; neither part can contain a NUL. */
1026
+ function portKey(symbol, port) {
1027
+ return `${symbol}\u0000${port}`;
1028
+ }
397
1029
  /**
398
- * Layer table owned by the host. Records mutate in place, so callers holding a layer from `get()`
399
- * or `list()` observe later frames without re-reading the table.
1030
+ * Catalog the host assembles itself (RFC 0018).
1031
+ *
1032
+ * Widget ports and properties come from the definitions `widgetProvider.resolve` returned, the
1033
+ * device side from `deviceHost.getTopics()` and the schematic the runtime loaded. A host with an
1034
+ * explicit `WidgetHostOptions.catalog` skips this one entirely.
400
1035
  */
401
- var WidgetLayerStore = class {
1036
+ var HostBindingCatalog = class {
1037
+ #definitions = /* @__PURE__ */ new Map();
1038
+ #schematics = /* @__PURE__ */ new Set();
1039
+ #symbols = /* @__PURE__ */ new Set();
1040
+ #ports = /* @__PURE__ */ new Map();
1041
+ /** Whether the provider answered for `ref`; until it does, that widget stays unchecked. */
1042
+ knows(ref) {
1043
+ return this.#definitions.has(ref);
1044
+ }
1045
+ /** Records one definition, so the synchronous validation no longer needs the provider. */
1046
+ recordDefinition(ref, definition) {
1047
+ this.#definitions.set(ref, {
1048
+ ports: definition.ports,
1049
+ propertyKeys: Object.keys(definition.properties)
1050
+ });
1051
+ }
1052
+ /**
1053
+ * Replaces the device side after a schematic load.
1054
+ *
1055
+ * `schematics` holds every path that identifies the loaded schematic (the reference the document
1056
+ * wrote and the absolute URI it resolved to); `topics` are the endpoints the running devices
1057
+ * report. A symbol the runtime does not report an endpoint for still counts as present when the
1058
+ * schematic lists it.
1059
+ */
1060
+ setDeviceFacts(options) {
1061
+ this.#schematics = new Set(options.schematics.filter((path) => path !== void 0 && path !== ""));
1062
+ this.#symbols = new Set(options.schematic?.sheet.symbols.map((symbol) => symbol.id) ?? []);
1063
+ this.#ports = /* @__PURE__ */ new Map();
1064
+ for (const topic of options.topics) {
1065
+ this.#symbols.add(topic.symbol);
1066
+ const type = parsePayloadType(topic.type);
1067
+ if (type === void 0) continue;
1068
+ this.#ports.set(portKey(topic.symbol, topic.port), {
1069
+ direction: topic.direction,
1070
+ type
1071
+ });
1072
+ }
1073
+ }
1074
+ widgetDefinition(ref) {
1075
+ return this.#definitions.get(ref);
1076
+ }
1077
+ hasSchematic(path) {
1078
+ return this.#schematics.has(path);
1079
+ }
1080
+ hasSymbol(symbolId) {
1081
+ return this.#symbols.has(symbolId);
1082
+ }
1083
+ symbolPort(symbolId, port) {
1084
+ return this.#ports.get(portKey(symbolId, port));
1085
+ }
1086
+ };
1087
+ //#endregion
1088
+ //#region src/host/widgets.ts
1089
+ /**
1090
+ * Instance table owned by the host.
1091
+ *
1092
+ * The table is the single source of the two projections RFC 0018 defines: `listInstances()` reads a
1093
+ * bulk view without bitmaps, and the four `onDid*` events report one change each with the complete
1094
+ * state. The legacy `WidgetLayers` view stays for the canvas editor: records mutate in place, so a
1095
+ * caller holding a layer from `get()` sees later frames without re-reading the table.
1096
+ */
1097
+ var WidgetStore = class {
402
1098
  #records = /* @__PURE__ */ new Map();
403
- #listeners = /* @__PURE__ */ new Set();
1099
+ #changes = /* @__PURE__ */ new Set();
1100
+ #added = new Emitter();
1101
+ #updated = new Emitter();
1102
+ #removed = new Emitter();
1103
+ #reordered = new Emitter();
1104
+ /**
1105
+ * The four RFC 0018 events. A listener that throws is logged instead of breaking the document
1106
+ * flow, and the subscription itself is an ordinary {@link Disposable}.
1107
+ */
1108
+ onDidAddWidget = (listener, thisArgs, disposables) => this.#added.event((widget) => invoke(listener, widget, "widget add listener", thisArgs), void 0, disposables);
1109
+ onDidChangeWidget = (listener, thisArgs, disposables) => this.#updated.event((widget) => invoke(listener, widget, "widget change listener", thisArgs), void 0, disposables);
1110
+ onDidRemoveWidget = (listener, thisArgs, disposables) => this.#removed.event((instanceId) => invoke(listener, instanceId, "widget remove listener", thisArgs), void 0, disposables);
1111
+ onDidReorderWidgets = (listener, thisArgs, disposables) => this.#reordered.event((order) => invoke(listener, order, "widget reorder listener", thisArgs), void 0, disposables);
404
1112
  list() {
405
1113
  return [...this.#records.values()];
406
1114
  }
407
1115
  get(instanceId) {
408
1116
  return this.#records.get(instanceId);
409
1117
  }
1118
+ listInstances() {
1119
+ return [...this.#records.values()].map(toInstance);
1120
+ }
410
1121
  subscribe(listener) {
411
- this.#listeners.add(listener);
1122
+ this.#changes.add(listener);
412
1123
  return () => {
413
- this.#listeners.delete(listener);
1124
+ this.#changes.delete(listener);
414
1125
  };
415
1126
  }
416
1127
  add(init) {
417
1128
  this.remove(init.instanceId);
418
1129
  const record = {
419
1130
  instanceId: init.instanceId,
1131
+ widget: init.widget,
1132
+ x: init.x,
1133
+ y: init.y,
420
1134
  width: init.width,
421
1135
  height: init.height,
1136
+ rotation: init.rotation,
422
1137
  dpr: init.dpr,
1138
+ properties: init.properties,
1139
+ bindings: init.bindings,
423
1140
  bitmap: void 0,
424
1141
  sequence: 0
425
1142
  };
426
1143
  this.#records.set(init.instanceId, record);
427
- this.#emit({
1144
+ this.#emitChange({
428
1145
  type: "added",
429
1146
  instanceId: init.instanceId
430
1147
  });
1148
+ this.#emitAdd(record);
431
1149
  return record;
432
1150
  }
433
- setSize(instanceId, width, height) {
434
- const record = this.#records.get(instanceId);
435
- if (!record || record.width === width && record.height === height) return;
436
- record.width = width;
437
- record.height = height;
438
- this.#emit({
439
- type: "updated",
440
- instanceId
441
- });
442
- }
443
- setDpr(instanceId, dpr) {
1151
+ /**
1152
+ * Applies the document-derived fields of one instance and reports the ones that changed.
1153
+ *
1154
+ * @returns whether anything changed.
1155
+ */
1156
+ update(instanceId, patch) {
444
1157
  const record = this.#records.get(instanceId);
445
- if (!record || record.dpr === dpr) return;
446
- record.dpr = dpr;
447
- this.#emit({
448
- type: "updated",
449
- instanceId
450
- });
1158
+ if (!record) return false;
1159
+ let changed = false;
1160
+ if (patch.x !== void 0 && patch.x !== record.x) {
1161
+ record.x = patch.x;
1162
+ changed = true;
1163
+ }
1164
+ if (patch.y !== void 0 && patch.y !== record.y) {
1165
+ record.y = patch.y;
1166
+ changed = true;
1167
+ }
1168
+ if (patch.width !== void 0 && patch.width !== record.width) {
1169
+ record.width = patch.width;
1170
+ changed = true;
1171
+ }
1172
+ if (patch.height !== void 0 && patch.height !== record.height) {
1173
+ record.height = patch.height;
1174
+ changed = true;
1175
+ }
1176
+ if (patch.rotation !== void 0 && patch.rotation !== record.rotation) {
1177
+ record.rotation = patch.rotation;
1178
+ changed = true;
1179
+ }
1180
+ if (patch.dpr !== void 0 && patch.dpr !== record.dpr) {
1181
+ record.dpr = patch.dpr;
1182
+ changed = true;
1183
+ }
1184
+ if (patch.properties !== void 0 && !sameRecord(record.properties, patch.properties)) {
1185
+ record.properties = patch.properties;
1186
+ changed = true;
1187
+ }
1188
+ if (patch.bindings !== void 0 && !sameRecord(record.bindings, patch.bindings)) {
1189
+ record.bindings = patch.bindings;
1190
+ changed = true;
1191
+ }
1192
+ if (changed) this.#emitUpdate(record);
1193
+ return changed;
451
1194
  }
452
1195
  /** Installs a frame, closing the one it replaces, and bumps the sequence. */
453
1196
  setBitmap(instanceId, bitmap) {
@@ -460,10 +1203,7 @@ var WidgetLayerStore = class {
460
1203
  record.bitmap = bitmap;
461
1204
  record.sequence += 1;
462
1205
  closeBitmap(previous);
463
- this.#emit({
464
- type: "updated",
465
- instanceId
466
- });
1206
+ this.#emitUpdate(record);
467
1207
  }
468
1208
  remove(instanceId) {
469
1209
  const record = this.#records.get(instanceId);
@@ -471,16 +1211,17 @@ var WidgetLayerStore = class {
471
1211
  this.#records.delete(instanceId);
472
1212
  closeBitmap(record.bitmap);
473
1213
  record.bitmap = void 0;
474
- this.#emit({
1214
+ this.#emitChange({
475
1215
  type: "removed",
476
1216
  instanceId
477
1217
  });
1218
+ this.#emitRemove(instanceId);
478
1219
  }
479
1220
  /**
480
1221
  * Rewrites drawing order to `instanceIds` without touching a frame.
481
1222
  *
482
1223
  * Ids the table does not hold are skipped, and records the caller did not list keep their
483
- * relative order at the end: a mount in flight owns a layer before the document instance that
1224
+ * relative order at the end: a mount in flight owns an instance before the document entry that
484
1225
  * created it is reconciled.
485
1226
  */
486
1227
  reorder(instanceIds) {
@@ -493,19 +1234,88 @@ var WidgetLayerStore = class {
493
1234
  if (sameOrder([...this.#records.keys()], [...ordered.keys()])) return;
494
1235
  this.#records.clear();
495
1236
  for (const [instanceId, record] of ordered) this.#records.set(instanceId, record);
496
- this.#emit({ type: "reordered" });
1237
+ this.#emitChange({ type: "reordered" });
1238
+ this.#reordered.fire([...this.#records.keys()]);
497
1239
  }
498
1240
  clear() {
499
1241
  for (const instanceId of [...this.#records.keys()]) this.remove(instanceId);
500
1242
  }
501
- #emit(change) {
502
- for (const listener of [...this.#listeners]) try {
503
- listener(change);
504
- } catch (error) {
505
- console.error("[@mica-js/widget] layer listener threw", error);
1243
+ /**
1244
+ * Reports every instance as removed and then added again, in drawing order, without touching a
1245
+ * record: a subscriber rebuilds its composite from the same bitmaps.
1246
+ */
1247
+ invalidate() {
1248
+ const records = [...this.#records.values()];
1249
+ for (const record of records) {
1250
+ this.#emitChange({
1251
+ type: "removed",
1252
+ instanceId: record.instanceId
1253
+ });
1254
+ this.#emitRemove(record.instanceId);
506
1255
  }
1256
+ for (const record of records) {
1257
+ this.#emitChange({
1258
+ type: "added",
1259
+ instanceId: record.instanceId
1260
+ });
1261
+ this.#emitAdd(record);
1262
+ }
1263
+ }
1264
+ #emitUpdate(record) {
1265
+ this.#emitChange({
1266
+ type: "updated",
1267
+ instanceId: record.instanceId
1268
+ });
1269
+ this.#updated.fire(toWidget(record));
1270
+ }
1271
+ #emitAdd(record) {
1272
+ this.#added.fire(toWidget(record));
1273
+ }
1274
+ #emitRemove(instanceId) {
1275
+ this.#removed.fire(instanceId);
1276
+ }
1277
+ #emitChange(change) {
1278
+ for (const listener of [...this.#changes]) invoke(listener, change, "layer listener");
507
1279
  }
508
1280
  };
1281
+ function toWidget(record) {
1282
+ return {
1283
+ instanceId: record.instanceId,
1284
+ widget: record.widget,
1285
+ x: record.x,
1286
+ y: record.y,
1287
+ width: record.width,
1288
+ height: record.height,
1289
+ rotation: record.rotation,
1290
+ dpr: record.dpr,
1291
+ properties: record.properties,
1292
+ bindings: record.bindings,
1293
+ bitmap: record.bitmap,
1294
+ sequence: record.sequence
1295
+ };
1296
+ }
1297
+ function toInstance(record) {
1298
+ return {
1299
+ instanceId: record.instanceId,
1300
+ widget: record.widget,
1301
+ x: record.x,
1302
+ y: record.y,
1303
+ width: record.width,
1304
+ height: record.height,
1305
+ rotation: record.rotation,
1306
+ dpr: record.dpr,
1307
+ properties: record.properties,
1308
+ bindings: record.bindings,
1309
+ sequence: record.sequence
1310
+ };
1311
+ }
1312
+ function invoke(listener, payload, name, thisArgs) {
1313
+ try {
1314
+ listener.call(thisArgs, payload);
1315
+ } catch (error) {
1316
+ console.error(`[@mica-js/widget] ${name} threw`, error);
1317
+ }
1318
+ }
509
1319
  /** Closes a bitmap without letting a double close escape. */
510
1320
  function closeBitmap(bitmap) {
511
1321
  if (!bitmap) return;
@@ -513,48 +1323,37 @@ function closeBitmap(bitmap) {
513
1323
  bitmap.close();
514
1324
  } catch {}
515
1325
  }
516
- function sameOrder(left, right) {
517
- return left.length === right.length && left.every((id, index) => id === right[index]);
518
- }
519
- //#endregion
520
- //#region src/internal/runtime-source.ts
521
- /** ESM guest runtime for widget instances, bundled at build time by `vite.plugins.ts`. */
522
- var WIDGET_RUNTIME_SOURCE = "//#region src/runtime/protocol.ts\n/**\n* Guest event names. The sandbox reserves the `mica:` namespace for its own traffic: guest events\n* with that prefix never reach host listeners, and `sandbox.on('mica:...')` throws. Widget traffic\n* therefore lives in the `widget:` namespace.\n*/\nconst WIDGET_FRAME_EVENT = \"widget:frame\";\nconst WIDGET_PUBLISH_EVENT = \"widget:publish\";\nconst WIDGET_ERROR_EVENT = \"widget:error\";\n/** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */\nconst WIDGET_ASSET_FAILED_EVENT = \"widget:asset-failed\";\n/** Guest methods the host reaches through `sandbox.call()`. */\nconst WIDGET_LOAD_METHOD = \"load\";\nconst WIDGET_MOUNT_METHOD = \"mount\";\nconst WIDGET_UNMOUNT_METHOD = \"unmount\";\nconst WIDGET_RESIZE_METHOD = \"resize\";\nconst WIDGET_SET_PROPERTIES_METHOD = \"set-properties\";\nconst WIDGET_DELIVER_METHOD = \"deliver\";\nconst WIDGET_POINTER_METHOD = \"pointer\";\n/**\n* Releases every instance without terminating the guest. Widget modules stay evaluated, so the next\n* `load` reuses their factories and only fresh instances are created.\n*/\nconst WIDGET_RESET_RUNTIME_METHOD = \"reset-runtime\";\n//#endregion\n//#region src/runtime/props.ts\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n/**\n* Deep-copies plain data and freezes every container on the way back up. Typed arrays and other\n* objects are returned untouched: they are not part of the JSON-shaped property format, and\n* freezing a typed array with elements throws.\n*/\nfunction cloneFrozen(value) {\n if (Array.isArray(value)) return Object.freeze(value.map((item) => cloneFrozen(item)));\n if (isPlainObject(value)) {\n const entries = [];\n for (const key of Object.keys(value)) entries.push([key, cloneFrozen(value[key])]);\n return Object.freeze(Object.fromEntries(entries));\n }\n return value;\n}\n/**\n* Merges `definition.properties[*].default` under the props a document supplied.\n*\n* A key present in `props` wins, even when its value is `undefined`; a key is only filled from the\n* definition when the descriptor declares `default` itself, so `default: null` and \"no default\"\n* stay distinguishable. Defaults are cloned and deeply frozen per instance, so a widget cannot\n* mutate the definition or leak changes into another instance.\n*/\nfunction mergeProperties(properties, props) {\n const merged = /* @__PURE__ */ new Map();\n for (const key of Object.keys(properties ?? {})) {\n const descriptor = properties?.[key];\n if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, \"default\")) continue;\n merged.set(key, cloneFrozen(descriptor.default));\n }\n for (const key of Object.keys(props ?? {})) merged.set(key, props?.[key]);\n return Object.freeze(Object.fromEntries(merged));\n}\n//#endregion\n//#region src/runtime/worker-entry.ts\nconst DEFAULT_DPR = 1;\n/**\n* Guest entry point: the sandbox module loader looks for this export.\n*\n* The runtime is also reusable from tests, because it owns no module-level state.\n*/\nfunction setup(ctx) {\n const runtime = createWidgetRuntime(ctx);\n ctx.handle(WIDGET_LOAD_METHOD, (request) => runtime.load(request));\n ctx.handle(WIDGET_MOUNT_METHOD, (request) => runtime.mount(request));\n ctx.handle(WIDGET_UNMOUNT_METHOD, (instanceId) => runtime.unmount(instanceId));\n ctx.handle(WIDGET_RESIZE_METHOD, (instanceId, width, height, dpr) => runtime.resize(instanceId, width, height, dpr));\n ctx.handle(WIDGET_SET_PROPERTIES_METHOD, (instanceId, props) => runtime.setProperties(instanceId, props));\n ctx.handle(WIDGET_DELIVER_METHOD, (instanceId, port, payload, simTime) => runtime.deliver(instanceId, port, payload, simTime));\n ctx.handle(WIDGET_POINTER_METHOD, (instanceId, event) => runtime.pointer(instanceId, event));\n ctx.handle(WIDGET_RESET_RUNTIME_METHOD, () => runtime.resetRuntime());\n ctx.signal.addEventListener(\"abort\", () => runtime.dispose(), { once: true });\n}\n/** Creates an isolated runtime instance; each sandbox (and each test) gets its own. */\nfunction createWidgetRuntime(ctx, options = {}) {\n const importModule = options.importModule ?? importBlobModule;\n const factories = /* @__PURE__ */ new Map();\n const definitions = /* @__PURE__ */ new Map();\n const pendingFactories = /* @__PURE__ */ new Map();\n const sessions = /* @__PURE__ */ new Map();\n const dirty = /* @__PURE__ */ new Set();\n let scheduled = false;\n let disposed = false;\n function report(phase, instanceId, error) {\n const payload = {\n instanceId,\n phase,\n error: {\n name: errorName(error),\n message: errorMessage(error)\n }\n };\n try {\n ctx.emit(WIDGET_ERROR_EVENT, payload);\n } catch {}\n }\n function invalidate(session) {\n if (session.failed || session.disposed || disposed) return;\n dirty.add(session);\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(flush);\n }\n function flush() {\n scheduled = false;\n const pending = [...dirty];\n dirty.clear();\n for (const session of pending) paint(session);\n }\n function paint(session) {\n if (session.failed || session.disposed || disposed) return;\n const { context, canvas } = session;\n if (typeof context.setTransform === \"function\") {\n context.setTransform(1, 0, 0, 1, 0, 0);\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.setTransform(session.dpr, 0, 0, session.dpr, 0, 0);\n }\n const render = session.instance?.render;\n if (typeof render === \"function\") try {\n render.call(session.instance, context);\n } catch (error) {\n session.failed = true;\n dirty.delete(session);\n report(\"render\", session.instanceId, error);\n return;\n }\n commit(session);\n }\n function commit(session) {\n let bitmap;\n try {\n bitmap = session.canvas.transferToImageBitmap();\n } catch (error) {\n session.failed = true;\n report(\"render\", session.instanceId, error);\n return;\n }\n const payload = {\n instanceId: session.instanceId,\n bitmap,\n width: session.width,\n height: session.height,\n dpr: session.dpr\n };\n try {\n ctx.emit(WIDGET_FRAME_EVENT, payload, [bitmap]);\n } catch {\n closeBitmap(bitmap);\n }\n }\n function requireSession(instanceId) {\n const session = sessions.get(instanceId);\n if (!session) throw new Error(`Widget instance ${JSON.stringify(instanceId)} is not mounted`);\n return session;\n }\n function createSession(request, definition) {\n const canvas = createCanvas(request.width, request.height, request.dpr);\n const properties = definition?.properties ?? {};\n return {\n instanceId: request.instanceId,\n width: toLogicalSize(request.width),\n height: toLogicalSize(request.height),\n dpr: toDpr(request.dpr),\n props: mergeProperties(properties, request.props),\n properties,\n assets: toAssetMap(request.assets),\n reportedAssets: /* @__PURE__ */ new Set(),\n canvas,\n context: contextOf(canvas),\n subscriptions: /* @__PURE__ */ new Map(),\n instance: void 0,\n failed: false,\n disposed: false\n };\n }\n function reportAssetFailure(session, src, message) {\n if (session.disposed || disposed || session.reportedAssets.has(src)) return;\n session.reportedAssets.add(src);\n const payload = {\n instanceId: session.instanceId,\n src,\n error: {\n name: \"Error\",\n message\n }\n };\n try {\n ctx.emit(WIDGET_ASSET_FAILED_EVENT, payload);\n } catch {}\n }\n function readAsset(session, src) {\n if (typeof src !== \"string\") return Promise.reject(/* @__PURE__ */ new TypeError(\"Widget asset src must be a string\"));\n const bytes = session.assets.get(src);\n if (bytes !== void 0 && !session.disposed && !disposed) return Promise.resolve(new Uint8Array(bytes));\n const message = `Widget asset ${JSON.stringify(src)} was not prefetched`;\n if (session.disposed || disposed) return Promise.reject(new Error(message));\n reportAssetFailure(session, src, message);\n return Promise.reject(new Error(message));\n }\n function createApi(session) {\n return {\n instanceId: session.instanceId,\n get width() {\n return session.width;\n },\n get height() {\n return session.height;\n },\n get props() {\n return session.props;\n },\n assets: { readBinary: (src) => readAsset(session, src) },\n subscribe(port, listener) {\n if (session.disposed || typeof listener !== \"function\") return () => {};\n let listeners = session.subscriptions.get(port);\n if (!listeners) {\n listeners = /* @__PURE__ */ new Set();\n session.subscriptions.set(port, listeners);\n }\n listeners.add(listener);\n return () => {\n session.subscriptions.get(port)?.delete(listener);\n };\n },\n publish(port, payload, simTime) {\n if (session.disposed || disposed) return;\n const message = {\n instanceId: session.instanceId,\n port,\n payload,\n simTime: toSimTime(simTime)\n };\n try {\n ctx.emit(WIDGET_PUBLISH_EVENT, message);\n } catch (error) {\n report(\"deliver\", session.instanceId, error);\n }\n },\n invalidate() {\n invalidate(session);\n }\n };\n }\n function release(session) {\n session.disposed = true;\n dirty.delete(session);\n session.subscriptions.clear();\n const instance = session.instance;\n session.instance = void 0;\n if (instance && typeof instance.dispose === \"function\") try {\n instance.dispose();\n } catch (error) {\n report(\"render\", session.instanceId, error);\n }\n session.assets.clear();\n session.canvas.width = 1;\n session.canvas.height = 1;\n }\n async function evaluate(ref, code) {\n const loaded = await importModule(code);\n const factory = loaded && typeof loaded === \"object\" ? loaded.default : void 0;\n if (typeof factory !== \"function\") throw new Error(`Widget ${JSON.stringify(ref)} must default-export a factory function`);\n return factory;\n }\n return {\n async load(request) {\n const packages = Array.isArray(request.packages) ? request.packages : [];\n let failure;\n let failed = false;\n for (const pkg of packages) {\n const modules = pkg.modules;\n if (!modules || typeof modules !== \"object\") continue;\n for (const widgetId of Object.keys(modules)) {\n const widgetModule = modules[widgetId];\n if (!widgetModule) continue;\n const ref = `${pkg.id}:${widgetId}`;\n if (factories.has(ref)) continue;\n try {\n let pending = pendingFactories.get(ref);\n if (!pending) {\n pending = evaluate(ref, widgetModule.code);\n pendingFactories.set(ref, pending);\n }\n factories.set(ref, await pending);\n definitions.set(ref, widgetModule.definition);\n } catch (error) {\n if (!failed) {\n failure = error;\n failed = true;\n }\n } finally {\n pendingFactories.delete(ref);\n }\n }\n }\n if (failed) throw failure;\n },\n mount(request) {\n if (disposed) throw new Error(\"The widget runtime is disposed\");\n const { instanceId, widget } = request;\n if (sessions.has(instanceId)) throw new Error(`Widget instance ${JSON.stringify(instanceId)} is already mounted`);\n const factory = factories.get(widget);\n if (!factory) throw new Error(`Widget ${JSON.stringify(widget)} is not loaded`);\n const session = createSession(request, definitions.get(widget));\n sessions.set(instanceId, session);\n try {\n session.instance = toWidgetInstance(factory(createApi(session)));\n } catch (error) {\n sessions.delete(instanceId);\n release(session);\n report(\"mount\", instanceId, error);\n throw error instanceof Error ? error : new Error(String(error));\n }\n dirty.delete(session);\n paint(session);\n },\n unmount(instanceId) {\n const session = sessions.get(instanceId);\n if (!session) return;\n sessions.delete(instanceId);\n release(session);\n },\n resize(instanceId, width, height, dpr) {\n const session = requireSession(instanceId);\n session.width = toLogicalSize(width);\n session.height = toLogicalSize(height);\n session.dpr = toDpr(dpr);\n session.canvas.width = toPixelSize(width, session.dpr);\n session.canvas.height = toPixelSize(height, session.dpr);\n dirty.delete(session);\n paint(session);\n },\n setProperties(instanceId, props) {\n const session = requireSession(instanceId);\n session.props = mergeProperties(session.properties, props);\n invalidate(session);\n },\n deliver(instanceId, port, payload, simTime) {\n const listeners = requireSession(instanceId).subscriptions.get(port);\n if (!listeners || listeners.size === 0) return;\n const meta = { simTime };\n for (const listener of [...listeners]) try {\n listener(payload, meta);\n } catch (error) {\n report(\"deliver\", instanceId, error);\n }\n },\n pointer(instanceId, event) {\n const session = requireSession(instanceId);\n if (session.failed || session.disposed) return;\n const handler = session.instance?.input;\n if (typeof handler !== \"function\") return;\n try {\n handler.call(session.instance, event);\n } catch (error) {\n report(\"deliver\", instanceId, error);\n }\n },\n resetRuntime() {\n if (disposed) return;\n dirty.clear();\n for (const session of [...sessions.values()]) {\n sessions.delete(session.instanceId);\n release(session);\n }\n sessions.clear();\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n dirty.clear();\n for (const session of [...sessions.values()]) release(session);\n sessions.clear();\n factories.clear();\n definitions.clear();\n pendingFactories.clear();\n }\n };\n}\nfunction createCanvas(width, height, dpr) {\n return new OffscreenCanvas(toPixelSize(width, dpr), toPixelSize(height, dpr));\n}\nfunction contextOf(canvas) {\n const context = canvas.getContext(\"2d\");\n if (!context) throw new Error(\"The widget runtime needs a 2D context\");\n return context;\n}\nfunction toWidgetInstance(value) {\n return value && typeof value === \"object\" ? value : {};\n}\nfunction toLogicalSize(value) {\n return Number.isFinite(value) && value > 0 ? value : 0;\n}\nfunction toDpr(value) {\n return Number.isFinite(value) && value > 0 ? value : DEFAULT_DPR;\n}\nfunction toPixelSize(logical, dpr) {\n return Math.max(1, Math.round(toLogicalSize(logical) * toDpr(dpr)));\n}\nfunction toAssetMap(assets) {\n const map = /* @__PURE__ */ new Map();\n if (typeof assets !== \"object\" || assets === null) return map;\n for (const key of Object.keys(assets)) {\n const bytes = assets[key];\n if (bytes instanceof Uint8Array) map.set(key, new Uint8Array(bytes));\n }\n return map;\n}\nfunction toSimTime(value) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\nfunction closeBitmap(bitmap) {\n try {\n bitmap.close();\n } catch {}\n}\nfunction errorName(error) {\n return error instanceof Error && error.name ? error.name : \"Error\";\n}\nfunction errorMessage(error) {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === \"string\" ? error : String(error);\n}\nfunction importBlobModule(code) {\n const url = URL.createObjectURL(new Blob([code], { type: \"text/javascript\" }));\n return import(\n /* @vite-ignore */\n url\n).finally(() => URL.revokeObjectURL(url));\n}\n//#endregion\nexport { createWidgetRuntime, setup };\n";
523
- //#endregion
524
- //#region src/host/sandbox.ts
525
1326
  /**
526
- * Default sandbox over `@mica-js/sandbox`.
1327
+ * Shallow comparison of two record maps.
527
1328
  *
528
- * The import stays dynamic on purpose: consumers that inject their own sandbox never load it, and
529
- * Node-side consumers can import this package without a DOM.
1329
+ * The document owns property/binding values, so a nested object only counts as changed when the
1330
+ * caller replaced the object itself; deep equality would swallow those edits. The key sets matter
1331
+ * as much as the values, because a missing property key falls back to the definition default.
530
1332
  */
531
- var createDefaultWidgetSandbox = async (options) => {
532
- const { createSandbox } = await import("@mica-js/sandbox");
533
- const handle = await createSandbox({
534
- name: "mica-widget-runtime",
535
- source: {
536
- type: "module",
537
- code: WIDGET_RUNTIME_SOURCE
538
- },
539
- captureConsole: false,
540
- ...options.container === void 0 ? {} : { container: options.container }
541
- });
542
- return {
543
- get state() {
544
- return handle.state;
545
- },
546
- call: (method, ...args) => handle.request(method, args),
547
- on: (type, listener) => handle.on(type, listener),
548
- terminate: (reason) => handle.terminate(reason)
549
- };
550
- };
1333
+ function sameRecord(left, right) {
1334
+ if (left === right) return true;
1335
+ const keys = Object.keys(left);
1336
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
1337
+ }
1338
+ function sameOrder(left, right) {
1339
+ return left.length === right.length && left.every((id, index) => id === right[index]);
1340
+ }
551
1341
  //#endregion
552
- //#region src/host/create-widget-host.ts
1342
+ //#region src/host/widget-host.ts
553
1343
  /** Host state before any document was loaded. */
554
1344
  var EMPTY_DOCUMENT = {
555
1345
  version: CANVAS_VERSION,
556
1346
  widgets: []
557
1347
  };
1348
+ /** One fixed step, in milliseconds; the host converts it to picoseconds for the simulator. */
1349
+ var DEFAULT_STEP_MS = 25;
1350
+ var PS_PER_MS = 1e9;
1351
+ function defaultRequestFrame(callback, delayMs) {
1352
+ const timer = setTimeout(callback, delayMs);
1353
+ return () => {
1354
+ clearTimeout(timer);
1355
+ };
1356
+ }
558
1357
  /** Startup or shutdown failure; already reported, so call sites must not report it twice. */
559
1358
  var WidgetRuntimeError = class extends Error {
560
1359
  constructor(message, options) {
@@ -581,67 +1380,226 @@ var WidgetMountCancelledError = class extends Error {
581
1380
  * a crash the next reconciliation starts a fresh sandbox instead of rebuilding instances
582
1381
  * automatically.
583
1382
  */
584
- function createWidgetHost(options) {
585
- return new WidgetHostImpl(options);
1383
+ function createWidgetHost(options, createSandbox) {
1384
+ return new WidgetHostImpl(options, createSandbox);
586
1385
  }
587
1386
  var WidgetHostImpl = class {
588
1387
  #provider;
1388
+ #fs;
589
1389
  #container;
590
1390
  #onDiagnostic;
591
1391
  #onPublish;
592
1392
  #assets;
593
1393
  #catalog;
594
- #simulation;
1394
+ /** Catalog assembled from the widget provider and the running simulation (RFC 0018). */
1395
+ #autoCatalog = new HostBindingCatalog();
1396
+ #deviceHost;
1397
+ #mode;
1398
+ #frameOptions;
595
1399
  #createSandbox;
596
- #layerStore = new WidgetLayerStore();
1400
+ #audio;
1401
+ #store = new WidgetStore();
597
1402
  #instances = /* @__PURE__ */ new Map();
598
1403
  #detachers = [];
599
1404
  #documentListeners = /* @__PURE__ */ new Set();
1405
+ /** Input events waiting for the next step start; only used while a frame clock runs. */
1406
+ #pendingInputs = [];
1407
+ /** `WidgetHost.audio`; a no-op control surface when no audio was configured. */
1408
+ audio;
1409
+ /** Port the worklet handed over before a sandbox existed; flushed on the next attach. */
1410
+ #pendingAudioPort;
1411
+ /** Latest availability, replayed to a sandbox that was created after the change. */
1412
+ #lastAudioState;
600
1413
  #document = EMPTY_DOCUMENT;
601
- #unsubscribeSimulation;
1414
+ /** Instances whose binding diagnostics prevent guest mounting for the current snapshot. */
1415
+ #bindingSkipped = /* @__PURE__ */ new Set();
1416
+ /** URI the current snapshot was read from; `undefined` for the parsed-document entry. */
1417
+ #documentUri;
1418
+ /** Absolute URI of the schematic the runtime was told to load. */
1419
+ #schematicUri;
1420
+ #unsubscribeDevicePublish;
1421
+ #cancelFrame;
1422
+ #paused = false;
1423
+ #advancing = false;
1424
+ /** Whether a document was loaded; only then does the clock have something to advance. */
1425
+ #loaded = false;
1426
+ /** Last simulation time reported by the device host, used as a publish timestamp fallback. */
1427
+ #simTime = 0;
1428
+ /**
1429
+ * Last payload the simulation published per endpoint.
1430
+ *
1431
+ * A level topic only publishes when it changes, so an instance that mounts afterwards is seeded
1432
+ * from here instead of waiting for a change that may never come.
1433
+ */
1434
+ #lastPublished = /* @__PURE__ */ new Map();
602
1435
  #reconcilePending = false;
603
1436
  /** The next coordination pass has to reset the guest before it syncs instances. */
604
1437
  #resetPending = false;
1438
+ /** The next coordination pass has to reset the device before it resets the guest. */
1439
+ #deviceResetPending = false;
1440
+ /** The next coordination pass has to re-read the document and reload the schematic. */
1441
+ #reloadPending = false;
1442
+ #reloadSchematicPending = false;
605
1443
  #reconcilePass;
606
1444
  /** Identifies the drain that owns {@link #reconcilePass}; only that drain may release it. */
607
1445
  #reconcileOwner = 0;
1446
+ /**
1447
+ * One end of the direct device channel, consumed by the first sandbox this host starts.
1448
+ *
1449
+ * It is transferred to the guest at startup, so it cannot be reused: a restart runs in fallback.
1450
+ */
1451
+ #devicePort;
1452
+ /** True while the running guest owns the direct device channel and routes topic traffic itself. */
1453
+ #directDevice = false;
608
1454
  #sandbox;
609
1455
  #starting;
610
1456
  #disposing;
611
1457
  #disposed = false;
612
1458
  #dpr;
613
- constructor(options) {
614
- this.#provider = options.provider;
1459
+ constructor(options, createSandbox) {
1460
+ const provider = options.widgetProvider ?? options.provider;
1461
+ if (provider === void 0) throw new TypeError("createWidgetHost requires a widgetProvider");
1462
+ this.#provider = provider;
1463
+ this.#fs = options.fs;
615
1464
  this.#container = options.container;
616
- this.#onDiagnostic = options.onDiagnostic;
617
- this.#onPublish = options.onPublish;
1465
+ this.#onDiagnostic = options.onDidReportDiagnostic ?? options.onDiagnostic;
1466
+ this.#onPublish = options.onDidPublish ?? options.onPublish;
618
1467
  this.#assets = options.assets;
619
1468
  this.#catalog = options.catalog;
620
- this.#simulation = options.simulation;
621
- this.#createSandbox = options.sandbox ?? createDefaultWidgetSandbox;
1469
+ this.#deviceHost = options.deviceHost;
1470
+ this.#devicePort = options.devicePort;
1471
+ this.#mode = options.mode ?? "simulation";
1472
+ const frame = options.frame;
1473
+ const stepMs = frame?.stepMs !== void 0 && Number.isFinite(frame.stepMs) && frame.stepMs > 0 ? frame.stepMs : DEFAULT_STEP_MS;
1474
+ this.#frameOptions = {
1475
+ stepMs,
1476
+ requestFrame: frame?.requestFrame ?? ((callback) => defaultRequestFrame(callback, stepMs))
1477
+ };
1478
+ this.#createSandbox = createSandbox;
622
1479
  this.#dpr = options.dpr ?? currentDevicePixelRatio();
623
- this.#unsubscribeSimulation = this.#simulation?.onPublish((publish) => {
624
- this.#onSimulationPublish(publish);
1480
+ let audio;
1481
+ if (options.audio !== void 0) {
1482
+ const getAudioWorklet = options.audio.getAudioWorklet;
1483
+ const context = options.audio.context;
1484
+ const audioOptions = {
1485
+ context,
1486
+ report: (code, instanceId, message) => this.#report(code, message, this.#instanceIds(instanceId)),
1487
+ notify: {
1488
+ emitPort: (port) => this.#emitAudioPort(port),
1489
+ emitState: (state) => this.#emitAudioState(state)
1490
+ }
1491
+ };
1492
+ if (options.audio.destination !== void 0) Object.assign(audioOptions, { destination: options.audio.destination });
1493
+ if (getAudioWorklet !== void 0) Object.assign(audioOptions, { loadWorklet: () => getAudioWorklet(context) });
1494
+ if (options.audio.limits !== void 0) Object.assign(audioOptions, { limits: options.audio.limits });
1495
+ audio = new WidgetAudioEngine(audioOptions);
1496
+ }
1497
+ this.#audio = audio;
1498
+ this.audio = this.#audio ?? NO_AUDIO_CONTROLS;
1499
+ this.#unsubscribeDevicePublish = this.#deviceHost.onDidPublish((publish) => {
1500
+ if (this.#mode === "simulation") this.#onSimulationPublish(publish);
625
1501
  });
626
1502
  }
627
1503
  getDocument() {
628
1504
  return this.#document;
629
1505
  }
1506
+ getMode() {
1507
+ return this.#mode;
1508
+ }
1509
+ async setMode(mode) {
1510
+ if (this.#disposed) throw new WidgetRuntimeError("Widget host is disposed");
1511
+ if (mode === this.#mode) return;
1512
+ const previous = this.#mode;
1513
+ this.#stopClock();
1514
+ this.#pendingInputs.length = 0;
1515
+ try {
1516
+ this.#clearWidgetInstances();
1517
+ this.#resetPending = true;
1518
+ this.#deviceResetPending = true;
1519
+ this.#reloadPending = false;
1520
+ this.#reloadSchematicPending = false;
1521
+ this.#mode = mode;
1522
+ await this.#scheduleReconcile();
1523
+ if (this.#mode === "simulation" && this.#loaded && !this.#paused) this.#startClock();
1524
+ } catch (error) {
1525
+ this.#mode = previous;
1526
+ if (previous === "simulation" && this.#loaded && !this.#paused) this.#startClock();
1527
+ throw error;
1528
+ }
1529
+ }
630
1530
  getLayers() {
631
- return this.#layerStore;
1531
+ return this.#store;
1532
+ }
1533
+ listInstances() {
1534
+ return this.#store.listInstances();
1535
+ }
1536
+ onDidAddWidget = this.#store.onDidAddWidget;
1537
+ onDidChangeWidget = this.#store.onDidChangeWidget;
1538
+ onDidRemoveWidget = this.#store.onDidRemoveWidget;
1539
+ onDidReorderWidgets = this.#store.onDidReorderWidgets;
1540
+ invalidate() {
1541
+ if (this.#disposed) return;
1542
+ this.#store.invalidate();
1543
+ }
1544
+ pause() {
1545
+ this.#paused = true;
1546
+ this.#stopClock();
632
1547
  }
633
- async loadDocument(document) {
634
- const parsed = parseCanvas(document);
635
- this.#assertBindings(parsed);
636
- this.#commit(parsed);
1548
+ resume() {
1549
+ if (this.#disposed) return;
1550
+ this.#paused = false;
1551
+ if (this.#loaded) this.#startClock();
1552
+ }
1553
+ async loadDocument(source) {
1554
+ const documentUri = typeof source === "string" ? source : void 0;
1555
+ const input = documentUri === void 0 ? source : await this.#readDocumentText(documentUri);
1556
+ const parsed = parseCanvas(input);
1557
+ const schematicUri = this.#resolveSchematicUri(parsed, documentUri);
1558
+ await this.#loadSchematic(schematicUri);
1559
+ await this.#refreshCatalog(parsed, parsed.schematic, schematicUri);
1560
+ const bindingSkipped = this.#bindingSkipIds(parsed);
1561
+ this.#documentUri = documentUri;
1562
+ this.#schematicUri = schematicUri;
1563
+ this.#commit(parsed, bindingSkipped);
637
1564
  const pass = this.#scheduleReconcile();
638
1565
  this.#emitDocument(parsed);
639
1566
  await pass;
1567
+ this.#loaded = true;
1568
+ if (this.#mode === "simulation") this.#startClock();
1569
+ }
1570
+ /**
1571
+ * Reads a document URI: `data:` decodes locally, every other scheme goes through `fs`.
1572
+ *
1573
+ * Relative references never reach the reader; the caller supplies an absolute URI, which is also
1574
+ * what `HostFs.read` expects.
1575
+ */
1576
+ async #readDocumentText(uri) {
1577
+ if (!isAbsoluteHostUri(uri)) throw new TypeError(`WidgetHost.loadDocument requires an absolute URI: ${uri}`);
1578
+ if (uri.slice(0, 5).toLowerCase() === "data:") return decodeDataUriText(uri);
1579
+ const fs = this.#fs;
1580
+ if (fs === void 0) throw new HostFsError("NoFileSystem", uri, "WidgetHost has no HostFs configured to read this document URI");
1581
+ return new TextDecoder().decode(await fs.read(uri));
1582
+ }
1583
+ /**
1584
+ * Resolves the document's `schematic` reference against the canvas URI.
1585
+ *
1586
+ * `undefined` clears the runtime. An absolute reference passes through; a relative one needs the
1587
+ * canvas URI as its base, so the parsed-document form can only carry absolute references.
1588
+ */
1589
+ #resolveSchematicUri(document, documentUri) {
1590
+ const schematic = document.schematic;
1591
+ if (schematic === void 0 || schematic === "") return void 0;
1592
+ if (documentUri === void 0) return schematic;
1593
+ return resolveHostUri(documentUri, schematic);
1594
+ }
1595
+ /** Loads (or clears) the schematic on the device host. */
1596
+ async #loadSchematic(uri) {
1597
+ await this.#deviceHost.loadSchematic(uri);
640
1598
  }
641
1599
  applyCommand(command) {
642
1600
  const document = applyCanvasCommand(this.#document, command);
643
- this.#assertBindings(document);
644
- this.#commit(document);
1601
+ const bindingSkipped = this.#bindingSkipIds(document);
1602
+ this.#commit(document, bindingSkipped);
645
1603
  this.#scheduleReconcile();
646
1604
  this.#emitDocument(document);
647
1605
  }
@@ -653,14 +1611,31 @@ var WidgetHostImpl = class {
653
1611
  }
654
1612
  reset() {
655
1613
  if (this.#disposed) return Promise.reject(new WidgetRuntimeError("Widget host is disposed"));
1614
+ return this.#resetRuntime({
1615
+ reloadDocument: this.#documentUri !== void 0,
1616
+ reloadSchematic: this.#schematicUri !== void 0,
1617
+ resetDevice: true
1618
+ });
1619
+ }
1620
+ #clearWidgetInstances() {
1621
+ for (const instanceId of this.#instances.keys()) this.#audio?.close(instanceId);
656
1622
  this.#instances.clear();
657
- this.#layerStore.clear();
1623
+ this.#store.clear();
1624
+ }
1625
+ async #resetRuntime(options) {
1626
+ this.#stopClock();
1627
+ this.#pendingInputs.length = 0;
1628
+ this.#clearWidgetInstances();
658
1629
  this.#resetPending = true;
659
- return this.#scheduleReconcile();
1630
+ this.#deviceResetPending = options.resetDevice;
1631
+ this.#reloadPending = options.reloadDocument;
1632
+ this.#reloadSchematicPending = options.reloadSchematic;
1633
+ await this.#scheduleReconcile();
1634
+ if (this.#mode === "simulation" && this.#loaded && !this.#paused) this.#startClock();
660
1635
  }
661
1636
  deliver(instanceId, port, payload, simTime) {
662
1637
  if (!this.#requireInstance(instanceId)) return;
663
- this.#fire("widget/deliver-failed", WIDGET_DELIVER_METHOD, [
1638
+ this.#fire("widget/deliver-failed", widgetDeliverMethod, [
664
1639
  instanceId,
665
1640
  port,
666
1641
  payload,
@@ -669,14 +1644,21 @@ var WidgetHostImpl = class {
669
1644
  }
670
1645
  dispatch(instanceId, event) {
671
1646
  if (!this.#requireInstance(instanceId)) return;
672
- this.#fire("widget/deliver-failed", WIDGET_POINTER_METHOD, [instanceId, event], instanceId);
1647
+ if (this.#loaded) {
1648
+ this.#pendingInputs.push({
1649
+ instanceId,
1650
+ event
1651
+ });
1652
+ return;
1653
+ }
1654
+ this.#fire("widget/deliver-failed", widgetPointerMethod, [instanceId, event], instanceId);
673
1655
  }
674
1656
  resize(dpr) {
675
1657
  if (!Number.isFinite(dpr) || dpr <= 0 || dpr === this.#dpr) return;
676
1658
  this.#dpr = dpr;
677
- for (const layer of this.#layerStore.list()) {
678
- this.#layerStore.setDpr(layer.instanceId, dpr);
679
- this.#fire("widget/render-failed", WIDGET_RESIZE_METHOD, [
1659
+ for (const layer of this.#store.list()) {
1660
+ this.#store.update(layer.instanceId, { dpr });
1661
+ this.#fire("widget/render-failed", widgetResizeMethod, [
680
1662
  layer.instanceId,
681
1663
  layer.width,
682
1664
  layer.height,
@@ -689,9 +1671,79 @@ var WidgetHostImpl = class {
689
1671
  this.#disposing = pending;
690
1672
  return pending;
691
1673
  }
692
- /** Runs the binding checks both document entry points share; nothing needs them without a catalog. */
693
- #assertBindings(document) {
694
- assertCanvasBindings(document, this.#catalog === void 0 ? {} : { catalog: this.#catalog });
1674
+ /**
1675
+ * Runs the binding checks both document entry points share.
1676
+ *
1677
+ * An explicit `catalog` option wins. Otherwise the host checks against the catalog it assembled
1678
+ * from the widget provider and the running simulation (RFC 0018).
1679
+ */
1680
+ #bindingSkipIds(document) {
1681
+ const explicit = this.#catalog;
1682
+ const catalog = explicit ?? this.#autoCatalog;
1683
+ const resolved = explicit !== void 0 || document.widgets.every((widget) => this.#autoCatalog.knows(widget.widget));
1684
+ const diagnostics = validateCanvasBindings(document, resolved ? { catalog } : {
1685
+ catalog,
1686
+ skipWidgets: true
1687
+ });
1688
+ const bindingCodes = /* @__PURE__ */ new Set([
1689
+ "canvas/unknown-symbol",
1690
+ "canvas/unknown-target-port",
1691
+ "canvas/unknown-port",
1692
+ "topic/type-mismatch"
1693
+ ]);
1694
+ if (diagnostics.some((diagnostic) => {
1695
+ const pointer = diagnostic.pointer ?? "";
1696
+ return !bindingCodes.has(diagnostic.code) || !/^\/widgets\/\d+\/bindings(?:\/|$)/.test(pointer);
1697
+ })) assertCanvasBindings(document, resolved ? { catalog } : {
1698
+ catalog,
1699
+ skipWidgets: true
1700
+ });
1701
+ const skipped = /* @__PURE__ */ new Set();
1702
+ for (const diagnostic of diagnostics) {
1703
+ if (!bindingCodes.has(diagnostic.code)) continue;
1704
+ const match = /^\/widgets\/(\d+)\/bindings(?:\/|$)/.exec(diagnostic.pointer ?? "");
1705
+ if (match === null) continue;
1706
+ const widget = document.widgets[Number(match[1])];
1707
+ if (widget !== void 0) {
1708
+ skipped.add(widget.id);
1709
+ this.#reportBindingDiagnostic(widget, diagnostic.code, diagnostic.message, diagnostic.pointer);
1710
+ }
1711
+ }
1712
+ return skipped;
1713
+ }
1714
+ /**
1715
+ * Re-assembles the automatic catalog after the device host loaded a schematic (RFC 0018).
1716
+ *
1717
+ * The device side is read once the load resolved, so `getTopics()` and `getSchematic()` describe
1718
+ * the runtime the instances will talk to; the widget side resolves every reference the document
1719
+ * names before validation runs.
1720
+ */
1721
+ async #refreshCatalog(document, schematic, schematicUri) {
1722
+ if (this.#catalog !== void 0) return;
1723
+ const deviceHost = this.#deviceHost;
1724
+ const [topics, loaded] = await Promise.all([deviceHost.getTopics(), deviceHost.getSchematic()]);
1725
+ this.#autoCatalog.setDeviceFacts({
1726
+ schematics: [schematic, schematicUri],
1727
+ schematic: loaded,
1728
+ topics
1729
+ });
1730
+ await this.#resolveDefinitions(document);
1731
+ }
1732
+ /**
1733
+ * Resolves the widget definitions the document references, so validation itself stays synchronous.
1734
+ *
1735
+ * A rejection or an unknown reference is only recorded as "not resolved": the mount of every
1736
+ * instance using it reports the failure on its own.
1737
+ */
1738
+ async #resolveDefinitions(document) {
1739
+ const refs = new Set(document.widgets.map((widget) => widget.widget));
1740
+ await Promise.all([...refs].map(async (ref) => {
1741
+ if (this.#autoCatalog.knows(ref)) return;
1742
+ try {
1743
+ const module = await this.#provider.resolve(ref);
1744
+ if (module !== void 0) this.#autoCatalog.recordDefinition(ref, module.definition);
1745
+ } catch {}
1746
+ }));
695
1747
  }
696
1748
  /**
697
1749
  * Makes `document` the new snapshot and drops the instances it no longer lists.
@@ -699,8 +1751,9 @@ var WidgetHostImpl = class {
699
1751
  * Removal is synchronous on purpose: a mount still in flight for a removed id has to be cancelled
700
1752
  * right away, while the coordination pass that would have removed it may be blocked on it.
701
1753
  */
702
- #commit(document) {
1754
+ #commit(document, bindingSkipped = /* @__PURE__ */ new Set()) {
703
1755
  this.#document = document;
1756
+ this.#bindingSkipped = new Set(bindingSkipped);
704
1757
  const live = new Set(document.widgets.map((widget) => widget.id));
705
1758
  for (const instanceId of [...this.#instances.keys()]) if (!live.has(instanceId)) this.#unmount(instanceId);
706
1759
  }
@@ -725,9 +1778,23 @@ var WidgetHostImpl = class {
725
1778
  try {
726
1779
  while (this.#reconcilePending && !this.#disposed) {
727
1780
  this.#reconcilePending = false;
1781
+ if (this.#reloadPending) {
1782
+ this.#reloadPending = false;
1783
+ await this.#reloadDocument();
1784
+ }
1785
+ if (this.#deviceResetPending) {
1786
+ this.#deviceResetPending = false;
1787
+ await this.#deviceHost.reset();
1788
+ this.#simTime = await this.#deviceHost.getSimTime();
1789
+ this.#lastPublished.clear();
1790
+ }
728
1791
  if (this.#resetPending) {
729
1792
  this.#resetPending = false;
730
1793
  await this.#resetGuestRuntime();
1794
+ if (this.#reloadSchematicPending) {
1795
+ this.#reloadSchematicPending = false;
1796
+ await this.#reloadSchematic();
1797
+ }
731
1798
  }
732
1799
  await this.#syncInstances();
733
1800
  }
@@ -738,15 +1805,47 @@ var WidgetHostImpl = class {
738
1805
  }
739
1806
  }
740
1807
  }
1808
+ /**
1809
+ * Re-reads the document behind the current URI, for `reset()`.
1810
+ *
1811
+ * A document that no longer parses is reported instead of rejecting: the reset still has to put
1812
+ * the instances back with the snapshot the host already holds.
1813
+ */
1814
+ async #reloadDocument() {
1815
+ const uri = this.#documentUri;
1816
+ if (uri === void 0) return;
1817
+ try {
1818
+ const parsed = parseCanvas(await this.#readDocumentText(uri));
1819
+ const bindingSkipped = this.#bindingSkipIds(parsed);
1820
+ this.#schematicUri = this.#resolveSchematicUri(parsed, uri);
1821
+ this.#commit(parsed, bindingSkipped);
1822
+ this.#emitDocument(parsed);
1823
+ } catch (error) {
1824
+ this.#report("widget/runtime-failed", `The canvas document "${uri}" could not be reloaded: ${describeError(error)}`);
1825
+ }
1826
+ }
1827
+ /** Re-executes the runtime half of `loadDocument`: the schematic goes back to time 0. */
1828
+ async #reloadSchematic() {
1829
+ try {
1830
+ await this.#loadSchematic(this.#schematicUri);
1831
+ await this.#refreshCatalog(this.#document, this.#document.schematic, this.#schematicUri);
1832
+ } catch (error) {
1833
+ this.#report("widget/runtime-failed", `The schematic could not be reloaded: ${describeError(error)}`);
1834
+ }
1835
+ }
741
1836
  /** Mounts, resizes, sets properties and reorders instances to match the document. */
742
1837
  async #syncInstances() {
743
1838
  for (const { id: instanceId } of this.#document.widgets) {
744
1839
  if (this.#disposed) return;
745
1840
  const widget = this.#document.widgets.find((entry) => entry.id === instanceId);
746
1841
  if (widget === void 0) continue;
1842
+ if (this.#bindingSkipped.has(instanceId)) {
1843
+ if (this.#instances.has(instanceId)) this.#unmount(instanceId);
1844
+ continue;
1845
+ }
747
1846
  await this.#syncInstance(widget);
748
1847
  }
749
- this.#layerStore.reorder(this.#document.widgets.map((widget) => widget.id));
1848
+ this.#store.reorder(this.#document.widgets.map((widget) => widget.id));
750
1849
  }
751
1850
  async #syncInstance(widget) {
752
1851
  const existing = this.#instances.get(widget.id);
@@ -760,13 +1859,17 @@ var WidgetHostImpl = class {
760
1859
  return;
761
1860
  }
762
1861
  const placement = placementOf(widget);
763
- if (placement.width !== existing.placement.width || placement.height !== existing.placement.height) this.#update(widget.id, {
764
- width: placement.width,
765
- height: placement.height
1862
+ const props = widget.properties ?? {};
1863
+ this.#store.update(widget.id, {
1864
+ ...placement,
1865
+ properties: props,
1866
+ bindings: widget.bindings ?? {}
766
1867
  });
1868
+ if (placement.width !== existing.placement.width || placement.height !== existing.placement.height) this.#resizeGuest(widget.id, placement.width, placement.height);
767
1869
  existing.placement = placement;
768
- const props = widget.properties ?? {};
769
- if (!sameProperties(existing.props, props)) {
1870
+ const bindings = widget.bindings ?? {};
1871
+ if (!sameBindings(existing.bindings, bindings)) this.#setBindings(widget.id, bindings);
1872
+ if (!sameRecord(existing.props, props)) {
770
1873
  if (this.#referencesUnprefetchedAsset(existing, props)) {
771
1874
  this.#unmount(widget.id);
772
1875
  await this.#mount(widget);
@@ -810,22 +1913,29 @@ var WidgetHostImpl = class {
810
1913
  token: Symbol(instanceId),
811
1914
  placement: placementOf(widget),
812
1915
  props: widget.properties ?? {},
1916
+ bindings: widget.bindings ?? {},
813
1917
  assets: /* @__PURE__ */ new Set()
814
1918
  };
815
1919
  this.#instances.set(instanceId, record);
816
- this.#layerStore.add({
1920
+ this.#store.add({
817
1921
  instanceId,
818
- width: widget.width,
819
- height: widget.height,
820
- dpr: this.#dpr
1922
+ widget: ref,
1923
+ ...record.placement,
1924
+ dpr: this.#dpr,
1925
+ properties: record.props,
1926
+ bindings: widget.bindings ?? {}
821
1927
  });
822
- this.#layerStore.reorder(this.#document.widgets.map((entry) => entry.id));
1928
+ this.#store.reorder(this.#document.widgets.map((entry) => entry.id));
823
1929
  let mounted = false;
824
1930
  try {
825
1931
  mounted = await this.#mountInstance(instanceId, ref, record);
826
1932
  } finally {
827
1933
  if (!mounted) this.#forget(instanceId, record);
828
1934
  }
1935
+ if (mounted) {
1936
+ this.#setBindings(instanceId, record.bindings);
1937
+ this.#replayPublished(widget);
1938
+ }
829
1939
  }
830
1940
  /**
831
1941
  * Runs one mount attempt; every await re-checks that this attempt still owns the id.
@@ -851,11 +1961,12 @@ var WidgetHostImpl = class {
851
1961
  });
852
1962
  return false;
853
1963
  }
1964
+ this.#autoCatalog.recordDefinition(ref, module.definition);
854
1965
  this.#requireOwnership(instanceId, record);
855
1966
  const sandbox = await this.#ensureSandbox();
856
1967
  this.#requireOwnership(instanceId, record);
857
1968
  try {
858
- await sandbox.call(WIDGET_LOAD_METHOD, { packages: [{
1969
+ await sandbox.call(widgetLoadMethod, { packages: [{
859
1970
  id: resolved.packageId,
860
1971
  modules: { [resolved.widgetId]: {
861
1972
  definition: module.definition,
@@ -867,16 +1978,20 @@ var WidgetHostImpl = class {
867
1978
  const assets = await this.#prefetchAssets(instanceId, ref, props);
868
1979
  record.assets = new Set(collectAssetRefs(props).keys());
869
1980
  this.#requireOwnership(instanceId, record);
870
- const layer = this.#layerStore.get(instanceId);
1981
+ const layer = this.#store.get(instanceId);
871
1982
  if (!layer) throw new WidgetMountCancelledError(instanceId);
872
- await sandbox.call(WIDGET_MOUNT_METHOD, {
1983
+ const audio = this.#audio === void 0 ? { state: "unavailable" } : await this.#audio.open(instanceId);
1984
+ if (audio.session !== void 0) record.audioSession = audio.session;
1985
+ this.#requireOwnership(instanceId, record);
1986
+ await sandbox.call(widgetMountMethod, {
873
1987
  instanceId,
874
1988
  widget: ref,
875
1989
  width: layer.width,
876
1990
  height: layer.height,
877
1991
  dpr: layer.dpr,
878
1992
  props,
879
- ...assets === void 0 ? {} : { assets }
1993
+ ...assets === void 0 ? {} : { assets },
1994
+ audio
880
1995
  });
881
1996
  } catch (error) {
882
1997
  if (error instanceof WidgetRuntimeError) throw error;
@@ -905,17 +2020,17 @@ var WidgetHostImpl = class {
905
2020
  return;
906
2021
  }
907
2022
  this.#forget(instanceId, instance);
908
- this.#fire(void 0, WIDGET_UNMOUNT_METHOD, [instanceId], instanceId);
2023
+ this.#fire(void 0, widgetUnmountMethod, [instanceId], instanceId);
909
2024
  }
910
- #update(instanceId, size) {
2025
+ /** Repaints one instance at a new size; the store already carries the new geometry. */
2026
+ #resizeGuest(instanceId, width, height) {
911
2027
  if (!this.#requireInstance(instanceId)) return;
912
- this.#layerStore.setSize(instanceId, size.width, size.height);
913
- const layer = this.#layerStore.get(instanceId);
2028
+ const layer = this.#store.get(instanceId);
914
2029
  if (!layer) return;
915
- this.#fire("widget/render-failed", WIDGET_RESIZE_METHOD, [
2030
+ this.#fire("widget/render-failed", widgetResizeMethod, [
916
2031
  instanceId,
917
- layer.width,
918
- layer.height,
2032
+ width,
2033
+ height,
919
2034
  layer.dpr
920
2035
  ], instanceId);
921
2036
  }
@@ -923,7 +2038,21 @@ var WidgetHostImpl = class {
923
2038
  const instance = this.#requireInstance(instanceId);
924
2039
  if (!instance) return;
925
2040
  instance.props = props;
926
- this.#fire("widget/render-failed", WIDGET_SET_PROPERTIES_METHOD, [instanceId, props], instanceId);
2041
+ this.#fire("widget/render-failed", widgetSetPropertiesMethod, [instanceId, props], instanceId);
2042
+ }
2043
+ /**
2044
+ * Hands one instance's binding map to the guest.
2045
+ *
2046
+ * Only a guest with the direct device channel needs it: that guest then routes publishes to the
2047
+ * device and device publishes back to the instance. A guest without one keeps the host as its only
2048
+ * router, so the call is skipped rather than sent into a runtime that ignores it.
2049
+ */
2050
+ #setBindings(instanceId, bindings) {
2051
+ const instance = this.#instances.get(instanceId);
2052
+ if (instance === void 0) return;
2053
+ instance.bindings = bindings;
2054
+ if (!this.#directDevice) return;
2055
+ this.#fire("widget/deliver-failed", widgetSetBindingsMethod, [instanceId, bindings], instanceId);
927
2056
  }
928
2057
  #requireInstance(instanceId) {
929
2058
  const instance = this.#instances.get(instanceId);
@@ -940,9 +2069,13 @@ var WidgetHostImpl = class {
940
2069
  }
941
2070
  /** Drops this attempt's reservation and layer; a newer record for the same id is left alone. */
942
2071
  #forget(instanceId, record) {
943
- if (this.#instances.get(instanceId) !== record) return;
2072
+ if (this.#instances.get(instanceId) !== record) {
2073
+ if (record.audioSession !== void 0) this.#audio?.closeSession(instanceId, record.audioSession);
2074
+ return;
2075
+ }
944
2076
  this.#instances.delete(instanceId);
945
- this.#layerStore.remove(instanceId);
2077
+ this.#store.remove(instanceId);
2078
+ this.#audio?.close(instanceId);
946
2079
  }
947
2080
  /**
948
2081
  * Asks the guest to release its sessions.
@@ -958,7 +2091,7 @@ var WidgetHostImpl = class {
958
2091
  try {
959
2092
  const sandbox = await this.#ensureSandbox();
960
2093
  if (this.#disposed) return;
961
- await sandbox.call(WIDGET_RESET_RUNTIME_METHOD);
2094
+ await sandbox.call(widgetResetRuntimeMethod);
962
2095
  } catch (error) {
963
2096
  if (this.#disposed || error instanceof WidgetRuntimeError) return;
964
2097
  if (this.#isTerminated()) {
@@ -976,7 +2109,13 @@ var WidgetHostImpl = class {
976
2109
  return Promise.resolve(existing);
977
2110
  }
978
2111
  if (!this.#starting) {
979
- const pending = this.#createSandbox(this.#container === void 0 ? {} : { container: this.#container }).catch((error) => {
2112
+ const devicePort = this.#devicePort;
2113
+ this.#devicePort = void 0;
2114
+ const pending = this.#createSandbox({
2115
+ ...this.#container === void 0 ? {} : { container: this.#container },
2116
+ ...this.#fs === void 0 ? {} : { fs: this.#fs },
2117
+ ...devicePort === void 0 ? {} : { devicePort }
2118
+ }).catch((error) => {
980
2119
  throw this.#failRuntime(`The widget sandbox failed to start: ${describeError(error)}`, error);
981
2120
  }).then(async (sandbox) => {
982
2121
  if (this.#disposed) {
@@ -984,6 +2123,7 @@ var WidgetHostImpl = class {
984
2123
  throw new WidgetRuntimeError("Widget host is disposed");
985
2124
  }
986
2125
  this.#sandbox = sandbox;
2126
+ this.#directDevice = sandbox.directDevice === true;
987
2127
  this.#attach(sandbox);
988
2128
  return sandbox;
989
2129
  });
@@ -996,16 +2136,24 @@ var WidgetHostImpl = class {
996
2136
  return this.#starting;
997
2137
  }
998
2138
  /**
999
- * Reads every asset reference found in the merged props. Failures are reported and skipped:
1000
- * a missing image must not stop the instance from mounting.
2139
+ * Reads every asset reference found in the merged props.
2140
+ *
2141
+ * RFC 0018 step 4: widget property resources resolve against the canvas document URI, so a host
2142
+ * without a `WidgetAssetProvider` reads them through `fs` (a `data:` reference is decoded
2143
+ * locally). Failures are reported and skipped: a missing image must not stop the mount.
1001
2144
  */
1002
2145
  async #prefetchAssets(instanceId, ref, props) {
1003
2146
  const source = this.#assets;
1004
- if (!source) return void 0;
2147
+ const fs = this.#fs;
2148
+ const baseUri = this.#documentUri;
2149
+ let read;
2150
+ if (source !== void 0) read = (assetRef) => source.resolve(assetRef);
2151
+ else if (fs !== void 0 && baseUri !== void 0) read = (assetRef) => readHostAsset(fs, baseUri, assetRef);
2152
+ else return;
1005
2153
  const refs = collectAssetRefs(props);
1006
2154
  const entries = await Promise.all([...refs.values()].map(async (assetRef) => {
1007
2155
  try {
1008
- const bytes = await source.resolve(assetRef);
2156
+ const bytes = await read(assetRef);
1009
2157
  if (!(bytes instanceof Uint8Array)) throw new TypeError("WidgetAssetProvider.resolve() must resolve to a Uint8Array");
1010
2158
  return [assetRef.src, bytes];
1011
2159
  } catch (error) {
@@ -1019,7 +2167,51 @@ var WidgetHostImpl = class {
1019
2167
  return Object.fromEntries(entries.filter((entry) => entry !== void 0));
1020
2168
  }
1021
2169
  #attach(sandbox) {
1022
- this.#detachers.push(sandbox.on(WIDGET_FRAME_EVENT, (payload) => this.#onFrame(payload)), sandbox.on(WIDGET_PUBLISH_EVENT, (payload) => this.#onPublishMessage(payload)), sandbox.on(WIDGET_ERROR_EVENT, (payload) => this.#onErrorMessage(payload)), sandbox.on(WIDGET_ASSET_FAILED_EVENT, (payload) => this.#onAssetFailedMessage(payload)));
2170
+ this.#detachers.push(sandbox.on(widgetFrameEvent, (payload) => this.#onFrame(payload)), sandbox.on(widgetPublishEvent, (payload) => this.#onPublishMessage(payload)), sandbox.on(widgetErrorEvent, (payload) => this.#onErrorMessage(payload)), sandbox.on(widgetAssetFailedEvent, (payload) => this.#onAssetFailedMessage(payload)));
2171
+ this.#flushAudioPort();
2172
+ this.#flushAudioState();
2173
+ }
2174
+ #emitAudioPort(port) {
2175
+ this.#pendingAudioPort = port;
2176
+ this.#flushAudioPort();
2177
+ }
2178
+ /** Drops a port nobody received; the host owns it until it is transferred. */
2179
+ #releaseAudioPort() {
2180
+ const port = this.#pendingAudioPort;
2181
+ this.#pendingAudioPort = void 0;
2182
+ try {
2183
+ port?.close();
2184
+ } catch {}
2185
+ }
2186
+ /** Transfers the direct worker ↔ worklet port; skipped until a sandbox can receive it. */
2187
+ #flushAudioPort() {
2188
+ const port = this.#pendingAudioPort;
2189
+ const sandbox = this.#sandbox;
2190
+ if (port === void 0 || sandbox === void 0) return;
2191
+ this.#pendingAudioPort = void 0;
2192
+ if (sandbox.audio === void 0) {
2193
+ try {
2194
+ port.close();
2195
+ } catch {}
2196
+ return;
2197
+ }
2198
+ try {
2199
+ sandbox.audio.attachPort(port);
2200
+ } catch {}
2201
+ }
2202
+ #emitAudioState(state) {
2203
+ if (this.#lastAudioState === state) return;
2204
+ this.#lastAudioState = state;
2205
+ this.#flushAudioState();
2206
+ }
2207
+ /** Pushes the latest availability; a mounted instance already received it in its mount request. */
2208
+ #flushAudioState() {
2209
+ const state = this.#lastAudioState;
2210
+ const sandbox = this.#sandbox;
2211
+ if (state === void 0 || sandbox === void 0) return;
2212
+ try {
2213
+ sandbox.audio?.setState(state);
2214
+ } catch {}
1023
2215
  }
1024
2216
  #detach() {
1025
2217
  for (const detach of this.#detachers.splice(0)) try {
@@ -1030,7 +2222,7 @@ var WidgetHostImpl = class {
1030
2222
  const frame = payload;
1031
2223
  if (!frame || typeof frame !== "object" || typeof frame.instanceId !== "string") return;
1032
2224
  if (!isBitmap(frame.bitmap)) return;
1033
- this.#layerStore.setBitmap(frame.instanceId, frame.bitmap);
2225
+ this.#store.setBitmap(frame.instanceId, frame.bitmap);
1034
2226
  }
1035
2227
  #onPublishMessage(payload) {
1036
2228
  const message = payload;
@@ -1040,31 +2232,29 @@ var WidgetHostImpl = class {
1040
2232
  instanceId: message.instanceId,
1041
2233
  port: message.port,
1042
2234
  payload: message.payload,
1043
- simTime: typeof message.simTime === "number" && Number.isFinite(message.simTime) ? message.simTime : 0
2235
+ simTime: typeof message.simTime === "number" && Number.isFinite(message.simTime) ? message.simTime : this.#simTime
1044
2236
  };
1045
- this.#forwardToSimulation(publish);
2237
+ if (message.direct !== true) this.#forwardToDeviceHost(publish);
1046
2238
  this.#onPublish?.(publish);
1047
2239
  }
1048
2240
  /** Sends a widget publish to the endpoint its port is bound to; unbound ports stay host-local. */
1049
- #forwardToSimulation(publish) {
1050
- const simulation = this.#simulation;
1051
- if (simulation === void 0) return;
2241
+ #forwardToDeviceHost(publish) {
1052
2242
  const widget = this.#document.widgets.find((candidate) => candidate.id === publish.instanceId);
1053
2243
  const target = widget?.bindings?.[publish.port];
1054
2244
  if (target === void 0) return;
1055
- try {
1056
- simulation.deliver(target, publish.payload);
1057
- } catch (error) {
2245
+ this.#deviceHost.deliver(target, publish.payload, publish.simTime).catch((error) => {
1058
2246
  this.#report("widget/deliver-failed", `Publish from "${publish.instanceId}" could not reach ${target.symbol}.${target.port}: ${describeError(error)}`, {
1059
2247
  instanceId: publish.instanceId,
1060
2248
  widget: widget?.widget
1061
2249
  });
1062
- }
2250
+ });
1063
2251
  }
1064
2252
  /** Fans a device publish out to every widget port bound to its endpoint. */
1065
2253
  #onSimulationPublish(publish) {
1066
2254
  if (this.#disposed) return;
1067
2255
  const { target } = publish;
2256
+ this.#lastPublished.set(targetKey(target), publish);
2257
+ if (this.#directDevice) return;
1068
2258
  for (const widget of this.#document.widgets) {
1069
2259
  const bindings = widget.bindings;
1070
2260
  if (bindings === void 0) continue;
@@ -1075,6 +2265,19 @@ var WidgetHostImpl = class {
1075
2265
  }
1076
2266
  }
1077
2267
  }
2268
+ /**
2269
+ * Seeds one freshly mounted instance with the values its endpoints already carry.
2270
+ *
2271
+ * `deliver` only forwards what the simulation publishes, and a level topic publishes on change
2272
+ * only, so without this a widget mounted mid-run would wait for the next change to show anything.
2273
+ */
2274
+ #replayPublished(widget) {
2275
+ for (const [port, target] of Object.entries(widget.bindings ?? {})) {
2276
+ const publish = this.#lastPublished.get(targetKey(target));
2277
+ if (publish === void 0) continue;
2278
+ this.deliver(widget.id, port, publish.payload, publish.simTime);
2279
+ }
2280
+ }
1078
2281
  #onAssetFailedMessage(payload) {
1079
2282
  const message = payload;
1080
2283
  if (!message || typeof message !== "object") return;
@@ -1119,23 +2322,83 @@ var WidgetHostImpl = class {
1119
2322
  #isTerminated() {
1120
2323
  return this.#sandbox?.state === "terminated";
1121
2324
  }
2325
+ /**
2326
+ * Starts the frame clock. RFC 0018 gives the host the clock, so a loaded document advances on its
2327
+ * own; a pause or a disposed host keeps it stopped.
2328
+ */
2329
+ #startClock() {
2330
+ if (this.#disposed || this.#paused || this.#mode !== "simulation") return;
2331
+ this.#scheduleFrame();
2332
+ }
2333
+ #stopClock() {
2334
+ const cancel = this.#cancelFrame;
2335
+ this.#cancelFrame = void 0;
2336
+ cancel?.();
2337
+ }
2338
+ #scheduleFrame() {
2339
+ if (this.#cancelFrame !== void 0 || this.#disposed) return;
2340
+ this.#cancelFrame = this.#frameOptions.requestFrame(() => {
2341
+ this.#cancelFrame = void 0;
2342
+ this.#advanceFrame();
2343
+ });
2344
+ }
2345
+ /** Advances one fixed simulation step, then schedules the next 25 ms clock tick. */
2346
+ async #advanceFrame() {
2347
+ if (this.#advancing || this.#disposed || this.#paused) return;
2348
+ this.#advancing = true;
2349
+ try {
2350
+ if (this.#disposed || this.#paused) return;
2351
+ this.#flushInputs();
2352
+ if (this.#mode === "simulation") {
2353
+ const report = await this.#deviceHost.tick(this.#frameOptions.stepMs * PS_PER_MS);
2354
+ this.#simTime = report.simTime;
2355
+ }
2356
+ } catch (error) {
2357
+ this.#report("widget/runtime-failed", `A simulation step failed: ${describeError(error)}`);
2358
+ } finally {
2359
+ this.#advancing = false;
2360
+ if (!this.#disposed && !this.#paused && this.#mode === "simulation") this.#scheduleFrame();
2361
+ }
2362
+ }
2363
+ /** Dispatches the queued input events at the start of a step. */
2364
+ #flushInputs() {
2365
+ for (const input of this.#pendingInputs.splice(0)) {
2366
+ if (!this.#instances.has(input.instanceId)) continue;
2367
+ this.#fire("widget/deliver-failed", widgetPointerMethod, [input.instanceId, input.event], input.instanceId);
2368
+ }
2369
+ }
1122
2370
  /** Abandons the runtime: layers are cleared and the failure is reported once. */
1123
2371
  #failRuntime(message, cause) {
1124
2372
  this.#sandbox = void 0;
1125
2373
  this.#starting = void 0;
2374
+ this.#directDevice = false;
1126
2375
  this.#detach();
1127
- this.#layerStore.clear();
2376
+ this.#store.clear();
1128
2377
  this.#instances.clear();
2378
+ this.#pendingInputs.length = 0;
2379
+ this.#releaseAudioPort();
2380
+ this.#audio?.reset();
1129
2381
  if (!this.#disposed) this.#report("widget/runtime-failed", message);
1130
2382
  return new WidgetRuntimeError(message, cause === void 0 ? void 0 : { cause });
1131
2383
  }
1132
2384
  async #shutdown() {
1133
2385
  this.#disposed = true;
2386
+ this.#stopClock();
1134
2387
  this.#detach();
1135
- this.#unsubscribeSimulation?.();
1136
- this.#unsubscribeSimulation = void 0;
1137
- this.#layerStore.clear();
2388
+ this.#unsubscribeDevicePublish?.dispose();
2389
+ this.#unsubscribeDevicePublish = void 0;
2390
+ this.#pendingInputs.length = 0;
2391
+ this.#store.clear();
1138
2392
  this.#instances.clear();
2393
+ this.#lastPublished.clear();
2394
+ this.#directDevice = false;
2395
+ const devicePort = this.#devicePort;
2396
+ this.#devicePort = void 0;
2397
+ try {
2398
+ devicePort?.close();
2399
+ } catch {}
2400
+ this.#releaseAudioPort();
2401
+ this.#audio?.dispose();
1139
2402
  const pending = this.#starting;
1140
2403
  const sandbox = this.#sandbox;
1141
2404
  this.#starting = void 0;
@@ -1149,12 +2412,31 @@ var WidgetHostImpl = class {
1149
2412
  if (late) await terminate(late);
1150
2413
  }
1151
2414
  }
2415
+ /** Diagnostic ids for one instance; audio failures without an instance report no ids. */
2416
+ #instanceIds(instanceId) {
2417
+ if (instanceId === "") return {};
2418
+ const widget = this.#instances.get(instanceId)?.widget;
2419
+ return widget === void 0 ? { instanceId } : {
2420
+ instanceId,
2421
+ widget
2422
+ };
2423
+ }
2424
+ #reportBindingDiagnostic(widget, code, message, pointer) {
2425
+ this.#report("widget/binding-failed", message, {
2426
+ instanceId: widget.id,
2427
+ widget: widget.widget,
2428
+ bindingCode: code,
2429
+ pointer
2430
+ });
2431
+ }
1152
2432
  #report(code, message, ids = {}) {
1153
2433
  const diagnostic = {
1154
2434
  code,
1155
2435
  message,
1156
2436
  ...ids.instanceId === void 0 ? {} : { instanceId: ids.instanceId },
1157
- ...ids.widget === void 0 ? {} : { widget: ids.widget }
2437
+ ...ids.widget === void 0 ? {} : { widget: ids.widget },
2438
+ ...ids.bindingCode === void 0 ? {} : { bindingCode: ids.bindingCode },
2439
+ ...ids.pointer === void 0 ? {} : { pointer: ids.pointer }
1158
2440
  };
1159
2441
  try {
1160
2442
  this.#onDiagnostic?.(diagnostic);
@@ -1179,19 +2461,6 @@ function placementOf(widget) {
1179
2461
  rotation: widget.rotation
1180
2462
  };
1181
2463
  }
1182
- /**
1183
- * Shallow comparison of two property maps.
1184
- *
1185
- * The document owns property values, so a nested object only counts as changed when the caller
1186
- * replaced the object itself; deep equality would swallow those edits. The key sets matter as much
1187
- * as the values, because a missing key falls back to the definition default while an explicit
1188
- * `undefined` overrides it.
1189
- */
1190
- function sameProperties(left, right) {
1191
- if (left === right) return true;
1192
- const keys = Object.keys(left);
1193
- return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
1194
- }
1195
2464
  function splitRef(ref) {
1196
2465
  const separator = ref.indexOf(":");
1197
2466
  if (separator <= 0 || separator === ref.length - 1) return void 0;
@@ -1200,6 +2469,20 @@ function splitRef(ref) {
1200
2469
  widgetId: ref.slice(separator + 1)
1201
2470
  };
1202
2471
  }
2472
+ /** Map key of one binding endpoint; the separator cannot occur in a symbol id or a port name. */
2473
+ function targetKey(target) {
2474
+ return `${target.symbol}\u0000${target.port}`;
2475
+ }
2476
+ /** Compares two binding maps by endpoint; the document reparses objects it never changed. */
2477
+ function sameBindings(left, right) {
2478
+ if (left === right) return true;
2479
+ const ports = Object.keys(left);
2480
+ if (ports.length !== Object.keys(right).length) return false;
2481
+ return ports.every((port) => {
2482
+ const bound = right[port];
2483
+ return bound !== void 0 && targetKey(left[port]) === targetKey(bound);
2484
+ });
2485
+ }
1203
2486
  function currentDevicePixelRatio() {
1204
2487
  const ratio = globalThis.devicePixelRatio;
1205
2488
  return typeof ratio === "number" && Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
@@ -1211,6 +2494,28 @@ function describeError(error) {
1211
2494
  if (error instanceof Error && error.message) return error.message;
1212
2495
  return typeof error === "string" ? error : String(error);
1213
2496
  }
2497
+ /**
2498
+ * Reads one widget property resource (RFC 0018 step 4).
2499
+ *
2500
+ * `inline` references carry base64 and a `data:` reference carries its own bytes, so neither
2501
+ * reaches `fs`; every other reference resolves against the canvas document URI first.
2502
+ */
2503
+ function readHostAsset(fs, baseUri, ref) {
2504
+ if (ref.src.slice(0, 5).toLowerCase() === "data:") return Promise.resolve(decodeDataUri(ref.src));
2505
+ if (ref.mode === "inline") return Promise.resolve(decodeBase64Asset(ref.src));
2506
+ return fs.read(resolveHostUri(baseUri, ref.src));
2507
+ }
2508
+ function decodeBase64Asset(text) {
2509
+ let binary;
2510
+ try {
2511
+ binary = atob(text);
2512
+ } catch (cause) {
2513
+ throw new TypeError("Inline asset src is not valid base64", { cause });
2514
+ }
2515
+ const bytes = new Uint8Array(binary.length);
2516
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
2517
+ return bytes;
2518
+ }
1214
2519
  async function terminate(sandbox) {
1215
2520
  try {
1216
2521
  await sandbox.terminate("widget host disposed");
@@ -1219,10 +2524,109 @@ async function terminate(sandbox) {
1219
2524
  /** Asks the guest to drop an instance the host has already given up on. */
1220
2525
  async function releaseGuestInstance(sandbox, instanceId) {
1221
2526
  try {
1222
- await sandbox.call(WIDGET_UNMOUNT_METHOD, instanceId);
2527
+ await sandbox.call(widgetUnmountMethod, instanceId);
1223
2528
  } catch {}
1224
2529
  }
1225
2530
  //#endregion
1226
- export { WIDGET_RUNTIME_SOURCE, WidgetLoadError, createDefaultWidgetSandbox, createPackageWidgetProvider, createStaticWidgetProvider, createWidgetHost, loadWidgetPackage };
2531
+ //#region src/host/sandbox.ts
2532
+ /** Adapts a provider-created widget worker to WidgetHost's RPC-facing surface. */
2533
+ async function createWidgetSandboxFromWorker(worker, options) {
2534
+ const devicePort = options.devicePort;
2535
+ let port;
2536
+ let rpc;
2537
+ let logRegistration;
2538
+ try {
2539
+ await worker.ready;
2540
+ const channel = new MessageChannel();
2541
+ port = channel.port1;
2542
+ const endpoint = createRpc(port);
2543
+ rpc = endpoint;
2544
+ logRegistration = endpoint.register(loggerService, { write(record) {
2545
+ (console[record.level] ?? console.log).call(console, `[${record.scope}]`, record.message, ...record.data);
2546
+ } });
2547
+ const transfer = devicePort === void 0 ? [channel.port2] : [channel.port2, devicePort];
2548
+ worker.postMessage(null, transfer);
2549
+ } catch (error) {
2550
+ logRegistration?.dispose();
2551
+ rpc?.dispose();
2552
+ await worker.terminate("widget sandbox failed to start").catch(() => void 0);
2553
+ throw error;
2554
+ }
2555
+ const endpoint = rpc;
2556
+ if (endpoint === void 0) throw new Error("Widget RPC endpoint was not created.");
2557
+ const listeners = /* @__PURE__ */ new Map();
2558
+ const dispatch = (type, payload) => {
2559
+ for (const listener of [...listeners.get(type) ?? []]) listener(payload);
2560
+ };
2561
+ endpoint.register(widgetHostCapabilitiesService, { async read(uri) {
2562
+ if (!options.fs) throw new Error(`No HostFs configured for ${uri}`);
2563
+ try {
2564
+ return await options.fs.read(uri);
2565
+ } catch (error) {
2566
+ if (isHostFsError(error)) {
2567
+ const payload = toHostFsErrorPayload(error);
2568
+ throw Object.assign(new Error(JSON.stringify(payload)), { name: "HostFsError" });
2569
+ }
2570
+ throw error;
2571
+ }
2572
+ } }, { transfer: (member, value) => member === "read" && value instanceof Uint8Array ? [value.buffer] : [] });
2573
+ endpoint.register(widgetHostControlService, { event: dispatch });
2574
+ const guest = endpoint.getProxy(widgetGuestService);
2575
+ const audio = endpoint.getProxy(widgetAudioGuestService, { transfer: (member, args) => member === "attachPort" ? [args[0]] : [] });
2576
+ return {
2577
+ get state() {
2578
+ return worker.state;
2579
+ },
2580
+ directDevice: devicePort !== void 0,
2581
+ call: (method, ...args) => guest[method](...args),
2582
+ on: (type, listener) => {
2583
+ let set = listeners.get(type);
2584
+ if (!set) listeners.set(type, set = /* @__PURE__ */ new Set());
2585
+ set.add(listener);
2586
+ return () => set?.delete(listener);
2587
+ },
2588
+ emit: (type, payload, transfer) => {
2589
+ endpoint.getProxy(widgetGuestControlService, { transfer: () => transfer ?? [] }).dispatchEvent(type, payload).catch(() => void 0);
2590
+ },
2591
+ audio: {
2592
+ attachPort: (port) => {
2593
+ audio.attachPort(port).catch(() => void 0);
2594
+ },
2595
+ setState: (state) => {
2596
+ audio.setState(state).catch(() => void 0);
2597
+ }
2598
+ },
2599
+ terminate: async (reason) => {
2600
+ logRegistration?.dispose();
2601
+ endpoint.dispose();
2602
+ await worker.terminate(reason);
2603
+ }
2604
+ };
2605
+ }
2606
+ //#endregion
2607
+ //#region src/host/guest.ts
2608
+ /**
2609
+ * The widget guest worker script, bundled and minified into this module by
2610
+ * `@mica-js/sandbox/vite` while the package itself is built.
2611
+ *
2612
+ * It is a classic script: every dependency is inlined, so the sandbox can run it without a module
2613
+ * loader and the package publishes no separate `*.sandbox.js` file.
2614
+ */
2615
+ var widgetGuestScript = "(function(){function e(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var t=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(t,n,r)=>{if(this.#t)return e(()=>{});let i={listener:t,thisArgs:n};this.#e.add(i);let a=e(()=>{this.#e.delete(i)});return r?.push(a),a};get hasListeners(){return this.#e.size>0}fire(e){if(!this.#t)for(let t of[...this.#e])t.listener.call(t.thisArgs,e)}dispose(){this.#t||(this.#t=!0,this.#e.clear())}};function n(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.kind===`close`)return!0;if(!Number.isSafeInteger(t.id)||t.id<=0)return!1;switch(t.kind){case`call`:case`listen`:return typeof t.service==`string`&&t.service.length>0&&typeof t.member==`string`&&t.member.length>0&&Array.isArray(t.args)&&(t.kind!==`listen`||t.args.length===0);case`unlisten`:return!0;case`result`:return Object.hasOwn(t,`value`);case`error`:case`subscription-error`:return typeof t.name==`string`&&typeof t.message==`string`;case`event`:return Array.isArray(t.args);default:return!1}}function r(e,t){return Object.assign(Error(t),{name:e})}function i(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw r(`MethodNotFound`,`Method is not exposed: ${t}`);for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(typeof e.value==`function`)return e.value;break}}throw r(`MethodNotFound`,`Method is not callable: ${t}`)}function a(a,l={}){let u=l,d=c(u.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new t,_=new t,v=0,y=0,b=!1;function x(e){let t=o(e);try{u.onError?.(t)}catch{}g.fire(t)}function S(){if(b)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function C(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function w(e,t){S(),a.postMessage(e,t?[...t]:void 0)}function T(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function E(e,t,n){return new Promise((i,a)=>{let s=t>0?setTimeout(()=>{T(e.id)?.reject(r(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:i,reject:a,timer:s});try{w(e,n)}catch(t){T(e.id)?.reject(o(t))}})}function D(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function O(e,t,n){if(b)return;let r=o(n);try{w({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),A()}}function k(){if(!b){b=!0,a.removeEventListener(`message`,M),a.removeEventListener(`close`,k),a.removeEventListener(`messageerror`,A);for(let e of p.keys())T(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())D(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function A(){if(!b){try{w({kind:`close`})}catch(e){x(e)}k()}}async function j(e){try{let t=f.get(e.service);if(!t)throw r(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,a=i(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw r(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let o=a.call(n,(...n)=>{if(!(b||h.get(e.id)!==i))try{w({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){D(e.id),O(`subscription-error`,e.id,t)}});if(typeof o!=`function`)throw r(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=o,h.get(e.id)!==i&&i.stop(),b||w({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw r(`InvalidCall`,`Event members require a subscription`);let i=await a.apply(n,e.args);b||w({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&D(e.id),O(`error`,e.id,t)}}function M(e){let t=e.data;if(!n(t))x(r(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=y){x(r(`RpcProtocolError`,`Request IDs must increase`));return}y=t.id,j(t);break;case`unlisten`:D(t.id);break;case`result`:T(t.id)?.resolve(t.value);break;case`error`:T(t.id)?.reject(r(t.name,t.message));break;case`subscription-error`:{let e=r(t.name,t.message),n=m.delete(t.id),i=T(t.id);i?i.reject(e):n&&x(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){x(e)}break;case`close`:k()}}return a.addEventListener(`message`,M),a.addEventListener(`close`,k),a.addEventListener(`messageerror`,A),a.start?.(),{register(t,n,i={}){S();let a=s(t);if(typeof n!=`object`||!n)throw TypeError(`RPC services must be objects`);if(f.has(a))throw Error(`Service already registered: ${a}`);let o={implementation:n,options:i};return f.set(a,o),e(()=>{if(f.get(a)===o){f.delete(a);for(let[e,t]of h)t.registration===o&&(D(e),O(`subscription-error`,e,r(`ServiceUnregistered`,`Service unregistered: ${a}`)))}})},getProxy(t,n={}){let r=s(t),i=c(n.timeoutMs??d),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(t,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?t=>{if(S(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=C();m.set(n,t),E({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!b)try{w({kind:`unlisten`,id:n})}catch(e){x(e)}x(e)});let a=e(()=>{if(m.delete(n)&&(T(n)?.resolve(void 0),!b))try{w({kind:`unlisten`,id:n})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(S(),E({kind:`call`,id:C(),service:r,member:o,args:e},i,n.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(t,n,r)=>b?(t.call(n,void 0),e(()=>{})):_.event(e=>{try{t.call(n,e)}catch(e){x(e)}},void 0,r),dispose:A}}function o(e){return e instanceof Error?e:Error(String(e))}function s(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function c(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function l(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}let u=l(`logger`),d=l(`audio-worklet`);l(`audio-control`);let f=l(`audio-guest`),p=Object.freeze({}),m=[`sine`,`square`,`triangle`,`sawtooth`],h=[`s16`,`f32`],g={min:8e3,max:96e3},_={min:50,max:2e3},v={min:0,max:1},y={min:0,max:24e3},b={min:0,max:1e4};function x(e,t,n){if(e===void 0)return p;if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${n} must be a plain object`);let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)throw TypeError(`${n} must be a plain object`);let i=e,a=new Set(t);for(let e of Object.keys(i)){if(!a.has(e))throw TypeError(`${n} does not accept the option \"${e}\"`);if(i[e]===void 0)throw TypeError(`${n}.${e} must not be undefined`)}return i}function S(e,t,n){if(e===void 0){if(n===void 0)throw TypeError(`${t} is required`);return n}if(typeof e!=`number`)throw TypeError(`${t} must be a number`);if(!Number.isFinite(e))throw RangeError(`${t} must be a finite number`);return e}function C(e,t,n){if(t.integer===!0&&!Number.isInteger(e))throw RangeError(`${n} must be an integer`);if((t.exclusiveMin===!0?e<=t.min:e<t.min)||e>t.max){let e=t.exclusiveMin===!0?`(${t.min}, ${t.max}]`:`[${t.min}, ${t.max}]`;throw RangeError(`${n} must be in ${e}`)}return e}function w(e,t,n,r,i){return C(i===void 0?S(e[t],`${n}.${t}`):S(e[t],`${n}.${t}`,i),r,`${n}.${t}`)}function T(e,t,n,r){if(e[t]!==void 0)return w(e,t,n,r)}function E(e,t,n,r,i){let a=e[t];if(a===void 0)return i;if(!n.includes(a))throw RangeError(`${r}.${t} must be one of ${n.join(`, `)}`);return a}function D(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function`)}let O=[`unavailable`,`suspended`,`running`],k=[`buffering`,`playing`,`ended`,`closed`],A=[`finished`,`stopped`,`dropped`,`error`,`unavailable`,`disposed`];function j(){let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}}function M(e){let t=e.maxVoices??8,n=e.maxStreams??4,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s,c,l=()=>{},u=new Promise(e=>{l=e}),f=`unavailable`,p=!1,S=0,C=0;function M(t,n){try{e.onListenerError?.(t,n)}catch{}}function P(){return u.then(()=>p?void 0:c)}function F(e){let t={instanceId:e,session:void 0,state:f,stateListeners:/* @__PURE__ */ new Set,voices:/* @__PURE__ */ new Map,streams:/* @__PURE__ */ new Map,api:void 0};return t.api=q(t),t}function I(e){let t=r.get(e);return t||(t=F(e),r.set(e,t)),t}function L(e,t){e.settled||(e.settled=!0,i.delete(e.id),r.get(e.instanceId)?.voices.delete(e.id),e.resolve({reason:t}))}function R(e,t){e.settled||(e.closed=!0,e.state=t===`finished`?`ended`:`closed`,o.delete(e.id),r.get(e.instanceId)?.streams.delete(e.id),V(e),e.settled=!0,e.resolve({reason:t}))}function z(e){return Math.max(0,e.writtenFrames+e.pendingFrames-e.consumedFrames)}function B(e){return{state:e.state,underruns:e.underruns,dropped:e.dropped,bufferedFrames:z(e),capacityFrames:e.capacityFrames}}function V(e){if(e.statusListeners.size===0)return;let t=B(e);for(let n of[...e.statusListeners])try{n(t)}catch(t){M(e.instanceId,t)}}function H(e){for(let t of[...e.drainListeners])try{t()}catch(t){M(e.instanceId,t)}}function U(e){if(e.closed)return;let t=e.capacityFrames/2;e.drainNotified?z(e)>t&&(e.drainNotified=!1):z(e)>t||(e.drainNotified=!0,H(e))}function W(e){if(f!==e){f=e;for(let t of r.values())if(t.state!==e){t.state=e;for(let n of[...t.stateListeners])try{n(e)}catch(e){M(t.instanceId,e)}}}}function G(e,n){S+=1;let{promise:r,resolve:a}=j(),o={id:`t${S}`,instanceId:e.instanceId,dead:n,settled:!1,ended:r,resolve:a};if(e.voices.size>=t){let t=e.voices.values().next().value;t!==void 0&&L(t,`dropped`)}return e.voices.set(o.id,o),i.set(o.id,o),o}function K(e){return{id:e.id,ended:e.ended,stop(){if(!e.settled){if(!e.dead){let t=r.get(e.instanceId)?.session;t!==void 0&&P().then(n=>n?.stopTone(t,e.id,{fadeMs:0})).catch(()=>void 0)}L(e,`stopped`)}}}}function q(e){return{get state(){return e.state},onStateChange(t){return D(t,`api.audio.onStateChange(listener)`),e.stateListeners.add(t),()=>{e.stateListeners.delete(t)}},tone(t){let n=x(t,[`type`,`frequency`,`volume`],`options`),r=E(n,`type`,m,`options`,`sine`),i=w(n,`frequency`,`options`,{...y,exclusiveMin:!0}),a=w(n,`volume`,`options`,v,1),o=e.session,s=G(e,e.state===`unavailable`||o===void 0);return!s.dead&&o!==void 0&&P().then(e=>e?.createTone(o,{voiceId:s.id,type:r,frequency:i,volume:a})).catch(()=>void 0),Object.assign(K(s),{set(e,t){let n=x(e,[`volume`,`frequency`],`options`),r=w(x(t,[`rampMs`],`options`),`rampMs`,`options`,b,0),i=T(n,`volume`,`options`,v),a=T(n,`frequency`,`options`,{...y,exclusiveMin:!0});s.settled||s.dead||o===void 0||P().then(e=>e?.setTone(o,s.id,{rampMs:r,...i===void 0?{}:{volume:i},...a===void 0?{}:{frequency:a}})).catch(()=>void 0)}})},createStream(t){let r=x(t,[`sampleRate`,`channels`,`format`,`bufferMs`,`startMs`,`volume`],`options`),i=w(r,`sampleRate`,`options`,{...g,integer:!0}),a=E(r,`channels`,[1,2],`options`,1),s=E(r,`format`,h,`options`,`f32`),c=w(r,`bufferMs`,`options`,_,500),l=w(r,`startMs`,`options`,{min:0,max:c},50),u=w(r,`volume`,`options`,v,1),d=Math.max(1,Math.ceil(c*i/1e3)),f=Math.min(d,Math.max(0,Math.ceil(l*i/1e3)));C+=1;let p=e.streams.size>=n,m=e.state===`unavailable`||e.session===void 0,{promise:y,resolve:b}=j(),S={id:`s${C}`,instanceId:e.instanceId,session:e.session,sampleRate:i,channels:a,format:s,capacityFrames:d,startFrames:f,volume:u,unavailable:m,writtenFrames:0,pendingFrames:0,consumedFrames:0,underruns:0,dropped:0,state:p?`closed`:`buffering`,drainNotified:!1,endRequested:!1,closed:p,settled:p,ended:y,resolve:b,statusListeners:/* @__PURE__ */ new Set,drainListeners:/* @__PURE__ */ new Set};if(p)b({reason:`stopped`});else if(e.streams.set(S.id,S),o.set(S.id,S),!m&&e.session!==void 0){let t=e.session;P().then(e=>e?.createStream(t,{streamId:S.id,sampleRate:i,channels:a,format:s,capacityFrames:d,startFrames:f,volume:u})).then(e=>{e?.accepted===!1&&R(S,`stopped`)}).catch(()=>void 0)}return J(S)}}}function J(e){return{id:e.id,sampleRate:e.sampleRate,channels:e.channels,format:e.format,capacityFrames:e.capacityFrames,startFrames:e.startFrames,volume:e.volume,get bufferedFrames(){return z(e)},get underruns(){return e.underruns},get dropped(){return e.dropped},get state(){return e.state},ended:e.ended,write(t){if(e.closed)return Promise.resolve(!1);let n=e.format===`s16`?Int16Array:Float32Array;if(!(t instanceof n))throw TypeError(`api.audio stream.write expects a ${n.name} for format \"${e.format}\"`);let r=t.length;if(r===0)throw RangeError(`api.audio stream.write expects at least one sample`);if(r%e.channels!==0)throw RangeError(`api.audio stream.write expects a whole number of ${e.channels}-channel frames`);let i=r/e.channels;if(i>e.capacityFrames)throw RangeError(`api.audio stream.write accepts at most ${e.capacityFrames} frames per call`);if(e.unavailable)return Promise.resolve(!1);if(z(e)+i>e.capacityFrames)return e.dropped+=1,V(e),Promise.resolve(!1);let a=e.format===`s16`?new Int16Array(t):new Float32Array(t),o=e.session??``;return e.pendingFrames+=i,P().then(async t=>{if(t===void 0||e.closed)return e.pendingFrames-=i,!1;try{let n=await t.writeStream(o,e.id,a);return e.pendingFrames-=i,n?e.writtenFrames+=i:e.dropped+=1,V(e),U(e),n}catch{return e.pendingFrames-=i,!1}})},clear(){if(!e.closed){if(e.consumedFrames=e.writtenFrames,!e.unavailable&&e.session!==void 0){let t=e.session;P().then(n=>n?.clearStream(t,e.id)).catch(()=>void 0)}V(e),U(e)}},end(){if(e.closed||e.endRequested)return;if(e.endRequested=!0,e.unavailable||e.session===void 0){R(e,`finished`);return}let t=e.session;P().then(n=>n?.endStream(t,e.id)).catch(()=>void 0)},close(){if(!e.settled){if(!e.closed&&!e.unavailable&&e.session!==void 0){let t=e.session;P().then(n=>n?.closeStream(t,e.id)).catch(()=>void 0)}R(e,`stopped`)}},onDrain(t){return D(t,`api.audio stream.onDrain(listener)`),e.drainListeners.add(t),()=>{e.drainListeners.delete(t)}},onStatus(t){return D(t,`api.audio stream.onStatus(listener)`),e.statusListeners.add(t),()=>{e.statusListeners.delete(t)}}}}function Y(e){if(typeof e!=`object`||!e||typeof e.streamId!=`string`)return;let t=o.get(e.streamId);t&&(typeof e.consumedFrames==`number`&&Number.isFinite(e.consumedFrames)&&(t.consumedFrames=Math.max(t.consumedFrames,Math.floor(e.consumedFrames))),typeof e.underruns==`number`&&Number.isFinite(e.underruns)&&(t.underruns=Math.max(0,Math.floor(e.underruns))),!t.closed&&k.includes(e.state)&&(t.state=e.state),V(t),U(t))}function X(e){if(typeof e!=`object`||!e||typeof e.id!=`string`)return;let t=A.includes(e.reason)?e.reason:`stopped`;if(e.target===`tone`){let n=i.get(e.id);n&&L(n,t);return}let n=o.get(e.id);n&&R(n,t)}function Z(e){let t=r.get(e);if(t){r.delete(e);for(let e of t.voices.values())L(e,`disposed`);t.voices.clear();for(let e of[...t.streams.values()])R(e,`disposed`);t.streams.clear(),t.stateListeners.clear()}}return{get state(){return f},api(e){return I(e).api},open(e,t){let n=I(e);n.session=t?.session,t!==void 0&&(n.state=t.state,f=t.state)},setState(e){O.includes(e)&&W(e)},attachPort(e){if(p||s!==void 0)return;let t=a(e);s=t,c=t.getProxy(d,{transfer:(e,t)=>e===`writeStream`&&N(t[2])?[t[2].buffer]:[]}),c.onDidProgress(e=>Y(e)),c.onDidEnded(e=>X(e)),l()},release:Z,dispose(){if(!p){for(let e of[...r.keys()])Z(e);p=!0,l(),s?.dispose(),s=void 0,c=void 0,i.clear(),o.clear()}}}}function N(e){return e instanceof Int16Array||e instanceof Float32Array}let P=l(`guest`),F=l(`guest-control`),I=l(`host-control`);l(`host-capabilities`);let L=l(`guest`);function R(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function z(e){if(Array.isArray(e))return Object.freeze(e.map(e=>z(e)));if(R(e)){let t=[];for(let n of Object.keys(e))t.push([n,z(e[n])]);return Object.freeze(Object.fromEntries(t))}return e}function B(e,t){let n=/* @__PURE__ */ new Map;for(let t of Object.keys(e??{})){let r=e?.[t];r&&Object.prototype.hasOwnProperty.call(r,`default`)&&n.set(t,z(r.default))}for(let e of Object.keys(t??{}))n.set(e,t?.[e]);return Object.freeze(Object.fromEntries(n))}function V(e,t={}){let n=t.createEndpoint?.(e)??a(e);n.getProxy(u).write({level:`debug`,scope:`widget-runtime`,message:`guest-started`,data:[]}).catch(()=>void 0);let r=/* @__PURE__ */ new Map,i=t.ports?.[0],o=i===void 0?void 0:a(i),s=o?.getProxy(L),c=(e,t)=>{for(let n of[...r.get(e)??[]])try{n(t)}catch{}},l=n.getProxy(I,{transfer:(e,t)=>e===`event`&&Array.isArray(t[2])?[...t[2]]:[]}),d=!1,p=H({emit(e,t,n){if(d)throw Error(`The widget sandbox is gone`);l.event(e,t,n).catch(()=>void 0)},on(e,t){let n=r.get(e);return n||r.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}},{...t,...s===void 0?{}:{device:s}}),m=()=>{if(!d){d=!0,r.clear(),p.dispose(),n.dispose(),o?.dispose();try{e.close()}catch{}try{i?.close()}catch{}}};return n.register(P,{load:e=>p.load(e),mount:e=>p.mount(e),unmount:e=>p.unmount(e),resize:(e,t,n,r)=>p.resize(e,t,n,r),\"set-properties\":(e,t)=>p.setProperties(e,t),\"set-bindings\":(e,t)=>p.setBindings(e,t),deliver:(e,t,n,r)=>p.deliver(e,t,n,r),pointer:(e,t)=>p.pointer(e,t),\"reset-runtime\":()=>p.resetRuntime()}),n.register(F,{dispatchEvent:c,terminate:m}),n.register(f,{attachPort:e=>p.attachAudioPort(e),setState:e=>p.setAudioState(e)}),{runtime:p,dispose:m}}function H(e,t={}){let n=t.importModule??te,r=t.device,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=!1,u=!1,d=M({onListenerError:(e,t)=>f(`deliver`,e,t)});function f(t,n,r){let i={instanceId:n,phase:t,error:{name:Q(r),message:ee(r)}};try{e.emit(`widget:error`,i)}catch{}}function p(e,t,n,r){let i=b(e).subscriptions.get(t);if(!i||i.size===0)return;let a={simTime:r};for(let t of[...i])try{t(n,a)}catch(t){f(`deliver`,e,t)}}function m(e){if(!u)for(let t of[...s.values()])for(let[n,r]of Object.entries(t.bindings))r.symbol===e.target.symbol&&r.port===e.target.port&&p(t.instanceId,n,e.payload,e.simTime)}let h=r?.onDidPublish(m)??(()=>{});function g(e){e.failed||e.disposed||u||(c.add(e),!l&&(l=!0,queueMicrotask(_)))}function _(){l=!1;let e=[...c];c.clear();for(let t of e)v(t)}function v(e){if(e.failed||e.disposed||u)return;let{context:t,canvas:n}=e;typeof t.setTransform==`function`&&(t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,n.width,n.height),t.setTransform(e.dpr,0,0,e.dpr,0,0));let r=e.instance?.render;if(typeof r==`function`)try{r.call(e.instance,t)}catch(t){e.failed=!0,c.delete(e),f(`render`,e.instanceId,t);return}y(e)}function y(t){let n;try{n=t.canvas.transferToImageBitmap()}catch(e){t.failed=!0,f(`render`,t.instanceId,e);return}let r={instanceId:t.instanceId,bitmap:n,width:t.width,height:t.height,dpr:t.dpr};try{e.emit(`widget:frame`,r,[n])}catch{Z(n)}}function b(e){let t=s.get(e);if(!t)throw Error(`Widget instance ${JSON.stringify(e)} is not mounted`);return t}function x(e,t){let n=U(e.width,e.height,e.dpr),r=t?.properties??{};return d.open(e.instanceId,e.audio),{instanceId:e.instanceId,width:K(e.width),height:K(e.height),dpr:q(e.dpr),props:B(r,e.props),properties:r,assets:Y(e.assets),reportedAssets:/* @__PURE__ */ new Set,canvas:n,context:W(n),subscriptions:/* @__PURE__ */ new Map,bindings:{},instance:void 0,failed:!1,disposed:!1}}function S(t,n,r){if(t.disposed||u||t.reportedAssets.has(n))return;t.reportedAssets.add(n);let i={instanceId:t.instanceId,src:n,error:{name:`Error`,message:r}};try{e.emit(`widget:asset-failed`,i)}catch{}}function C(e,t){if(typeof t!=`string`)return Promise.reject(/* @__PURE__ */ TypeError(`Widget asset src must be a string`));let n=e.assets.get(t);if(n!==void 0&&!e.disposed&&!u)return Promise.resolve(new Uint8Array(n));let r=`Widget asset ${JSON.stringify(t)} was not prefetched`;return e.disposed||u||S(e,t,r),Promise.reject(Error(r))}function w(t){return{instanceId:t.instanceId,get width(){return t.width},get height(){return t.height},get props(){return t.props},assets:{readBinary:e=>C(t,e)},audio:d.api(t.instanceId),subscribe(e,n){if(t.disposed||typeof n!=`function`)return()=>{};let r=t.subscriptions.get(e);return r||(r=/* @__PURE__ */ new Set,t.subscriptions.set(e,r)),r.add(n),()=>{t.subscriptions.get(e)?.delete(n)}},publish(n,i,a){if(t.disposed||u)return;let o={instanceId:t.instanceId,port:n,payload:i,simTime:X(a)},s=t.bindings[n],c=s!==void 0&&r!==void 0;s!==void 0&&r!==void 0&&r.deliver(s,i,o.simTime).catch(e=>{f(`deliver`,t.instanceId,e)});try{e.emit(`widget:publish`,c?{...o,direct:c}:o)}catch(e){f(`deliver`,t.instanceId,e)}},invalidate(){g(t)}}}function T(e){e.disposed=!0,c.delete(e),e.subscriptions.clear(),d.release(e.instanceId);let t=e.instance;if(e.instance=void 0,t&&typeof t.dispose==`function`)try{t.dispose()}catch(t){f(`render`,e.instanceId,t)}e.assets.clear(),e.canvas.width=1,e.canvas.height=1}async function E(e,t){let r=await n(t),i=r&&typeof r==`object`?r.default:void 0;if(typeof i!=`function`)throw Error(`Widget ${JSON.stringify(e)} must default-export a factory function`);return i}return{async load(e){let t=Array.isArray(e.packages)?e.packages:[],n,r=!1;for(let e of t){let t=e.modules;if(t&&typeof t==`object`)for(let s of Object.keys(t)){let c=t[s];if(!c)continue;let l=`${e.id}:${s}`;if(!i.has(l))try{let e=o.get(l);e||(e=E(l,c.code),o.set(l,e)),i.set(l,await e),a.set(l,c.definition)}catch(e){r||=(n=e,!0)}finally{o.delete(l)}}}if(r)throw n},mount(e){if(u)throw Error(`The widget runtime is disposed`);let{instanceId:t,widget:n}=e;if(s.has(t))throw Error(`Widget instance ${JSON.stringify(t)} is already mounted`);let r=i.get(n);if(!r)throw Error(`Widget ${JSON.stringify(n)} is not loaded`);let o=x(e,a.get(n));s.set(t,o);try{o.instance=G(r(w(o)))}catch(e){throw s.delete(t),T(o),f(`mount`,t,e),e instanceof Error?e:Error(String(e))}c.delete(o),v(o)},unmount(e){let t=s.get(e);t&&(s.delete(e),T(t))},resize(e,t,n,r){let i=b(e);i.width=K(t),i.height=K(n),i.dpr=q(r),i.canvas.width=J(t,i.dpr),i.canvas.height=J(n,i.dpr),c.delete(i),v(i)},setProperties(e,t){let n=b(e);n.props=B(n.properties,t),g(n)},setBindings(e,t){let n=s.get(e);n!==void 0&&(n.bindings=t??{})},deliver(e,t,n,r){p(e,t,n,r)},pointer(e,t){let n=b(e);if(n.failed||n.disposed)return;let r=n.instance?.input;if(typeof r==`function`)try{r.call(n.instance,t)}catch(t){f(`deliver`,e,t)}},resetRuntime(){if(!u){c.clear();for(let e of[...s.values()])s.delete(e.instanceId),T(e);s.clear()}},dispose(){if(!u){u=!0,h(),c.clear();for(let e of[...s.values()])T(e);s.clear(),d.dispose(),i.clear(),a.clear(),o.clear()}},attachAudioPort(e){d.attachPort(e)},setAudioState(e){d.setState(e)}}}function U(e,t,n){return new OffscreenCanvas(J(e,n),J(t,n))}function W(e){let t=e.getContext(`2d`);if(!t)throw Error(`The widget runtime needs a 2D context`);return t}function G(e){return e&&typeof e==`object`?e:{}}function K(e){return Number.isFinite(e)&&e>0?e:0}function q(e){return Number.isFinite(e)&&e>0?e:1}function J(e,t){return Math.max(1,Math.round(K(e)*q(t)))}function Y(e){let t=/* @__PURE__ */ new Map;if(typeof e!=`object`||!e)return t;for(let n of Object.keys(e)){let r=e[n];r instanceof Uint8Array&&t.set(n,new Uint8Array(r))}return t}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function Z(e){try{e.close()}catch{}}function Q(e){return e instanceof Error&&e.name?e.name:`Error`}function ee(e){return e instanceof Error&&e.message?e.message:typeof e==`string`?e:String(e)}function te(e){let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}let $=!1;self.addEventListener(`message`,e=>{if($)return;let t=e.ports[0];t!==void 0&&($=!0,V(t,{ports:e.ports.slice(1)}))})})();";
2616
+ /**
2617
+ * Creates the widget host guest worker.
2618
+ *
2619
+ * This is the guest `WidgetHost` talks to, and it is the same one `@mica-js/canvas-editor`'s
2620
+ * `SandboxHostProvider` starts by default. Hosts only start it; the RPC surface is wired by
2621
+ * `createWidgetSandboxFromWorker`.
2622
+ */
2623
+ function createWidgetHostGuestSandbox(options = {}) {
2624
+ return new SandboxWorker(widgetGuestScript, {
2625
+ name: "widget",
2626
+ ...options
2627
+ });
2628
+ }
2629
+ //#endregion
2630
+ export { HostFsError, WidgetLoadError, createPackageWidgetProvider, createStaticWidgetProvider, createWidgetAudioWorklet, createWidgetHost, createWidgetHostGuestSandbox, createWidgetSandboxFromWorker, decodeDataUri, decodeDataUriText, fromHostFsErrorPayload, isAbsoluteHostUri, isHostFsError, loadWidgetPackage, resolveHostUri, toHostFsErrorPayload, widgetAudioWorkletUrl, widgetGuestScript };
1227
2631
 
1228
2632
  //# sourceMappingURL=index.js.map