@mica-js/widget 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -667,7 +667,7 @@ defineRpcService("audio-worklet");
|
|
|
667
667
|
var widgetAudioControlService = defineRpcService("audio-control");
|
|
668
668
|
var widgetAudioGuestService = defineRpcService("audio-guest");
|
|
669
669
|
//#endregion
|
|
670
|
-
//#region \0mica-widget-audio-worklet-code
|
|
670
|
+
//#region \0mica-widget-audio-worklet-code:/home/runner/work/mica-js/mica-js/packages/widget/src/guest/audio/entry.ts
|
|
671
671
|
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)})();";
|
|
672
672
|
//#endregion
|
|
673
673
|
//#region src/host/audio/worklet.ts
|
|
@@ -908,6 +908,7 @@ var WidgetAudioEngine = class {
|
|
|
908
908
|
control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));
|
|
909
909
|
worklet.connect(this.#destination);
|
|
910
910
|
await this.#attachRuntime();
|
|
911
|
+
if (this.#suspended) await control.suspend();
|
|
911
912
|
this.#available = true;
|
|
912
913
|
return true;
|
|
913
914
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["workletScript","closePort","guestScript"],"sources":["../src/errors.ts","../src/package/load.ts","../src/package/static-provider.ts","../src/package/package-provider.ts","../src/host-fs/errors.ts","../src/host-fs/data-uri.ts","../src/host-fs/uri.ts","../src/guest/widget/props.ts","../src/guest/widget/protocol.ts","../src/guest/audio/protocol.ts","../src/host/audio/worklet.ts","../src/host/audio/engine.ts","../src/host/audio/noop.ts","../src/runtime/errors.ts","../src/runtime/runtime.ts","../src/host/sandbox.ts","../src/host/guest.ts"],"sourcesContent":["export type WidgetLoadErrorCode =\n | 'widget/package-not-found'\n | 'widget/invalid-manifest'\n | 'widget/invalid-definition'\n | 'widget/no-implementation'\n | 'widget/not-self-contained'\n | 'widget/load-failed'\n /** A descriptor field carries a value outside its closed set (RFC 0017 `delivery`). */\n | 'schema/invalid-value';\n\nexport interface WidgetLoadErrorOptions {\n /** Package id, when the package was already identified. */\n readonly packageId?: string;\n /** Package-relative path the failure refers to. */\n readonly path?: string;\n readonly cause?: unknown;\n}\n\n/** Thrown when a widget reference resolves to a package that cannot be turned into a module. */\nexport class WidgetLoadError extends Error {\n readonly code: WidgetLoadErrorCode;\n readonly packageId: string | undefined;\n readonly path: string | undefined;\n\n constructor(code: WidgetLoadErrorCode, message: string, options: WidgetLoadErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'WidgetLoadError';\n this.code = code;\n this.packageId = options.packageId;\n this.path = options.path;\n }\n}\n","import { parseDeliveryKind, parsePayloadType } from '@mica-js/document/canvas';\nimport { WidgetLoadError, type WidgetLoadErrorCode } from '../errors';\nimport type { PortDefinition, PropertyDefinition, WidgetDefinition, WidgetModule } from '../types';\n\n/** Read-only view of the files that make up one package. */\nexport interface PackageFiles {\n /** Human-readable label used in diagnostics. */\n readonly label: string;\n /** Reads a package-relative POSIX path and resolves to its bytes. */\n read(path: string): Promise<Uint8Array>;\n}\n\nexport interface WidgetPackage {\n readonly id: string;\n readonly version: string;\n /**\n * SHA-256 (hex) over the `[widget id, source]` pairs in widget-id order, so distinct package\n * contents never collide and reordering the manifest does not change the hash.\n */\n readonly contentHash: string;\n readonly modules: Readonly<Record<string, WidgetModule>>;\n}\n\nconst PACKAGE_JSON = 'package.json';\nconst JSON_EXTENSION = '.json';\nconst IMPLEMENTATION_EXTENSION = '.js';\n/** Package and widget ids are stable kebab-case identifiers (see #1). */\nconst ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;\n\ninterface WidgetEntry {\n readonly id: string;\n readonly path: string;\n readonly displayName: string | undefined;\n readonly description: string | undefined;\n}\n\ninterface PackageManifest {\n readonly id: string;\n readonly version: string;\n readonly widgets: readonly WidgetEntry[];\n}\n\n/**\n * Reads a package manifest, every declared widget definition and its paired implementation.\n * Only the three declared path kinds are read; the package is never enumerated.\n *\n * @throws {WidgetLoadError}\n */\nexport async function loadWidgetPackage(files: PackageFiles): Promise<WidgetPackage> {\n const manifest = await readManifest(files);\n const modules: Record<string, WidgetModule> = {};\n const sources: (readonly [string, string])[] = [];\n\n for (const entry of manifest.widgets) {\n const definition = await readDefinition(files, manifest.id, entry);\n const implementationPath = toImplementationPath(entry.path);\n const code = await readImplementation(files, manifest.id, entry.id, implementationPath);\n modules[entry.id] = { definition, code };\n sources.push([entry.id, code]);\n }\n\n // Ids travel with each source, so the digest separates adjacent widgets and empty files.\n const contentHash = await sha256Hex(JSON.stringify(sources), manifest.id);\n return { id: manifest.id, version: manifest.version, contentHash, modules };\n}\n\nasync function readManifest(files: PackageFiles): Promise<PackageManifest> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(PACKAGE_JSON);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/package-not-found',\n `Package ${JSON.stringify(files.label)} has no readable ${PACKAGE_JSON}.`,\n { path: PACKAGE_JSON, cause },\n );\n }\n\n const manifest = requireObject(\n parseJson(bytes, 'widget/invalid-manifest', PACKAGE_JSON, undefined, PACKAGE_JSON),\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must be a JSON object`,\n undefined,\n PACKAGE_JSON,\n );\n\n const id = manifest['name'];\n if (typeof id !== 'string' || !ID_PATTERN.test(id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must declare a kebab-case \"name\".`,\n { path: PACKAGE_JSON },\n );\n }\n\n const version = manifest['version'];\n if (typeof version !== 'string' || version.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} must declare a non-empty \"version\".`,\n { packageId: id, path: PACKAGE_JSON },\n );\n }\n\n const widgetsValue = manifest['widgets'];\n const widgets =\n widgetsValue === undefined\n ? {}\n : requireObject(\n widgetsValue,\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} \"widgets\" must be an object`,\n id,\n PACKAGE_JSON,\n );\n\n const entries = Object.keys(widgets)\n .sort()\n .map((widgetId) => readEntry(widgets[widgetId], widgetId, id));\n\n return { id, version, widgets: entries };\n}\n\nfunction readEntry(value: unknown, widgetId: string, packageId: string): WidgetEntry {\n if (!ID_PATTERN.test(widgetId)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(packageId)} declares widget id ${JSON.stringify(widgetId)}; ids must be kebab-case.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n\n const entry = requireObject(\n value,\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} entry must be an object`,\n packageId,\n PACKAGE_JSON,\n );\n\n const path = entry['path'];\n if (typeof path !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} must declare a string \"path\".`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n const problem = packagePathProblem(path);\n if (problem !== undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} ${problem}.`,\n { packageId, path },\n );\n }\n if (!path.endsWith(JSON_EXTENSION)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} must point at a ${JSON_EXTENSION} description.`,\n { packageId, path },\n );\n }\n\n return {\n id: widgetId,\n path,\n displayName: optionalString(entry, 'displayName', widgetId, packageId),\n description: optionalString(entry, 'description', widgetId, packageId),\n };\n}\n\nasync function readDefinition(\n files: PackageFiles,\n packageId: string,\n entry: WidgetEntry,\n): Promise<WidgetDefinition> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(entry.path);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(entry.id)} declares a missing definition at ${JSON.stringify(entry.path)}.`,\n { packageId, path: entry.path, cause },\n );\n }\n\n const record = requireObject(\n parseJson(bytes, 'widget/invalid-definition', entry.path, packageId, entry.path),\n 'widget/invalid-definition',\n `Widget definition ${JSON.stringify(entry.path)} must be a JSON object`,\n packageId,\n entry.path,\n );\n\n const properties = readProperties(record['properties'], packageId, entry.path);\n const ports = readPorts(record['ports'], packageId, entry.path);\n\n return {\n properties,\n ports,\n ...(entry.displayName === undefined ? {} : { displayName: entry.displayName }),\n ...(entry.description === undefined ? {} : { description: entry.description }),\n };\n}\n\nfunction readProperties(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PropertyDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"properties\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const properties: Record<string, PropertyDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n const type = descriptor['type'];\n if (typeof type !== 'string' || type.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a non-empty string \"type\".`,\n { packageId, path },\n );\n }\n properties[key] = { ...descriptor, type };\n }\n return properties;\n}\n\nfunction readPorts(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PortDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"ports\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const ports: Record<string, PortDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const direction = descriptor['direction'];\n if (direction !== 'input' && direction !== 'output') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"direction\" as \"input\" or \"output\".`,\n { packageId, path },\n );\n }\n\n const typeName = descriptor['type'];\n if (typeof typeName !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a string \"type\".`,\n { packageId, path },\n );\n }\n const type = parsePayloadType(typeName);\n if (type === undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} declares unknown payload type ${JSON.stringify(typeName)}.`,\n { packageId, path },\n );\n }\n\n const title = portText(descriptor, 'title', key, packageId, path);\n const description = portText(descriptor, 'description', key, packageId, path);\n // RFC 0017: `delivery` is optional and independent of `type`; an unparsable value is rejected\n // here instead of silently falling back to the payload type default.\n const declaredDelivery = descriptor['delivery'];\n const delivery =\n declaredDelivery === undefined ? undefined : parseDeliveryKind(declaredDelivery);\n if (declaredDelivery !== undefined && delivery === undefined) {\n throw new WidgetLoadError(\n 'schema/invalid-value',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"delivery\" as \"level\" or \"message\".`,\n { packageId, path },\n );\n }\n ports[key] = {\n direction,\n type,\n ...(delivery === undefined ? {} : { delivery }),\n ...(title === undefined ? {} : { title }),\n ...(description === undefined ? {} : { description }),\n };\n }\n return ports;\n}\n\nasync function readImplementation(\n files: PackageFiles,\n packageId: string,\n widgetId: string,\n path: string,\n): Promise<string> {\n try {\n return decode(await files.read(path));\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/no-implementation',\n `Widget ${JSON.stringify(widgetId)} in package ${JSON.stringify(packageId)} has no implementation at ${JSON.stringify(path)}.`,\n { packageId, path, cause },\n );\n }\n}\n\n/** Rejects absolute paths, drive letters, backslashes and escaping `..` segments. */\nfunction packagePathProblem(path: string): string | undefined {\n if (path.length === 0) {\n return 'must not be empty';\n }\n if (path.startsWith('/')) {\n return 'must be relative to the package root';\n }\n if (/^[A-Za-z]:/.test(path)) {\n return 'must not carry a drive letter';\n }\n if (path.includes('\\\\')) {\n return 'must use POSIX separators';\n }\n if (path.split('/').includes('..')) {\n return 'must stay inside the package';\n }\n return undefined;\n}\n\nfunction toImplementationPath(definitionPath: string): string {\n return definitionPath.slice(0, -JSON_EXTENSION.length) + IMPLEMENTATION_EXTENSION;\n}\n\n/** Reads an optional manifest field; failures always point at `package.json`, where the field lives. */\nfunction optionalString(\n record: Record<string, unknown>,\n key: 'displayName' | 'description',\n widgetId: string,\n packageId: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} \"${key}\" in ${PACKAGE_JSON} must be a string.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n return value;\n}\n\nfunction portText(\n record: Record<string, unknown>,\n key: 'title' | 'description',\n portId: string,\n packageId: string,\n path: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(portId)} \"${key}\" in ${JSON.stringify(path)} must be a string.`,\n { packageId, path },\n );\n }\n return value;\n}\n\nfunction parseJson(\n bytes: Uint8Array,\n code: WidgetLoadErrorCode,\n what: string,\n packageId: string | undefined,\n path: string,\n): unknown {\n try {\n return JSON.parse(decode(bytes)) as unknown;\n } catch (cause) {\n throw new WidgetLoadError(code, `${what} is not valid JSON.`, {\n path,\n cause,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n}\n\nfunction requireObject(\n value: unknown,\n code: WidgetLoadErrorCode,\n message: string,\n packageId: string | undefined,\n path: string,\n): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WidgetLoadError(code, `${message}.`, {\n path,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n return value as Record<string, unknown>;\n}\n\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Record for keys taken from untrusted definition JSON: no inherited setter can intercept an\n * assignment, so a declared entry can never become an object prototype.\n */\nfunction createRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\n/** `__proto__` is never a stable widget key, and on any object it would shadow the prototype. */\nfunction isUnsafeRecordKey(key: string): boolean {\n return key === '__proto__';\n}\n\nasync function sha256Hex(text: string, packageId: string): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (subtle === undefined) {\n throw new WidgetLoadError(\n 'widget/load-failed',\n 'Computing the widget package content hash requires Web Crypto (globalThis.crypto.subtle).',\n { packageId, path: PACKAGE_JSON },\n );\n }\n const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n","import type { WidgetModule, WidgetProvider } from '../types';\n\n/** Provider over a fixed module table, used for builtin widgets and tests. */\nexport function createStaticWidgetProvider(\n modules: Readonly<Record<string, WidgetModule>>,\n): WidgetProvider {\n const index = new Map(Object.entries(modules));\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n","import { WidgetLoadError } from '../errors';\nimport { loadWidgetPackage, type PackageFiles } from './load';\nimport type { WidgetModule, WidgetProvider } from '../types';\n\nexport interface PackageWidgetProviderOptions {\n readonly files: PackageFiles | readonly PackageFiles[];\n}\n\n/**\n * Loads every package up front and indexes its widgets under `<packageId>:<widgetId>`.\n * Resolution never touches the file system again, and unknown references return `undefined`.\n *\n * @throws {WidgetLoadError}\n */\nexport async function createPackageWidgetProvider(\n options: PackageWidgetProviderOptions,\n): Promise<WidgetProvider> {\n const filesList: readonly PackageFiles[] = Array.isArray(options.files)\n ? options.files\n : [options.files as PackageFiles];\n\n const index = new Map<string, WidgetModule>();\n const packageIds = new Set<string>();\n\n for (const files of filesList) {\n const widgetPackage = await loadWidgetPackage(withPathCache(files));\n if (packageIds.has(widgetPackage.id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package id ${JSON.stringify(widgetPackage.id)} is provided more than once.`,\n { packageId: widgetPackage.id, path: 'package.json' },\n );\n }\n packageIds.add(widgetPackage.id);\n for (const [widgetId, module] of Object.entries(widgetPackage.modules)) {\n index.set(`${widgetPackage.id}:${widgetId}`, module);\n }\n }\n\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n\n/** Reads each path at most once for the lifetime of the provider. */\nfunction withPathCache(files: PackageFiles): PackageFiles {\n const cache = new Map<string, Promise<Uint8Array>>();\n return {\n label: files.label,\n read(path) {\n const cached = cache.get(path);\n if (cached !== undefined) {\n return cached;\n }\n const pending = files.read(path);\n cache.set(path, pending);\n return pending;\n },\n };\n}\n","/** Failure classification of a `HostFs.read` rejection. */\nexport type HostFsErrorCode = 'FileNotFound' | 'NoPermissions' | 'NoFileSystem' | 'Unavailable';\n\n/**\n * Structured-clone payload for a `HostFsError` that crosses a thread boundary.\n *\n * The receiving side rebuilds the instance from `code`; `message` keeps the original wording when\n * it survives the transport and falls back to the default message for the code otherwise.\n */\nexport interface HostFsErrorPayload {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n readonly message?: string;\n}\n\nexport interface HostFsErrorOptions {\n readonly cause?: unknown;\n}\n\nconst DEFAULT_MESSAGES: Record<HostFsErrorCode, string> = {\n FileNotFound: 'Host resource not found',\n NoPermissions: 'Host resource access denied',\n NoFileSystem: 'No host file system handles the URI scheme',\n Unavailable: 'Host file system is unavailable',\n};\n\nconst ERROR_CODES: readonly HostFsErrorCode[] = [\n 'FileNotFound',\n 'NoPermissions',\n 'NoFileSystem',\n 'Unavailable',\n];\n\nfunction isHostFsErrorCode(value: unknown): value is HostFsErrorCode {\n return typeof value === 'string' && (ERROR_CODES as readonly string[]).includes(value);\n}\n\n/** Rejection of `HostFs.read`: `code` classifies the failure, `uri` names the resource. */\nexport class HostFsError extends Error {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n\n constructor(\n code: HostFsErrorCode,\n uri: string,\n message?: string,\n options: HostFsErrorOptions = {},\n ) {\n super(\n message ?? `${DEFAULT_MESSAGES[code]}: ${uri}`,\n options.cause === undefined ? undefined : { cause: options.cause },\n );\n this.name = 'HostFsError';\n this.code = code;\n this.uri = uri;\n }\n}\n\n/** Narrows an unknown rejection to a `HostFsError` created in this realm. */\nexport function isHostFsError(value: unknown): value is HostFsError {\n return value instanceof HostFsError;\n}\n\n/** Copies the fields a thread hop must carry; the instance itself does not survive a structured clone. */\nexport function toHostFsErrorPayload(error: HostFsError): HostFsErrorPayload {\n return { code: error.code, uri: error.uri, message: error.message };\n}\n\n/** Rebuilds a `HostFsError` from its payload, rejecting codes outside the contract. */\nexport function fromHostFsErrorPayload(payload: HostFsErrorPayload): HostFsError {\n const code: unknown = payload.code;\n if (!isHostFsErrorCode(code)) {\n throw new TypeError(`Unknown HostFsError code: ${String(code)}`);\n }\n return new HostFsError(code, payload.uri, payload.message);\n}\n","/**\n * Decodes a self-contained `data:` URI to its bytes.\n *\n * `data:` resources never reach `HostFs`: the bytes travel with the reference, so the host decodes\n * them locally. `;base64` payloads are decoded from base64; other payloads are percent-decoded,\n * while characters that need no escaping are encoded as UTF-8. The URI fragment is ignored.\n *\n * @throws TypeError when the URI has no payload separator or the payload is not decodable.\n */\nexport function decodeDataUri(uri: string): Uint8Array {\n const { base64, payload } = splitDataUri(uri);\n return base64 ? decodeBase64(payload) : decodePercentPayload(payload);\n}\n\n/**\n * Decodes a self-contained `data:` URI to its text payload.\n *\n * The decoded bytes are read as UTF-8, so a payload that carries binary or malformed UTF-8 is a\n * decode failure rather than replacement characters.\n *\n * @throws TypeError when the URI has no payload separator, the payload is not decodable, or the\n * bytes are not UTF-8.\n */\nexport function decodeDataUriText(uri: string): string {\n const bytes = decodeDataUri(uri);\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid UTF-8', { cause });\n }\n}\n\ninterface DataUriPayload {\n readonly base64: boolean;\n readonly payload: string;\n}\n\n/** Splits the URI into its `;base64` flag and payload. */\nfunction splitDataUri(uri: string): DataUriPayload {\n if (uri.slice(0, 5).toLowerCase() !== 'data:') {\n throw new TypeError('Not a data: URI');\n }\n const hash = uri.indexOf('#');\n const body = hash < 0 ? uri : uri.slice(0, hash);\n const comma = body.indexOf(',');\n if (comma < 0) {\n throw new TypeError('Data URI must separate its payload with a comma');\n }\n\n const metadata = body.slice('data:'.length, comma);\n return { base64: /;base64$/i.test(metadata), payload: body.slice(comma + 1) };\n}\n\nfunction decodeBase64(payload: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid base64', { cause });\n }\n\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\nfunction isHexDigit(value: string | undefined): value is string {\n return value !== undefined && /^[0-9A-Fa-f]$/.test(value);\n}\n\n/**\n * Percent-decodes a payload to bytes, so `%89PNG` keeps its binary value instead of being read as\n * (invalid) UTF-8. Literal characters are UTF-8 encoded.\n */\nfunction decodePercentPayload(payload: string): Uint8Array {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n let literal = 0;\n let index = 0;\n\n while (index < payload.length) {\n if (payload[index] !== '%') {\n index += 1;\n continue;\n }\n const high = payload[index + 1];\n const low = payload[index + 2];\n if (!isHexDigit(high) || !isHexDigit(low)) {\n throw new TypeError('Data URI payload is not valid percent-encoding');\n }\n if (index > literal) chunks.push(encoder.encode(payload.slice(literal, index)));\n chunks.push(new Uint8Array([Number.parseInt(`${high}${low}`, 16)]));\n index += 3;\n literal = index;\n }\n\n if (literal < payload.length) chunks.push(encoder.encode(payload.slice(literal)));\n\n let total = 0;\n for (const chunk of chunks) total += chunk.length;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","interface UriParts {\n readonly scheme: string | undefined;\n readonly authority: string | undefined;\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\ninterface PathReference {\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\nconst ABSOLUTE_URI = /^[A-Za-z][A-Za-z0-9+.-]*:/;\n\n/** Whether `uri` carries a scheme, i.e. is absolute rather than a relative reference. */\nexport function isAbsoluteHostUri(uri: string): boolean {\n return ABSOLUTE_URI.test(uri);\n}\n\n/** Splits a reference into path, query and fragment without interpreting leading slashes. */\nfunction splitPath(value: string): PathReference {\n const hash = value.indexOf('#');\n const fragment = hash < 0 ? undefined : value.slice(hash + 1);\n const beforeFragment = hash < 0 ? value : value.slice(0, hash);\n const question = beforeFragment.indexOf('?');\n const query = question < 0 ? undefined : beforeFragment.slice(question + 1);\n const path = question < 0 ? beforeFragment : beforeFragment.slice(0, question);\n return { path, query, fragment };\n}\n\nfunction parseUri(value: string): UriParts {\n const schemeMatch = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(value);\n const scheme = schemeMatch?.[1];\n let rest = schemeMatch === null ? value : value.slice(schemeMatch[0].length);\n\n let authority: string | undefined;\n if (rest.startsWith('//')) {\n const tail = rest.slice(2);\n const end = tail.search(/[/?#]/);\n authority = end < 0 ? tail : tail.slice(0, end);\n rest = end < 0 ? '' : tail.slice(end);\n }\n\n const { path, query, fragment } = splitPath(rest);\n return { scheme, authority, path, query, fragment };\n}\n\nfunction removeLastSegment(output: string): string {\n const slash = output.lastIndexOf('/');\n return slash < 0 ? '' : output.slice(0, slash);\n}\n\n/** RFC 3986 §5.2.4: drops `.` and `..` segments without touching empty segments. */\nfunction removeDotSegments(path: string): string {\n let input = path;\n let output = '';\n while (input.length > 0) {\n if (input.startsWith('../')) {\n input = input.slice(3);\n } else if (input.startsWith('./')) {\n input = input.slice(2);\n } else if (input.startsWith('/./')) {\n input = `/${input.slice(3)}`;\n } else if (input === '/.') {\n input = '/';\n } else if (input.startsWith('/../')) {\n input = `/${input.slice(4)}`;\n output = removeLastSegment(output);\n } else if (input === '/..') {\n input = '/';\n output = removeLastSegment(output);\n } else if (input === '.' || input === '..') {\n input = '';\n } else {\n const segment = /^\\/?[^/]*/.exec(input)?.[0] ?? input;\n output += segment;\n input = input.slice(segment.length);\n }\n }\n return output;\n}\n\n/** RFC 3986 §5.3: merges a relative path with the base path. */\nfunction mergePath(base: UriParts, referencePath: string): string {\n if (referencePath === '') return base.path;\n if (base.authority !== undefined && base.path === '') return `/${referencePath}`;\n const slash = base.path.lastIndexOf('/');\n return slash < 0 ? referencePath : `${base.path.slice(0, slash + 1)}${referencePath}`;\n}\n\nfunction compose(\n scheme: string,\n authority: string | undefined,\n path: string,\n query: string | undefined,\n fragment: string | undefined,\n): string {\n let uri = `${scheme}:`;\n if (authority !== undefined) uri += `//${authority}`;\n uri += path;\n if (query !== undefined) uri += `?${query}`;\n if (fragment !== undefined) uri += `#${fragment}`;\n return uri;\n}\n\n/**\n * Resolves a document reference against the absolute URI of the document that contains it.\n *\n * - a reference with a scheme is an absolute URI and is returned unchanged;\n * - a reference starting with `/` replaces the path and keeps the base scheme and authority;\n * - any other reference is merged with the base directory and normalized.\n *\n * The result always keeps the scheme and authority of `baseUri`, so a `//host/path` reference\n * stays inside the base authority instead of replacing it. Hosts pass a base URI whose path is\n * not empty; a base with an authority and an empty path resolves relative references under that\n * authority.\n *\n * @throws TypeError when `baseUri` is not an absolute URI.\n */\nexport function resolveHostUri(baseUri: string, reference: string): string {\n const base = parseUri(baseUri);\n if (base.scheme === undefined) {\n throw new TypeError(`Host URI base must be absolute: ${baseUri}`);\n }\n if (isAbsoluteHostUri(reference)) return reference;\n\n const target = splitPath(reference);\n const replacesPath = reference.startsWith('/');\n const path = replacesPath\n ? removeDotSegments(target.path)\n : removeDotSegments(mergePath(base, target.path));\n const keepBaseQuery = !replacesPath && target.path === '' && target.query === undefined;\n const query = keepBaseQuery ? base.query : target.query;\n return compose(base.scheme, base.authority, path, query, target.fragment);\n}\n","import type { PropertyDefinition } from '../../types';\nimport type { WidgetAssetRef } from './types';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\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/**\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: unknown): unknown {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => cloneFrozen(item)));\n }\n if (isPlainObject(value)) {\n const entries: [string, unknown][] = [];\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\nfunction isAssetMode(value: unknown): value is WidgetAssetRef['mode'] {\n return value === 'file' || value === 'inline' || value === 'store';\n}\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 */\nexport function mergeProperties(\n properties: Readonly<Record<string, PropertyDefinition>> | undefined,\n props: Readonly<Record<string, unknown>> | undefined,\n): Readonly<Record<string, unknown>> {\n const merged = new Map<string, unknown>();\n\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 ?? {})) {\n merged.set(key, props?.[key]);\n }\n\n return Object.freeze(Object.fromEntries(merged));\n}\n\n/**\n * Collects image / binary property values (`{ src, mode }`) from nested objects and arrays.\n * Results are keyed by `src`, so one resource referenced twice is only read once.\n */\nexport function collectAssetRefs(\n value: unknown,\n found: Map<string, WidgetAssetRef> = new Map(),\n seen: Set<object> = new Set(),\n): Map<string, WidgetAssetRef> {\n if (typeof value !== 'object' || value === null) return found;\n if (seen.has(value)) return found;\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) collectAssetRefs(item, found, seen);\n return found;\n }\n if (!isPlainObject(value)) return found;\n\n const candidate = value as { src?: unknown; mode?: unknown };\n if (typeof candidate.src === 'string' && isAssetMode(candidate.mode)) {\n if (!found.has(candidate.src)) {\n found.set(candidate.src, { src: candidate.src, mode: candidate.mode });\n }\n }\n for (const key of Object.keys(value)) collectAssetRefs(value[key], found, seen);\n return found;\n}\n","import { defineRpcService } from '@mica-js/core/rpc';\nimport type { TimePs } from '@mica-js/core';\nimport type { CanvasBindingTarget } from '@mica-js/document/canvas';\nimport type { WidgetDefinition } from '../../types';\nimport type { WidgetAudioMountInfo } from '../audio/protocol';\nimport type { WidgetInputEvent } from './types';\n\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 */\nexport const widgetFrameEvent = 'widget:frame';\nexport const widgetPublishEvent = 'widget:publish';\nexport const widgetErrorEvent = 'widget:error';\n/** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */\nexport const widgetAssetFailedEvent = 'widget:asset-failed';\n\n/** Guest methods the host reaches through `sandbox.call()`. */\nexport const widgetLoadMethod = 'load';\nexport const widgetMountMethod = 'mount';\nexport const widgetUnmountMethod = 'unmount';\nexport const widgetResizeMethod = 'resize';\nexport const widgetSetPropertiesMethod = 'set-properties';\n/** Replaces the prefetched bytes of one mounted instance without remounting it. */\nexport const widgetSetAssetsMethod = 'set-assets';\n/**\n * Replaces the device endpoints one instance writes to and reads from (RFC 0018).\n *\n * The guest routes topic traffic itself when it holds a direct device channel, so it needs the same\n * binding map the host validates against. A guest without that channel ignores the call.\n */\nexport const widgetSetBindingsMethod = 'set-bindings';\nexport const widgetDeliverMethod = 'deliver';\nexport const widgetPointerMethod = 'pointer';\n/**\n * Configures explicit stepping and connects the direct simulation-runtime port before mounting.\n * Without explicit stepping the standalone guest retains automatic repaint scheduling.\n */\nexport const widgetConfigureMethod = 'configure';\n/**\n * Advances the guest to a caller-supplied time.\n *\n * The editor owns the clock: it delivers the same step to widgets and devices, so the guest must\n * not schedule time-bound work on its own.\n */\nexport const widgetStepMethod = 'step';\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 */\nexport const widgetResetRuntimeMethod = 'reset-runtime';\n/** Instance boundary that produced a widget error. */\nexport type WidgetErrorPhase = 'mount' | 'render' | 'deliver';\n\n/** Widget errors cross the sandbox boundary as plain data. */\nexport interface SerializedWidgetError {\n readonly name: string;\n readonly message: string;\n}\n\n/** One rendered frame, always transferred so the host owns the bitmap. */\nexport interface WidgetFrameMessage {\n readonly instanceId: string;\n readonly bitmap: ImageBitmap;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n /**\n * Mount generation echoed from {@link WidgetMountRequest.generation}. The editor runtime\n * rejects a frame whose generation no longer owns the instance; standalone guests may omit it.\n */\n readonly generation?: number;\n}\n\n/** Payload a widget published on an output port. */\nexport interface WidgetPublishMessage {\n readonly instanceId: string;\n readonly port: string;\n readonly payload: unknown;\n /** Simulation time supplied by the widget; `0` when it did not pass one. */\n readonly simTime: number;\n /**\n * The guest already handed this publish to the device guest over its direct channel, so the host\n * must not forward it a second time. Absent when the guest has no channel or no binding.\n */\n readonly direct?: boolean;\n}\n\n/** Asset read that failed inside the guest; reported once per instance and `src`. */\nexport interface WidgetAssetFailedMessage {\n readonly instanceId: string;\n readonly src: string;\n readonly error: SerializedWidgetError;\n}\n\n/** Failure contained to one instance; the guest keeps every other instance running. */\nexport interface WidgetErrorMessage {\n readonly instanceId: string;\n readonly phase: WidgetErrorPhase;\n readonly error: SerializedWidgetError;\n}\n\nexport interface WidgetLoadModule {\n readonly definition: WidgetDefinition;\n readonly code: string;\n}\n\nexport interface WidgetLoadPackage {\n readonly id: string;\n readonly modules: Readonly<Record<string, WidgetLoadModule>>;\n}\n\nexport interface WidgetLoadRequest {\n readonly packages: readonly WidgetLoadPackage[];\n}\n\nexport interface WidgetMountRequest {\n readonly instanceId: string;\n readonly widget: string;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n readonly props?: Readonly<Record<string, unknown>>;\n /** Bytes the host prefetched for this instance, keyed by `WidgetAssetRef.src`. */\n readonly assets?: Readonly<Record<string, Uint8Array>>;\n /**\n * Audio availability at mount time. Read synchronously by the factory through\n * `api.audio.state`; `session` is the one-shot token the worklet accepts for this generation.\n */\n readonly audio?: WidgetAudioMountInfo;\n /**\n * Mount generation assigned by the editor runtime. Frames echo it, so a frame produced by a\n * replaced instance can never be adopted by its successor.\n */\n readonly generation?: number;\n}\n\n/** Service the guest reaches over the transferred direct port. */\nexport type WidgetDirectTopicService = 'simulation-runtime';\n\n/** One-time guest configuration applied before the first mount. */\nexport interface IWidgetGuestRuntimeConfig {\n /**\n * Removes the guest's automatic repaint scheduling: an `invalidate()` only marks the instance\n * dirty, and the next {@link IWidgetGuestStep} paints it.\n */\n readonly explicitStepping?: boolean;\n /** Contract behind the direct port; defaults to `simulation-runtime` at first use. */\n readonly directTopicService?: WidgetDirectTopicService;\n}\n\n/** Caller-supplied time of one widget step. */\nexport interface IWidgetGuestStep {\n /** Simulation time after the step, in picoseconds. */\n readonly simTime: TimePs;\n /** Length of the step, in picoseconds. */\n readonly dt: TimePs;\n /** Editor mode; widgets keep running in both, the caller decides what advances. */\n readonly mode: 'edit' | 'simulation';\n}\n\n/** Every guest method the host reaches through `sandbox.call()`, in one RPC service. */\nexport interface WidgetGuestService {\n [widgetLoadMethod](request: WidgetLoadRequest): Promise<void>;\n /** Rejects when the factory or the first paint fails, so a candidate instance is not adopted. */\n [widgetMountMethod](request: WidgetMountRequest): Promise<void>;\n [widgetUnmountMethod](instanceId: string): void;\n [widgetResizeMethod](instanceId: string, width: number, height: number, dpr: number): void;\n [widgetSetPropertiesMethod](instanceId: string, props: Readonly<Record<string, unknown>>): void;\n [widgetSetAssetsMethod](instanceId: string, assets: Readonly<Record<string, Uint8Array>>): void;\n [widgetSetBindingsMethod](\n instanceId: string,\n bindings: Readonly<Record<string, CanvasBindingTarget>>,\n ): void;\n [widgetDeliverMethod](instanceId: string, port: string, payload: unknown, simTime: number): void;\n [widgetPointerMethod](instanceId: string, event: WidgetInputEvent): void;\n [widgetConfigureMethod](config: IWidgetGuestRuntimeConfig): boolean;\n /**\n * Resolves after queued direct input and deferred repaints are applied, and after every direct\n * widget → simulation delivery started by this step has settled.\n */\n [widgetStepMethod](step: IWidgetGuestStep): Promise<void>;\n [widgetResetRuntimeMethod](): void;\n}\n\n/** Host → guest control lane: events pushed into the runtime and forced teardown. */\nexport interface WidgetGuestControlService {\n dispatchEvent(type: string, payload: unknown): void;\n terminate(): void;\n}\n\n/** Guest → host control lane: the event bus plus capability reads. */\nexport interface WidgetHostControlService {\n event(type: string, payload: unknown, transfer?: readonly Transferable[]): void;\n}\n\n/** Host file system reads the guest may perform; bytes travel as a transferred buffer. */\nexport interface WidgetHostCapabilitiesService {\n read(uri: string): Promise<Uint8Array>;\n}\n\n/**\n * Wire names shared by the worker script and the host adapter. Both sides must agree on the exact\n * strings, so they are defined once and registered with `register` / `getProxy`.\n */\nexport const widgetGuestService = defineRpcService<WidgetGuestService>('guest');\nexport const widgetGuestControlService =\n defineRpcService<WidgetGuestControlService>('guest-control');\nexport const widgetHostControlService = defineRpcService<WidgetHostControlService>('host-control');\nexport const widgetHostCapabilitiesService =\n defineRpcService<WidgetHostCapabilitiesService>('host-capabilities');\n\n/** The one member of {@link widgetHostControlService} that carries a transfer list. */\nexport const widgetHostEventMethod = 'event';\n\n/** One publish the editor simulation runtime sends over the direct port. */\nexport interface IWidgetSimulationPublish {\n readonly target: CanvasBindingTarget;\n readonly payload: unknown;\n /** Simulation time the publish belongs to, in picoseconds. */\n readonly simTime: TimePs;\n}\n\n/**\n * The slice of the editor simulation runtime the guest reaches over the direct port.\n *\n * The editor registers this service on the device worker (or an in-process simulation) under the\n * `simulation-runtime` id and transfers the other end of the port to this guest. The contract is\n * declared locally on purpose: the widget package must not depend on the simulator implementation\n * to state the wire shape. `deliver` takes the same `{ target, payload, simTime }` message that\n * `onDidPublish` reports.\n */\nexport interface IWidgetSimulationRuntimeChannel {\n /** Queues one message for a device endpoint; consumed by the simulation's next step. */\n deliver(message: IWidgetSimulationPublish): Promise<void>;\n /** Subscribes to simulation publishes; the guest fans them out to its bound instances. */\n onDidPublish(listener: (publish: IWidgetSimulationPublish) => void): () => void;\n}\n\n/** Wire name of {@link IWidgetSimulationRuntimeChannel}. */\nexport const widgetSimulationRuntimeService =\n defineRpcService<IWidgetSimulationRuntimeChannel>('simulation-runtime');\n","/**\n * Typed RPC contracts of the widget audio path (RFC 0016).\n *\n * Three endpoints carry the whole path:\n *\n * - the guest runtime talks to the `AudioWorklet` over a `MessagePort` it receives from the host;\n * - the host talks to the same worklet over the `AudioWorkletNode` port;\n * - the host pushes availability and the direct port into the guest over the sandbox RPC endpoint.\n *\n * `createRpc` serializes every call, so PCM stays on the worker ↔ worklet port and never passes\n * through the render host.\n */\n\nimport { defineRpcService } from '@mica-js/core/rpc';\n\n/** Name the worklet registers its processor under. */\nexport const widgetAudioWorkletProcessor = 'mica-widget-audio';\n\n/** Per-instance ceiling on simultaneous tones. */\nexport const defaultMaxVoices = 8;\n/** Per-instance ceiling on open PCM streams. */\nexport const defaultMaxStreams = 4;\n\n/** Availability of the host audio path. */\nexport type WidgetAudioState = 'unavailable' | 'suspended' | 'running';\n\n/** Why a tone or stream stopped. */\nexport type WidgetAudioEndReason =\n 'finished' | 'stopped' | 'dropped' | 'error' | 'unavailable' | 'disposed';\n\n/** Sample layout of a PCM stream. */\nexport type WidgetAudioFormat = 's16' | 'f32';\n\n/** Waveforms the worklet synthesizes for `api.audio.tone()`. */\nexport type WidgetOscillatorType = 'sine' | 'square' | 'triangle' | 'sawtooth';\n\n/** Playback state of a PCM stream, as the guest sees it. */\nexport type WidgetAudioStreamState = 'buffering' | 'playing' | 'ended' | 'closed';\n\n/** Per-instance ceilings; a host may tighten them through its options. */\nexport interface WidgetAudioLimits {\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\n/** One mount generation of one instance, opened by the host before the guest can use it. */\nexport interface WidgetAudioSessionOpen {\n /** One-shot token every guest call must carry. */\n readonly session: string;\n /** Guest runtime that owns the token; a port from another runtime is rejected. */\n readonly runtimeId: string;\n readonly instanceId: string;\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\nexport interface WidgetAudioToneInit {\n /** Guest-assigned id; unique per session. */\n readonly voiceId: string;\n readonly type: WidgetOscillatorType;\n /** Hz, `(0, 24000]`. */\n readonly frequency: number;\n /** `0`–`1`. */\n readonly volume: number;\n}\n\nexport interface WidgetAudioToneSettings {\n readonly volume?: number;\n readonly frequency?: number;\n /** Smoothing window in milliseconds, `0`–`10000`. */\n readonly rampMs: number;\n}\n\nexport interface WidgetAudioStop {\n /** Fade-out in milliseconds, `0`–`10000`. */\n readonly fadeMs: number;\n}\n\nexport interface WidgetAudioStreamInit {\n /** Guest-assigned id; unique per session. */\n readonly streamId: string;\n /** Source rate in Hz, `8000`–`96000`. */\n readonly sampleRate: number;\n readonly channels: 1 | 2;\n readonly format: WidgetAudioFormat;\n readonly capacityFrames: number;\n readonly startFrames: number;\n readonly volume: number;\n}\n\n/** Answer of `createStream`: the worklet re-checks the per-session quota. */\nexport interface WidgetAudioStreamOpened {\n readonly accepted: boolean;\n}\n\n/** Credit report; `consumedFrames` is cumulative over the stream's lifetime. */\nexport interface WidgetAudioProgress {\n readonly streamId: string;\n readonly consumedFrames: number;\n readonly underruns: number;\n readonly state: WidgetAudioStreamState;\n}\n\n/** Terminal event of one tone or stream. */\nexport interface WidgetAudioEndedMessage {\n readonly target: 'tone' | 'stream';\n readonly id: string;\n readonly reason: WidgetAudioEndReason;\n}\n\n/** Diagnostic codes the audio path reports. */\nexport type WidgetAudioDiagnosticCode = 'widget/audio-failed' | 'widget/audio-limit';\n\n/** Quota or validation class the receiving side dedupes against. */\nexport type WidgetAudioDiagnosticCategory = 'voices' | 'streams' | 'capacity' | 'worklet';\n\nexport interface WidgetAudioDiagnostic {\n /** Session the diagnostic belongs to; the host maps it back to the instance. */\n readonly session: string;\n readonly code: WidgetAudioDiagnosticCode;\n readonly category: WidgetAudioDiagnosticCategory;\n readonly message: string;\n}\n\n/**\n * Guest → worklet.\n *\n * Every member names a session; the worklet checks that the session belongs to the runtime that\n * owns the calling port, so a guest cannot steer another instance.\n */\nexport interface WidgetAudioWorkletService {\n createTone(session: string, init: WidgetAudioToneInit): void;\n setTone(session: string, voiceId: string, settings: WidgetAudioToneSettings): void;\n stopTone(session: string, voiceId: string, options: WidgetAudioStop): void;\n createStream(session: string, init: WidgetAudioStreamInit): WidgetAudioStreamOpened;\n /** `samples` travels as a transferred buffer; `true` means the whole block was accepted. */\n writeStream(session: string, streamId: string, samples: Int16Array | Float32Array): boolean;\n /** Drops everything that has not played yet and keeps the stream open. */\n clearStream(session: string, streamId: string): void;\n /** Drains the buffer, then ends the stream with `finished`. */\n endStream(session: string, streamId: string): void;\n /** Discards the buffer and closes the stream immediately. */\n closeStream(session: string, streamId: string): void;\n onDidProgress(listener: (progress: WidgetAudioProgress) => void): () => void;\n onDidEnded(listener: (ended: WidgetAudioEndedMessage) => void): () => void;\n}\n\nexport const widgetAudioWorkletService =\n defineRpcService<WidgetAudioWorkletService>('audio-worklet');\n\n/** Host → worklet, over the `AudioWorkletNode` port. */\nexport interface WidgetAudioControlService {\n openSession(init: WidgetAudioSessionOpen): void;\n closeSession(session: string): void;\n setSessionVolume(session: string, volume: number): void;\n setMuted(muted: boolean): void;\n suspend(): void;\n resume(): void;\n /** `port` is the guest end of the direct PCM channel; it is always transferred. */\n attachGuestPort(runtimeId: string, port: MessagePort): void;\n detachGuestPort(runtimeId: string): void;\n onDidDiagnostic(listener: (diagnostic: WidgetAudioDiagnostic) => void): () => void;\n}\n\nexport const widgetAudioControlService =\n defineRpcService<WidgetAudioControlService>('audio-control');\n\n/** Host → guest: audio availability and the direct PCM port handoff. */\nexport interface WidgetAudioGuestService {\n attachPort(port: MessagePort): void;\n setState(state: WidgetAudioState): void;\n}\n\nexport const widgetAudioGuestService = defineRpcService<WidgetAudioGuestService>('audio-guest');\n\n/** Attached to `mount` so the factory can read `api.audio.state` synchronously. */\nexport interface WidgetAudioMountInfo {\n readonly state: WidgetAudioState;\n /** One-shot token this mount generation uses on the direct port. */\n readonly session?: string;\n}\n","import workletScript from '../../guest/audio/entry.ts?audio-worklet-code';\nimport { widgetAudioWorkletProcessor } from '../../guest/audio/protocol';\n\nlet objectUrl: string | undefined;\n\n/**\n * Blob URL of the packaged `AudioWorkletProcessor` script.\n *\n * The script is bundled and minified into this module while the package is built, so an\n * `AudioContext` can load it through `addModule()` without the package publishing a separate\n * `*.worklet.js` asset. The URL is created once per page and reused by every host.\n */\nexport function widgetAudioWorkletUrl(): string {\n objectUrl ??= URL.createObjectURL(new Blob([workletScript], { type: 'text/javascript' }));\n return objectUrl;\n}\n\n/**\n * Loads the packaged processor into `context` and creates its node.\n *\n * Pass it as `WidgetAudioOptions.getAudioWorklet`; runtimes that provide no loader of their\n * own use the same processor internally.\n */\nexport async function createWidgetAudioWorklet(context: AudioContext): Promise<AudioWorkletNode> {\n if (typeof context.audioWorklet?.addModule !== 'function') {\n throw new Error('The AudioContext does not support AudioWorklet.addModule().');\n }\n await context.audioWorklet.addModule(widgetAudioWorkletUrl());\n return new AudioWorkletNode(context, widgetAudioWorkletProcessor);\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport {\n defaultMaxStreams,\n defaultMaxVoices,\n widgetAudioControlService,\n widgetAudioWorkletProcessor,\n} from '../../guest/audio/protocol';\nimport type {\n WidgetAudioControlService,\n WidgetAudioDiagnostic,\n WidgetAudioDiagnosticCode,\n WidgetAudioLimits,\n WidgetAudioMountInfo,\n WidgetAudioState,\n} from '../../guest/audio/protocol';\nimport { widgetAudioWorkletUrl } from './worklet';\n\n/** Structural stand-ins for the Web Audio nodes the engine touches; tests inject fakes. */\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): unknown;\n disconnect?(): void;\n}\n\nexport interface AudioContextLike {\n readonly sampleRate: number;\n /** `suspended` | `running` | `closed` for a real context. */\n readonly state: string;\n readonly destination: AudioNodeLike;\n readonly audioWorklet?: { addModule(url: string): Promise<void> };\n /**\n * Fired by a real context whenever the browser suspends or resumes it on its own (autoplay\n * policy, hidden page, a caller calling `suspend()` / `resume()`). Used as a fallback when the\n * context lacks `addEventListener`; fakes may leave it `null`.\n */\n onstatechange?: ((event?: unknown) => void) | null;\n /** Preferred over `onstatechange`: subscribing must not clobber the caller's own handler. */\n addEventListener?(type: 'statechange', listener: () => void): void;\n removeEventListener?(type: 'statechange', listener: () => void): void;\n}\n\nexport interface AudioWorkletNodeLike extends AudioNodeLike {\n readonly port: MessagePort;\n}\n\nexport interface MessageChannelLike {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\n/** Host-side sinks the engine reports into; the widget host owns the sandbox plumbing. */\nexport interface WidgetAudioNotifier {\n /** Hands the direct guest ↔ worklet port to the sandbox. */\n emitPort(port: MessagePort): void;\n emitState(state: WidgetAudioState): void;\n}\n\nexport interface WidgetAudioEngineOptions {\n readonly context: AudioContextLike;\n readonly destination?: AudioNodeLike;\n readonly limits?: Partial<WidgetAudioLimits>;\n readonly report: (code: WidgetAudioDiagnosticCode, instanceId: string, message: string) => void;\n readonly notify: WidgetAudioNotifier;\n /** Loads the audio worklet node; tests or applications may provide their own loader. */\n readonly loadWorklet?: () => Promise<AudioWorkletNodeLike>;\n readonly createChannel?: () => MessageChannelLike;\n readonly createWorkletNode?: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n}\n\ninterface InstanceAudio {\n readonly instanceId: string;\n readonly session: string;\n}\n\n/**\n * Host half of the audio path (RFC 0016).\n *\n * Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the\n * worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.\n * No audio node other than that worklet is created here: tones, mixing and volume all live inside\n * the worklet.\n */\nexport class WidgetAudioEngine {\n readonly #context: AudioContextLike;\n readonly #destination: AudioNodeLike;\n readonly #report: WidgetAudioEngineOptions['report'];\n readonly #notify: WidgetAudioNotifier;\n readonly #limits: WidgetAudioLimits;\n readonly #loadWorklet: (() => Promise<AudioWorkletNodeLike>) | undefined;\n readonly #createChannel: () => MessageChannelLike;\n readonly #createWorkletNode: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n readonly #runtimeId = `r${Math.random().toString(36).slice(2, 10)}`;\n readonly #instances = new Map<string, InstanceAudio>();\n #worklet: AudioWorkletNodeLike | undefined;\n #endpoint: RpcEndpoint | undefined;\n #control: RpcProxy<WidgetAudioControlService> | undefined;\n #booting: Promise<boolean> | undefined;\n #available: boolean | undefined;\n #muted = false;\n #suspended = false;\n #sessionCounter = 0;\n #disposed = false;\n #lastState: WidgetAudioState | undefined;\n #detachStateListener: (() => void) | undefined;\n /** Context state moved without an engine call; guests get the same ordered notification. */\n readonly #onContextStateChange = (): void => {\n if (this.#disposed) return;\n this.#syncState();\n };\n\n constructor(options: WidgetAudioEngineOptions) {\n this.#context = options.context;\n this.#destination = options.destination ?? options.context.destination;\n this.#report = options.report;\n this.#notify = options.notify;\n this.#limits = {\n maxVoices: Math.max(1, Math.floor(options.limits?.maxVoices ?? defaultMaxVoices)),\n maxStreams: Math.max(1, Math.floor(options.limits?.maxStreams ?? defaultMaxStreams)),\n };\n this.#loadWorklet = options.loadWorklet;\n this.#createChannel =\n options.createChannel ??\n (() => {\n const channel = new MessageChannel();\n return { port1: channel.port1, port2: channel.port2 };\n });\n this.#createWorkletNode =\n options.createWorkletNode ??\n ((context, name) => {\n const ctor = (\n globalThis as {\n AudioWorkletNode?: new (\n context: unknown,\n name: string,\n options: unknown,\n ) => AudioWorkletNodeLike;\n }\n ).AudioWorkletNode;\n if (!ctor) throw new Error('AudioWorkletNode is not available');\n return new ctor(context, name, {\n numberOfInputs: 0,\n numberOfOutputs: 1,\n outputChannelCount: [2],\n });\n });\n }\n\n /**\n * Current availability.\n *\n * `unavailable` means \"no audio at all\": the host configured none, the browser lacks\n * `AudioWorklet`, or the worklet module failed to load.\n */\n get state(): WidgetAudioState {\n if (this.#disposed || this.#available === false) return 'unavailable';\n if (this.#available !== true || this.#suspended) return 'suspended';\n return this.#context.state === 'running' ? 'running' : 'suspended';\n }\n\n /** Limits in force, so a caller can mirror them in its own UI. */\n get limits(): WidgetAudioLimits {\n return this.#limits;\n }\n\n /**\n * Opens the mount generation of one instance.\n *\n * Resolves once the worklet registered the session token, so the `mount` request that carries it\n * can never arrive after the first guest call of that generation.\n */\n async open(instanceId: string): Promise<WidgetAudioMountInfo> {\n if (this.#disposed) return { state: 'unavailable' };\n const available = await this.#boot();\n if (!available) return { state: 'unavailable' };\n\n this.close(instanceId);\n this.#sessionCounter += 1;\n const session = `${this.#runtimeId}-${this.#sessionCounter}`;\n this.#instances.set(instanceId, { instanceId, session });\n try {\n await this.#control?.openSession({\n session,\n runtimeId: this.#runtimeId,\n instanceId,\n maxVoices: this.#limits.maxVoices,\n maxStreams: this.#limits.maxStreams,\n });\n } catch (error) {\n this.#report(\n 'widget/audio-failed',\n instanceId,\n `The audio worklet rejected the session: ${describe(error)}`,\n );\n }\n this.#syncState();\n return { state: this.state, session };\n }\n\n setMuted(muted: boolean): void {\n this.#muted = muted === true;\n this.#call((control) => control.setMuted(this.#muted));\n }\n\n setInstanceVolume(instanceId: string, volume: number): void {\n if (typeof volume !== 'number') {\n throw new TypeError('WidgetAudioControls.setInstanceVolume expects a number');\n }\n if (!Number.isFinite(volume) || volume < 0 || volume > 1) {\n throw new RangeError('WidgetAudioControls.setInstanceVolume expects a value in [0, 1]');\n }\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#call((control) => control.setSessionVolume(instance.session, volume));\n }\n\n /** Freezes audio without touching the caller's `AudioContext`. */\n suspend(): void {\n if (this.#disposed || this.#suspended) return;\n this.#suspended = true;\n this.#call((control) => control.suspend());\n this.#syncState();\n }\n\n resume(): void {\n if (this.#disposed) return;\n this.#suspended = false;\n this.#call((control) => control.resume());\n this.#syncState();\n }\n\n /**\n * Closes the instance only when it still belongs to `session`.\n *\n * A mount attempt that lost its id may have opened its own audio generation after the host's\n * cleanup sweep; closing by id alone would tear down the replacement instead.\n */\n closeSession(instanceId: string, session: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance || instance.session !== session) return;\n this.close(instanceId);\n }\n\n /** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */\n close(instanceId: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#instances.delete(instanceId);\n this.#call((control) => control.closeSession(instance.session));\n }\n\n /**\n * Drops every instance and hands the worklet a fresh guest channel.\n *\n * Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs\n * a port of its own.\n */\n reset(): void {\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n if (this.#available === true && this.#control !== undefined) {\n void this.#restartRuntime();\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n // Sent before the flag flips: the worklet drops the runtime, its sessions and its guest port.\n this.#call((control) => control.detachGuestPort(this.#runtimeId));\n this.#disposed = true;\n this.#detachStateListener?.();\n this.#detachStateListener = undefined;\n this.#endpoint?.dispose();\n this.#endpoint = undefined;\n this.#control = undefined;\n const worklet = this.#worklet;\n this.#worklet = undefined;\n if (worklet !== undefined) {\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n }\n }\n\n /** Boots the worklet once; a failure is permanent for the lifetime of the engine. */\n #boot(): Promise<boolean> {\n this.#booting ??= this.#start().catch((error: unknown) => {\n this.#available = false;\n // A load that fails after `dispose()` is not a widget problem and has no live host to hear it.\n if (!this.#disposed) {\n this.#report('widget/audio-failed', '', `Widget audio is unavailable: ${describe(error)}`);\n }\n return false;\n });\n return this.#booting;\n }\n\n async #start(): Promise<boolean> {\n if (\n this.#loadWorklet === undefined &&\n typeof this.#context.audioWorklet?.addModule !== 'function'\n ) {\n this.#available = false;\n return false;\n }\n\n this.#listenForContextState();\n const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());\n if (this.#disposed) {\n // `dispose()` ran while the module was loading: release the node instead of wiring it up.\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n return false;\n }\n this.#worklet = worklet;\n const endpoint = createRpc(worklet.port);\n this.#endpoint = endpoint;\n const control = endpoint.getProxy(widgetAudioControlService, {\n transfer: (member, args) => (member === 'attachGuestPort' ? [args[1] as MessagePort] : []),\n });\n this.#control = control;\n control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));\n worklet.connect(this.#destination);\n await this.#attachRuntime();\n this.#available = true;\n return true;\n }\n\n /**\n * Mirrors the context's own `statechange` onto mounted guests.\n *\n * The caller owns the `AudioContext`, so its state can move without the engine asking: autoplay\n * policy keeping it suspended, the browser suspending a hidden page, or the caller calling\n * `resume()`. Guests read `api.audio.state` and `onStateChange`, so those moves must be forwarded.\n */\n #listenForContextState(): void {\n if (this.#detachStateListener) return;\n const context = this.#context;\n if (typeof context.addEventListener === 'function') {\n context.addEventListener('statechange', this.#onContextStateChange);\n this.#detachStateListener = () =>\n context.removeEventListener?.('statechange', this.#onContextStateChange);\n return;\n }\n if (!('onstatechange' in context)) return;\n // Contexts that only expose the handler property keep the caller's value for `dispose()`.\n const previous = context.onstatechange;\n context.onstatechange = this.#onContextStateChange;\n this.#detachStateListener = () => {\n if (context.onstatechange === this.#onContextStateChange) context.onstatechange = previous;\n };\n }\n\n /** Worklet → host diagnostics, attributed back to the instance that owns the session. */\n #onDiagnostic(diagnostic: WidgetAudioDiagnostic): void {\n const owner = [...this.#instances.values()].find(\n (entry) => entry.session === diagnostic.session,\n );\n // A revoked token means the message is late; the RFC drops it instead of raising diagnostics.\n if (!owner) return;\n this.#report(diagnostic.code, owner.instanceId, diagnostic.message);\n }\n\n async #loadDefaultWorklet(): Promise<AudioWorkletNodeLike> {\n await this.#context.audioWorklet?.addModule(widgetAudioWorkletUrl());\n return this.#createWorkletNode(this.#context, widgetAudioWorkletProcessor);\n }\n\n async #restartRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined) return;\n try {\n await control.detachGuestPort(this.#runtimeId);\n } catch {\n // The worklet already forgot the runtime; a new channel follows anyway.\n }\n await this.#attachRuntime();\n }\n\n /** Transfers a fresh port to the worklet and hands the other end to the guest. */\n async #attachRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n const channel = this.#createChannel();\n try {\n await control.attachGuestPort(this.#runtimeId, channel.port1);\n } catch (error) {\n closePort(channel.port1);\n closePort(channel.port2);\n this.#report(\n 'widget/audio-failed',\n '',\n `The audio worklet rejected the guest port: ${describe(error)}`,\n );\n return;\n }\n this.#notify.emitPort(channel.port2);\n }\n\n /** Fires one host → worklet call; a missing or closed worklet is not a widget failure. */\n #call(run: (control: RpcProxy<WidgetAudioControlService>) => Promise<unknown>): void {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n try {\n void run(control).catch(() => undefined);\n } catch {\n // The endpoint is already closed.\n }\n }\n\n #syncState(): void {\n const next = this.state;\n if (next === this.#lastState) return;\n this.#lastState = next;\n this.#notify.emitState(next);\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describe(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n","import type { WidgetAudioState } from '../../guest/audio/protocol';\nimport type { WidgetAudioControls } from './types';\n\n/**\n * Controls of a host that was created without `audio`.\n *\n * The state is `unavailable` and every setter is a no-op, so callers never have to branch on\n * whether audio is configured.\n */\nexport const NO_AUDIO_CONTROLS: WidgetAudioControls = {\n state: 'unavailable' as WidgetAudioState,\n setMuted(): void {},\n setInstanceVolume(): void {},\n suspend(): void {},\n resume(): void {},\n};\n","/** Rejections the widget runtime produces before or around the guest boundary. */\nexport type WidgetRuntimeErrorCode =\n | 'widget/disposed'\n | 'widget/instance-exists'\n | 'widget/unknown-instance'\n | 'widget/unknown-port'\n | 'widget/invalid-instance'\n | 'widget/invalid-update'\n | 'widget/invalid-payload'\n | 'widget/invalid-direction'\n | 'widget/invalid-time'\n | 'widget/invalid-step'\n | 'widget/sandbox-failed';\n\n/**\n * Typed rejection of one runtime call.\n *\n * Widget boundary failures (render, input, publish) become diagnostics instead; errors with this\n * type mean the caller asked for something the runtime cannot do.\n */\nexport class WidgetRuntimeError extends Error {\n readonly code: WidgetRuntimeErrorCode;\n\n constructor(code: WidgetRuntimeErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WidgetRuntimeError';\n this.code = code;\n }\n}\n","import { timePs } from '@mica-js/core';\nimport type { TimePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { CanvasBindingTarget, PayloadType } from '@mica-js/document/canvas';\nimport type { WidgetAudioMountInfo } from '../guest/audio/protocol';\nimport { mergeProperties } from '../guest/widget/props';\nimport {\n widgetAssetFailedEvent,\n widgetConfigureMethod,\n widgetDeliverMethod,\n widgetErrorEvent,\n widgetFrameEvent,\n widgetLoadMethod,\n widgetMountMethod,\n widgetPointerMethod,\n widgetPublishEvent,\n widgetResizeMethod,\n widgetSetAssetsMethod,\n widgetSetBindingsMethod,\n widgetSetPropertiesMethod,\n widgetStepMethod,\n widgetUnmountMethod,\n} from '../guest/widget/protocol';\nimport type {\n WidgetAssetFailedMessage,\n WidgetErrorMessage,\n WidgetFrameMessage,\n WidgetPublishMessage,\n} from '../guest/widget/protocol';\nimport type { WidgetInputEvent } from '../guest/widget/types';\nimport { WidgetAudioEngine } from '../host/audio/engine';\nimport type {\n AudioContextLike,\n AudioNodeLike,\n AudioWorkletNodeLike,\n WidgetAudioEngineOptions,\n} from '../host/audio/engine';\nimport { NO_AUDIO_CONTROLS } from '../host/audio/noop';\nimport type { WidgetAudioControls, WidgetAudioOptions } from '../host/audio/types';\nimport type { WidgetSandbox } from '../host/types';\nimport type { WidgetModule } from '../types';\nimport { WidgetRuntimeError } from './errors';\nimport type {\n IPreparedWidgetInstance,\n IWidgetFrame,\n IWidgetFrameContext,\n IWidgetInstanceUpdate,\n IWidgetMessage,\n IWidgetRuntime,\n IWidgetRuntimeDiagnostic,\n IWidgetRuntimeDiagnosticCode,\n IWidgetRuntimeDiagnosticPhase,\n IWidgetRuntimeOptions,\n} from './types';\n\ninterface IRuntimeInstance {\n readonly instanceId: string;\n readonly widget: string;\n readonly module: WidgetModule;\n readonly generation: number;\n width: number;\n height: number;\n dpr: number;\n bitmap: ImageBitmap | undefined;\n sequence: number;\n mounted: boolean;\n audioSession: string | undefined;\n}\n\n/** One deliver or pointer call accepted by `deliver` / `dispatch`, waiting for the next step. */\ninterface IPendingCall {\n readonly instanceId: string;\n readonly method: string;\n readonly args: readonly unknown[];\n}\n\n/**\n * Creates the widget runtime over an existing sandbox.\n *\n * The runtime owns the sandbox: `dispose()` terminates it, so the caller must not keep using it\n * afterwards. The runtime never reads documents or files, resolves widget modules, drives a clock\n * or talks to a device runtime; those stay with the editor that calls it.\n */\nexport function createWidgetRuntime(\n sandbox: WidgetSandbox,\n options: IWidgetRuntimeOptions = {},\n): IWidgetRuntime {\n return new WidgetRuntimeImpl(sandbox, options);\n}\n\nclass WidgetRuntimeImpl implements IWidgetRuntime {\n readonly #sandbox: WidgetSandbox;\n readonly #engine: WidgetAudioEngine | undefined;\n readonly #instances = new Map<string, IRuntimeInstance>();\n readonly #pending: IPendingCall[] = [];\n readonly #published = new Emitter<IWidgetMessage>();\n readonly #rendered = new Emitter<IWidgetFrame>();\n readonly #diagnostics = new Emitter<IWidgetRuntimeDiagnostic>();\n readonly #unsubscribers: (() => void)[] = [];\n\n readonly onDidPublish: Event<IWidgetMessage> = this.#published.event;\n readonly onDidRender: Event<IWidgetFrame> = this.#rendered.event;\n readonly onDidDiagnostic: Event<IWidgetRuntimeDiagnostic> = this.#diagnostics.event;\n readonly audio: WidgetAudioControls;\n\n /** Serializes mount, update, unmount, setBindings and step; a failure never poisons the chain. */\n #tail: Promise<void> = Promise.resolve();\n #configured: Promise<boolean> | undefined;\n #simTime: TimePs = timePs(0);\n #generation = 0;\n #disposed = false;\n #disposal: Promise<void> | undefined;\n\n constructor(sandbox: WidgetSandbox, options: IWidgetRuntimeOptions) {\n this.#sandbox = sandbox;\n\n const audioOptions: WidgetAudioOptions | undefined = options.audio;\n if (audioOptions === undefined) {\n this.audio = NO_AUDIO_CONTROLS;\n } else {\n const context = audioOptions.context;\n const getAudioWorklet = audioOptions.getAudioWorklet;\n const engineOptions: WidgetAudioEngineOptions = {\n context: context as unknown as AudioContextLike,\n ...(audioOptions.destination === undefined\n ? {}\n : { destination: audioOptions.destination as unknown as AudioNodeLike }),\n ...(getAudioWorklet === undefined\n ? {}\n : {\n loadWorklet: () => getAudioWorklet(context) as Promise<AudioWorkletNodeLike>,\n }),\n ...(audioOptions.limits === undefined ? {} : { limits: audioOptions.limits }),\n report: (code, instanceId, message) =>\n this.#report(code, 'audio', message, instanceId === '' ? {} : { instanceId }),\n notify: {\n emitPort: (port) => {\n const lane = sandbox.audio;\n if (lane === undefined) {\n closePort(port);\n return;\n }\n try {\n lane.attachPort(port);\n } catch {\n closePort(port);\n }\n },\n emitState: (state) => {\n try {\n sandbox.audio?.setState(state);\n } catch {\n // The sandbox is already gone; its guest state no longer matters.\n }\n },\n },\n };\n const engine = new WidgetAudioEngine(engineOptions);\n this.#engine = engine;\n this.audio = engine;\n }\n\n this.#unsubscribers.push(\n sandbox.on(widgetFrameEvent, (payload) => this.#onFrame(payload)),\n sandbox.on(widgetPublishEvent, (payload) => this.#onPublish(payload)),\n sandbox.on(widgetErrorEvent, (payload) => this.#onError(payload)),\n sandbox.on(widgetAssetFailedEvent, (payload) => this.#onAssetFailed(payload)),\n );\n }\n\n mount(instance: IPreparedWidgetInstance): Promise<void> {\n return this.#run(async () => {\n const prepared = normalizePrepared(instance);\n this.#assertActive();\n if (this.#instances.has(prepared.instanceId)) {\n throw new WidgetRuntimeError(\n 'widget/instance-exists',\n `Widget instance \"${prepared.instanceId}\" is already mounted.`,\n );\n }\n const ref = splitRef(prepared.widget);\n if (ref === undefined) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `Widget reference \"${prepared.widget}\" must use the \"<package>:<widget>\" form.`,\n );\n }\n\n await this.#configure();\n this.#assertActive();\n\n const record: IRuntimeInstance = {\n instanceId: prepared.instanceId,\n widget: prepared.widget,\n module: prepared.module,\n generation: ++this.#generation,\n width: prepared.width,\n height: prepared.height,\n dpr: prepared.dpr,\n bitmap: undefined,\n sequence: 0,\n mounted: false,\n audioSession: undefined,\n };\n this.#instances.set(record.instanceId, record);\n\n try {\n await this.#sandbox.call(widgetLoadMethod, {\n packages: [\n {\n id: ref.packageId,\n modules: {\n [ref.widgetId]: {\n definition: prepared.module.definition,\n code: prepared.module.code,\n },\n },\n },\n ],\n });\n this.#assertOwnership(record);\n\n const audio = await this.#openAudio(record);\n this.#assertOwnership(record);\n\n const properties = mergeProperties(\n prepared.module.definition.properties,\n prepared.properties,\n );\n await this.#sandbox.call(widgetMountMethod, {\n instanceId: record.instanceId,\n widget: record.widget,\n width: record.width,\n height: record.height,\n dpr: record.dpr,\n props: properties,\n ...(prepared.assets === undefined ? {} : { assets: prepared.assets }),\n generation: record.generation,\n audio,\n });\n this.#assertOwnership(record);\n record.mounted = true;\n } catch (error) {\n this.#forget(record);\n await this.#releaseGuest(record.instanceId);\n if (record.audioSession !== undefined) {\n this.#engine?.closeSession(record.instanceId, record.audioSession);\n }\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Mount of widget instance \"${prepared.instanceId}\" was cancelled before it finished.`,\n );\n }\n if (this.#sandbox.state === 'terminated') {\n this.#report(\n 'widget/runtime-failed',\n 'runtime',\n 'The widget sandbox terminated during mount.',\n );\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n 'The widget sandbox terminated during mount.',\n { cause: error },\n );\n }\n this.#report(\n 'widget/mount-failed',\n 'mount',\n `Widget \"${prepared.widget}\" failed to mount: ${describeError(error)}`,\n { instanceId: prepared.instanceId, widget: prepared.widget },\n );\n throw error instanceof WidgetRuntimeError\n ? error\n : new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget \"${prepared.widget}\" failed to mount: ${describeError(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n update(instanceId: string, update: IWidgetInstanceUpdate): Promise<void> {\n return this.#run(async () => {\n requireId(instanceId);\n this.#assertActive();\n const record = this.#requireMounted(instanceId);\n\n if (update.width !== undefined || update.height !== undefined || update.dpr !== undefined) {\n const width =\n update.width === undefined ? record.width : requireSize(update.width, 'width');\n const height =\n update.height === undefined ? record.height : requireSize(update.height, 'height');\n const dpr = update.dpr === undefined ? record.dpr : requireDpr(update.dpr);\n await this.#call(\n widgetResizeMethod,\n [instanceId, width, height, dpr],\n record,\n 'widget/update-failed',\n 'update',\n );\n record.width = width;\n record.height = height;\n record.dpr = dpr;\n }\n\n if (update.properties !== undefined) {\n const properties = mergeProperties(record.module.definition.properties, update.properties);\n await this.#call(\n widgetSetPropertiesMethod,\n [instanceId, properties],\n record,\n 'widget/update-failed',\n 'update',\n );\n }\n\n if (update.assets !== undefined) {\n await this.#call(\n widgetSetAssetsMethod,\n [instanceId, update.assets],\n record,\n 'widget/update-failed',\n 'update',\n );\n }\n });\n }\n\n unmount(instanceId: string): Promise<void> {\n return this.#run(async () => {\n requireId(instanceId);\n // Disposal already cleared every instance and terminated the sandbox.\n if (this.#disposed) return;\n const record = this.#instances.get(instanceId);\n if (record === undefined) return;\n\n this.#instances.delete(instanceId);\n this.#closeRecord(record);\n for (let index = this.#pending.length - 1; index >= 0; index -= 1) {\n if (this.#pending[index]?.instanceId === instanceId) this.#pending.splice(index, 1);\n }\n if (record.audioSession !== undefined) {\n this.#engine?.closeSession(instanceId, record.audioSession);\n }\n try {\n await this.#sandbox.call(widgetUnmountMethod, instanceId);\n } catch (error) {\n this.#report(\n 'widget/unmount-failed',\n 'unmount',\n `Widget instance \"${instanceId}\" could not be released: ${describeError(error)}`,\n { instanceId, widget: record.widget },\n );\n }\n });\n }\n\n deliver(message: IWidgetMessage): Promise<void> {\n try {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n const record = this.#requireMounted(message.instanceId);\n const port = record.module.definition.ports[message.port];\n if (port === undefined) {\n throw new WidgetRuntimeError(\n 'widget/unknown-port',\n `Widget instance \"${message.instanceId}\" has no port ${JSON.stringify(message.port)}.`,\n );\n }\n if (port.direction !== 'input') {\n throw new WidgetRuntimeError(\n 'widget/invalid-direction',\n `Port \"${message.port}\" of \"${message.instanceId}\" is an output.`,\n );\n }\n if (!payloadMatches(port.type, message.payload)) {\n throw new WidgetRuntimeError(\n 'widget/invalid-payload',\n `Payload for \"${message.instanceId}.${message.port}\" does not match ${port.type}.`,\n );\n }\n const simTime = requireTime(message.simTime, 'simTime');\n this.#pending.push({\n instanceId: message.instanceId,\n method: widgetDeliverMethod,\n args: [message.instanceId, message.port, message.payload, simTime],\n });\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n dispatch(instanceId: string, event: WidgetInputEvent): Promise<void> {\n try {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n this.#requireMounted(instanceId);\n if (\n typeof event !== 'object' ||\n event === null ||\n typeof event.type !== 'string' ||\n event.type === ''\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-payload',\n 'A widget input event needs a nonempty type.',\n );\n }\n this.#pending.push({\n instanceId,\n method: widgetPointerMethod,\n args: [instanceId, event],\n });\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n step(context: IWidgetFrameContext): Promise<void> {\n return this.#run(async () => {\n this.#assertActive();\n const simTime = requireTime(context.simTime, 'simTime');\n const dt = requireTime(context.dt, 'dt');\n if (context.mode !== 'edit' && context.mode !== 'simulation') {\n throw new WidgetRuntimeError(\n 'widget/invalid-step',\n `Unknown widget step mode: ${String(context.mode)}.`,\n );\n }\n\n await this.#configure();\n this.#assertActive();\n\n for (const call of this.#pending.splice(0)) {\n const record = this.#instances.get(call.instanceId);\n if (record === undefined || !record.mounted) {\n this.#report(\n 'widget/deliver-failed',\n 'deliver',\n `Queued ${call.method} for \"${call.instanceId}\" was dropped: the instance is not mounted.`,\n { instanceId: call.instanceId },\n );\n continue;\n }\n try {\n await this.#sandbox.call(call.method, ...call.args);\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n 'Widget step was cancelled by runtime disposal.',\n );\n }\n this.#report(\n 'widget/deliver-failed',\n 'deliver',\n `Widget call \"${call.method}\" failed for \"${call.instanceId}\": ${describeError(error)}`,\n { instanceId: call.instanceId, widget: record.widget },\n );\n }\n }\n\n this.#simTime = simTime;\n try {\n await this.#sandbox.call(widgetStepMethod, { simTime, dt, mode: context.mode });\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n 'Widget step was cancelled by runtime disposal.',\n );\n }\n this.#report('widget/step-failed', 'step', `Widget step failed: ${describeError(error)}`);\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget step failed: ${describeError(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n setBindings(\n instanceId: string,\n bindings: Readonly<Record<string, CanvasBindingTarget>>,\n ): Promise<void> {\n return this.#run(async () => {\n const normalized = normalizeBindings(bindings);\n requireId(instanceId);\n this.#assertActive();\n const record = this.#requireMounted(instanceId);\n await this.#call(\n widgetSetBindingsMethod,\n [instanceId, normalized],\n record,\n 'widget/update-failed',\n 'update',\n );\n });\n }\n\n dispose(): Promise<void> {\n if (this.#disposal !== undefined) return this.#disposal;\n this.#disposed = true;\n this.#pending.length = 0;\n // Terminating now is what cancels a mount that is still waiting for the guest: its pending\n // calls reject, the operation cleans up its own record, and the queued shutdown then runs.\n const terminating = terminateSandbox(this.#sandbox);\n this.#disposal = this.#run(async () => {\n const records = [...this.#instances.values()];\n this.#instances.clear();\n for (const record of records) this.#closeRecord(record);\n for (const unsubscribe of this.#unsubscribers.splice(0)) {\n try {\n unsubscribe();\n } catch {\n // The sandbox may already be gone.\n }\n }\n this.#engine?.dispose();\n await terminating;\n this.#published.dispose();\n this.#rendered.dispose();\n this.#diagnostics.dispose();\n });\n return this.#disposal;\n }\n\n /** Runs one operation after the previous one, whether it resolved or rejected. */\n #run<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.#tail.then(operation, operation);\n this.#tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n #assertActive(): void {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n if (this.#sandbox.state === 'terminated') {\n throw new WidgetRuntimeError('widget/sandbox-failed', 'The widget sandbox is terminated.');\n }\n }\n\n #assertOwnership(record: IRuntimeInstance): void {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Mount of widget instance \"${record.instanceId}\" was cancelled before it finished.`,\n );\n }\n if (this.#instances.get(record.instanceId) !== record) {\n throw new WidgetRuntimeError(\n 'widget/unknown-instance',\n `Widget instance \"${record.instanceId}\" was replaced during mount.`,\n );\n }\n }\n\n #requireMounted(instanceId: string): IRuntimeInstance {\n const record = this.#instances.get(instanceId);\n if (record === undefined || !record.mounted) {\n throw new WidgetRuntimeError(\n 'widget/unknown-instance',\n `Widget instance \"${instanceId}\" is not mounted.`,\n );\n }\n return record;\n }\n\n #configure(): Promise<boolean> {\n const existing = this.#configured;\n if (existing !== undefined) return existing;\n\n const pending = this.#sandbox\n .call(widgetConfigureMethod, {\n explicitStepping: true,\n directTopicService: 'simulation-runtime',\n })\n .then((result) => result === true)\n .catch((error: unknown) => {\n this.#configured = undefined;\n const message = `Widget guest configuration failed: ${describeError(error)}`;\n this.#report('widget/runtime-failed', 'runtime', message);\n throw new WidgetRuntimeError('widget/sandbox-failed', message, { cause: error });\n });\n this.#configured = pending;\n return pending;\n }\n\n async #openAudio(record: IRuntimeInstance): Promise<WidgetAudioMountInfo> {\n const engine = this.#engine;\n if (engine === undefined) return { state: 'unavailable' };\n const info = await engine.open(record.instanceId);\n if (info.session !== undefined) record.audioSession = info.session;\n return info;\n }\n\n async #call(\n method: string,\n args: readonly unknown[],\n record: IRuntimeInstance,\n code: IWidgetRuntimeDiagnosticCode,\n phase: IWidgetRuntimeDiagnosticPhase,\n ): Promise<void> {\n try {\n await this.#sandbox.call(method, ...args);\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Widget call \"${method}\" was cancelled by runtime disposal.`,\n );\n }\n this.#report(\n code,\n phase,\n `Widget call \"${method}\" failed for \"${record.instanceId}\": ${describeError(error)}`,\n { instanceId: record.instanceId, widget: record.widget },\n );\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget call \"${method}\" failed for \"${record.instanceId}\": ${describeError(error)}`,\n { cause: error },\n );\n }\n }\n\n #forget(record: IRuntimeInstance): void {\n if (this.#instances.get(record.instanceId) === record) {\n this.#instances.delete(record.instanceId);\n }\n this.#closeRecord(record);\n }\n\n #closeRecord(record: IRuntimeInstance): void {\n const bitmap = record.bitmap;\n record.bitmap = undefined;\n closeBitmap(bitmap);\n }\n\n async #releaseGuest(instanceId: string): Promise<void> {\n try {\n await this.#sandbox.call(widgetUnmountMethod, instanceId);\n } catch {\n // The guest never created the instance, or the sandbox is already gone.\n }\n }\n\n #onFrame(payload: unknown): void {\n const message = payload as Partial<WidgetFrameMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n const { instanceId, bitmap } = message;\n if (typeof instanceId !== 'string' || !isBitmap(bitmap)) return;\n if (this.#disposed) {\n closeBitmap(bitmap);\n return;\n }\n\n const record = this.#instances.get(instanceId);\n if (\n record === undefined ||\n (message.generation !== undefined && message.generation !== record.generation)\n ) {\n // A frame of an unmounted instance, or of the instance that used to own this id.\n closeBitmap(bitmap);\n return;\n }\n\n const width = frameNumber(message.width, record.width);\n const height = frameNumber(message.height, record.height);\n const dpr = frameNumber(message.dpr, record.dpr);\n const previous = record.bitmap;\n record.bitmap = bitmap;\n record.width = width;\n record.height = height;\n record.dpr = dpr;\n record.sequence += 1;\n closeBitmap(previous);\n\n this.#fire(this.#rendered, 'render', {\n instanceId,\n width,\n height,\n dpr,\n bitmap,\n sequence: record.sequence,\n });\n }\n\n #onPublish(payload: unknown): void {\n const message = payload as Partial<WidgetPublishMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n const { instanceId, port } = message;\n if (typeof instanceId !== 'string' || typeof port !== 'string') return;\n if (this.#disposed) return;\n\n const record = this.#instances.get(instanceId);\n if (record === undefined) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Publish from unknown widget instance \"${instanceId}\" was dropped.`,\n { instanceId, port },\n );\n return;\n }\n const definitionPort = record.module.definition.ports[port];\n if (definitionPort === undefined) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Widget \"${instanceId}\" published on unknown port \"${port}\".`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n if (definitionPort.direction !== 'output') {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Widget \"${instanceId}\" published on input port \"${port}\".`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n if (!payloadMatches(definitionPort.type, message.payload)) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Publish on \"${instanceId}.${port}\" does not match ${definitionPort.type}.`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n\n this.#fire(this.#published, 'publish', {\n instanceId,\n port,\n payload: message.payload,\n simTime: publishTime(message.simTime, this.#simTime),\n ...(message.direct === true ? { direct: true as const } : {}),\n });\n }\n\n #onError(payload: unknown): void {\n const message = payload as Partial<WidgetErrorMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n // A mount failure travels back through the rejected `mount()` call instead.\n if (message.phase !== 'render' && message.phase !== 'deliver') return;\n\n const record = this.#instances.get(message.instanceId);\n const code: IWidgetRuntimeDiagnosticCode =\n message.phase === 'render' ? 'widget/render-failed' : 'widget/deliver-failed';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown widget failure';\n this.#report(\n code,\n message.phase,\n `Widget \"${message.instanceId}\" failed during ${message.phase}: ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n ...(record === undefined ? {} : { widget: record.widget }),\n },\n );\n }\n\n #onAssetFailed(payload: unknown): void {\n const message = payload as Partial<WidgetAssetFailedMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n\n const src = typeof message.src === 'string' ? message.src : 'unknown';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown asset failure';\n const record = this.#instances.get(message.instanceId);\n this.#report(\n 'widget/asset-failed',\n 'asset',\n `Widget \"${message.instanceId}\" could not read asset \"${src}\": ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n ...(record === undefined ? {} : { widget: record.widget }),\n },\n );\n }\n\n #report(\n code: IWidgetRuntimeDiagnosticCode,\n phase: IWidgetRuntimeDiagnosticPhase,\n message: string,\n ids: {\n readonly instanceId?: string;\n readonly widget?: string;\n readonly port?: string;\n } = {},\n ): void {\n if (this.#disposed) return;\n const diagnostic: IWidgetRuntimeDiagnostic = {\n code,\n message,\n phase,\n ...(ids.instanceId === undefined ? {} : { instanceId: ids.instanceId }),\n ...(ids.widget === undefined ? {} : { widget: ids.widget }),\n ...(ids.port === undefined ? {} : { port: ids.port }),\n };\n this.#fire(this.#diagnostics, 'diagnostic', diagnostic);\n }\n\n /** Observer exceptions never break the instance flow a diagnostic or frame reports. */\n #fire<T>(emitter: Emitter<T>, label: string, value: T): void {\n try {\n emitter.fire(value);\n } catch (error) {\n console.error(`[@mica-js/widget] ${label} listener threw`, error);\n }\n }\n}\n\nfunction normalizePrepared(instance: IPreparedWidgetInstance): IPreparedWidgetInstance {\n if (typeof instance !== 'object' || instance === null) {\n throw new WidgetRuntimeError('widget/invalid-instance', 'A prepared widget is required.');\n }\n requireId(instance.instanceId);\n if (typeof instance.widget !== 'string' || !instance.widget.includes(':')) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n 'A prepared widget needs a \"<package>:<widget>\" reference.',\n );\n }\n const module = instance.module;\n if (\n typeof module !== 'object' ||\n module === null ||\n typeof module.code !== 'string' ||\n typeof module.definition !== 'object' ||\n module.definition === null ||\n typeof module.definition.ports !== 'object' ||\n module.definition.ports === null\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `Widget \"${instance.widget}\" has no complete module.`,\n );\n }\n return {\n instanceId: instance.instanceId,\n widget: instance.widget,\n module,\n width: requireSize(instance.width, 'width'),\n height: requireSize(instance.height, 'height'),\n dpr: requireDpr(instance.dpr),\n ...(instance.properties === undefined ? {} : { properties: instance.properties }),\n ...(instance.assets === undefined ? {} : { assets: instance.assets }),\n };\n}\n\nfunction requireId(value: unknown): string {\n if (typeof value !== 'string' || value === '') {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n 'A widget instance id must be a nonempty string.',\n );\n }\n return value;\n}\n\nfunction requireSize(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `${name}=${String(value)} must be a finite nonnegative number.`,\n );\n }\n return value;\n}\n\nfunction requireDpr(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `dpr=${String(value)} must be a finite positive number.`,\n );\n }\n return value;\n}\n\nfunction requireTime(value: unknown, name: string): TimePs {\n try {\n return timePs(value as number);\n } catch (error) {\n throw new WidgetRuntimeError(\n 'widget/invalid-time',\n `${name} must be a valid time in picoseconds: ${describeError(error)}`,\n { cause: error },\n );\n }\n}\n\nfunction publishTime(value: unknown, fallback: TimePs): TimePs {\n if (typeof value !== 'number') return fallback;\n try {\n return timePs(value);\n } catch {\n return fallback;\n }\n}\n\nfunction frameNumber(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;\n}\n\nfunction normalizeBindings(\n value: Readonly<Record<string, CanvasBindingTarget>>,\n): Readonly<Record<string, CanvasBindingTarget>> {\n if (typeof value !== 'object' || value === null) {\n throw new WidgetRuntimeError('widget/invalid-update', 'Bindings must be an object.');\n }\n const bindings: Record<string, CanvasBindingTarget> = {};\n for (const [port, target] of Object.entries(value)) {\n if (\n typeof target !== 'object' ||\n target === null ||\n typeof target.symbol !== 'string' ||\n target.symbol === '' ||\n typeof target.port !== 'string' ||\n target.port === ''\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-update',\n `Binding \"${port}\" needs a nonempty symbol and port.`,\n );\n }\n bindings[port] = { symbol: target.symbol, port: target.port };\n }\n return Object.freeze(bindings);\n}\n\nfunction splitRef(ref: string): { packageId: string; widgetId: string } | undefined {\n const separator = ref.indexOf(':');\n if (separator <= 0 || separator === ref.length - 1) return undefined;\n return { packageId: ref.slice(0, separator), widgetId: ref.slice(separator + 1) };\n}\n\nfunction isBitmap(value: unknown): value is ImageBitmap {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ImageBitmap).close === 'function'\n );\n}\n\nfunction isVec2d(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const point = value as { readonly x?: unknown; readonly y?: unknown };\n return typeof point.x === 'number' && typeof point.y === 'number';\n}\n\n/** Mirrors the shared value model: a payload must match the declared port type exactly. */\nfunction payloadMatches(type: PayloadType, payload: unknown): boolean {\n switch (type) {\n case 'boolean':\n return typeof payload === 'boolean';\n case 'number':\n return typeof payload === 'number';\n case 'string':\n return typeof payload === 'string';\n case 'bytes':\n case 'bytes<rgb565>':\n case 'bytes<segments>':\n return payload instanceof Uint8Array;\n case 'vec2d':\n return isVec2d(payload);\n case 'vec3d':\n return isVec2d(payload) && typeof (payload as { readonly z?: unknown }).z === 'number';\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap | undefined): void {\n if (bitmap === undefined) return;\n try {\n bitmap.close();\n } catch {\n // Already detached.\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describeError(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n\nasync function terminateSandbox(sandbox: WidgetSandbox): Promise<void> {\n try {\n await sandbox.terminate('widget runtime disposed');\n } catch {\n // Already terminated.\n }\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport { isHostFsError, toHostFsErrorPayload } from '../host-fs/errors';\nimport { widgetAudioGuestService } from '../guest/audio/protocol';\nimport {\n widgetGuestControlService,\n widgetGuestService,\n widgetHostCapabilitiesService,\n widgetHostControlService,\n} from '../guest/widget/protocol';\nimport type { SandboxWorker } from '@mica-js/sandbox';\nimport type { WidgetSandbox, WidgetSandboxHostOptions } from './types';\n\n/** Adapts a provider-created widget worker to the runtime's RPC-facing surface. */\nexport async function createWidgetSandboxFromWorker(\n worker: SandboxWorker,\n options: WidgetSandboxHostOptions,\n): Promise<WidgetSandbox> {\n const devicePort = options.devicePort;\n let port: MessagePort;\n let rpc: ReturnType<typeof createRpc> | undefined;\n let logRegistration: { dispose(): void } | undefined;\n try {\n await worker.ready;\n const channel = new MessageChannel();\n port = channel.port1;\n const endpoint = createRpc(port);\n rpc = endpoint;\n logRegistration = endpoint.register(loggerService, {\n write(record) {\n const method = console[record.level] ?? console.log;\n method.call(console, `[${record.scope}]`, record.message, ...record.data);\n },\n });\n const transfer = devicePort === undefined ? [channel.port2] : [channel.port2, devicePort];\n worker.postMessage(null, transfer);\n } catch (error) {\n logRegistration?.dispose();\n rpc?.dispose();\n await worker.terminate('widget sandbox failed to start').catch(() => undefined);\n throw error;\n }\n const endpoint = rpc;\n if (endpoint === undefined) {\n throw new Error('Widget RPC endpoint was not created.');\n }\n const listeners = new Map<string, Set<(payload: unknown) => void>>();\n const dispatch = (type: string, payload: unknown) => {\n for (const listener of [...(listeners.get(type) ?? [])]) listener(payload);\n };\n endpoint.register(\n widgetHostCapabilitiesService,\n {\n async read(uri: string) {\n if (!options.fs) throw new Error(`No HostFs configured for ${uri}`);\n try {\n return await options.fs.read(uri);\n } catch (error) {\n if (isHostFsError(error)) {\n const payload = toHostFsErrorPayload(error);\n throw Object.assign(new Error(JSON.stringify(payload)), { name: 'HostFsError' });\n }\n throw error;\n }\n },\n },\n {\n transfer: (member, value) =>\n member === 'read' && value instanceof Uint8Array ? [value.buffer] : [],\n },\n );\n endpoint.register(widgetHostControlService, { event: dispatch });\n const guest = endpoint.getProxy(widgetGuestService) as unknown as Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n >;\n const audio = endpoint.getProxy(widgetAudioGuestService, {\n transfer: (member, args) => (member === 'attachPort' ? [args[0] as MessagePort] : []),\n });\n return {\n get state() {\n return worker.state;\n },\n directDevice: devicePort !== undefined,\n call: (method, ...args) => guest[method]!(...args),\n on: (type, listener) => {\n let set = listeners.get(type);\n if (!set) listeners.set(type, (set = new Set()));\n set.add(listener);\n return () => set?.delete(listener);\n },\n emit: (type, payload, transfer) => {\n void endpoint\n .getProxy(widgetGuestControlService, { transfer: () => transfer ?? [] })\n .dispatchEvent(type, payload)\n .catch(() => undefined);\n },\n audio: {\n attachPort: (port) => {\n void audio.attachPort(port).catch(() => undefined);\n },\n setState: (state) => {\n void audio.setState(state).catch(() => undefined);\n },\n },\n terminate: async (reason) => {\n logRegistration?.dispose();\n endpoint.dispose();\n await worker.terminate(reason);\n },\n } satisfies WidgetSandbox;\n}\n","import { SandboxWorker } from '@mica-js/sandbox';\nimport type { SandboxWorkerOptions } from '@mica-js/sandbox';\nimport guestScript from '../guest/widget/entry.ts?sandbox-worker-code';\n\n/**\n * The widget guest worker script, bundled and minified into this module by\n * `@mica-js/sandbox/vite` while the package itself is built.\n *\n * It is a classic script: every dependency is inlined, so the sandbox can run it without a module\n * loader and the package publishes no separate `*.sandbox.js` file.\n */\nexport const widgetGuestScript: string = guestScript;\n\n/**\n * Creates the widget host guest worker.\n *\n * Hosts start the guest, then wire its RPC surface with `createWidgetSandboxFromWorker`.\n */\nexport function createWidgetHostGuestSandbox(options: SandboxWorkerOptions = {}): SandboxWorker {\n return new SandboxWorker(widgetGuestScript, { name: 'widget', ...options });\n}\n"],"mappings":";;;;;;;;AAmBA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CACA;CAEA,YAAY,MAA2B,SAAiB,UAAkC,CAAC,GAAG;EAC5F,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,OAAO;EACZ,KAAK,OAAO;EAC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IAAI,IAAI;GAC5B,IAAI,CAAC,KAAK,UAAU,IAAI,MAAO,sBAAM,IAAI,IAAI,CAAE;GAC/C,IAAI,IAAI,QAAQ;GAChB,aAAa,KAAK,OAAO,QAAQ;EACnC;EACA,OAAO,MAAM,SAAS,aAAa;GACjC,SACG,SAAS,2BAA2B,EAAE,gBAAgB,YAAY,CAAC,EAAE,CAAC,CAAC,CACvE,cAAc,MAAM,OAAO,CAAC,CAC5B,YAAY,KAAA,CAAS;EAC1B;EACA,OAAO;GACL,aAAa,SAAS;IACpB,MAAW,WAAW,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;GACnD;GACA,WAAW,UAAU;IACnB,MAAW,SAAS,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS;GAClD;EACF;EACA,WAAW,OAAO,WAAW;GAC3B,iBAAiB,QAAQ;GACzB,SAAS,QAAQ;GACjB,MAAM,OAAO,UAAU,MAAM;EAC/B;CACF;AACF;;;;;;;;;;ACpGA,IAAa,oBAA4BC;;;;;;AAOzC,SAAgB,6BAA6B,UAAgC,CAAC,GAAkB;CAC9F,OAAO,IAAI,cAAc,mBAAmB;EAAE,MAAM;EAAU,GAAG;CAAQ,CAAC;AAC5E"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["workletScript","closePort","guestScript"],"sources":["../src/errors.ts","../src/package/load.ts","../src/package/static-provider.ts","../src/package/package-provider.ts","../src/host-fs/errors.ts","../src/host-fs/data-uri.ts","../src/host-fs/uri.ts","../src/guest/widget/props.ts","../src/guest/widget/protocol.ts","../src/guest/audio/protocol.ts","../src/host/audio/worklet.ts","../src/host/audio/engine.ts","../src/host/audio/noop.ts","../src/runtime/errors.ts","../src/runtime/runtime.ts","../src/host/sandbox.ts","../src/host/guest.ts"],"sourcesContent":["export type WidgetLoadErrorCode =\n | 'widget/package-not-found'\n | 'widget/invalid-manifest'\n | 'widget/invalid-definition'\n | 'widget/no-implementation'\n | 'widget/not-self-contained'\n | 'widget/load-failed'\n /** A descriptor field carries a value outside its closed set (RFC 0017 `delivery`). */\n | 'schema/invalid-value';\n\nexport interface WidgetLoadErrorOptions {\n /** Package id, when the package was already identified. */\n readonly packageId?: string;\n /** Package-relative path the failure refers to. */\n readonly path?: string;\n readonly cause?: unknown;\n}\n\n/** Thrown when a widget reference resolves to a package that cannot be turned into a module. */\nexport class WidgetLoadError extends Error {\n readonly code: WidgetLoadErrorCode;\n readonly packageId: string | undefined;\n readonly path: string | undefined;\n\n constructor(code: WidgetLoadErrorCode, message: string, options: WidgetLoadErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'WidgetLoadError';\n this.code = code;\n this.packageId = options.packageId;\n this.path = options.path;\n }\n}\n","import { parseDeliveryKind, parsePayloadType } from '@mica-js/document/canvas';\nimport { WidgetLoadError, type WidgetLoadErrorCode } from '../errors';\nimport type { PortDefinition, PropertyDefinition, WidgetDefinition, WidgetModule } from '../types';\n\n/** Read-only view of the files that make up one package. */\nexport interface PackageFiles {\n /** Human-readable label used in diagnostics. */\n readonly label: string;\n /** Reads a package-relative POSIX path and resolves to its bytes. */\n read(path: string): Promise<Uint8Array>;\n}\n\nexport interface WidgetPackage {\n readonly id: string;\n readonly version: string;\n /**\n * SHA-256 (hex) over the `[widget id, source]` pairs in widget-id order, so distinct package\n * contents never collide and reordering the manifest does not change the hash.\n */\n readonly contentHash: string;\n readonly modules: Readonly<Record<string, WidgetModule>>;\n}\n\nconst PACKAGE_JSON = 'package.json';\nconst JSON_EXTENSION = '.json';\nconst IMPLEMENTATION_EXTENSION = '.js';\n/** Package and widget ids are stable kebab-case identifiers (see #1). */\nconst ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;\n\ninterface WidgetEntry {\n readonly id: string;\n readonly path: string;\n readonly displayName: string | undefined;\n readonly description: string | undefined;\n}\n\ninterface PackageManifest {\n readonly id: string;\n readonly version: string;\n readonly widgets: readonly WidgetEntry[];\n}\n\n/**\n * Reads a package manifest, every declared widget definition and its paired implementation.\n * Only the three declared path kinds are read; the package is never enumerated.\n *\n * @throws {WidgetLoadError}\n */\nexport async function loadWidgetPackage(files: PackageFiles): Promise<WidgetPackage> {\n const manifest = await readManifest(files);\n const modules: Record<string, WidgetModule> = {};\n const sources: (readonly [string, string])[] = [];\n\n for (const entry of manifest.widgets) {\n const definition = await readDefinition(files, manifest.id, entry);\n const implementationPath = toImplementationPath(entry.path);\n const code = await readImplementation(files, manifest.id, entry.id, implementationPath);\n modules[entry.id] = { definition, code };\n sources.push([entry.id, code]);\n }\n\n // Ids travel with each source, so the digest separates adjacent widgets and empty files.\n const contentHash = await sha256Hex(JSON.stringify(sources), manifest.id);\n return { id: manifest.id, version: manifest.version, contentHash, modules };\n}\n\nasync function readManifest(files: PackageFiles): Promise<PackageManifest> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(PACKAGE_JSON);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/package-not-found',\n `Package ${JSON.stringify(files.label)} has no readable ${PACKAGE_JSON}.`,\n { path: PACKAGE_JSON, cause },\n );\n }\n\n const manifest = requireObject(\n parseJson(bytes, 'widget/invalid-manifest', PACKAGE_JSON, undefined, PACKAGE_JSON),\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must be a JSON object`,\n undefined,\n PACKAGE_JSON,\n );\n\n const id = manifest['name'];\n if (typeof id !== 'string' || !ID_PATTERN.test(id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must declare a kebab-case \"name\".`,\n { path: PACKAGE_JSON },\n );\n }\n\n const version = manifest['version'];\n if (typeof version !== 'string' || version.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} must declare a non-empty \"version\".`,\n { packageId: id, path: PACKAGE_JSON },\n );\n }\n\n const widgetsValue = manifest['widgets'];\n const widgets =\n widgetsValue === undefined\n ? {}\n : requireObject(\n widgetsValue,\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} \"widgets\" must be an object`,\n id,\n PACKAGE_JSON,\n );\n\n const entries = Object.keys(widgets)\n .sort()\n .map((widgetId) => readEntry(widgets[widgetId], widgetId, id));\n\n return { id, version, widgets: entries };\n}\n\nfunction readEntry(value: unknown, widgetId: string, packageId: string): WidgetEntry {\n if (!ID_PATTERN.test(widgetId)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(packageId)} declares widget id ${JSON.stringify(widgetId)}; ids must be kebab-case.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n\n const entry = requireObject(\n value,\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} entry must be an object`,\n packageId,\n PACKAGE_JSON,\n );\n\n const path = entry['path'];\n if (typeof path !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} must declare a string \"path\".`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n const problem = packagePathProblem(path);\n if (problem !== undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} ${problem}.`,\n { packageId, path },\n );\n }\n if (!path.endsWith(JSON_EXTENSION)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} must point at a ${JSON_EXTENSION} description.`,\n { packageId, path },\n );\n }\n\n return {\n id: widgetId,\n path,\n displayName: optionalString(entry, 'displayName', widgetId, packageId),\n description: optionalString(entry, 'description', widgetId, packageId),\n };\n}\n\nasync function readDefinition(\n files: PackageFiles,\n packageId: string,\n entry: WidgetEntry,\n): Promise<WidgetDefinition> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(entry.path);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(entry.id)} declares a missing definition at ${JSON.stringify(entry.path)}.`,\n { packageId, path: entry.path, cause },\n );\n }\n\n const record = requireObject(\n parseJson(bytes, 'widget/invalid-definition', entry.path, packageId, entry.path),\n 'widget/invalid-definition',\n `Widget definition ${JSON.stringify(entry.path)} must be a JSON object`,\n packageId,\n entry.path,\n );\n\n const properties = readProperties(record['properties'], packageId, entry.path);\n const ports = readPorts(record['ports'], packageId, entry.path);\n\n return {\n properties,\n ports,\n ...(entry.displayName === undefined ? {} : { displayName: entry.displayName }),\n ...(entry.description === undefined ? {} : { description: entry.description }),\n };\n}\n\nfunction readProperties(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PropertyDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"properties\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const properties: Record<string, PropertyDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n const type = descriptor['type'];\n if (typeof type !== 'string' || type.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a non-empty string \"type\".`,\n { packageId, path },\n );\n }\n properties[key] = { ...descriptor, type };\n }\n return properties;\n}\n\nfunction readPorts(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PortDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"ports\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const ports: Record<string, PortDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const direction = descriptor['direction'];\n if (direction !== 'input' && direction !== 'output') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"direction\" as \"input\" or \"output\".`,\n { packageId, path },\n );\n }\n\n const typeName = descriptor['type'];\n if (typeof typeName !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a string \"type\".`,\n { packageId, path },\n );\n }\n const type = parsePayloadType(typeName);\n if (type === undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} declares unknown payload type ${JSON.stringify(typeName)}.`,\n { packageId, path },\n );\n }\n\n const title = portText(descriptor, 'title', key, packageId, path);\n const description = portText(descriptor, 'description', key, packageId, path);\n // RFC 0017: `delivery` is optional and independent of `type`; an unparsable value is rejected\n // here instead of silently falling back to the payload type default.\n const declaredDelivery = descriptor['delivery'];\n const delivery =\n declaredDelivery === undefined ? undefined : parseDeliveryKind(declaredDelivery);\n if (declaredDelivery !== undefined && delivery === undefined) {\n throw new WidgetLoadError(\n 'schema/invalid-value',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"delivery\" as \"level\" or \"message\".`,\n { packageId, path },\n );\n }\n ports[key] = {\n direction,\n type,\n ...(delivery === undefined ? {} : { delivery }),\n ...(title === undefined ? {} : { title }),\n ...(description === undefined ? {} : { description }),\n };\n }\n return ports;\n}\n\nasync function readImplementation(\n files: PackageFiles,\n packageId: string,\n widgetId: string,\n path: string,\n): Promise<string> {\n try {\n return decode(await files.read(path));\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/no-implementation',\n `Widget ${JSON.stringify(widgetId)} in package ${JSON.stringify(packageId)} has no implementation at ${JSON.stringify(path)}.`,\n { packageId, path, cause },\n );\n }\n}\n\n/** Rejects absolute paths, drive letters, backslashes and escaping `..` segments. */\nfunction packagePathProblem(path: string): string | undefined {\n if (path.length === 0) {\n return 'must not be empty';\n }\n if (path.startsWith('/')) {\n return 'must be relative to the package root';\n }\n if (/^[A-Za-z]:/.test(path)) {\n return 'must not carry a drive letter';\n }\n if (path.includes('\\\\')) {\n return 'must use POSIX separators';\n }\n if (path.split('/').includes('..')) {\n return 'must stay inside the package';\n }\n return undefined;\n}\n\nfunction toImplementationPath(definitionPath: string): string {\n return definitionPath.slice(0, -JSON_EXTENSION.length) + IMPLEMENTATION_EXTENSION;\n}\n\n/** Reads an optional manifest field; failures always point at `package.json`, where the field lives. */\nfunction optionalString(\n record: Record<string, unknown>,\n key: 'displayName' | 'description',\n widgetId: string,\n packageId: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} \"${key}\" in ${PACKAGE_JSON} must be a string.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n return value;\n}\n\nfunction portText(\n record: Record<string, unknown>,\n key: 'title' | 'description',\n portId: string,\n packageId: string,\n path: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(portId)} \"${key}\" in ${JSON.stringify(path)} must be a string.`,\n { packageId, path },\n );\n }\n return value;\n}\n\nfunction parseJson(\n bytes: Uint8Array,\n code: WidgetLoadErrorCode,\n what: string,\n packageId: string | undefined,\n path: string,\n): unknown {\n try {\n return JSON.parse(decode(bytes)) as unknown;\n } catch (cause) {\n throw new WidgetLoadError(code, `${what} is not valid JSON.`, {\n path,\n cause,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n}\n\nfunction requireObject(\n value: unknown,\n code: WidgetLoadErrorCode,\n message: string,\n packageId: string | undefined,\n path: string,\n): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WidgetLoadError(code, `${message}.`, {\n path,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n return value as Record<string, unknown>;\n}\n\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Record for keys taken from untrusted definition JSON: no inherited setter can intercept an\n * assignment, so a declared entry can never become an object prototype.\n */\nfunction createRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\n/** `__proto__` is never a stable widget key, and on any object it would shadow the prototype. */\nfunction isUnsafeRecordKey(key: string): boolean {\n return key === '__proto__';\n}\n\nasync function sha256Hex(text: string, packageId: string): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (subtle === undefined) {\n throw new WidgetLoadError(\n 'widget/load-failed',\n 'Computing the widget package content hash requires Web Crypto (globalThis.crypto.subtle).',\n { packageId, path: PACKAGE_JSON },\n );\n }\n const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n","import type { WidgetModule, WidgetProvider } from '../types';\n\n/** Provider over a fixed module table, used for builtin widgets and tests. */\nexport function createStaticWidgetProvider(\n modules: Readonly<Record<string, WidgetModule>>,\n): WidgetProvider {\n const index = new Map(Object.entries(modules));\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n","import { WidgetLoadError } from '../errors';\nimport { loadWidgetPackage, type PackageFiles } from './load';\nimport type { WidgetModule, WidgetProvider } from '../types';\n\nexport interface PackageWidgetProviderOptions {\n readonly files: PackageFiles | readonly PackageFiles[];\n}\n\n/**\n * Loads every package up front and indexes its widgets under `<packageId>:<widgetId>`.\n * Resolution never touches the file system again, and unknown references return `undefined`.\n *\n * @throws {WidgetLoadError}\n */\nexport async function createPackageWidgetProvider(\n options: PackageWidgetProviderOptions,\n): Promise<WidgetProvider> {\n const filesList: readonly PackageFiles[] = Array.isArray(options.files)\n ? options.files\n : [options.files as PackageFiles];\n\n const index = new Map<string, WidgetModule>();\n const packageIds = new Set<string>();\n\n for (const files of filesList) {\n const widgetPackage = await loadWidgetPackage(withPathCache(files));\n if (packageIds.has(widgetPackage.id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package id ${JSON.stringify(widgetPackage.id)} is provided more than once.`,\n { packageId: widgetPackage.id, path: 'package.json' },\n );\n }\n packageIds.add(widgetPackage.id);\n for (const [widgetId, module] of Object.entries(widgetPackage.modules)) {\n index.set(`${widgetPackage.id}:${widgetId}`, module);\n }\n }\n\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n\n/** Reads each path at most once for the lifetime of the provider. */\nfunction withPathCache(files: PackageFiles): PackageFiles {\n const cache = new Map<string, Promise<Uint8Array>>();\n return {\n label: files.label,\n read(path) {\n const cached = cache.get(path);\n if (cached !== undefined) {\n return cached;\n }\n const pending = files.read(path);\n cache.set(path, pending);\n return pending;\n },\n };\n}\n","/** Failure classification of a `HostFs.read` rejection. */\nexport type HostFsErrorCode = 'FileNotFound' | 'NoPermissions' | 'NoFileSystem' | 'Unavailable';\n\n/**\n * Structured-clone payload for a `HostFsError` that crosses a thread boundary.\n *\n * The receiving side rebuilds the instance from `code`; `message` keeps the original wording when\n * it survives the transport and falls back to the default message for the code otherwise.\n */\nexport interface HostFsErrorPayload {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n readonly message?: string;\n}\n\nexport interface HostFsErrorOptions {\n readonly cause?: unknown;\n}\n\nconst DEFAULT_MESSAGES: Record<HostFsErrorCode, string> = {\n FileNotFound: 'Host resource not found',\n NoPermissions: 'Host resource access denied',\n NoFileSystem: 'No host file system handles the URI scheme',\n Unavailable: 'Host file system is unavailable',\n};\n\nconst ERROR_CODES: readonly HostFsErrorCode[] = [\n 'FileNotFound',\n 'NoPermissions',\n 'NoFileSystem',\n 'Unavailable',\n];\n\nfunction isHostFsErrorCode(value: unknown): value is HostFsErrorCode {\n return typeof value === 'string' && (ERROR_CODES as readonly string[]).includes(value);\n}\n\n/** Rejection of `HostFs.read`: `code` classifies the failure, `uri` names the resource. */\nexport class HostFsError extends Error {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n\n constructor(\n code: HostFsErrorCode,\n uri: string,\n message?: string,\n options: HostFsErrorOptions = {},\n ) {\n super(\n message ?? `${DEFAULT_MESSAGES[code]}: ${uri}`,\n options.cause === undefined ? undefined : { cause: options.cause },\n );\n this.name = 'HostFsError';\n this.code = code;\n this.uri = uri;\n }\n}\n\n/** Narrows an unknown rejection to a `HostFsError` created in this realm. */\nexport function isHostFsError(value: unknown): value is HostFsError {\n return value instanceof HostFsError;\n}\n\n/** Copies the fields a thread hop must carry; the instance itself does not survive a structured clone. */\nexport function toHostFsErrorPayload(error: HostFsError): HostFsErrorPayload {\n return { code: error.code, uri: error.uri, message: error.message };\n}\n\n/** Rebuilds a `HostFsError` from its payload, rejecting codes outside the contract. */\nexport function fromHostFsErrorPayload(payload: HostFsErrorPayload): HostFsError {\n const code: unknown = payload.code;\n if (!isHostFsErrorCode(code)) {\n throw new TypeError(`Unknown HostFsError code: ${String(code)}`);\n }\n return new HostFsError(code, payload.uri, payload.message);\n}\n","/**\n * Decodes a self-contained `data:` URI to its bytes.\n *\n * `data:` resources never reach `HostFs`: the bytes travel with the reference, so the host decodes\n * them locally. `;base64` payloads are decoded from base64; other payloads are percent-decoded,\n * while characters that need no escaping are encoded as UTF-8. The URI fragment is ignored.\n *\n * @throws TypeError when the URI has no payload separator or the payload is not decodable.\n */\nexport function decodeDataUri(uri: string): Uint8Array {\n const { base64, payload } = splitDataUri(uri);\n return base64 ? decodeBase64(payload) : decodePercentPayload(payload);\n}\n\n/**\n * Decodes a self-contained `data:` URI to its text payload.\n *\n * The decoded bytes are read as UTF-8, so a payload that carries binary or malformed UTF-8 is a\n * decode failure rather than replacement characters.\n *\n * @throws TypeError when the URI has no payload separator, the payload is not decodable, or the\n * bytes are not UTF-8.\n */\nexport function decodeDataUriText(uri: string): string {\n const bytes = decodeDataUri(uri);\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid UTF-8', { cause });\n }\n}\n\ninterface DataUriPayload {\n readonly base64: boolean;\n readonly payload: string;\n}\n\n/** Splits the URI into its `;base64` flag and payload. */\nfunction splitDataUri(uri: string): DataUriPayload {\n if (uri.slice(0, 5).toLowerCase() !== 'data:') {\n throw new TypeError('Not a data: URI');\n }\n const hash = uri.indexOf('#');\n const body = hash < 0 ? uri : uri.slice(0, hash);\n const comma = body.indexOf(',');\n if (comma < 0) {\n throw new TypeError('Data URI must separate its payload with a comma');\n }\n\n const metadata = body.slice('data:'.length, comma);\n return { base64: /;base64$/i.test(metadata), payload: body.slice(comma + 1) };\n}\n\nfunction decodeBase64(payload: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid base64', { cause });\n }\n\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\nfunction isHexDigit(value: string | undefined): value is string {\n return value !== undefined && /^[0-9A-Fa-f]$/.test(value);\n}\n\n/**\n * Percent-decodes a payload to bytes, so `%89PNG` keeps its binary value instead of being read as\n * (invalid) UTF-8. Literal characters are UTF-8 encoded.\n */\nfunction decodePercentPayload(payload: string): Uint8Array {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n let literal = 0;\n let index = 0;\n\n while (index < payload.length) {\n if (payload[index] !== '%') {\n index += 1;\n continue;\n }\n const high = payload[index + 1];\n const low = payload[index + 2];\n if (!isHexDigit(high) || !isHexDigit(low)) {\n throw new TypeError('Data URI payload is not valid percent-encoding');\n }\n if (index > literal) chunks.push(encoder.encode(payload.slice(literal, index)));\n chunks.push(new Uint8Array([Number.parseInt(`${high}${low}`, 16)]));\n index += 3;\n literal = index;\n }\n\n if (literal < payload.length) chunks.push(encoder.encode(payload.slice(literal)));\n\n let total = 0;\n for (const chunk of chunks) total += chunk.length;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","interface UriParts {\n readonly scheme: string | undefined;\n readonly authority: string | undefined;\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\ninterface PathReference {\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\nconst ABSOLUTE_URI = /^[A-Za-z][A-Za-z0-9+.-]*:/;\n\n/** Whether `uri` carries a scheme, i.e. is absolute rather than a relative reference. */\nexport function isAbsoluteHostUri(uri: string): boolean {\n return ABSOLUTE_URI.test(uri);\n}\n\n/** Splits a reference into path, query and fragment without interpreting leading slashes. */\nfunction splitPath(value: string): PathReference {\n const hash = value.indexOf('#');\n const fragment = hash < 0 ? undefined : value.slice(hash + 1);\n const beforeFragment = hash < 0 ? value : value.slice(0, hash);\n const question = beforeFragment.indexOf('?');\n const query = question < 0 ? undefined : beforeFragment.slice(question + 1);\n const path = question < 0 ? beforeFragment : beforeFragment.slice(0, question);\n return { path, query, fragment };\n}\n\nfunction parseUri(value: string): UriParts {\n const schemeMatch = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(value);\n const scheme = schemeMatch?.[1];\n let rest = schemeMatch === null ? value : value.slice(schemeMatch[0].length);\n\n let authority: string | undefined;\n if (rest.startsWith('//')) {\n const tail = rest.slice(2);\n const end = tail.search(/[/?#]/);\n authority = end < 0 ? tail : tail.slice(0, end);\n rest = end < 0 ? '' : tail.slice(end);\n }\n\n const { path, query, fragment } = splitPath(rest);\n return { scheme, authority, path, query, fragment };\n}\n\nfunction removeLastSegment(output: string): string {\n const slash = output.lastIndexOf('/');\n return slash < 0 ? '' : output.slice(0, slash);\n}\n\n/** RFC 3986 §5.2.4: drops `.` and `..` segments without touching empty segments. */\nfunction removeDotSegments(path: string): string {\n let input = path;\n let output = '';\n while (input.length > 0) {\n if (input.startsWith('../')) {\n input = input.slice(3);\n } else if (input.startsWith('./')) {\n input = input.slice(2);\n } else if (input.startsWith('/./')) {\n input = `/${input.slice(3)}`;\n } else if (input === '/.') {\n input = '/';\n } else if (input.startsWith('/../')) {\n input = `/${input.slice(4)}`;\n output = removeLastSegment(output);\n } else if (input === '/..') {\n input = '/';\n output = removeLastSegment(output);\n } else if (input === '.' || input === '..') {\n input = '';\n } else {\n const segment = /^\\/?[^/]*/.exec(input)?.[0] ?? input;\n output += segment;\n input = input.slice(segment.length);\n }\n }\n return output;\n}\n\n/** RFC 3986 §5.3: merges a relative path with the base path. */\nfunction mergePath(base: UriParts, referencePath: string): string {\n if (referencePath === '') return base.path;\n if (base.authority !== undefined && base.path === '') return `/${referencePath}`;\n const slash = base.path.lastIndexOf('/');\n return slash < 0 ? referencePath : `${base.path.slice(0, slash + 1)}${referencePath}`;\n}\n\nfunction compose(\n scheme: string,\n authority: string | undefined,\n path: string,\n query: string | undefined,\n fragment: string | undefined,\n): string {\n let uri = `${scheme}:`;\n if (authority !== undefined) uri += `//${authority}`;\n uri += path;\n if (query !== undefined) uri += `?${query}`;\n if (fragment !== undefined) uri += `#${fragment}`;\n return uri;\n}\n\n/**\n * Resolves a document reference against the absolute URI of the document that contains it.\n *\n * - a reference with a scheme is an absolute URI and is returned unchanged;\n * - a reference starting with `/` replaces the path and keeps the base scheme and authority;\n * - any other reference is merged with the base directory and normalized.\n *\n * The result always keeps the scheme and authority of `baseUri`, so a `//host/path` reference\n * stays inside the base authority instead of replacing it. Hosts pass a base URI whose path is\n * not empty; a base with an authority and an empty path resolves relative references under that\n * authority.\n *\n * @throws TypeError when `baseUri` is not an absolute URI.\n */\nexport function resolveHostUri(baseUri: string, reference: string): string {\n const base = parseUri(baseUri);\n if (base.scheme === undefined) {\n throw new TypeError(`Host URI base must be absolute: ${baseUri}`);\n }\n if (isAbsoluteHostUri(reference)) return reference;\n\n const target = splitPath(reference);\n const replacesPath = reference.startsWith('/');\n const path = replacesPath\n ? removeDotSegments(target.path)\n : removeDotSegments(mergePath(base, target.path));\n const keepBaseQuery = !replacesPath && target.path === '' && target.query === undefined;\n const query = keepBaseQuery ? base.query : target.query;\n return compose(base.scheme, base.authority, path, query, target.fragment);\n}\n","import type { PropertyDefinition } from '../../types';\nimport type { WidgetAssetRef } from './types';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\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/**\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: unknown): unknown {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => cloneFrozen(item)));\n }\n if (isPlainObject(value)) {\n const entries: [string, unknown][] = [];\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\nfunction isAssetMode(value: unknown): value is WidgetAssetRef['mode'] {\n return value === 'file' || value === 'inline' || value === 'store';\n}\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 */\nexport function mergeProperties(\n properties: Readonly<Record<string, PropertyDefinition>> | undefined,\n props: Readonly<Record<string, unknown>> | undefined,\n): Readonly<Record<string, unknown>> {\n const merged = new Map<string, unknown>();\n\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 ?? {})) {\n merged.set(key, props?.[key]);\n }\n\n return Object.freeze(Object.fromEntries(merged));\n}\n\n/**\n * Collects image / binary property values (`{ src, mode }`) from nested objects and arrays.\n * Results are keyed by `src`, so one resource referenced twice is only read once.\n */\nexport function collectAssetRefs(\n value: unknown,\n found: Map<string, WidgetAssetRef> = new Map(),\n seen: Set<object> = new Set(),\n): Map<string, WidgetAssetRef> {\n if (typeof value !== 'object' || value === null) return found;\n if (seen.has(value)) return found;\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) collectAssetRefs(item, found, seen);\n return found;\n }\n if (!isPlainObject(value)) return found;\n\n const candidate = value as { src?: unknown; mode?: unknown };\n if (typeof candidate.src === 'string' && isAssetMode(candidate.mode)) {\n if (!found.has(candidate.src)) {\n found.set(candidate.src, { src: candidate.src, mode: candidate.mode });\n }\n }\n for (const key of Object.keys(value)) collectAssetRefs(value[key], found, seen);\n return found;\n}\n","import { defineRpcService } from '@mica-js/core/rpc';\nimport type { TimePs } from '@mica-js/core';\nimport type { CanvasBindingTarget } from '@mica-js/document/canvas';\nimport type { WidgetDefinition } from '../../types';\nimport type { WidgetAudioMountInfo } from '../audio/protocol';\nimport type { WidgetInputEvent } from './types';\n\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 */\nexport const widgetFrameEvent = 'widget:frame';\nexport const widgetPublishEvent = 'widget:publish';\nexport const widgetErrorEvent = 'widget:error';\n/** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */\nexport const widgetAssetFailedEvent = 'widget:asset-failed';\n\n/** Guest methods the host reaches through `sandbox.call()`. */\nexport const widgetLoadMethod = 'load';\nexport const widgetMountMethod = 'mount';\nexport const widgetUnmountMethod = 'unmount';\nexport const widgetResizeMethod = 'resize';\nexport const widgetSetPropertiesMethod = 'set-properties';\n/** Replaces the prefetched bytes of one mounted instance without remounting it. */\nexport const widgetSetAssetsMethod = 'set-assets';\n/**\n * Replaces the device endpoints one instance writes to and reads from (RFC 0018).\n *\n * The guest routes topic traffic itself when it holds a direct device channel, so it needs the same\n * binding map the host validates against. A guest without that channel ignores the call.\n */\nexport const widgetSetBindingsMethod = 'set-bindings';\nexport const widgetDeliverMethod = 'deliver';\nexport const widgetPointerMethod = 'pointer';\n/**\n * Configures explicit stepping and connects the direct simulation-runtime port before mounting.\n * Without explicit stepping the standalone guest retains automatic repaint scheduling.\n */\nexport const widgetConfigureMethod = 'configure';\n/**\n * Advances the guest to a caller-supplied time.\n *\n * The editor owns the clock: it delivers the same step to widgets and devices, so the guest must\n * not schedule time-bound work on its own.\n */\nexport const widgetStepMethod = 'step';\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 */\nexport const widgetResetRuntimeMethod = 'reset-runtime';\n/** Instance boundary that produced a widget error. */\nexport type WidgetErrorPhase = 'mount' | 'render' | 'deliver';\n\n/** Widget errors cross the sandbox boundary as plain data. */\nexport interface SerializedWidgetError {\n readonly name: string;\n readonly message: string;\n}\n\n/** One rendered frame, always transferred so the host owns the bitmap. */\nexport interface WidgetFrameMessage {\n readonly instanceId: string;\n readonly bitmap: ImageBitmap;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n /**\n * Mount generation echoed from {@link WidgetMountRequest.generation}. The editor runtime\n * rejects a frame whose generation no longer owns the instance; standalone guests may omit it.\n */\n readonly generation?: number;\n}\n\n/** Payload a widget published on an output port. */\nexport interface WidgetPublishMessage {\n readonly instanceId: string;\n readonly port: string;\n readonly payload: unknown;\n /** Simulation time supplied by the widget; `0` when it did not pass one. */\n readonly simTime: number;\n /**\n * The guest already handed this publish to the device guest over its direct channel, so the host\n * must not forward it a second time. Absent when the guest has no channel or no binding.\n */\n readonly direct?: boolean;\n}\n\n/** Asset read that failed inside the guest; reported once per instance and `src`. */\nexport interface WidgetAssetFailedMessage {\n readonly instanceId: string;\n readonly src: string;\n readonly error: SerializedWidgetError;\n}\n\n/** Failure contained to one instance; the guest keeps every other instance running. */\nexport interface WidgetErrorMessage {\n readonly instanceId: string;\n readonly phase: WidgetErrorPhase;\n readonly error: SerializedWidgetError;\n}\n\nexport interface WidgetLoadModule {\n readonly definition: WidgetDefinition;\n readonly code: string;\n}\n\nexport interface WidgetLoadPackage {\n readonly id: string;\n readonly modules: Readonly<Record<string, WidgetLoadModule>>;\n}\n\nexport interface WidgetLoadRequest {\n readonly packages: readonly WidgetLoadPackage[];\n}\n\nexport interface WidgetMountRequest {\n readonly instanceId: string;\n readonly widget: string;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n readonly props?: Readonly<Record<string, unknown>>;\n /** Bytes the host prefetched for this instance, keyed by `WidgetAssetRef.src`. */\n readonly assets?: Readonly<Record<string, Uint8Array>>;\n /**\n * Audio availability at mount time. Read synchronously by the factory through\n * `api.audio.state`; `session` is the one-shot token the worklet accepts for this generation.\n */\n readonly audio?: WidgetAudioMountInfo;\n /**\n * Mount generation assigned by the editor runtime. Frames echo it, so a frame produced by a\n * replaced instance can never be adopted by its successor.\n */\n readonly generation?: number;\n}\n\n/** Service the guest reaches over the transferred direct port. */\nexport type WidgetDirectTopicService = 'simulation-runtime';\n\n/** One-time guest configuration applied before the first mount. */\nexport interface IWidgetGuestRuntimeConfig {\n /**\n * Removes the guest's automatic repaint scheduling: an `invalidate()` only marks the instance\n * dirty, and the next {@link IWidgetGuestStep} paints it.\n */\n readonly explicitStepping?: boolean;\n /** Contract behind the direct port; defaults to `simulation-runtime` at first use. */\n readonly directTopicService?: WidgetDirectTopicService;\n}\n\n/** Caller-supplied time of one widget step. */\nexport interface IWidgetGuestStep {\n /** Simulation time after the step, in picoseconds. */\n readonly simTime: TimePs;\n /** Length of the step, in picoseconds. */\n readonly dt: TimePs;\n /** Editor mode; widgets keep running in both, the caller decides what advances. */\n readonly mode: 'edit' | 'simulation';\n}\n\n/** Every guest method the host reaches through `sandbox.call()`, in one RPC service. */\nexport interface WidgetGuestService {\n [widgetLoadMethod](request: WidgetLoadRequest): Promise<void>;\n /** Rejects when the factory or the first paint fails, so a candidate instance is not adopted. */\n [widgetMountMethod](request: WidgetMountRequest): Promise<void>;\n [widgetUnmountMethod](instanceId: string): void;\n [widgetResizeMethod](instanceId: string, width: number, height: number, dpr: number): void;\n [widgetSetPropertiesMethod](instanceId: string, props: Readonly<Record<string, unknown>>): void;\n [widgetSetAssetsMethod](instanceId: string, assets: Readonly<Record<string, Uint8Array>>): void;\n [widgetSetBindingsMethod](\n instanceId: string,\n bindings: Readonly<Record<string, CanvasBindingTarget>>,\n ): void;\n [widgetDeliverMethod](instanceId: string, port: string, payload: unknown, simTime: number): void;\n [widgetPointerMethod](instanceId: string, event: WidgetInputEvent): void;\n [widgetConfigureMethod](config: IWidgetGuestRuntimeConfig): boolean;\n /**\n * Resolves after queued direct input and deferred repaints are applied, and after every direct\n * widget → simulation delivery started by this step has settled.\n */\n [widgetStepMethod](step: IWidgetGuestStep): Promise<void>;\n [widgetResetRuntimeMethod](): void;\n}\n\n/** Host → guest control lane: events pushed into the runtime and forced teardown. */\nexport interface WidgetGuestControlService {\n dispatchEvent(type: string, payload: unknown): void;\n terminate(): void;\n}\n\n/** Guest → host control lane: the event bus plus capability reads. */\nexport interface WidgetHostControlService {\n event(type: string, payload: unknown, transfer?: readonly Transferable[]): void;\n}\n\n/** Host file system reads the guest may perform; bytes travel as a transferred buffer. */\nexport interface WidgetHostCapabilitiesService {\n read(uri: string): Promise<Uint8Array>;\n}\n\n/**\n * Wire names shared by the worker script and the host adapter. Both sides must agree on the exact\n * strings, so they are defined once and registered with `register` / `getProxy`.\n */\nexport const widgetGuestService = defineRpcService<WidgetGuestService>('guest');\nexport const widgetGuestControlService =\n defineRpcService<WidgetGuestControlService>('guest-control');\nexport const widgetHostControlService = defineRpcService<WidgetHostControlService>('host-control');\nexport const widgetHostCapabilitiesService =\n defineRpcService<WidgetHostCapabilitiesService>('host-capabilities');\n\n/** The one member of {@link widgetHostControlService} that carries a transfer list. */\nexport const widgetHostEventMethod = 'event';\n\n/** One publish the editor simulation runtime sends over the direct port. */\nexport interface IWidgetSimulationPublish {\n readonly target: CanvasBindingTarget;\n readonly payload: unknown;\n /** Simulation time the publish belongs to, in picoseconds. */\n readonly simTime: TimePs;\n}\n\n/**\n * The slice of the editor simulation runtime the guest reaches over the direct port.\n *\n * The editor registers this service on the device worker (or an in-process simulation) under the\n * `simulation-runtime` id and transfers the other end of the port to this guest. The contract is\n * declared locally on purpose: the widget package must not depend on the simulator implementation\n * to state the wire shape. `deliver` takes the same `{ target, payload, simTime }` message that\n * `onDidPublish` reports.\n */\nexport interface IWidgetSimulationRuntimeChannel {\n /** Queues one message for a device endpoint; consumed by the simulation's next step. */\n deliver(message: IWidgetSimulationPublish): Promise<void>;\n /** Subscribes to simulation publishes; the guest fans them out to its bound instances. */\n onDidPublish(listener: (publish: IWidgetSimulationPublish) => void): () => void;\n}\n\n/** Wire name of {@link IWidgetSimulationRuntimeChannel}. */\nexport const widgetSimulationRuntimeService =\n defineRpcService<IWidgetSimulationRuntimeChannel>('simulation-runtime');\n","/**\n * Typed RPC contracts of the widget audio path (RFC 0016).\n *\n * Three endpoints carry the whole path:\n *\n * - the guest runtime talks to the `AudioWorklet` over a `MessagePort` it receives from the host;\n * - the host talks to the same worklet over the `AudioWorkletNode` port;\n * - the host pushes availability and the direct port into the guest over the sandbox RPC endpoint.\n *\n * `createRpc` serializes every call, so PCM stays on the worker ↔ worklet port and never passes\n * through the render host.\n */\n\nimport { defineRpcService } from '@mica-js/core/rpc';\n\n/** Name the worklet registers its processor under. */\nexport const widgetAudioWorkletProcessor = 'mica-widget-audio';\n\n/** Per-instance ceiling on simultaneous tones. */\nexport const defaultMaxVoices = 8;\n/** Per-instance ceiling on open PCM streams. */\nexport const defaultMaxStreams = 4;\n\n/** Availability of the host audio path. */\nexport type WidgetAudioState = 'unavailable' | 'suspended' | 'running';\n\n/** Why a tone or stream stopped. */\nexport type WidgetAudioEndReason =\n 'finished' | 'stopped' | 'dropped' | 'error' | 'unavailable' | 'disposed';\n\n/** Sample layout of a PCM stream. */\nexport type WidgetAudioFormat = 's16' | 'f32';\n\n/** Waveforms the worklet synthesizes for `api.audio.tone()`. */\nexport type WidgetOscillatorType = 'sine' | 'square' | 'triangle' | 'sawtooth';\n\n/** Playback state of a PCM stream, as the guest sees it. */\nexport type WidgetAudioStreamState = 'buffering' | 'playing' | 'ended' | 'closed';\n\n/** Per-instance ceilings; a host may tighten them through its options. */\nexport interface WidgetAudioLimits {\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\n/** One mount generation of one instance, opened by the host before the guest can use it. */\nexport interface WidgetAudioSessionOpen {\n /** One-shot token every guest call must carry. */\n readonly session: string;\n /** Guest runtime that owns the token; a port from another runtime is rejected. */\n readonly runtimeId: string;\n readonly instanceId: string;\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\nexport interface WidgetAudioToneInit {\n /** Guest-assigned id; unique per session. */\n readonly voiceId: string;\n readonly type: WidgetOscillatorType;\n /** Hz, `(0, 24000]`. */\n readonly frequency: number;\n /** `0`–`1`. */\n readonly volume: number;\n}\n\nexport interface WidgetAudioToneSettings {\n readonly volume?: number;\n readonly frequency?: number;\n /** Smoothing window in milliseconds, `0`–`10000`. */\n readonly rampMs: number;\n}\n\nexport interface WidgetAudioStop {\n /** Fade-out in milliseconds, `0`–`10000`. */\n readonly fadeMs: number;\n}\n\nexport interface WidgetAudioStreamInit {\n /** Guest-assigned id; unique per session. */\n readonly streamId: string;\n /** Source rate in Hz, `8000`–`96000`. */\n readonly sampleRate: number;\n readonly channels: 1 | 2;\n readonly format: WidgetAudioFormat;\n readonly capacityFrames: number;\n readonly startFrames: number;\n readonly volume: number;\n}\n\n/** Answer of `createStream`: the worklet re-checks the per-session quota. */\nexport interface WidgetAudioStreamOpened {\n readonly accepted: boolean;\n}\n\n/** Credit report; `consumedFrames` is cumulative over the stream's lifetime. */\nexport interface WidgetAudioProgress {\n readonly streamId: string;\n readonly consumedFrames: number;\n readonly underruns: number;\n readonly state: WidgetAudioStreamState;\n}\n\n/** Terminal event of one tone or stream. */\nexport interface WidgetAudioEndedMessage {\n readonly target: 'tone' | 'stream';\n readonly id: string;\n readonly reason: WidgetAudioEndReason;\n}\n\n/** Diagnostic codes the audio path reports. */\nexport type WidgetAudioDiagnosticCode = 'widget/audio-failed' | 'widget/audio-limit';\n\n/** Quota or validation class the receiving side dedupes against. */\nexport type WidgetAudioDiagnosticCategory = 'voices' | 'streams' | 'capacity' | 'worklet';\n\nexport interface WidgetAudioDiagnostic {\n /** Session the diagnostic belongs to; the host maps it back to the instance. */\n readonly session: string;\n readonly code: WidgetAudioDiagnosticCode;\n readonly category: WidgetAudioDiagnosticCategory;\n readonly message: string;\n}\n\n/**\n * Guest → worklet.\n *\n * Every member names a session; the worklet checks that the session belongs to the runtime that\n * owns the calling port, so a guest cannot steer another instance.\n */\nexport interface WidgetAudioWorkletService {\n createTone(session: string, init: WidgetAudioToneInit): void;\n setTone(session: string, voiceId: string, settings: WidgetAudioToneSettings): void;\n stopTone(session: string, voiceId: string, options: WidgetAudioStop): void;\n createStream(session: string, init: WidgetAudioStreamInit): WidgetAudioStreamOpened;\n /** `samples` travels as a transferred buffer; `true` means the whole block was accepted. */\n writeStream(session: string, streamId: string, samples: Int16Array | Float32Array): boolean;\n /** Drops everything that has not played yet and keeps the stream open. */\n clearStream(session: string, streamId: string): void;\n /** Drains the buffer, then ends the stream with `finished`. */\n endStream(session: string, streamId: string): void;\n /** Discards the buffer and closes the stream immediately. */\n closeStream(session: string, streamId: string): void;\n onDidProgress(listener: (progress: WidgetAudioProgress) => void): () => void;\n onDidEnded(listener: (ended: WidgetAudioEndedMessage) => void): () => void;\n}\n\nexport const widgetAudioWorkletService =\n defineRpcService<WidgetAudioWorkletService>('audio-worklet');\n\n/** Host → worklet, over the `AudioWorkletNode` port. */\nexport interface WidgetAudioControlService {\n openSession(init: WidgetAudioSessionOpen): void;\n closeSession(session: string): void;\n setSessionVolume(session: string, volume: number): void;\n setMuted(muted: boolean): void;\n suspend(): void;\n resume(): void;\n /** `port` is the guest end of the direct PCM channel; it is always transferred. */\n attachGuestPort(runtimeId: string, port: MessagePort): void;\n detachGuestPort(runtimeId: string): void;\n onDidDiagnostic(listener: (diagnostic: WidgetAudioDiagnostic) => void): () => void;\n}\n\nexport const widgetAudioControlService =\n defineRpcService<WidgetAudioControlService>('audio-control');\n\n/** Host → guest: audio availability and the direct PCM port handoff. */\nexport interface WidgetAudioGuestService {\n attachPort(port: MessagePort): void;\n setState(state: WidgetAudioState): void;\n}\n\nexport const widgetAudioGuestService = defineRpcService<WidgetAudioGuestService>('audio-guest');\n\n/** Attached to `mount` so the factory can read `api.audio.state` synchronously. */\nexport interface WidgetAudioMountInfo {\n readonly state: WidgetAudioState;\n /** One-shot token this mount generation uses on the direct port. */\n readonly session?: string;\n}\n","import workletScript from '../../guest/audio/entry.ts?audio-worklet-code';\nimport { widgetAudioWorkletProcessor } from '../../guest/audio/protocol';\n\nlet objectUrl: string | undefined;\n\n/**\n * Blob URL of the packaged `AudioWorkletProcessor` script.\n *\n * The script is bundled and minified into this module while the package is built, so an\n * `AudioContext` can load it through `addModule()` without the package publishing a separate\n * `*.worklet.js` asset. The URL is created once per page and reused by every host.\n */\nexport function widgetAudioWorkletUrl(): string {\n objectUrl ??= URL.createObjectURL(new Blob([workletScript], { type: 'text/javascript' }));\n return objectUrl;\n}\n\n/**\n * Loads the packaged processor into `context` and creates its node.\n *\n * Pass it as `WidgetAudioOptions.getAudioWorklet`; runtimes that provide no loader of their\n * own use the same processor internally.\n */\nexport async function createWidgetAudioWorklet(context: AudioContext): Promise<AudioWorkletNode> {\n if (typeof context.audioWorklet?.addModule !== 'function') {\n throw new Error('The AudioContext does not support AudioWorklet.addModule().');\n }\n await context.audioWorklet.addModule(widgetAudioWorkletUrl());\n return new AudioWorkletNode(context, widgetAudioWorkletProcessor);\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport {\n defaultMaxStreams,\n defaultMaxVoices,\n widgetAudioControlService,\n widgetAudioWorkletProcessor,\n} from '../../guest/audio/protocol';\nimport type {\n WidgetAudioControlService,\n WidgetAudioDiagnostic,\n WidgetAudioDiagnosticCode,\n WidgetAudioLimits,\n WidgetAudioMountInfo,\n WidgetAudioState,\n} from '../../guest/audio/protocol';\nimport { widgetAudioWorkletUrl } from './worklet';\n\n/** Structural stand-ins for the Web Audio nodes the engine touches; tests inject fakes. */\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): unknown;\n disconnect?(): void;\n}\n\nexport interface AudioContextLike {\n readonly sampleRate: number;\n /** `suspended` | `running` | `closed` for a real context. */\n readonly state: string;\n readonly destination: AudioNodeLike;\n readonly audioWorklet?: { addModule(url: string): Promise<void> };\n /**\n * Fired by a real context whenever the browser suspends or resumes it on its own (autoplay\n * policy, hidden page, a caller calling `suspend()` / `resume()`). Used as a fallback when the\n * context lacks `addEventListener`; fakes may leave it `null`.\n */\n onstatechange?: ((event?: unknown) => void) | null;\n /** Preferred over `onstatechange`: subscribing must not clobber the caller's own handler. */\n addEventListener?(type: 'statechange', listener: () => void): void;\n removeEventListener?(type: 'statechange', listener: () => void): void;\n}\n\nexport interface AudioWorkletNodeLike extends AudioNodeLike {\n readonly port: MessagePort;\n}\n\nexport interface MessageChannelLike {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\n/** Host-side sinks the engine reports into; the widget host owns the sandbox plumbing. */\nexport interface WidgetAudioNotifier {\n /** Hands the direct guest ↔ worklet port to the sandbox. */\n emitPort(port: MessagePort): void;\n emitState(state: WidgetAudioState): void;\n}\n\nexport interface WidgetAudioEngineOptions {\n readonly context: AudioContextLike;\n readonly destination?: AudioNodeLike;\n readonly limits?: Partial<WidgetAudioLimits>;\n readonly report: (code: WidgetAudioDiagnosticCode, instanceId: string, message: string) => void;\n readonly notify: WidgetAudioNotifier;\n /** Loads the audio worklet node; tests or applications may provide their own loader. */\n readonly loadWorklet?: () => Promise<AudioWorkletNodeLike>;\n readonly createChannel?: () => MessageChannelLike;\n readonly createWorkletNode?: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n}\n\ninterface InstanceAudio {\n readonly instanceId: string;\n readonly session: string;\n}\n\n/**\n * Host half of the audio path (RFC 0016).\n *\n * Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the\n * worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.\n * No audio node other than that worklet is created here: tones, mixing and volume all live inside\n * the worklet.\n */\nexport class WidgetAudioEngine {\n readonly #context: AudioContextLike;\n readonly #destination: AudioNodeLike;\n readonly #report: WidgetAudioEngineOptions['report'];\n readonly #notify: WidgetAudioNotifier;\n readonly #limits: WidgetAudioLimits;\n readonly #loadWorklet: (() => Promise<AudioWorkletNodeLike>) | undefined;\n readonly #createChannel: () => MessageChannelLike;\n readonly #createWorkletNode: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n readonly #runtimeId = `r${Math.random().toString(36).slice(2, 10)}`;\n readonly #instances = new Map<string, InstanceAudio>();\n #worklet: AudioWorkletNodeLike | undefined;\n #endpoint: RpcEndpoint | undefined;\n #control: RpcProxy<WidgetAudioControlService> | undefined;\n #booting: Promise<boolean> | undefined;\n #available: boolean | undefined;\n #muted = false;\n #suspended = false;\n #sessionCounter = 0;\n #disposed = false;\n #lastState: WidgetAudioState | undefined;\n #detachStateListener: (() => void) | undefined;\n /** Context state moved without an engine call; guests get the same ordered notification. */\n readonly #onContextStateChange = (): void => {\n if (this.#disposed) return;\n this.#syncState();\n };\n\n constructor(options: WidgetAudioEngineOptions) {\n this.#context = options.context;\n this.#destination = options.destination ?? options.context.destination;\n this.#report = options.report;\n this.#notify = options.notify;\n this.#limits = {\n maxVoices: Math.max(1, Math.floor(options.limits?.maxVoices ?? defaultMaxVoices)),\n maxStreams: Math.max(1, Math.floor(options.limits?.maxStreams ?? defaultMaxStreams)),\n };\n this.#loadWorklet = options.loadWorklet;\n this.#createChannel =\n options.createChannel ??\n (() => {\n const channel = new MessageChannel();\n return { port1: channel.port1, port2: channel.port2 };\n });\n this.#createWorkletNode =\n options.createWorkletNode ??\n ((context, name) => {\n const ctor = (\n globalThis as {\n AudioWorkletNode?: new (\n context: unknown,\n name: string,\n options: unknown,\n ) => AudioWorkletNodeLike;\n }\n ).AudioWorkletNode;\n if (!ctor) throw new Error('AudioWorkletNode is not available');\n return new ctor(context, name, {\n numberOfInputs: 0,\n numberOfOutputs: 1,\n outputChannelCount: [2],\n });\n });\n }\n\n /**\n * Current availability.\n *\n * `unavailable` means \"no audio at all\": the host configured none, the browser lacks\n * `AudioWorklet`, or the worklet module failed to load.\n */\n get state(): WidgetAudioState {\n if (this.#disposed || this.#available === false) return 'unavailable';\n if (this.#available !== true || this.#suspended) return 'suspended';\n return this.#context.state === 'running' ? 'running' : 'suspended';\n }\n\n /** Limits in force, so a caller can mirror them in its own UI. */\n get limits(): WidgetAudioLimits {\n return this.#limits;\n }\n\n /**\n * Opens the mount generation of one instance.\n *\n * Resolves once the worklet registered the session token, so the `mount` request that carries it\n * can never arrive after the first guest call of that generation.\n */\n async open(instanceId: string): Promise<WidgetAudioMountInfo> {\n if (this.#disposed) return { state: 'unavailable' };\n const available = await this.#boot();\n if (!available) return { state: 'unavailable' };\n\n this.close(instanceId);\n this.#sessionCounter += 1;\n const session = `${this.#runtimeId}-${this.#sessionCounter}`;\n this.#instances.set(instanceId, { instanceId, session });\n try {\n await this.#control?.openSession({\n session,\n runtimeId: this.#runtimeId,\n instanceId,\n maxVoices: this.#limits.maxVoices,\n maxStreams: this.#limits.maxStreams,\n });\n } catch (error) {\n this.#report(\n 'widget/audio-failed',\n instanceId,\n `The audio worklet rejected the session: ${describe(error)}`,\n );\n }\n this.#syncState();\n return { state: this.state, session };\n }\n\n setMuted(muted: boolean): void {\n this.#muted = muted === true;\n this.#call((control) => control.setMuted(this.#muted));\n }\n\n setInstanceVolume(instanceId: string, volume: number): void {\n if (typeof volume !== 'number') {\n throw new TypeError('WidgetAudioControls.setInstanceVolume expects a number');\n }\n if (!Number.isFinite(volume) || volume < 0 || volume > 1) {\n throw new RangeError('WidgetAudioControls.setInstanceVolume expects a value in [0, 1]');\n }\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#call((control) => control.setSessionVolume(instance.session, volume));\n }\n\n /** Freezes audio without touching the caller's `AudioContext`. */\n suspend(): void {\n if (this.#disposed || this.#suspended) return;\n this.#suspended = true;\n this.#call((control) => control.suspend());\n this.#syncState();\n }\n\n resume(): void {\n if (this.#disposed) return;\n this.#suspended = false;\n this.#call((control) => control.resume());\n this.#syncState();\n }\n\n /**\n * Closes the instance only when it still belongs to `session`.\n *\n * A mount attempt that lost its id may have opened its own audio generation after the host's\n * cleanup sweep; closing by id alone would tear down the replacement instead.\n */\n closeSession(instanceId: string, session: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance || instance.session !== session) return;\n this.close(instanceId);\n }\n\n /** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */\n close(instanceId: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#instances.delete(instanceId);\n this.#call((control) => control.closeSession(instance.session));\n }\n\n /**\n * Drops every instance and hands the worklet a fresh guest channel.\n *\n * Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs\n * a port of its own.\n */\n reset(): void {\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n if (this.#available === true && this.#control !== undefined) {\n void this.#restartRuntime();\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n // Sent before the flag flips: the worklet drops the runtime, its sessions and its guest port.\n this.#call((control) => control.detachGuestPort(this.#runtimeId));\n this.#disposed = true;\n this.#detachStateListener?.();\n this.#detachStateListener = undefined;\n this.#endpoint?.dispose();\n this.#endpoint = undefined;\n this.#control = undefined;\n const worklet = this.#worklet;\n this.#worklet = undefined;\n if (worklet !== undefined) {\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n }\n }\n\n /** Boots the worklet once; a failure is permanent for the lifetime of the engine. */\n #boot(): Promise<boolean> {\n this.#booting ??= this.#start().catch((error: unknown) => {\n this.#available = false;\n // A load that fails after `dispose()` is not a widget problem and has no live host to hear it.\n if (!this.#disposed) {\n this.#report('widget/audio-failed', '', `Widget audio is unavailable: ${describe(error)}`);\n }\n return false;\n });\n return this.#booting;\n }\n\n async #start(): Promise<boolean> {\n if (\n this.#loadWorklet === undefined &&\n typeof this.#context.audioWorklet?.addModule !== 'function'\n ) {\n this.#available = false;\n return false;\n }\n\n this.#listenForContextState();\n const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());\n if (this.#disposed) {\n // `dispose()` ran while the module was loading: release the node instead of wiring it up.\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n return false;\n }\n this.#worklet = worklet;\n const endpoint = createRpc(worklet.port);\n this.#endpoint = endpoint;\n const control = endpoint.getProxy(widgetAudioControlService, {\n transfer: (member, args) => (member === 'attachGuestPort' ? [args[1] as MessagePort] : []),\n });\n this.#control = control;\n control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));\n worklet.connect(this.#destination);\n await this.#attachRuntime();\n if (this.#suspended) await control.suspend();\n this.#available = true;\n return true;\n }\n\n /**\n * Mirrors the context's own `statechange` onto mounted guests.\n *\n * The caller owns the `AudioContext`, so its state can move without the engine asking: autoplay\n * policy keeping it suspended, the browser suspending a hidden page, or the caller calling\n * `resume()`. Guests read `api.audio.state` and `onStateChange`, so those moves must be forwarded.\n */\n #listenForContextState(): void {\n if (this.#detachStateListener) return;\n const context = this.#context;\n if (typeof context.addEventListener === 'function') {\n context.addEventListener('statechange', this.#onContextStateChange);\n this.#detachStateListener = () =>\n context.removeEventListener?.('statechange', this.#onContextStateChange);\n return;\n }\n if (!('onstatechange' in context)) return;\n // Contexts that only expose the handler property keep the caller's value for `dispose()`.\n const previous = context.onstatechange;\n context.onstatechange = this.#onContextStateChange;\n this.#detachStateListener = () => {\n if (context.onstatechange === this.#onContextStateChange) context.onstatechange = previous;\n };\n }\n\n /** Worklet → host diagnostics, attributed back to the instance that owns the session. */\n #onDiagnostic(diagnostic: WidgetAudioDiagnostic): void {\n const owner = [...this.#instances.values()].find(\n (entry) => entry.session === diagnostic.session,\n );\n // A revoked token means the message is late; the RFC drops it instead of raising diagnostics.\n if (!owner) return;\n this.#report(diagnostic.code, owner.instanceId, diagnostic.message);\n }\n\n async #loadDefaultWorklet(): Promise<AudioWorkletNodeLike> {\n await this.#context.audioWorklet?.addModule(widgetAudioWorkletUrl());\n return this.#createWorkletNode(this.#context, widgetAudioWorkletProcessor);\n }\n\n async #restartRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined) return;\n try {\n await control.detachGuestPort(this.#runtimeId);\n } catch {\n // The worklet already forgot the runtime; a new channel follows anyway.\n }\n await this.#attachRuntime();\n }\n\n /** Transfers a fresh port to the worklet and hands the other end to the guest. */\n async #attachRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n const channel = this.#createChannel();\n try {\n await control.attachGuestPort(this.#runtimeId, channel.port1);\n } catch (error) {\n closePort(channel.port1);\n closePort(channel.port2);\n this.#report(\n 'widget/audio-failed',\n '',\n `The audio worklet rejected the guest port: ${describe(error)}`,\n );\n return;\n }\n this.#notify.emitPort(channel.port2);\n }\n\n /** Fires one host → worklet call; a missing or closed worklet is not a widget failure. */\n #call(run: (control: RpcProxy<WidgetAudioControlService>) => Promise<unknown>): void {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n try {\n void run(control).catch(() => undefined);\n } catch {\n // The endpoint is already closed.\n }\n }\n\n #syncState(): void {\n const next = this.state;\n if (next === this.#lastState) return;\n this.#lastState = next;\n this.#notify.emitState(next);\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describe(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n","import type { WidgetAudioState } from '../../guest/audio/protocol';\nimport type { WidgetAudioControls } from './types';\n\n/**\n * Controls of a host that was created without `audio`.\n *\n * The state is `unavailable` and every setter is a no-op, so callers never have to branch on\n * whether audio is configured.\n */\nexport const NO_AUDIO_CONTROLS: WidgetAudioControls = {\n state: 'unavailable' as WidgetAudioState,\n setMuted(): void {},\n setInstanceVolume(): void {},\n suspend(): void {},\n resume(): void {},\n};\n","/** Rejections the widget runtime produces before or around the guest boundary. */\nexport type WidgetRuntimeErrorCode =\n | 'widget/disposed'\n | 'widget/instance-exists'\n | 'widget/unknown-instance'\n | 'widget/unknown-port'\n | 'widget/invalid-instance'\n | 'widget/invalid-update'\n | 'widget/invalid-payload'\n | 'widget/invalid-direction'\n | 'widget/invalid-time'\n | 'widget/invalid-step'\n | 'widget/sandbox-failed';\n\n/**\n * Typed rejection of one runtime call.\n *\n * Widget boundary failures (render, input, publish) become diagnostics instead; errors with this\n * type mean the caller asked for something the runtime cannot do.\n */\nexport class WidgetRuntimeError extends Error {\n readonly code: WidgetRuntimeErrorCode;\n\n constructor(code: WidgetRuntimeErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WidgetRuntimeError';\n this.code = code;\n }\n}\n","import { timePs } from '@mica-js/core';\nimport type { TimePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { CanvasBindingTarget, PayloadType } from '@mica-js/document/canvas';\nimport type { WidgetAudioMountInfo } from '../guest/audio/protocol';\nimport { mergeProperties } from '../guest/widget/props';\nimport {\n widgetAssetFailedEvent,\n widgetConfigureMethod,\n widgetDeliverMethod,\n widgetErrorEvent,\n widgetFrameEvent,\n widgetLoadMethod,\n widgetMountMethod,\n widgetPointerMethod,\n widgetPublishEvent,\n widgetResizeMethod,\n widgetSetAssetsMethod,\n widgetSetBindingsMethod,\n widgetSetPropertiesMethod,\n widgetStepMethod,\n widgetUnmountMethod,\n} from '../guest/widget/protocol';\nimport type {\n WidgetAssetFailedMessage,\n WidgetErrorMessage,\n WidgetFrameMessage,\n WidgetPublishMessage,\n} from '../guest/widget/protocol';\nimport type { WidgetInputEvent } from '../guest/widget/types';\nimport { WidgetAudioEngine } from '../host/audio/engine';\nimport type {\n AudioContextLike,\n AudioNodeLike,\n AudioWorkletNodeLike,\n WidgetAudioEngineOptions,\n} from '../host/audio/engine';\nimport { NO_AUDIO_CONTROLS } from '../host/audio/noop';\nimport type { WidgetAudioControls, WidgetAudioOptions } from '../host/audio/types';\nimport type { WidgetSandbox } from '../host/types';\nimport type { WidgetModule } from '../types';\nimport { WidgetRuntimeError } from './errors';\nimport type {\n IPreparedWidgetInstance,\n IWidgetFrame,\n IWidgetFrameContext,\n IWidgetInstanceUpdate,\n IWidgetMessage,\n IWidgetRuntime,\n IWidgetRuntimeDiagnostic,\n IWidgetRuntimeDiagnosticCode,\n IWidgetRuntimeDiagnosticPhase,\n IWidgetRuntimeOptions,\n} from './types';\n\ninterface IRuntimeInstance {\n readonly instanceId: string;\n readonly widget: string;\n readonly module: WidgetModule;\n readonly generation: number;\n width: number;\n height: number;\n dpr: number;\n bitmap: ImageBitmap | undefined;\n sequence: number;\n mounted: boolean;\n audioSession: string | undefined;\n}\n\n/** One deliver or pointer call accepted by `deliver` / `dispatch`, waiting for the next step. */\ninterface IPendingCall {\n readonly instanceId: string;\n readonly method: string;\n readonly args: readonly unknown[];\n}\n\n/**\n * Creates the widget runtime over an existing sandbox.\n *\n * The runtime owns the sandbox: `dispose()` terminates it, so the caller must not keep using it\n * afterwards. The runtime never reads documents or files, resolves widget modules, drives a clock\n * or talks to a device runtime; those stay with the editor that calls it.\n */\nexport function createWidgetRuntime(\n sandbox: WidgetSandbox,\n options: IWidgetRuntimeOptions = {},\n): IWidgetRuntime {\n return new WidgetRuntimeImpl(sandbox, options);\n}\n\nclass WidgetRuntimeImpl implements IWidgetRuntime {\n readonly #sandbox: WidgetSandbox;\n readonly #engine: WidgetAudioEngine | undefined;\n readonly #instances = new Map<string, IRuntimeInstance>();\n readonly #pending: IPendingCall[] = [];\n readonly #published = new Emitter<IWidgetMessage>();\n readonly #rendered = new Emitter<IWidgetFrame>();\n readonly #diagnostics = new Emitter<IWidgetRuntimeDiagnostic>();\n readonly #unsubscribers: (() => void)[] = [];\n\n readonly onDidPublish: Event<IWidgetMessage> = this.#published.event;\n readonly onDidRender: Event<IWidgetFrame> = this.#rendered.event;\n readonly onDidDiagnostic: Event<IWidgetRuntimeDiagnostic> = this.#diagnostics.event;\n readonly audio: WidgetAudioControls;\n\n /** Serializes mount, update, unmount, setBindings and step; a failure never poisons the chain. */\n #tail: Promise<void> = Promise.resolve();\n #configured: Promise<boolean> | undefined;\n #simTime: TimePs = timePs(0);\n #generation = 0;\n #disposed = false;\n #disposal: Promise<void> | undefined;\n\n constructor(sandbox: WidgetSandbox, options: IWidgetRuntimeOptions) {\n this.#sandbox = sandbox;\n\n const audioOptions: WidgetAudioOptions | undefined = options.audio;\n if (audioOptions === undefined) {\n this.audio = NO_AUDIO_CONTROLS;\n } else {\n const context = audioOptions.context;\n const getAudioWorklet = audioOptions.getAudioWorklet;\n const engineOptions: WidgetAudioEngineOptions = {\n context: context as unknown as AudioContextLike,\n ...(audioOptions.destination === undefined\n ? {}\n : { destination: audioOptions.destination as unknown as AudioNodeLike }),\n ...(getAudioWorklet === undefined\n ? {}\n : {\n loadWorklet: () => getAudioWorklet(context) as Promise<AudioWorkletNodeLike>,\n }),\n ...(audioOptions.limits === undefined ? {} : { limits: audioOptions.limits }),\n report: (code, instanceId, message) =>\n this.#report(code, 'audio', message, instanceId === '' ? {} : { instanceId }),\n notify: {\n emitPort: (port) => {\n const lane = sandbox.audio;\n if (lane === undefined) {\n closePort(port);\n return;\n }\n try {\n lane.attachPort(port);\n } catch {\n closePort(port);\n }\n },\n emitState: (state) => {\n try {\n sandbox.audio?.setState(state);\n } catch {\n // The sandbox is already gone; its guest state no longer matters.\n }\n },\n },\n };\n const engine = new WidgetAudioEngine(engineOptions);\n this.#engine = engine;\n this.audio = engine;\n }\n\n this.#unsubscribers.push(\n sandbox.on(widgetFrameEvent, (payload) => this.#onFrame(payload)),\n sandbox.on(widgetPublishEvent, (payload) => this.#onPublish(payload)),\n sandbox.on(widgetErrorEvent, (payload) => this.#onError(payload)),\n sandbox.on(widgetAssetFailedEvent, (payload) => this.#onAssetFailed(payload)),\n );\n }\n\n mount(instance: IPreparedWidgetInstance): Promise<void> {\n return this.#run(async () => {\n const prepared = normalizePrepared(instance);\n this.#assertActive();\n if (this.#instances.has(prepared.instanceId)) {\n throw new WidgetRuntimeError(\n 'widget/instance-exists',\n `Widget instance \"${prepared.instanceId}\" is already mounted.`,\n );\n }\n const ref = splitRef(prepared.widget);\n if (ref === undefined) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `Widget reference \"${prepared.widget}\" must use the \"<package>:<widget>\" form.`,\n );\n }\n\n await this.#configure();\n this.#assertActive();\n\n const record: IRuntimeInstance = {\n instanceId: prepared.instanceId,\n widget: prepared.widget,\n module: prepared.module,\n generation: ++this.#generation,\n width: prepared.width,\n height: prepared.height,\n dpr: prepared.dpr,\n bitmap: undefined,\n sequence: 0,\n mounted: false,\n audioSession: undefined,\n };\n this.#instances.set(record.instanceId, record);\n\n try {\n await this.#sandbox.call(widgetLoadMethod, {\n packages: [\n {\n id: ref.packageId,\n modules: {\n [ref.widgetId]: {\n definition: prepared.module.definition,\n code: prepared.module.code,\n },\n },\n },\n ],\n });\n this.#assertOwnership(record);\n\n const audio = await this.#openAudio(record);\n this.#assertOwnership(record);\n\n const properties = mergeProperties(\n prepared.module.definition.properties,\n prepared.properties,\n );\n await this.#sandbox.call(widgetMountMethod, {\n instanceId: record.instanceId,\n widget: record.widget,\n width: record.width,\n height: record.height,\n dpr: record.dpr,\n props: properties,\n ...(prepared.assets === undefined ? {} : { assets: prepared.assets }),\n generation: record.generation,\n audio,\n });\n this.#assertOwnership(record);\n record.mounted = true;\n } catch (error) {\n this.#forget(record);\n await this.#releaseGuest(record.instanceId);\n if (record.audioSession !== undefined) {\n this.#engine?.closeSession(record.instanceId, record.audioSession);\n }\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Mount of widget instance \"${prepared.instanceId}\" was cancelled before it finished.`,\n );\n }\n if (this.#sandbox.state === 'terminated') {\n this.#report(\n 'widget/runtime-failed',\n 'runtime',\n 'The widget sandbox terminated during mount.',\n );\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n 'The widget sandbox terminated during mount.',\n { cause: error },\n );\n }\n this.#report(\n 'widget/mount-failed',\n 'mount',\n `Widget \"${prepared.widget}\" failed to mount: ${describeError(error)}`,\n { instanceId: prepared.instanceId, widget: prepared.widget },\n );\n throw error instanceof WidgetRuntimeError\n ? error\n : new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget \"${prepared.widget}\" failed to mount: ${describeError(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n update(instanceId: string, update: IWidgetInstanceUpdate): Promise<void> {\n return this.#run(async () => {\n requireId(instanceId);\n this.#assertActive();\n const record = this.#requireMounted(instanceId);\n\n if (update.width !== undefined || update.height !== undefined || update.dpr !== undefined) {\n const width =\n update.width === undefined ? record.width : requireSize(update.width, 'width');\n const height =\n update.height === undefined ? record.height : requireSize(update.height, 'height');\n const dpr = update.dpr === undefined ? record.dpr : requireDpr(update.dpr);\n await this.#call(\n widgetResizeMethod,\n [instanceId, width, height, dpr],\n record,\n 'widget/update-failed',\n 'update',\n );\n record.width = width;\n record.height = height;\n record.dpr = dpr;\n }\n\n if (update.properties !== undefined) {\n const properties = mergeProperties(record.module.definition.properties, update.properties);\n await this.#call(\n widgetSetPropertiesMethod,\n [instanceId, properties],\n record,\n 'widget/update-failed',\n 'update',\n );\n }\n\n if (update.assets !== undefined) {\n await this.#call(\n widgetSetAssetsMethod,\n [instanceId, update.assets],\n record,\n 'widget/update-failed',\n 'update',\n );\n }\n });\n }\n\n unmount(instanceId: string): Promise<void> {\n return this.#run(async () => {\n requireId(instanceId);\n // Disposal already cleared every instance and terminated the sandbox.\n if (this.#disposed) return;\n const record = this.#instances.get(instanceId);\n if (record === undefined) return;\n\n this.#instances.delete(instanceId);\n this.#closeRecord(record);\n for (let index = this.#pending.length - 1; index >= 0; index -= 1) {\n if (this.#pending[index]?.instanceId === instanceId) this.#pending.splice(index, 1);\n }\n if (record.audioSession !== undefined) {\n this.#engine?.closeSession(instanceId, record.audioSession);\n }\n try {\n await this.#sandbox.call(widgetUnmountMethod, instanceId);\n } catch (error) {\n this.#report(\n 'widget/unmount-failed',\n 'unmount',\n `Widget instance \"${instanceId}\" could not be released: ${describeError(error)}`,\n { instanceId, widget: record.widget },\n );\n }\n });\n }\n\n deliver(message: IWidgetMessage): Promise<void> {\n try {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n const record = this.#requireMounted(message.instanceId);\n const port = record.module.definition.ports[message.port];\n if (port === undefined) {\n throw new WidgetRuntimeError(\n 'widget/unknown-port',\n `Widget instance \"${message.instanceId}\" has no port ${JSON.stringify(message.port)}.`,\n );\n }\n if (port.direction !== 'input') {\n throw new WidgetRuntimeError(\n 'widget/invalid-direction',\n `Port \"${message.port}\" of \"${message.instanceId}\" is an output.`,\n );\n }\n if (!payloadMatches(port.type, message.payload)) {\n throw new WidgetRuntimeError(\n 'widget/invalid-payload',\n `Payload for \"${message.instanceId}.${message.port}\" does not match ${port.type}.`,\n );\n }\n const simTime = requireTime(message.simTime, 'simTime');\n this.#pending.push({\n instanceId: message.instanceId,\n method: widgetDeliverMethod,\n args: [message.instanceId, message.port, message.payload, simTime],\n });\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n dispatch(instanceId: string, event: WidgetInputEvent): Promise<void> {\n try {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n this.#requireMounted(instanceId);\n if (\n typeof event !== 'object' ||\n event === null ||\n typeof event.type !== 'string' ||\n event.type === ''\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-payload',\n 'A widget input event needs a nonempty type.',\n );\n }\n this.#pending.push({\n instanceId,\n method: widgetPointerMethod,\n args: [instanceId, event],\n });\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n step(context: IWidgetFrameContext): Promise<void> {\n return this.#run(async () => {\n this.#assertActive();\n const simTime = requireTime(context.simTime, 'simTime');\n const dt = requireTime(context.dt, 'dt');\n if (context.mode !== 'edit' && context.mode !== 'simulation') {\n throw new WidgetRuntimeError(\n 'widget/invalid-step',\n `Unknown widget step mode: ${String(context.mode)}.`,\n );\n }\n\n await this.#configure();\n this.#assertActive();\n\n for (const call of this.#pending.splice(0)) {\n const record = this.#instances.get(call.instanceId);\n if (record === undefined || !record.mounted) {\n this.#report(\n 'widget/deliver-failed',\n 'deliver',\n `Queued ${call.method} for \"${call.instanceId}\" was dropped: the instance is not mounted.`,\n { instanceId: call.instanceId },\n );\n continue;\n }\n try {\n await this.#sandbox.call(call.method, ...call.args);\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n 'Widget step was cancelled by runtime disposal.',\n );\n }\n this.#report(\n 'widget/deliver-failed',\n 'deliver',\n `Widget call \"${call.method}\" failed for \"${call.instanceId}\": ${describeError(error)}`,\n { instanceId: call.instanceId, widget: record.widget },\n );\n }\n }\n\n this.#simTime = simTime;\n try {\n await this.#sandbox.call(widgetStepMethod, { simTime, dt, mode: context.mode });\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n 'Widget step was cancelled by runtime disposal.',\n );\n }\n this.#report('widget/step-failed', 'step', `Widget step failed: ${describeError(error)}`);\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget step failed: ${describeError(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n setBindings(\n instanceId: string,\n bindings: Readonly<Record<string, CanvasBindingTarget>>,\n ): Promise<void> {\n return this.#run(async () => {\n const normalized = normalizeBindings(bindings);\n requireId(instanceId);\n this.#assertActive();\n const record = this.#requireMounted(instanceId);\n await this.#call(\n widgetSetBindingsMethod,\n [instanceId, normalized],\n record,\n 'widget/update-failed',\n 'update',\n );\n });\n }\n\n dispose(): Promise<void> {\n if (this.#disposal !== undefined) return this.#disposal;\n this.#disposed = true;\n this.#pending.length = 0;\n // Terminating now is what cancels a mount that is still waiting for the guest: its pending\n // calls reject, the operation cleans up its own record, and the queued shutdown then runs.\n const terminating = terminateSandbox(this.#sandbox);\n this.#disposal = this.#run(async () => {\n const records = [...this.#instances.values()];\n this.#instances.clear();\n for (const record of records) this.#closeRecord(record);\n for (const unsubscribe of this.#unsubscribers.splice(0)) {\n try {\n unsubscribe();\n } catch {\n // The sandbox may already be gone.\n }\n }\n this.#engine?.dispose();\n await terminating;\n this.#published.dispose();\n this.#rendered.dispose();\n this.#diagnostics.dispose();\n });\n return this.#disposal;\n }\n\n /** Runs one operation after the previous one, whether it resolved or rejected. */\n #run<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.#tail.then(operation, operation);\n this.#tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n #assertActive(): void {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n if (this.#sandbox.state === 'terminated') {\n throw new WidgetRuntimeError('widget/sandbox-failed', 'The widget sandbox is terminated.');\n }\n }\n\n #assertOwnership(record: IRuntimeInstance): void {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Mount of widget instance \"${record.instanceId}\" was cancelled before it finished.`,\n );\n }\n if (this.#instances.get(record.instanceId) !== record) {\n throw new WidgetRuntimeError(\n 'widget/unknown-instance',\n `Widget instance \"${record.instanceId}\" was replaced during mount.`,\n );\n }\n }\n\n #requireMounted(instanceId: string): IRuntimeInstance {\n const record = this.#instances.get(instanceId);\n if (record === undefined || !record.mounted) {\n throw new WidgetRuntimeError(\n 'widget/unknown-instance',\n `Widget instance \"${instanceId}\" is not mounted.`,\n );\n }\n return record;\n }\n\n #configure(): Promise<boolean> {\n const existing = this.#configured;\n if (existing !== undefined) return existing;\n\n const pending = this.#sandbox\n .call(widgetConfigureMethod, {\n explicitStepping: true,\n directTopicService: 'simulation-runtime',\n })\n .then((result) => result === true)\n .catch((error: unknown) => {\n this.#configured = undefined;\n const message = `Widget guest configuration failed: ${describeError(error)}`;\n this.#report('widget/runtime-failed', 'runtime', message);\n throw new WidgetRuntimeError('widget/sandbox-failed', message, { cause: error });\n });\n this.#configured = pending;\n return pending;\n }\n\n async #openAudio(record: IRuntimeInstance): Promise<WidgetAudioMountInfo> {\n const engine = this.#engine;\n if (engine === undefined) return { state: 'unavailable' };\n const info = await engine.open(record.instanceId);\n if (info.session !== undefined) record.audioSession = info.session;\n return info;\n }\n\n async #call(\n method: string,\n args: readonly unknown[],\n record: IRuntimeInstance,\n code: IWidgetRuntimeDiagnosticCode,\n phase: IWidgetRuntimeDiagnosticPhase,\n ): Promise<void> {\n try {\n await this.#sandbox.call(method, ...args);\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Widget call \"${method}\" was cancelled by runtime disposal.`,\n );\n }\n this.#report(\n code,\n phase,\n `Widget call \"${method}\" failed for \"${record.instanceId}\": ${describeError(error)}`,\n { instanceId: record.instanceId, widget: record.widget },\n );\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget call \"${method}\" failed for \"${record.instanceId}\": ${describeError(error)}`,\n { cause: error },\n );\n }\n }\n\n #forget(record: IRuntimeInstance): void {\n if (this.#instances.get(record.instanceId) === record) {\n this.#instances.delete(record.instanceId);\n }\n this.#closeRecord(record);\n }\n\n #closeRecord(record: IRuntimeInstance): void {\n const bitmap = record.bitmap;\n record.bitmap = undefined;\n closeBitmap(bitmap);\n }\n\n async #releaseGuest(instanceId: string): Promise<void> {\n try {\n await this.#sandbox.call(widgetUnmountMethod, instanceId);\n } catch {\n // The guest never created the instance, or the sandbox is already gone.\n }\n }\n\n #onFrame(payload: unknown): void {\n const message = payload as Partial<WidgetFrameMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n const { instanceId, bitmap } = message;\n if (typeof instanceId !== 'string' || !isBitmap(bitmap)) return;\n if (this.#disposed) {\n closeBitmap(bitmap);\n return;\n }\n\n const record = this.#instances.get(instanceId);\n if (\n record === undefined ||\n (message.generation !== undefined && message.generation !== record.generation)\n ) {\n // A frame of an unmounted instance, or of the instance that used to own this id.\n closeBitmap(bitmap);\n return;\n }\n\n const width = frameNumber(message.width, record.width);\n const height = frameNumber(message.height, record.height);\n const dpr = frameNumber(message.dpr, record.dpr);\n const previous = record.bitmap;\n record.bitmap = bitmap;\n record.width = width;\n record.height = height;\n record.dpr = dpr;\n record.sequence += 1;\n closeBitmap(previous);\n\n this.#fire(this.#rendered, 'render', {\n instanceId,\n width,\n height,\n dpr,\n bitmap,\n sequence: record.sequence,\n });\n }\n\n #onPublish(payload: unknown): void {\n const message = payload as Partial<WidgetPublishMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n const { instanceId, port } = message;\n if (typeof instanceId !== 'string' || typeof port !== 'string') return;\n if (this.#disposed) return;\n\n const record = this.#instances.get(instanceId);\n if (record === undefined) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Publish from unknown widget instance \"${instanceId}\" was dropped.`,\n { instanceId, port },\n );\n return;\n }\n const definitionPort = record.module.definition.ports[port];\n if (definitionPort === undefined) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Widget \"${instanceId}\" published on unknown port \"${port}\".`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n if (definitionPort.direction !== 'output') {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Widget \"${instanceId}\" published on input port \"${port}\".`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n if (!payloadMatches(definitionPort.type, message.payload)) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Publish on \"${instanceId}.${port}\" does not match ${definitionPort.type}.`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n\n this.#fire(this.#published, 'publish', {\n instanceId,\n port,\n payload: message.payload,\n simTime: publishTime(message.simTime, this.#simTime),\n ...(message.direct === true ? { direct: true as const } : {}),\n });\n }\n\n #onError(payload: unknown): void {\n const message = payload as Partial<WidgetErrorMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n // A mount failure travels back through the rejected `mount()` call instead.\n if (message.phase !== 'render' && message.phase !== 'deliver') return;\n\n const record = this.#instances.get(message.instanceId);\n const code: IWidgetRuntimeDiagnosticCode =\n message.phase === 'render' ? 'widget/render-failed' : 'widget/deliver-failed';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown widget failure';\n this.#report(\n code,\n message.phase,\n `Widget \"${message.instanceId}\" failed during ${message.phase}: ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n ...(record === undefined ? {} : { widget: record.widget }),\n },\n );\n }\n\n #onAssetFailed(payload: unknown): void {\n const message = payload as Partial<WidgetAssetFailedMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n\n const src = typeof message.src === 'string' ? message.src : 'unknown';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown asset failure';\n const record = this.#instances.get(message.instanceId);\n this.#report(\n 'widget/asset-failed',\n 'asset',\n `Widget \"${message.instanceId}\" could not read asset \"${src}\": ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n ...(record === undefined ? {} : { widget: record.widget }),\n },\n );\n }\n\n #report(\n code: IWidgetRuntimeDiagnosticCode,\n phase: IWidgetRuntimeDiagnosticPhase,\n message: string,\n ids: {\n readonly instanceId?: string;\n readonly widget?: string;\n readonly port?: string;\n } = {},\n ): void {\n if (this.#disposed) return;\n const diagnostic: IWidgetRuntimeDiagnostic = {\n code,\n message,\n phase,\n ...(ids.instanceId === undefined ? {} : { instanceId: ids.instanceId }),\n ...(ids.widget === undefined ? {} : { widget: ids.widget }),\n ...(ids.port === undefined ? {} : { port: ids.port }),\n };\n this.#fire(this.#diagnostics, 'diagnostic', diagnostic);\n }\n\n /** Observer exceptions never break the instance flow a diagnostic or frame reports. */\n #fire<T>(emitter: Emitter<T>, label: string, value: T): void {\n try {\n emitter.fire(value);\n } catch (error) {\n console.error(`[@mica-js/widget] ${label} listener threw`, error);\n }\n }\n}\n\nfunction normalizePrepared(instance: IPreparedWidgetInstance): IPreparedWidgetInstance {\n if (typeof instance !== 'object' || instance === null) {\n throw new WidgetRuntimeError('widget/invalid-instance', 'A prepared widget is required.');\n }\n requireId(instance.instanceId);\n if (typeof instance.widget !== 'string' || !instance.widget.includes(':')) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n 'A prepared widget needs a \"<package>:<widget>\" reference.',\n );\n }\n const module = instance.module;\n if (\n typeof module !== 'object' ||\n module === null ||\n typeof module.code !== 'string' ||\n typeof module.definition !== 'object' ||\n module.definition === null ||\n typeof module.definition.ports !== 'object' ||\n module.definition.ports === null\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `Widget \"${instance.widget}\" has no complete module.`,\n );\n }\n return {\n instanceId: instance.instanceId,\n widget: instance.widget,\n module,\n width: requireSize(instance.width, 'width'),\n height: requireSize(instance.height, 'height'),\n dpr: requireDpr(instance.dpr),\n ...(instance.properties === undefined ? {} : { properties: instance.properties }),\n ...(instance.assets === undefined ? {} : { assets: instance.assets }),\n };\n}\n\nfunction requireId(value: unknown): string {\n if (typeof value !== 'string' || value === '') {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n 'A widget instance id must be a nonempty string.',\n );\n }\n return value;\n}\n\nfunction requireSize(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `${name}=${String(value)} must be a finite nonnegative number.`,\n );\n }\n return value;\n}\n\nfunction requireDpr(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `dpr=${String(value)} must be a finite positive number.`,\n );\n }\n return value;\n}\n\nfunction requireTime(value: unknown, name: string): TimePs {\n try {\n return timePs(value as number);\n } catch (error) {\n throw new WidgetRuntimeError(\n 'widget/invalid-time',\n `${name} must be a valid time in picoseconds: ${describeError(error)}`,\n { cause: error },\n );\n }\n}\n\nfunction publishTime(value: unknown, fallback: TimePs): TimePs {\n if (typeof value !== 'number') return fallback;\n try {\n return timePs(value);\n } catch {\n return fallback;\n }\n}\n\nfunction frameNumber(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;\n}\n\nfunction normalizeBindings(\n value: Readonly<Record<string, CanvasBindingTarget>>,\n): Readonly<Record<string, CanvasBindingTarget>> {\n if (typeof value !== 'object' || value === null) {\n throw new WidgetRuntimeError('widget/invalid-update', 'Bindings must be an object.');\n }\n const bindings: Record<string, CanvasBindingTarget> = {};\n for (const [port, target] of Object.entries(value)) {\n if (\n typeof target !== 'object' ||\n target === null ||\n typeof target.symbol !== 'string' ||\n target.symbol === '' ||\n typeof target.port !== 'string' ||\n target.port === ''\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-update',\n `Binding \"${port}\" needs a nonempty symbol and port.`,\n );\n }\n bindings[port] = { symbol: target.symbol, port: target.port };\n }\n return Object.freeze(bindings);\n}\n\nfunction splitRef(ref: string): { packageId: string; widgetId: string } | undefined {\n const separator = ref.indexOf(':');\n if (separator <= 0 || separator === ref.length - 1) return undefined;\n return { packageId: ref.slice(0, separator), widgetId: ref.slice(separator + 1) };\n}\n\nfunction isBitmap(value: unknown): value is ImageBitmap {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ImageBitmap).close === 'function'\n );\n}\n\nfunction isVec2d(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const point = value as { readonly x?: unknown; readonly y?: unknown };\n return typeof point.x === 'number' && typeof point.y === 'number';\n}\n\n/** Mirrors the shared value model: a payload must match the declared port type exactly. */\nfunction payloadMatches(type: PayloadType, payload: unknown): boolean {\n switch (type) {\n case 'boolean':\n return typeof payload === 'boolean';\n case 'number':\n return typeof payload === 'number';\n case 'string':\n return typeof payload === 'string';\n case 'bytes':\n case 'bytes<rgb565>':\n case 'bytes<segments>':\n return payload instanceof Uint8Array;\n case 'vec2d':\n return isVec2d(payload);\n case 'vec3d':\n return isVec2d(payload) && typeof (payload as { readonly z?: unknown }).z === 'number';\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap | undefined): void {\n if (bitmap === undefined) return;\n try {\n bitmap.close();\n } catch {\n // Already detached.\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describeError(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n\nasync function terminateSandbox(sandbox: WidgetSandbox): Promise<void> {\n try {\n await sandbox.terminate('widget runtime disposed');\n } catch {\n // Already terminated.\n }\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport { isHostFsError, toHostFsErrorPayload } from '../host-fs/errors';\nimport { widgetAudioGuestService } from '../guest/audio/protocol';\nimport {\n widgetGuestControlService,\n widgetGuestService,\n widgetHostCapabilitiesService,\n widgetHostControlService,\n} from '../guest/widget/protocol';\nimport type { SandboxWorker } from '@mica-js/sandbox';\nimport type { WidgetSandbox, WidgetSandboxHostOptions } from './types';\n\n/** Adapts a provider-created widget worker to the runtime's RPC-facing surface. */\nexport async function createWidgetSandboxFromWorker(\n worker: SandboxWorker,\n options: WidgetSandboxHostOptions,\n): Promise<WidgetSandbox> {\n const devicePort = options.devicePort;\n let port: MessagePort;\n let rpc: ReturnType<typeof createRpc> | undefined;\n let logRegistration: { dispose(): void } | undefined;\n try {\n await worker.ready;\n const channel = new MessageChannel();\n port = channel.port1;\n const endpoint = createRpc(port);\n rpc = endpoint;\n logRegistration = endpoint.register(loggerService, {\n write(record) {\n const method = console[record.level] ?? console.log;\n method.call(console, `[${record.scope}]`, record.message, ...record.data);\n },\n });\n const transfer = devicePort === undefined ? [channel.port2] : [channel.port2, devicePort];\n worker.postMessage(null, transfer);\n } catch (error) {\n logRegistration?.dispose();\n rpc?.dispose();\n await worker.terminate('widget sandbox failed to start').catch(() => undefined);\n throw error;\n }\n const endpoint = rpc;\n if (endpoint === undefined) {\n throw new Error('Widget RPC endpoint was not created.');\n }\n const listeners = new Map<string, Set<(payload: unknown) => void>>();\n const dispatch = (type: string, payload: unknown) => {\n for (const listener of [...(listeners.get(type) ?? [])]) listener(payload);\n };\n endpoint.register(\n widgetHostCapabilitiesService,\n {\n async read(uri: string) {\n if (!options.fs) throw new Error(`No HostFs configured for ${uri}`);\n try {\n return await options.fs.read(uri);\n } catch (error) {\n if (isHostFsError(error)) {\n const payload = toHostFsErrorPayload(error);\n throw Object.assign(new Error(JSON.stringify(payload)), { name: 'HostFsError' });\n }\n throw error;\n }\n },\n },\n {\n transfer: (member, value) =>\n member === 'read' && value instanceof Uint8Array ? [value.buffer] : [],\n },\n );\n endpoint.register(widgetHostControlService, { event: dispatch });\n const guest = endpoint.getProxy(widgetGuestService) as unknown as Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n >;\n const audio = endpoint.getProxy(widgetAudioGuestService, {\n transfer: (member, args) => (member === 'attachPort' ? [args[0] as MessagePort] : []),\n });\n return {\n get state() {\n return worker.state;\n },\n directDevice: devicePort !== undefined,\n call: (method, ...args) => guest[method]!(...args),\n on: (type, listener) => {\n let set = listeners.get(type);\n if (!set) listeners.set(type, (set = new Set()));\n set.add(listener);\n return () => set?.delete(listener);\n },\n emit: (type, payload, transfer) => {\n void endpoint\n .getProxy(widgetGuestControlService, { transfer: () => transfer ?? [] })\n .dispatchEvent(type, payload)\n .catch(() => undefined);\n },\n audio: {\n attachPort: (port) => {\n void audio.attachPort(port).catch(() => undefined);\n },\n setState: (state) => {\n void audio.setState(state).catch(() => undefined);\n },\n },\n terminate: async (reason) => {\n logRegistration?.dispose();\n endpoint.dispose();\n await worker.terminate(reason);\n },\n } satisfies WidgetSandbox;\n}\n","import { SandboxWorker } from '@mica-js/sandbox';\nimport type { SandboxWorkerOptions } from '@mica-js/sandbox';\nimport guestScript from '../guest/widget/entry.ts?sandbox-worker-code';\n\n/**\n * The widget guest worker script, bundled and minified into this module by\n * `@mica-js/sandbox/vite` while the package itself is built.\n *\n * It is a classic script: every dependency is inlined, so the sandbox can run it without a module\n * loader and the package publishes no separate `*.sandbox.js` file.\n */\nexport const widgetGuestScript: string = guestScript;\n\n/**\n * Creates the widget host guest worker.\n *\n * Hosts start the guest, then wire its RPC surface with `createWidgetSandboxFromWorker`.\n */\nexport function createWidgetHostGuestSandbox(options: SandboxWorkerOptions = {}): SandboxWorker {\n return new SandboxWorker(widgetGuestScript, { name: 'widget', ...options });\n}\n"],"mappings":";;;;;;;;AAmBA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CACA;CAEA,YAAY,MAA2B,SAAiB,UAAkC,CAAC,GAAG;EAC5F,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,YAAY,QAAQ;EACzB,KAAK,OAAO,QAAQ;CACtB;AACF;;;ACRA,IAAM,eAAe;AACrB,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;;AAEjC,IAAM,aAAa;;;;;;;AAqBnB,eAAsB,kBAAkB,OAA6C;CACnF,MAAM,WAAW,MAAM,aAAa,KAAK;CACzC,MAAM,UAAwC,CAAC;CAC/C,MAAM,UAAyC,CAAC;CAEhD,KAAK,MAAM,SAAS,SAAS,SAAS;EACpC,MAAM,aAAa,MAAM,eAAe,OAAO,SAAS,IAAI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