@mica-js/editor 0.6.0 → 0.7.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/fused-runtime.js +1 -1
- package/dist/fused.d.ts +76 -0
- package/dist/fused.js +2 -1
- package/dist/fused.js.map +1 -1
- package/dist/{runtime-CE38_qhr.js → runtime-DV_lH_Yd.js} +3 -3
- package/dist/{runtime-CE38_qhr.js.map → runtime-DV_lH_Yd.js.map} +1 -1
- package/dist/workers-DYiiXPha.js +34 -0
- package/dist/{workers-BsocIPUc.js.map → workers-DYiiXPha.js.map} +1 -1
- package/package.json +3 -3
- package/dist/workers-BsocIPUc.js +0 -34
package/dist/workers-BsocIPUc.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { SandboxWorker } from "@mica-js/sandbox";
|
|
2
|
-
//#region \0mica-sandbox-worker:/home/runner/work/mica-js/mica-js/packages/editor/src/fused/runtime/display/entry.ts
|
|
3
|
-
var EntrySandbox$1 = class extends SandboxWorker {
|
|
4
|
-
constructor(options = {}) {
|
|
5
|
-
super("(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`);l(`audio-control`),l(`audio-guest`);let d=Object.freeze({}),f=[`sine`,`square`,`triangle`,`sawtooth`],p=[`s16`,`f32`],m={min:8e3,max:96e3},h={min:50,max:2e3},g={min:0,max:1},_={min:0,max:24e3},v={min:0,max:1e4};function y(e,t,n){if(e===void 0)return d;if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${n} must be a plain object`);let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)throw TypeError(`${n} must be a plain object`);let i=e,a=new Set(t);for(let e of Object.keys(i)){if(!a.has(e))throw TypeError(`${n} does not accept the option \"${e}\"`);if(i[e]===void 0)throw TypeError(`${n}.${e} must not be undefined`)}return i}function b(e,t,n){if(e===void 0){if(n===void 0)throw TypeError(`${t} is required`);return n}if(typeof e!=`number`)throw TypeError(`${t} must be a number`);if(!Number.isFinite(e))throw RangeError(`${t} must be a finite number`);return e}function x(e,t,n){if(t.integer===!0&&!Number.isInteger(e))throw RangeError(`${n} must be an integer`);if((t.exclusiveMin===!0?e<=t.min:e<t.min)||e>t.max){let e=t.exclusiveMin===!0?`(${t.min}, ${t.max}]`:`[${t.min}, ${t.max}]`;throw RangeError(`${n} must be in ${e}`)}return e}function S(e,t,n,r,i){return x(i===void 0?b(e[t],`${n}.${t}`):b(e[t],`${n}.${t}`,i),r,`${n}.${t}`)}function C(e,t,n,r){if(e[t]!==void 0)return S(e,t,n,r)}function w(e,t,n,r,i){let a=e[t];if(a===void 0)return i;if(!n.includes(a))throw RangeError(`${r}.${t} must be one of ${n.join(`, `)}`);return a}function T(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function`)}let E=[`unavailable`,`suspended`,`running`],D=[`buffering`,`playing`,`ended`,`closed`],O=[`finished`,`stopped`,`dropped`,`error`,`unavailable`,`disposed`];function k(){let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}}function A(e){let t=e.maxVoices??8,n=e.maxStreams??4,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s,c,l=()=>{},d=new Promise(e=>{l=e}),b=`unavailable`,x=!1,A=0,M=0;function N(t,n){try{e.onListenerError?.(t,n)}catch{}}function P(){return d.then(()=>x?void 0:c)}function ee(e){let t={instanceId:e,session:void 0,state:b,stateListeners:/* @__PURE__ */ new Set,voices:/* @__PURE__ */ new Map,streams:/* @__PURE__ */ new Map,api:void 0};return t.api=G(t),t}function F(e){let t=r.get(e);return t||(t=ee(e),r.set(e,t)),t}function I(e,t){e.settled||(e.settled=!0,i.delete(e.id),r.get(e.instanceId)?.voices.delete(e.id),e.resolve({reason:t}))}function L(e,t){e.settled||(e.closed=!0,e.state=t===`finished`?`ended`:`closed`,o.delete(e.id),r.get(e.instanceId)?.streams.delete(e.id),B(e),e.settled=!0,e.resolve({reason:t}))}function R(e){return Math.max(0,e.writtenFrames+e.pendingFrames-e.consumedFrames)}function z(e){return{state:e.state,underruns:e.underruns,dropped:e.dropped,bufferedFrames:R(e),capacityFrames:e.capacityFrames}}function B(e){if(e.statusListeners.size===0)return;let t=z(e);for(let n of[...e.statusListeners])try{n(t)}catch(t){N(e.instanceId,t)}}function V(e){for(let t of[...e.drainListeners])try{t()}catch(t){N(e.instanceId,t)}}function H(e){if(e.closed)return;let t=e.capacityFrames/2;e.drainNotified?R(e)>t&&(e.drainNotified=!1):R(e)>t||(e.drainNotified=!0,V(e))}function te(e){if(b!==e){b=e;for(let t of r.values())if(t.state!==e){t.state=e;for(let n of[...t.stateListeners])try{n(e)}catch(e){N(t.instanceId,e)}}}}function U(e,n){A+=1;let{promise:r,resolve:a}=k(),o={id:`t${A}`,instanceId:e.instanceId,dead:n,settled:!1,ended:r,resolve:a};if(e.voices.size>=t){let t=e.voices.values().next().value;t!==void 0&&I(t,`dropped`)}return e.voices.set(o.id,o),i.set(o.id,o),o}function W(e){return{id:e.id,ended:e.ended,stop(){if(!e.settled){if(!e.dead){let t=r.get(e.instanceId)?.session;t!==void 0&&P().then(n=>n?.stopTone(t,e.id,{fadeMs:0})).catch(()=>void 0)}I(e,`stopped`)}}}}function G(e){return{get state(){return e.state},onStateChange(t){return T(t,`api.audio.onStateChange(listener)`),e.stateListeners.add(t),()=>{e.stateListeners.delete(t)}},tone(t){let n=y(t,[`type`,`frequency`,`volume`],`options`),r=w(n,`type`,f,`options`,`sine`),i=S(n,`frequency`,`options`,{..._,exclusiveMin:!0}),a=S(n,`volume`,`options`,g,1),o=e.session,s=U(e,e.state===`unavailable`||o===void 0);return!s.dead&&o!==void 0&&P().then(e=>e?.createTone(o,{voiceId:s.id,type:r,frequency:i,volume:a})).catch(()=>void 0),Object.assign(W(s),{set(e,t){let n=y(e,[`volume`,`frequency`],`options`),r=S(y(t,[`rampMs`],`options`),`rampMs`,`options`,v,0),i=C(n,`volume`,`options`,g),a=C(n,`frequency`,`options`,{..._,exclusiveMin:!0});s.settled||s.dead||o===void 0||P().then(e=>e?.setTone(o,s.id,{rampMs:r,...i===void 0?{}:{volume:i},...a===void 0?{}:{frequency:a}})).catch(()=>void 0)}})},createStream(t){let r=y(t,[`sampleRate`,`channels`,`format`,`bufferMs`,`startMs`,`volume`],`options`),i=S(r,`sampleRate`,`options`,{...m,integer:!0}),a=w(r,`channels`,[1,2],`options`,1),s=w(r,`format`,p,`options`,`f32`),c=S(r,`bufferMs`,`options`,h,500),l=S(r,`startMs`,`options`,{min:0,max:c},50),u=S(r,`volume`,`options`,g,1),d=Math.max(1,Math.ceil(c*i/1e3)),f=Math.min(d,Math.max(0,Math.ceil(l*i/1e3)));M+=1;let _=e.streams.size>=n,v=e.state===`unavailable`||e.session===void 0,{promise:b,resolve:x}=k(),C={id:`s${M}`,instanceId:e.instanceId,session:e.session,sampleRate:i,channels:a,format:s,capacityFrames:d,startFrames:f,volume:u,unavailable:v,writtenFrames:0,pendingFrames:0,consumedFrames:0,underruns:0,dropped:0,state:_?`closed`:`buffering`,drainNotified:!1,endRequested:!1,closed:_,settled:_,ended:b,resolve:x,statusListeners:/* @__PURE__ */ new Set,drainListeners:/* @__PURE__ */ new Set};if(_)x({reason:`stopped`});else if(e.streams.set(C.id,C),o.set(C.id,C),!v&&e.session!==void 0){let t=e.session;P().then(e=>e?.createStream(t,{streamId:C.id,sampleRate:i,channels:a,format:s,capacityFrames:d,startFrames:f,volume:u})).then(e=>{e?.accepted===!1&&L(C,`stopped`)}).catch(()=>void 0)}return K(C)}}}function K(e){return{id:e.id,sampleRate:e.sampleRate,channels:e.channels,format:e.format,capacityFrames:e.capacityFrames,startFrames:e.startFrames,volume:e.volume,get bufferedFrames(){return R(e)},get underruns(){return e.underruns},get dropped(){return e.dropped},get state(){return e.state},ended:e.ended,write(t){if(e.closed)return Promise.resolve(!1);let n=e.format===`s16`?Int16Array:Float32Array;if(!(t instanceof n))throw TypeError(`api.audio stream.write expects a ${n.name} for format \"${e.format}\"`);let r=t.length;if(r===0)throw RangeError(`api.audio stream.write expects at least one sample`);if(r%e.channels!==0)throw RangeError(`api.audio stream.write expects a whole number of ${e.channels}-channel frames`);let i=r/e.channels;if(i>e.capacityFrames)throw RangeError(`api.audio stream.write accepts at most ${e.capacityFrames} frames per call`);if(e.unavailable)return Promise.resolve(!1);if(R(e)+i>e.capacityFrames)return e.dropped+=1,B(e),Promise.resolve(!1);let a=e.format===`s16`?new Int16Array(t):new Float32Array(t),o=e.session??``;return e.pendingFrames+=i,P().then(async t=>{if(t===void 0||e.closed)return e.pendingFrames-=i,!1;try{let n=await t.writeStream(o,e.id,a);return e.pendingFrames-=i,n?e.writtenFrames+=i:e.dropped+=1,B(e),H(e),n}catch{return e.pendingFrames-=i,!1}})},clear(){if(!e.closed){if(e.consumedFrames=e.writtenFrames,!e.unavailable&&e.session!==void 0){let t=e.session;P().then(n=>n?.clearStream(t,e.id)).catch(()=>void 0)}B(e),H(e)}},end(){if(e.closed||e.endRequested)return;if(e.endRequested=!0,e.unavailable||e.session===void 0){L(e,`finished`);return}let t=e.session;P().then(n=>n?.endStream(t,e.id)).catch(()=>void 0)},close(){if(!e.settled){if(!e.closed&&!e.unavailable&&e.session!==void 0){let t=e.session;P().then(n=>n?.closeStream(t,e.id)).catch(()=>void 0)}L(e,`stopped`)}},onDrain(t){return T(t,`api.audio stream.onDrain(listener)`),e.drainListeners.add(t),()=>{e.drainListeners.delete(t)}},onStatus(t){return T(t,`api.audio stream.onStatus(listener)`),e.statusListeners.add(t),()=>{e.statusListeners.delete(t)}}}}function q(e){if(typeof e!=`object`||!e||typeof e.streamId!=`string`)return;let t=o.get(e.streamId);t&&(typeof e.consumedFrames==`number`&&Number.isFinite(e.consumedFrames)&&(t.consumedFrames=Math.max(t.consumedFrames,Math.floor(e.consumedFrames))),typeof e.underruns==`number`&&Number.isFinite(e.underruns)&&(t.underruns=Math.max(0,Math.floor(e.underruns))),!t.closed&&D.includes(e.state)&&(t.state=e.state),B(t),H(t))}function J(e){if(typeof e!=`object`||!e||typeof e.id!=`string`)return;let t=O.includes(e.reason)?e.reason:`stopped`;if(e.target===`tone`){let n=i.get(e.id);n&&I(n,t);return}let n=o.get(e.id);n&&L(n,t)}function Y(e){let t=r.get(e);if(t){r.delete(e);for(let e of t.voices.values())I(e,`disposed`);t.voices.clear();for(let e of[...t.streams.values()])L(e,`disposed`);t.streams.clear(),t.stateListeners.clear()}}return{get state(){return b},api(e){return F(e).api},open(e,t){let n=F(e);n.session=t?.session,t!==void 0&&(n.state=t.state,b=t.state)},setState(e){E.includes(e)&&te(e)},attachPort(e){if(x||s!==void 0)return;let t=a(e);s=t,c=t.getProxy(u,{transfer:(e,t)=>e===`writeStream`&&j(t[2])?[t[2].buffer]:[]}),c.onDidProgress(e=>q(e)),c.onDidEnded(e=>J(e)),l()},release:Y,dispose(){if(!x){for(let e of[...r.keys()])Y(e);x=!0,l(),s?.dispose(),s=void 0,c=void 0,i.clear(),o.clear()}}}}function j(e){return e instanceof Int16Array||e instanceof Float32Array}function M(e){return{get state(){return e.state},onDidChangeState:t=>({dispose:e.onStateChange(t)}),tone:t=>e.tone(t),createStream(t){let n=e.createStream(t);return Object.assign(n,{onDidDrain:(e=>({dispose:n.onDrain(()=>e())})),onDidChangeStatus:(e=>({dispose:n.onStatus(e)}))})}}}l(`fused-simulation`);let N=l(`fused-display`),P=l(`fused-host-package`);l(`fused-host-resource`);let ee=l(`fused-model-channel`),F=l(`fused-model-sink`),I=l(`fused-host-audio`);var L=class extends Error{code;instanceId;details;constructor(e,t,n={}){super(t),this.name=n.name??`FusedBridgeError`,this.code=e,this.instanceId=n.instanceId,this.details=n.details}};function R(e){let t=te(e);return Object.assign(Error(JSON.stringify(t)),{name:`FusedSandboxFailure`})}function z(e){if(!(e instanceof Error)||e.name!==`FusedSandboxFailure`)return e instanceof Error?e:Error(String(e));let t=U(e.message);return t===void 0?e:new L(t.code,t.message,{...t.kind===`method`?{name:`MethodError`}:{},...t.instanceId===void 0?{}:{instanceId:t.instanceId},...t.details===void 0?{}:{details:t.details}})}async function B(e){try{return await e()}catch(e){throw z(e)}}function V(e){return typeof ImageBitmap<`u`&&e instanceof ImageBitmap}function H(e,t){if(e!==`render`)return[];let n=t;return n==null?[]:V(n.bitmap)?[n.bitmap]:[]}function te(e){let t=J(e),n=K(e);if(n!==void 0)return{kind:`method`,code:n.code,message:n.message,...n.details===void 0?{}:{details:q(n.details)}};let r=W(e),i=G(e);return{kind:r===`Error`?`failure`:`runtime`,code:r,message:t,...i===void 0?{}:{instanceId:i}}}function U(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let n=t;if(typeof n.code==`string`&&typeof n.message==`string`)return{kind:n.kind===`method`||n.kind===`runtime`?n.kind:`failure`,code:n.code,message:n.message,...typeof n.instanceId==`string`?{instanceId:n.instanceId}:{},...n.details===void 0?{}:{details:n.details}}}function W(e){if(typeof e!=`object`||!e)return`Error`;let t=e.code;if(typeof t==`string`&&t.length>0)return t;let n=e.name;return typeof n==`string`&&n.length>0?n:`Error`}function G(e){if(typeof e!=`object`||!e)return;let t=e.instanceId;return typeof t==`string`?t:void 0}function K(e){if(typeof e!=`object`||!e)return;let t=e;if(t.name===`MethodError`&&typeof t.code==`string`&&typeof t.message==`string`)return{code:t.code,message:t.message,...t.details===void 0?{}:{details:t.details}}}function q(e){if(e instanceof Uint8Array)return[...e];if(Array.isArray(e))return e.map(e=>q(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[n]=q(r);return t}return e}function J(e){return e instanceof Error?e.message:String(e)}function Y(e){return`${e.id}@${e.version}#${e.integrity}`}function ne(e){let t=e.getProxy(P),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>{let r=Y(e),i=n.get(r);return i===void 0&&(i=t.open(e),n.set(r,i)),i};return{open(e){return i(e).then(n=>({lock:n.lock,files:n.files,read:async n=>{let i=`${Y(e)}\\u0000${n}`,a=r.get(i);if(a!==void 0)return a.slice();let o=await t.read(e,n);if(!(o instanceof Uint8Array))throw new L(`package/not-found`,`The host returned no bytes for ${e.id}/${n}.`);return r.set(i,o),o.slice()}}))}}}let re=/^[A-Za-z]:/,ie=/^[A-Za-z][A-Za-z0-9+.-]*:/;function ae(e){for(let t of e){let e=t.codePointAt(0)??0;if(e<32||e===127)return!0}return!1}function oe(e){return se(e,`project root`)}function se(e,t){if(e.length===0)return`must not be empty`;if(e.startsWith(`/`))return`must be relative to the ${t}, not absolute`;if(re.test(e))return`must not carry a drive letter`;if(ie.test(e))return`must not be a URL`;if(e.includes(`\\\\`))return`must use POSIX separators`;if(ae(e))return`must not contain control characters`;let n=e.split(`/`);if(n[n.length-1]===``)return`must name a file, not a directory`;for(let e of n){if(e.length===0)return`must not contain empty segments`;if(e===`.`||e===`..`)return`must not contain \"${e}\" segments`}}function X(e){let t=e.slice(),n=Object.freeze({get length(){return t.length},get byteLength(){return t.length},slice(e,n){return t.slice(e,n)},*[Symbol.iterator](){for(let e of t)yield e}});return new Proxy(n,{get(e,n,r){return typeof n==`string`&&/^(0|[1-9]\\d*)$/.test(n)?t[Number(n)]:Reflect.get(e,n,r)},set(){throw TypeError(`Firmware bytes are read-only`)},defineProperty(){throw TypeError(`Firmware bytes are read-only`)}})}let Z=Object.freeze({maxFiles:1024,maxFileBytes:33554432,maxTotalBytes:67108864,maxMemoryBytes:67108864,maxPathBytes:1024,maxDepth:32});var Q=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`ProgramError`}};function ce(e){let t=oe(e);if(t!==void 0)throw new Q(`program/invalid-path`,`Program path ${JSON.stringify(e)} ${t}.`);if(new TextEncoder().encode(e).length>Z.maxPathBytes||e.split(`/`).length>Z.maxDepth)throw new Q(`program/resource-limit`,`Program path ${JSON.stringify(e)} exceeds the fixed path limits.`)}function le(e){if(!Array.isArray(e))throw new Q(`program/source-resolve-failed`,`A program file set must be an array.`);if(e.length>Z.maxFiles)throw new Q(`program/resource-limit`,`Program file count exceeds the fixed limit.`);let t=/* @__PURE__ */ new Map,n=0;for(let r of e){if(typeof r!=`object`||!r||typeof r.path!=`string`||!(r.data instanceof Uint8Array))throw new Q(`program/source-resolve-failed`,`Program files require a path and Uint8Array data.`);if(ce(r.path),t.has(r.path))throw new Q(`program/invalid-path`,`Duplicate program path ${r.path}.`);if(n+=r.data.byteLength,r.data.byteLength>Z.maxFileBytes||n>Z.maxTotalBytes)throw new Q(`program/resource-limit`,`Program file bytes exceed the fixed limit.`);t.set(r.path,X(r.data))}let r=Object.freeze([...t.keys()].sort());for(let e of r){let n=e.split(`/`);for(let r=1;r<n.length;r++)if(t.has(n.slice(0,r).join(`/`)))throw new Q(`program/invalid-path`,`Program file ${e} conflicts with a parent file.`)}return Object.freeze({paths:r,read(e){ce(e);let n=t.get(e);if(n===void 0)throw new Q(`program/file-not-found`,`Program file ${e} does not exist.`);return n}})}function ue(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>typeof t==`object`&&t&&!(t instanceof Uint8Array)?t.kind===`filesystem`?[e,le(t.files)]:[e,Object.freeze({segments:Object.freeze(t.segments.map(e=>Object.freeze({addressSpace:e.addressSpace,address:e.address,data:X(e.bytes)})))})]:[e,t])))}function $(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}function de(e){let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}function fe(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function pe(e){return new TextDecoder().decode(e).replace(/^\\uFEFF/,``)}function me(e,t){return`${e}\\u0000${t}`}function he(n){let r=/* @__PURE__ */ new Map,i=(i,a)=>{let o=me(i,a);return s=>{let c=r.get(o);c===void 0&&(c={emitter:new t,listeners:0},r.set(o,c));let l=c;l.listeners+=1,l.listeners===1&&n.subscribe(i,a);let u=l.emitter.event(s);return e(()=>{u.dispose(),--l.listeners,!(l.listeners>0)&&(r.delete(o),l.emitter.dispose(),n.unsubscribe(i,a))})}},a=(e,t,i)=>{let a=r.get(e);a!==void 0&&(r.delete(e),a.emitter.dispose(),n.unsubscribe(t,i))};return{event:i,deliver(e,t,n){r.get(me(e,t))?.emitter.fire(n)},release(e){let t=`${e}\\u0000`;for(let n of[...r.keys()])n.startsWith(t)&&a(n,e,n.slice(t.length))},dispose(){for(let e of[...r.keys()]){let t=e.indexOf(`\\0`);a(e,e.slice(0,t),e.slice(t+1))}},get activeSubscriptions(){return r.size}}}function ge(e,t=a){let n=t(e),r=n.getProxy(ee),i=/* @__PURE__ */ new Set,o=he({subscribe(e,t){let n=r.subscribe(e,t).catch(()=>void 0);i.add(n),n.finally(()=>i.delete(n))},unsubscribe(e,t){let n=r.unsubscribe(e,t).catch(()=>void 0);i.add(n),n.finally(()=>i.delete(n))}});return n.register(F,{deliver(e){_e(e)&&o.deliver(e.instanceId,e.event,e.payload)}}),{client(e){let t=new Set(e.methods),n=new Proxy(Object.create(null),{get(n,i){if(typeof i==`string`&&t.has(i))return t=>B(()=>r.call(e.instanceId,i,t))},has(e,n){return typeof n==`string`&&t.has(n)}}),i={};for(let t of e.events)i[t]=o.event(e.instanceId,t);return{methods:n,events:i}},release(e){o.release(e)},async settle(){for(;i.size>0;)await Promise.allSettled([...i]);await r.settle()},dispose(){o.dispose(),n.dispose()}}}function _e(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.instanceId==`string`&&typeof t.event==`string`}async function ve(e){let{instance:t}=e,n=t.view;if(n===void 0)throw new L(`view2d/unsupported`,`${t.device} declares no \\`view2d.entry\\`.`,{instanceId:t.instanceId});let r=await e.importModule(pe(await e.readAsset(n))),i=typeof r==`object`&&r?r.default:void 0;if(typeof i!=`function`)throw new L(`runtime/presentation-failed`,`${t.device}/${n} must default-export a presentation factory.`,{instanceId:t.instanceId});let a=!1,o=e.audio===void 0?A({}):void 0,s,c=i({mode:e.mode,props:ue(t.props),geometry:t.geometry,model:e.model,assets:{read:t=>e.readAsset(t),loadImage:async t=>createImageBitmap(new Blob([fe(await e.readAsset(t))]))},audio:e.audio??M(o.api(t.instanceId)),invalidate:()=>{a||e.invalidate()}});if(typeof c!=`object`||!c)throw new L(`runtime/presentation-failed`,`${t.device}/${n} returned no presentation object.`,{instanceId:t.instanceId});let l=!1;return{instanceId:t.instanceId,geometry:t.geometry,async activate(){if(a||l)return;l=!0;let e=c.initialize?.();$(e)&&await e},render(e){let n=c.renderOverlay;if(a||n===void 0)return;let r=u(e.width,e.height),i=r.getContext(`2d`);if(i===null)throw new L(`view2d/render-failed`,`The overlay canvas has no 2D context.`,{instanceId:t.instanceId});i.save();try{i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,e.width,e.height);let r=t.geometry.bounds;if(i.setTransform(e.scale,0,0,e.scale,-r.x*e.scale,-r.y*e.scale),$(n.call(c,i)))throw new L(`view2d/render-failed`,`renderOverlay must draw synchronously.`,{instanceId:t.instanceId})}finally{i.restore()}return r.transferToImageBitmap()},input(t){let n=c.input;if(!(a||n===void 0))try{let r=n.call(c,t);$(r)&&Promise.resolve(r).catch(t=>{e.report(`view2d/input-failed`,J(t))})}catch(t){e.report(`view2d/input-failed`,J(t))}},dispose(){if(!a){a=!0,o?.dispose();try{c.dispose?.()}catch(t){e.report(`runtime/presentation-failed`,`Releasing the presentation failed: ${J(t)}`)}}}};function u(n,r){if(!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0)throw new L(`view2d/render-failed`,`The overlay extent ${String(n)}x${String(r)} must be positive.`,{instanceId:t.instanceId});return(s===void 0||s.width!==n||s.height!==r)&&(s=e.createSurface(n,r)),s}}function ye(e,n={}){let r=(n.createEndpoint??a)(e),i=n.importModule??de,o=n.createSurface??((e,t)=>new OffscreenCanvas(e,t)),s=ne(r),c=new t,l=A({onListenerError:(e,t)=>c.fire({code:`audio/listener-failed`,message:J(t),instanceId:e})}),u=r.getProxy(I),d=/* @__PURE__ */ new Map,f=new t,p=n.ports?.[0],m=p===void 0?void 0:ge(p),h=/* @__PURE__ */ new Map,g=0,_=!1,v;return r.register(N,{attachAudio:e=>l.attachPort(e),setAudioState:e=>l.setState(e),prepare:x,activate:S,render:C,input:w,release:T,dispose:E,onDidInvalidate(e){let t=f.event(t=>e(t));return()=>t.dispose()},onDidReportDiagnostic(e){let t=c.event(t=>e(t));return()=>t.dispose()}},{transfer:H}),{rpc:r,dispose:O};function y(e){c.fire(e)}function b(e,t){return s.open(e).then(e=>e.read(t))}async function x(e){if(_)throw R(new L(`runtime/unavailable-state`,`The fused display guest is disposed.`));let t=++g;D();for(let n of e.instances){if(n.view===void 0)continue;let r=n.instanceId;try{if(e.mode===`run`){let e=await u.open(r);if(_||t!==g){e.session!==void 0&&u.close(r,e.session).catch(()=>void 0);return}l.open(r,e),e.session!==void 0&&d.set(r,e.session)}else l.open(r,void 0);let a=await ve({instance:n,mode:e.mode,model:e.mode===`run`?m?.client(n):void 0,audio:M(l.api(r)),readAsset:e=>b(n.lock,e),importModule:i,createSurface:o,invalidate:()=>{t===g&&!_&&f.fire({instanceId:r})},report:(e,t)=>y({code:e,message:t,instanceId:r})});if(_||t!==g){a.dispose();return}h.set(r,a)}catch(e){k(r),y({code:`runtime/presentation-failed`,message:J(e),instanceId:r})}}await m?.settle()}async function S(){if(_)return;let e=g;if(await m?.settle(),!(_||e!==g))for(let[t,n]of[...h])try{await n.activate()}catch(r){if(_||e!==g){n.dispose();return}y({code:`runtime/presentation-failed`,message:`Initializing the presentation failed: ${J(r)}`,instanceId:t}),T(t)}}async function C(e){if(_)return;let t=h.get(e.instanceId);if(t===void 0)return;let n=g,r;try{r=t.render(e)}catch(t){y({code:`view2d/render-failed`,message:J(t),instanceId:e.instanceId});return}if(r!==void 0){if(_||n!==g)be(r);else return{instanceId:e.instanceId,generation:e.generation,width:e.width,height:e.height,scale:e.scale,bitmap:r}}}function w(e,t){_||h.get(e)?.input(t)}function T(e){k(e);let t=h.get(e);t!==void 0&&(h.delete(e),t.dispose(),m?.release(e))}async function E(){_||(g+=1,D())}function D(){for(let e of[...d.keys()])k(e);let e=h;h=/* @__PURE__ */ new Map;for(let t of e.values())k(t.instanceId),t.dispose(),m?.release(t.instanceId)}function O(){return v===void 0&&(_=!0,v=(async()=>{g+=1,D(),m?.dispose(),l.dispose(),r.dispose(),c.dispose(),f.dispose()})()),v}function k(e){l.release(e);let t=d.get(e);d.delete(e),t!==void 0&&u.close(e,t).catch(()=>void 0)}}function be(e){V(e)&&e.close()}let xe=!1;self.addEventListener(`message`,e=>{if(xe)return;let t=e.ports[0];t!==void 0&&(xe=!0,ye(t,{ports:e.ports.slice(1)}))})})();", options);
|
|
6
|
-
}
|
|
7
|
-
};
|
|
8
|
-
//#endregion
|
|
9
|
-
//#region \0mica-sandbox-worker:/home/runner/work/mica-js/mica-js/packages/editor/src/fused/runtime/simulation/entry.ts
|
|
10
|
-
var EntrySandbox = class extends SandboxWorker {
|
|
11
|
-
constructor(options = {}) {
|
|
12
|
-
super("(function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);function t(e,t){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`${t}=${String(e)} must be a finite integer number of picoseconds`);if(e<0||e>72e14)throw RangeError(`${t}=${e} must be in [0, 7200000000000000] ps`);return e===0?0:e}function n(e){return t(e,`time`)}function r(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var i=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(e,t,n)=>{if(this.#t)return r(()=>{});let i={listener:e,thisArgs:t};this.#e.add(i);let a=r(()=>{this.#e.delete(i)});return n?.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 a(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 o(e,t){return Object.assign(Error(t),{name:e})}function s(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw o(`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 o(`MethodNotFound`,`Method is not callable: ${t}`)}function c(e,t={}){let n=t,c=d(n.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new i,_=new i,v=0,y=0,b=!1;function x(e){let t=l(e);try{n.onError?.(t)}catch{}g.fire(t)}function ee(){if(b)throw o(`RpcDisconnectedError`,`RPC endpoint is closed`)}function te(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function S(t,n){ee(),e.postMessage(t,n?[...n]:void 0)}function C(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function w(e,t,n){return new Promise((r,i)=>{let a=t>0?setTimeout(()=>{C(e.id)?.reject(o(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:r,reject:i,timer:a});try{S(e,n)}catch(t){C(e.id)?.reject(l(t))}})}function T(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function E(e,t,n){if(b)return;let r=l(n);try{S({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),ne()}}function D(){if(!b){b=!0,e.removeEventListener(`message`,ie),e.removeEventListener(`close`,D),e.removeEventListener(`messageerror`,ne);for(let e of p.keys())C(e)?.reject(o(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())T(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function ne(){if(!b){try{S({kind:`close`})}catch(e){x(e)}D()}}async function re(e){try{let t=f.get(e.service);if(!t)throw o(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,r=s(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw o(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let a=r.call(n,(...n)=>{if(!(b||h.get(e.id)!==i))try{S({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){T(e.id),E(`subscription-error`,e.id,t)}});if(typeof a!=`function`)throw o(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=a,h.get(e.id)!==i&&i.stop(),b||S({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw o(`InvalidCall`,`Event members require a subscription`);let i=await r.apply(n,e.args);b||S({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&T(e.id),E(`error`,e.id,t)}}function ie(e){let t=e.data;if(!a(t))x(o(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=y){x(o(`RpcProtocolError`,`Request IDs must increase`));return}y=t.id,re(t);break;case`unlisten`:T(t.id);break;case`result`:C(t.id)?.resolve(t.value);break;case`error`:C(t.id)?.reject(o(t.name,t.message));break;case`subscription-error`:{let e=o(t.name,t.message),n=m.delete(t.id),r=C(t.id);r?r.reject(e):n&&x(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){x(e)}break;case`close`:D()}}return e.addEventListener(`message`,ie),e.addEventListener(`close`,D),e.addEventListener(`messageerror`,ne),e.start?.(),{register(e,t,n={}){ee();let i=u(e);if(typeof t!=`object`||!t)throw TypeError(`RPC services must be objects`);if(f.has(i))throw Error(`Service already registered: ${i}`);let a={implementation:t,options:n};return f.set(i,a),r(()=>{if(f.get(i)===a){f.delete(i);for(let[e,t]of h)t.registration===a&&(T(e),E(`subscription-error`,e,o(`ServiceUnregistered`,`Service unregistered: ${i}`)))}})},getProxy(e,t={}){let n=u(e),i=d(t.timeoutMs??c),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(e,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?e=>{if(ee(),typeof e!=`function`)throw TypeError(`Expected an event listener`);let t=te();m.set(t,e),w({kind:`listen`,id:t,service:n,member:o,args:[]},i).catch(e=>{if(m.delete(t),!b)try{S({kind:`unlisten`,id:t})}catch(e){x(e)}x(e)});let a=r(()=>{if(m.delete(t)&&(C(t)?.resolve(void 0),!b))try{S({kind:`unlisten`,id:t})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(ee(),w({kind:`call`,id:te(),service:n,member:o,args:e},i,t.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(e,t,n)=>b?(e.call(t,void 0),r(()=>{})):_.event(n=>{try{e.call(t,n)}catch(e){x(e)}},void 0,n),dispose:ne}}function l(e){return e instanceof Error?e:Error(String(e))}function u(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function d(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function f(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function p(e){return e.length===0?``:`/${e.map(e=>e.replace(/~/g,`~0`).replace(/\\//g,`~1`)).join(`/`)}`}var m=class extends Error{diagnostics;constructor(e){super(g(e)),this.name=`FusedDocumentError`,this.diagnostics=e}get code(){return this.diagnostics[0]?.code}get pointer(){return this.diagnostics[0]?.pointer}};function h(e,t,n,r){e.push({severity:`error`,code:t,message:n,pointer:p(r)})}function g(e){let t=e.filter(e=>e.severity===`error`),[n,...r]=t.length>0?t:e;if(n===void 0)return`Fused device validation failed.`;let i=n.pointer===``?``:` at ${n.pointer}`,a=r.length===0?``:` (and ${r.length} more)`;return`${n.code}${i}: ${n.message}${a}`}let _=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,v=/^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:-[a-z0-9]+)*$/,y=/^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/,b=/^sha256:[0-9a-f]{64}$/,x=/^[A-Za-z][A-Za-z0-9]*$/,ee=/^onDid[A-Z][A-Za-z0-9]*$/,te=/^[A-Za-z_][A-Za-z0-9_]*$/,S=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,C=/^[A-Za-z][A-Za-z0-9]*$/,w=/^\\.[A-Za-z0-9]+$/,T=/^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,E=/^[A-Za-z]:/,D=/^[A-Za-z][A-Za-z0-9+.-]*:/;function ne(e){for(let t of e){let e=t.codePointAt(0)??0;if(e<32||e===127)return!0}return!1}function re(e){return _.test(e)}function ie(e){return v.test(e)}function ae(e){return e.length===0?`must not be empty`:ie(e)?void 0:`must be a \"publisher:name\" pair of lowercase dash-separated segments`}function oe(e){return y.test(e)}function O(e){return b.test(e)}function se(e){return x.test(e)}function ce(e){return ee.test(e)}function le(e){return te.test(e)}function ue(e){return S.test(e)}function de(e){return C.test(e)}function fe(e){return w.test(e)}function k(e){return T.test(e)}function pe(e){return j(e,`package root`)}function A(e){return j(e,`project root`)}function j(e,t){if(e.length===0)return`must not be empty`;if(e.startsWith(`/`))return`must be relative to the ${t}, not absolute`;if(E.test(e))return`must not carry a drive letter`;if(D.test(e))return`must not be a URL`;if(e.includes(`\\\\`))return`must use POSIX separators`;if(ne(e))return`must not contain control characters`;let n=e.split(`/`);if(n[n.length-1]===``)return`must name a file, not a directory`;for(let e of n){if(e.length===0)return`must not contain empty segments`;if(e===`.`||e===`..`)return`must not contain \"${e}\" segments`}}function me(e,t){let n=e.toLowerCase();return t.map(e=>e.toLowerCase()).some(e=>n.endsWith(e))?void 0:`must name a ${t.join(` or `)} file`}function he(e){return O(e)?void 0:`must be \"sha256:\" followed by 64 lowercase hexadecimal digits`}function ge(e){return k(e)?e.toUpperCase():void 0}function _e(e){let t=ve(e);if(!t.ok)throw new m(t.diagnostics);return t.value}function ve(e){return new ye(e).decode()}var ye=class{#e;#t=[];#n=0;#r=!1;constructor(e){this.#e=e}decode(){this.#o();let e=this.#s([],0);return this.#r?this.#i():(this.#o(),this.#n===this.#e.length?this.#t.length>0?this.#i():{ok:!0,value:e}:(this.#a(`Unexpected content after the JSON value.`),this.#i()))}#i(){return{ok:!1,diagnostics:this.#t}}#a(e){this.#r||h(this.#t,`json/invalid`,`Invalid JSON at offset ${String(this.#n)}: ${e}`,[]),this.#r=!0}#o(){for(;this.#n<this.#e.length;){let e=this.#e.charCodeAt(this.#n);if(e!==32&&e!==9&&e!==10&&e!==13)return;this.#n+=1}}#s(e,t){if(this.#o(),this.#n>=this.#e.length)return this.#a(`Unexpected end of input; expected a value.`);if(t>256)return this.#a(`Nesting deeper than 256 is not supported.`);switch(this.#e[this.#n]){case`{`:return this.#p(e,t+1);case`[`:return this.#m(e,t+1);case`\"`:return this.#u();case`t`:return this.#c(`true`,!0);case`f`:return this.#c(`false`,!1);case`n`:return this.#c(`null`,null);default:return this.#l()}}#c(e,t){return this.#e.startsWith(e,this.#n)?(this.#n+=e.length,t):this.#a(`Expected ${e}.`)}#l(){be.lastIndex=this.#n;let e=be.exec(this.#e);return e===null?this.#a(`Expected a value.`):(this.#n=be.lastIndex,Number(e[0]))}#u(){this.#n+=1;let e=``,t=this.#n;for(;;){if(this.#n>=this.#e.length)return this.#a(`Unterminated string.`);let n=this.#e.charCodeAt(this.#n);if(n===34)return e+=this.#e.slice(t,this.#n),this.#n+=1,e;if(n===92){e+=this.#e.slice(t,this.#n),this.#n+=1;let n=this.#d();if(n===void 0)return;e+=n,t=this.#n}else{if(n<32)return this.#a(`Control characters must be escaped inside strings.`);this.#n+=1}}}#d(){if(this.#n>=this.#e.length)return this.#a(`Unterminated escape sequence.`);let e=this.#e[this.#n];switch(this.#n+=1,e){case`\"`:return`\"`;case`\\\\`:return`\\\\`;case`/`:return`/`;case`b`:return`\\b`;case`f`:return`\\f`;case`n`:return`\n`;case`r`:return`\\r`;case`t`:return` `;case`u`:return this.#f();default:return this.#a(`Unknown escape sequence \"\\\\${String(e)}\".`)}}#f(){let e=this.#e.slice(this.#n,this.#n+4);return/^[0-9a-fA-F]{4}$/.test(e)?(this.#n+=4,String.fromCharCode(Number.parseInt(e,16))):this.#a(`Unicode escapes need exactly four hexadecimal digits.`)}#p(e,t){this.#n+=1;let n={},r=/* @__PURE__ */ new Set;if(this.#o(),this.#e[this.#n]===`}`)return this.#n+=1,n;for(;;){if(this.#o(),this.#e[this.#n]!==`\"`)return this.#a(`Expected a property name.`);let i=this.#u();if(i===void 0)return;if(this.#o(),this.#e[this.#n]!==`:`)return this.#a(`Expected \":\" after the property name.`);this.#n+=1;let a=[...e,i],o=r.has(i);o?h(this.#t,`json/duplicate-key`,`Duplicate JSON key ${JSON.stringify(i)}; the contract does not allow one key twice.`,a):r.add(i);let s=this.#s(a,t);if(this.#r)return;o||Object.defineProperty(n,i,{value:s,enumerable:!0,writable:!0,configurable:!0}),this.#o();let c=this.#e[this.#n];if(c===`,`)this.#n+=1;else return c===`}`?(this.#n+=1,n):this.#a(`Expected \",\" or \"}\" in the object.`)}}#m(e,t){this.#n+=1;let n=[];if(this.#o(),this.#e[this.#n]===`]`)return this.#n+=1,n;for(;;){let r=this.#s([...e,String(n.length)],t);if(this.#r)return;n.push(r),this.#o();let i=this.#e[this.#n];if(i===`,`)this.#n+=1;else return i===`]`?(this.#n+=1,n):this.#a(`Expected \",\" or \"]\" in the array.`)}}};let be=/-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/y;function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function xe(e){return e.some(e=>e.severity===`error`)}function P(e,t,n,r){for(let i of Object.keys(e))t.includes(i)||h(r,`schema/unknown-field`,`Unknown field \"${i}\".`,[...n,i])}function Se(e,t){if(typeof e!=`string`)return{ok:!0,value:e};let n=ve(e);return n.ok?{ok:!0,value:n.value}:(t.push(...n.diagnostics),{ok:!1,value:void 0})}function F(e,t,n,r,i=!0,a={}){let o=[...n,t];if(!N(e,t)){i&&h(r,`schema/missing-field`,`Missing required field \"${t}\".`,o);return}let s=e[t];if(typeof s!=`string`)h(r,`schema/invalid-type`,`Field \"${t}\" must be a string.`,o);else if(a.nonEmpty===!0&&s.length===0)h(r,`schema/invalid-value`,`Field \"${t}\" must not be empty.`,o);else return s}function I(e,t,n,r,i=!0){let a=[...n,t];if(!N(e,t)){i&&h(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(typeof o!=`number`)h(r,`schema/invalid-type`,`Field \"${t}\" must be a number.`,a);else if(!Number.isFinite(o))h(r,`schema/invalid-value`,`Field \"${t}\" must be a finite number.`,a);else return o}function Ce(e,t,n,r,i=!0){let a=I(e,t,n,r,i);if(a!==void 0){if(!Number.isSafeInteger(a))h(r,`schema/invalid-value`,`Field \"${t}\" must be a safe integer.`,[...n,t]);else return a}}function we(e,t,n,r,i=!0){let a=[...n,t];if(!N(e,t)){i&&h(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(typeof o!=`boolean`)h(r,`schema/invalid-type`,`Field \"${t}\" must be a boolean.`,a);else return o}function L(e,t,n,r,i=!0){let a=[...n,t];if(!N(e,t)){i&&h(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(!M(o))h(r,`schema/invalid-type`,`Field \"${t}\" must be an object.`,a);else return o}function Te(e,t,n,r,i=!0){let a=[...n,t];if(!N(e,t)){i&&h(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(!Array.isArray(o))h(r,`schema/invalid-type`,`Field \"${t}\" must be an array.`,a);else return o}function Ee(e,t){return e===t?0:e<t?-1:1}function De(e){if(typeof e!=`object`||!e||ArrayBuffer.isView(e)||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))De(t);return e}function Oe(e,t){let n=[],r=Se(e,n),i=r.ok?ke(r.value,[],n,t):void 0;if(i===void 0||xe(n))throw new m(n);return De(i)}function ke(e,t,n,r){if(!M(e)){h(n,`schema/invalid-type`,`Geometry must be an object.`,t);return}P(e,[`sizing`,`bounds`,`bodyBounds`,`bodyImage`,`pins`,`designator`],t,n);let i=Ae(e,t,n),a=Pe(L(e,`bounds`,t,n),[...t,`bounds`],n),o=Pe(L(e,`bodyBounds`,t,n),[...t,`bodyBounds`],n),s=je(e,t,n),c=Me(e,t,n),l=N(e,`designator`)?Fe(e.designator,[...t,`designator`],n):void 0;if(a!==void 0&&o!==void 0&&!Ie(o,a)&&h(n,`view2d/invalid-geometry`,`The body bounds must lie inside the bounds.`,[...t,`bodyBounds`]),c!==void 0&&r!==void 0&&Le(c,r,t,n),!(i===void 0||a===void 0||o===void 0||c===void 0||N(e,`designator`)&&l===void 0))return{sizing:i,bounds:a,bodyBounds:o,...s===void 0?{}:{bodyImage:s},pins:c,...l===void 0?{}:{designator:l}}}function Ae(e,t,n){let r=F(e,`sizing`,t,n,!0,{nonEmpty:!0});if(r!==void 0){if(r!==`physical`&&r!==`flexible`)h(n,`view2d/invalid-geometry`,`Field \"sizing\" must be \"physical\" or \"flexible\".`,[...t,`sizing`]);else return r}}function je(e,t,n){let r=F(e,`bodyImage`,t,n,!1,{nonEmpty:!0});if(r===void 0)return;let i=pe(r);if(i!==void 0){h(n,`view2d/invalid-geometry`,`Field \"bodyImage\" ${i}.`,[...t,`bodyImage`]);return}let a=me(r,[`.png`,`.svg`]);if(a!==void 0)h(n,`view2d/invalid-geometry`,`Field \"bodyImage\" ${a}.`,[...t,`bodyImage`]);else return r}function Me(e,t,n){let r=L(e,`pins`,t,n);if(r===void 0)return;let i=Object.create(null),a=!1;for(let[e,o]of Object.entries(r)){let r=[...t,`pins`,e];if(!le(e)){h(n,`view2d/invalid-geometry`,`Pin id ${JSON.stringify(e)} is not a legal model pin name.`,r),a=!0;continue}let s=Ne(o,r,n);s===void 0?a=!0:i[e]=s}return a?void 0:i}function Ne(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Pin geometry must be an object.`,t);return}P(e,[`position`,`outward`,`label`],t,n);let r=Fe(L(e,`position`,t,n),[...t,`position`],n),i=Fe(L(e,`outward`,t,n),[...t,`outward`],n);if(i!==void 0&&i.x===0&&i.y===0){h(n,`view2d/invalid-geometry`,`Field \"outward\" must be a non-zero vector.`,[...t,`outward`]);return}let a;if(N(e,`label`)){let r=e.label,i=[...t,`label`];if(!M(r)){h(n,`schema/invalid-type`,`Field \"label\" must be an object.`,i);return}P(r,[`position`,`visible`],i,n);let o=Fe(L(r,`position`,i,n),[...i,`position`],n),s=we(r,`visible`,i,n,!1);if(o===void 0)return;a={position:o,...s===void 0?{}:{visible:s}}}if(r!==void 0&&i!==void 0)return{position:r,outward:i,...a===void 0?{}:{label:a}}}function Pe(e,t,n){if(e===void 0)return;P(e,[`x`,`y`,`width`,`height`],t,n);let r=I(e,`x`,t,n),i=I(e,`y`,t,n),a=I(e,`width`,t,n),o=I(e,`height`,t,n);if(a!==void 0&&a<=0)h(n,`schema/invalid-value`,`Field \"width\" must be positive.`,[...t,`width`]);else if(o!==void 0&&o<=0)h(n,`schema/invalid-value`,`Field \"height\" must be positive.`,[...t,`height`]);else if(r!==void 0&&i!==void 0&&a!==void 0&&o!==void 0)return{x:r,y:i,width:a,height:o}}function Fe(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Point must be an object.`,t);return}P(e,[`x`,`y`],t,n);let r=I(e,`x`,t,n),i=I(e,`y`,t,n);return r===void 0||i===void 0?void 0:{x:r,y:i}}function Ie(e,t){return e.x>=t.x&&e.y>=t.y&&e.x+e.width<=t.x+t.width&&e.y+e.height<=t.y+t.height}function Le(e,t,n,r){let i=Object.keys(e).sort(Ee),a=[...t].sort(Ee),o=a.filter(e=>!i.includes(e)),s=i.filter(e=>!a.includes(e));(o.length!==0||s.length!==0)&&h(r,`view2d/pin-mismatch`,`Geometry pins must match the device pins: ${[o.length===0?void 0:`missing ${o.map(Re).join(`, `)}`,s.length===0?void 0:`undeclared ${s.map(Re).join(`, `)}`].filter(e=>e!==void 0).join(`; `)}.`,[...n,`pins`])}function Re(e){return JSON.stringify(e)}let ze=[`string`,`integer`,`number`,`boolean`,`color`,`enum`,`image`,`binary`,`firmware`,`program`],Be=[`type`,`title`,`description`,`default`,`nullable`,`group`,`order`],Ve={string:[...Be,`maxLength`],integer:[...Be,`min`,`max`,`step`],number:[...Be,`min`,`max`,`exclusiveMin`,`step`,`unit`],boolean:Be,color:[...Be,`alpha`],enum:[...Be,`options`],image:[...Be,`maxBytes`,`maxPixels`],binary:[...Be,`maxBytes`,`extensions`],firmware:[...Be,`maxBytes`,`addressSpaces`,`addressSpace`,`loadAddress`],program:[...Be,`loader`,`formats`,`addressSpaces`,`defaults`,`templates`]};function He(e){return ze.includes(e)}function Ue(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"properties\" must be an object.`,t);return}let r=Object.create(null),i=!1;for(let[a,o]of Object.entries(e)){let e=[...t,a];if(!se(a)){h(n,`package/invalid-manifest`,`Property key ${JSON.stringify(a)} must match [A-Za-z][A-Za-z0-9]*.`,e),i=!0;continue}let s=We(o,e,n);s===void 0?i=!0:r[a]=s}return i?void 0:r}function We(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Property description must be an object.`,t);return}let r=F(e,`type`,t,n,!0,{nonEmpty:!0});if(r===void 0)return;if(!He(r)){h(n,`package/invalid-manifest`,`Unknown property type ${JSON.stringify(r)}.`,[...t,`type`]);return}P(e,Ve[r],t,n);let i={type:r},a=!1,o=F(e,`title`,t,n,!1,{nonEmpty:!0});o!==void 0&&(i.title=o);let s=F(e,`description`,t,n,!1,{nonEmpty:!0});s!==void 0&&(i.description=s);let c=F(e,`group`,t,n,!1,{nonEmpty:!0});if(c!==void 0&&(i.group=c),we(e,`nullable`,t,n,!1)===!0&&(i.nullable=!0),N(e,`order`)){let r=Ce(e,`order`,t,n);r===void 0?a=!0:r<0?(h(n,`package/invalid-manifest`,`Field \"order\" must be a non-negative integer.`,[...t,`order`]),a=!0):i.order=r}switch(r){case`program`:Ye(e,t,n,i)||(a=!0);break;case`string`:{let r=Ge(e,`maxLength`,t,n);r===`invalid`?a=!0:r!==void 0&&(i.maxLength=r);break}case`integer`:case`number`:if(Ke(e,r,t,n,i)||(a=!0),r===`number`){let r=F(e,`unit`,t,n,!1,{nonEmpty:!0});r!==void 0&&(i.unit=r)}break;case`color`:we(e,`alpha`,t,n,!1)===!0&&(i.alpha=!0);break;case`enum`:{let r=qe(e,t,n);r===void 0?a=!0:i.options=r;break}case`image`:case`binary`:case`firmware`:{let o=Ge(e,`maxBytes`,t,n);if(o===`invalid`?a=!0:o!==void 0&&(i.maxBytes=o),r===`image`){let r=Ge(e,`maxPixels`,t,n);r===`invalid`?a=!0:r!==void 0&&(i.maxPixels=r)}if(r===`binary`){let r=Je(e,t,n);r===`invalid`?a=!0:r!==void 0&&(i.extensions=r)}r===`firmware`&&!Xe(e,t,n,i)&&(a=!0);break}}if(N(e,`default`)){let r=Qe(e.default,i,[...t,`default`],n);r===void 0?a=!0:i.default=r.value}return a?void 0:i}function Ge(e,t,n,r){if(!N(e,t))return;let i=Ce(e,t,n,r);return i===void 0?`invalid`:i<0?(h(r,`package/invalid-manifest`,`Field \"${t}\" must be a non-negative integer.`,[...n,t]),`invalid`):i}function Ke(e,t,n,r,i){let a=!0,o=I(e,`min`,n,r,!1),s=I(e,`max`,n,r,!1);if(t===`integer`)N(e,`min`)&&(o===void 0||!Number.isSafeInteger(o))?(h(r,`package/invalid-manifest`,`Field \"min\" must be a safe integer for an integer property.`,[...n,`min`]),a=!1):o!==void 0&&(i.min=o),N(e,`max`)&&(s===void 0||!Number.isSafeInteger(s))?(h(r,`package/invalid-manifest`,`Field \"max\" must be a safe integer for an integer property.`,[...n,`max`]),a=!1):s!==void 0&&(i.max=s);else{o!==void 0&&(i.min=o),s!==void 0&&(i.max=s);let t=I(e,`exclusiveMin`,n,r,!1);t!==void 0&&(i.exclusiveMin=t)}if(i.min!==void 0&&i.max!==void 0&&i.min>i.max&&(h(r,`package/invalid-manifest`,`Field \"min\" must not be greater than \"max\".`,[...n,`min`]),a=!1),N(e,`step`)){let o=I(e,`step`,n,r,!1);o===void 0||o<=0?(h(r,`package/invalid-manifest`,`Field \"step\" must be greater than zero.`,[...n,`step`]),a=!1):t===`integer`&&!Number.isSafeInteger(o)?(h(r,`package/invalid-manifest`,`Field \"step\" must be a safe integer for an integer property.`,[...n,`step`]),a=!1):i.step=o}return a}function qe(e,t,n){let r=Te(e,`options`,t,n);if(r===void 0)return;if(r.length===0){h(n,`package/invalid-manifest`,`Field \"options\" must contain at least one option.`,[...t,`options`]);return}let i=[],a=/* @__PURE__ */ new Set,o=!1;return r.forEach((e,r)=>{let s=[...t,`options`,String(r)];if(!M(e)){h(n,`schema/invalid-type`,`Enum option must be an object.`,s),o=!0;return}P(e,[`value`,`label`],s,n);let c=F(e,`value`,s,n,!0,{nonEmpty:!0}),l=F(e,`label`,s,n,!0,{nonEmpty:!0});c===void 0||l===void 0?o=!0:a.has(c)?(h(n,`package/invalid-manifest`,`Enum option value ${JSON.stringify(c)} is declared more than once.`,[...s,`value`]),o=!0):(a.add(c),i.push({value:c,label:l}))}),o?void 0:i}function Je(e,t,n){if(!N(e,`extensions`))return;let r=Te(e,`extensions`,t,n);if(r===void 0)return`invalid`;if(r.length===0)return h(n,`package/invalid-manifest`,`Field \"extensions\" must contain at least one extension.`,[...t,`extensions`]),`invalid`;let i=[],a=/* @__PURE__ */ new Set,o=!1;return r.forEach((e,r)=>{let s=[...t,`extensions`,String(r)];if(typeof e!=`string`||!fe(e)){h(n,`package/invalid-manifest`,`Extension filters must match \"\\\\.[A-Za-z0-9]+\".`,s),o=!0;return}let c=e.toLowerCase();a.has(c)?(h(n,`package/invalid-manifest`,`Extension filter ${JSON.stringify(e)} is declared more than once.`,s),o=!0):(a.add(c),i.push(e))}),o?`invalid`:i}function Ye(e,t,n,r){let i=(e,r)=>(h(n,`package/invalid-manifest`,e,[...t,r]),!1),a=!0;if(N(e,`templates`)){let t=e.templates;!Array.isArray(t)||t.some(e=>typeof e!=`string`||e.length===0)||new Set(t).size!==t.length?a=i(`Templates must be unique non-empty string IDs.`,`templates`):r.templates=t}let o=e.loader;if(o!==`memory`&&o!==`filesystem`)return i(`Program loader must be memory or filesystem.`,`loader`);if(r.loader=o,o===`filesystem`){for(let t of[`formats`,`addressSpaces`,`defaults`])N(e,t)&&(a=i(`Filesystem programs do not declare ${t}.`,t));return a}let s=e.formats;if(!Array.isArray(s)||s.length===0||!s.every(e=>e===`bin`||e===`hex`||e===`elf`)||new Set(s).size!==s.length)return i(`Memory formats must be a non-empty unique subset of bin, hex and elf.`,`formats`);r.formats=s;let c=L(e,`addressSpaces`,t,n);if(c===void 0||Object.keys(c).length===0)return i(`Memory programs require address spaces.`,`addressSpaces`);let l=Object.create(null);for(let[e,r]of Object.entries(c)){if(e.length===0){a=i(`Address space IDs must not be empty.`,`addressSpaces`);continue}let o=Ze(r,[...t,`addressSpaces`,e],n);o===void 0?a=!1:l[e]=o}if(r.addressSpaces=l,!s.includes(`bin`)&&!s.includes(`hex`))return N(e,`defaults`)?i(`ELF-only programs do not declare defaults.`,`defaults`):a;let u=L(e,`defaults`,t,n);if(u===void 0)return!1;let d=[...t,`defaults`];P(u,[`addressSpace`,`loadAddress`],d,n);let f=F(u,`addressSpace`,d,n,!0,{nonEmpty:!0});if(f===void 0||l[f]===void 0)return i(`Default addressSpace must name a declared space.`,`defaults`);let p=Ce(u,`loadAddress`,d,n,s.includes(`bin`));if(s.includes(`bin`)){let e=l[f];if(p===void 0||p<e.start||p>=e.start+e.size)return i(`Default loadAddress must lie in its address space.`,`defaults`)}else if(N(u,`loadAddress`))return i(`Only BIN programs declare a default loadAddress.`,`defaults`);return r.defaults={addressSpace:f,...p===void 0?{}:{loadAddress:p}},a}function Xe(e,t,n,r){let i=!0,a=[...t,`addressSpaces`],o=L(e,`addressSpaces`,t,n),s;if(o===void 0)i=!1;else if(Object.keys(o).length===0)h(n,`package/invalid-manifest`,`Field \"addressSpaces\" must declare at least one address space.`,a),i=!1;else{s=Object.create(null);for(let[e,t]of Object.entries(o)){let r=[...a,e];if(e.length===0){h(n,`package/invalid-manifest`,`Address space ids must not be empty.`,r),i=!1;continue}let o=Ze(t,r,n);o===void 0?i=!1:s[e]=o}i&&(r.addressSpaces=s)}let c=F(e,`addressSpace`,t,n,!0,{nonEmpty:!0}),l=Ce(e,`loadAddress`,t,n,!0);if(l!==void 0&&l<0&&(h(n,`package/invalid-manifest`,`Field \"loadAddress\" must be a non-negative safe integer.`,[...t,`loadAddress`]),i=!1),c===void 0||s===void 0)return!1;let u=s[c];return u===void 0?(h(n,`package/invalid-manifest`,`Field \"addressSpace\" must name a declared address space; \"${c}\" is unknown.`,[...t,`addressSpace`]),!1):(r.addressSpace=c,l!==void 0&&(r.loadAddress=l,(l<u.start||l>=u.start+u.size)&&(h(n,`package/invalid-manifest`,`Field \"loadAddress\" must lie inside the \"${c}\" range.`,[...t,`loadAddress`]),i=!1),i))}function Ze(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Address space must be an object.`,t);return}P(e,[`title`,`start`,`size`],t,n);let r=F(e,`title`,t,n,!1,{nonEmpty:!0}),i=Ce(e,`start`,t,n,!0),a=Ce(e,`size`,t,n,!0),o=!1;if(i!==void 0&&i<0&&(h(n,`package/invalid-manifest`,`Field \"start\" must be a non-negative safe integer.`,[...t,`start`]),o=!0),a!==void 0&&a<=0&&(h(n,`package/invalid-manifest`,`Field \"size\" must be a positive safe integer.`,[...t,`size`]),o=!0),i!==void 0&&a!==void 0&&!Number.isSafeInteger(i+a)&&(h(n,`package/invalid-manifest`,`The address space must end at a safe integer.`,[...t,`size`]),o=!0),!(o||i===void 0||a===void 0))return{...r===void 0?{}:{title:r},start:i,size:a}}function Qe(e,t,n,r){let i=e=>{h(r,`package/invalid-manifest`,e,n)};if(e===null)return t.nullable===!0?{value:null}:i(`A default of null requires \"nullable\": true.`);switch(t.type){case`string`:{if(typeof e!=`string`)return i(`Default must be a string.`);let n=t.maxLength;return n!==void 0&&[...e].length>n?i(`Default must be at most ${String(n)} characters.`):{value:e}}case`integer`:return typeof e!=`number`||!Number.isSafeInteger(e)?i(`Default must be a safe integer.`):t.min!==void 0&&e<t.min?i(`Default must be at least ${String(t.min)}.`):t.max!==void 0&&e>t.max?i(`Default must be at most ${String(t.max)}.`):{value:e};case`number`:return typeof e!=`number`||!Number.isFinite(e)?i(`Default must be a finite number.`):t.exclusiveMin!==void 0&&e<=t.exclusiveMin?i(`Default must be greater than ${String(t.exclusiveMin)}.`):t.min!==void 0&&e<t.min?i(`Default must be at least ${String(t.min)}.`):t.max!==void 0&&e>t.max?i(`Default must be at most ${String(t.max)}.`):{value:e};case`boolean`:return typeof e==`boolean`?{value:e}:i(`Default must be a boolean.`);case`color`:{let n=typeof e==`string`?ge(e):void 0;return n===void 0?i(`Default must be a \"#RRGGBB\" or \"#RRGGBBAA\" color.`):t.alpha!==!0&&n.length===9&&!n.endsWith(`FF`)?i(`Default must use an FF alpha channel unless \"alpha\": true.`):{value:n}}case`enum`:{let n=(t.options??[]).map(e=>e.value);return typeof e==`string`&&n.includes(e)?{value:e}:i(`Default must be one of ${n.map(e=>JSON.stringify(e)).join(`, `)}.`)}case`image`:case`binary`:{let t=$e(e,n,r);return t===void 0?void 0:{value:t}}case`firmware`:case`program`:{let a=$e(e,n,r);if(a===void 0)return;if(t.type===`program`){let e=a.src.split(`.`).at(-1)?.toLowerCase(),n=e===`bin`,r=e===`hex`||e===`ihx`,o=n?`bin`:r?`hex`:e===`elf`||e===`axf`?`elf`:void 0;if(t.loader===`memory`&&(o===void 0||!t.formats?.includes(o)))return i(`The default program file must use an accepted format.`);if((t.loader===`filesystem`||!n&&!r)&&(a.addressSpace!==void 0||a.loadAddress!==void 0))return i(`This program default does not accept address overrides.`);if(!n&&a.loadAddress!==void 0)return i(`Only BIN defaults accept loadAddress.`)}let o=a.addressSpace??(t.type===`program`?t.defaults?.addressSpace:void 0);if(o!==void 0){let e=t.addressSpaces?.[o];if(e===void 0)return i(`Default address space \"${o}\" is not declared.`);let n=a.loadAddress;if(n!==void 0&&(n<e.start||n>=e.start+e.size))return i(`Default load address must lie inside the \"${o}\" range.`)}return{value:a}}}}function $e(e,t,n){if(!M(e)){h(n,`package/invalid-manifest`,`Default must be a \"package\" resource reference.`,t);return}P(e,[`src`,`mode`,`addressSpace`,`loadAddress`],t,n);let r=F(e,`mode`,t,n,!0,{nonEmpty:!0}),i=F(e,`src`,t,n,!0,{nonEmpty:!0});if(r!==`package`){h(n,`package/invalid-manifest`,`A declared package default must use \"mode\": \"package\".`,[...t,`mode`]);return}if(i===void 0)return;let a=pe(i);if(a!==void 0){h(n,`package/invalid-manifest`,`Default \"src\" ${a}.`,[...t,`src`]);return}let o=F(e,`addressSpace`,t,n,!1,{nonEmpty:!0}),s=Ce(e,`loadAddress`,t,n,!1);if(s!==void 0&&s<0)h(n,`package/invalid-manifest`,`Default \"loadAddress\" must be a non-negative safe integer.`,[...t,`loadAddress`]);else return{src:i,mode:`package`,...o===void 0?{}:{addressSpace:o},...s===void 0?{}:{loadAddress:s}}}let et=[`null`,`boolean`,`number`,`string`,`binary`];function tt(e,t,n){let r=/* @__PURE__ */ new Set;for(let i of Object.keys(e))se(i)?r.add(i):h(n,`model/invalid-interface`,`Public type name ${JSON.stringify(i)} must match [A-Za-z][A-Za-z0-9]*.`,[...t,i]);let i=Object.create(null),a=!1;for(let[o,s]of Object.entries(e)){if(!r.has(o))continue;let e=nt(s,[...t,o],n,r);e===void 0?a=!0:i[o]=e}return a||rt(i,t,n),{types:i,names:r}}function nt(e,t,n,r){if(!M(e)){h(n,`schema/invalid-type`,`Value type must be an object.`,t);return}let i=N(e,`ref`),a=N(e,`type`);if(i&&a){h(n,`schema/invalid-value`,`Value type must declare either \"ref\" or \"type\", not both.`,t);return}if(i){P(e,[`ref`],t,n);let i=F(e,`ref`,t,n,!0,{nonEmpty:!0});if(i===void 0)return;if(!r.has(i)){h(n,`type/unknown`,`Unknown public type \"${i}\".`,[...t,`ref`]);return}return{ref:i}}if(!a){h(n,`schema/missing-field`,`Value type must declare \"type\" or \"ref\".`,[...t,`type`]);return}let o=F(e,`type`,t,n,!0,{nonEmpty:!0});if(o!==void 0){if(et.includes(o))return P(e,[`type`],t,n),{type:o};switch(o){case`array`:{P(e,[`type`,`items`],t,n);let i=[...t,`items`];if(!N(e,`items`)){h(n,`schema/missing-field`,`Missing required field \"items\".`,i);return}let a=nt(e.items,i,n,r);return a===void 0?void 0:{type:`array`,items:a}}case`object`:{P(e,[`type`,`properties`,`optional`,`additionalProperties`],t,n);let i=L(e,`properties`,t,n);if(i===void 0)return;let a=Object.create(null),o=!1;for(let[e,s]of Object.entries(i)){if(!se(e)){h(n,`model/invalid-interface`,`Property name ${JSON.stringify(e)} must match [A-Za-z][A-Za-z0-9]*.`,[...t,`properties`,e]),o=!0;continue}let i=nt(s,[...t,`properties`,e],n,r);i===void 0?o=!0:a[e]=i}let s=[],c=Te(e,`optional`,t,n,!1);if(c!==void 0){let e=/* @__PURE__ */ new Set;c.forEach((r,a)=>{let c=[...t,`optional`,String(a)];typeof r!=`string`||r.length===0?(h(n,`schema/invalid-type`,`Optional property names must be non-empty strings.`,c),o=!0):e.has(r)?(h(n,`schema/invalid-value`,`Optional property \"${r}\" is listed more than once.`,c),o=!0):(e.add(r),N(i,r)?s.push(r):(h(n,`model/invalid-interface`,`Optional property \"${r}\" is not declared in \"properties\".`,c),o=!0))})}let l;return N(e,`additionalProperties`)&&(l=nt(e.additionalProperties,[...t,`additionalProperties`],n,r),l===void 0&&(o=!0)),o?void 0:{type:`object`,properties:a,...c===void 0?{}:{optional:s},...l===void 0?{}:{additionalProperties:l}}}default:h(n,`model/invalid-interface`,`Unknown value type ${JSON.stringify(o)}.`,[...t,`type`]);return}}}function rt(e,t,n){for(let r of Object.keys(e)){let i=[],a=e[r];for(;a!==void 0&&!(`type`in a);){let o=a.ref;if(o===r||i.includes(o)){h(n,`model/invalid-interface`,`Public type \"${r}\" resolves through a cycle of \"ref\" declarations.`,[...t,r]);break}i.push(o),a=e[o]}}}function it(e,t,n={}){let r=[];if(at(e,t,[],r,n),xe(r))throw new m(r)}function at(e,t,n,r,i){let a=ot(t,n,r,i);if(a!==void 0)switch(a.type){case`null`:e!==null&&st(r,`null`,n);return;case`boolean`:typeof e!=`boolean`&&st(r,`a boolean`,n);return;case`number`:(typeof e!=`number`||!Number.isFinite(e))&&st(r,`a finite number`,n);return;case`string`:typeof e!=`string`&&st(r,`a string`,n);return;case`binary`:e instanceof Uint8Array||st(r,`a Uint8Array`,n);return;case`array`:if(!Array.isArray(e)){st(r,`an array`,n);return}e.forEach((e,t)=>{at(e,a.items,[...n,String(t)],r,i)});return;case`object`:{if(!ct(e)){st(r,`an object`,n);return}let t=a.optional??[];for(let[o,s]of Object.entries(a.properties))N(e,o)?at(e[o],s,[...n,o],r,i):t.includes(o)||h(r,`schema/invalid-value`,`Missing required property \"${o}\".`,[...n,o]);let o=a.additionalProperties;for(let t of Object.keys(e))N(a.properties,t)||(o===void 0?h(r,`schema/invalid-value`,`Unexpected property \"${t}\".`,[...n,t]):at(e[t],o,[...n,t],r,i));return}}}function ot(e,t,n,r){let i=[],a=e;for(;`ref`in a;){let e=a.ref;if(i.includes(e)){h(n,`model/invalid-interface`,`Public type \"${e}\" resolves through a cycle of \"ref\" declarations.`,t);return}i.push(e);let o=r[e];if(o===void 0){h(n,`type/unknown`,`Unknown public type \"${e}\".`,t);return}a=o}return a}function st(e,t,n){h(e,`schema/invalid-value`,`Value must be ${t}.`,n)}function ct(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Uint8Array)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}let lt=[`publisher`,`name`,`version`,`description`,`license`,`engines`,`displayName`,`icon`,`designatorPrefix`,`entries`,`properties`,`pins`,`model`,`view2d`,`view`],ut=/* @__PURE__ */ `$schema.author.bugs.bundleDependencies.bundledDependencies.contributors.cpu.dependencies.devDependencies.directories.exports.files.funding.homepage.imports.keywords.main.man.module.optionalDependencies.os.packageManager.peerDependencies.peerDependenciesMeta.private.publishConfig.repository.scripts.sideEffects.type.types.typings.workspaces`.split(`.`);function dt(e){let t=[],n=Se(e,t);if(!n.ok)throw new m(t);let r=ft(n.value,t);if(r===void 0||xe(t))throw new m(t);return De(r)}function ft(e,t){if(!M(e)){h(t,`json/not-object`,`Manifest must be a JSON object.`,[]);return}P(e,[...lt,...ut],[],t);let n=pt(e,`publisher`,t),r=pt(e,`name`,t),i=mt(e,t),a=F(e,`description`,[],t,!1),o=F(e,`license`,[],t,!1),s=ht(e,[],t),c=F(e,`displayName`,[],t,!0,{nonEmpty:!0}),l=gt(e,[],t),u=_t(e,[],t),d=N(e,`entries`)?vt(e.entries,[`entries`],t):void 0,f=N(e,`properties`)?Ue(e.properties,[`properties`],t):void 0,p=N(e,`pins`)?yt(e.pins,[`pins`],t):void 0,m=N(e,`model`),g=m?bt(e.model,[`model`],t):void 0,_=Object.keys(p??{}),v=N(e,`view2d`)?wt(e.view2d,[`view2d`],t,_):void 0,y=N(e,`view`)?Tt(e.view,[`view`],t):void 0;if(_.length>0&&!m&&h(t,`package/invalid-manifest`,`A device that declares pins must declare its model.`,[`model`]),!(n===void 0||r===void 0||i===void 0||s===void 0||c===void 0||N(e,`icon`)&&l===void 0||N(e,`designatorPrefix`)&&u===void 0||N(e,`entries`)&&d===void 0||N(e,`properties`)&&f===void 0||N(e,`pins`)&&p===void 0||m&&g===void 0||N(e,`view2d`)&&v===void 0||N(e,`view`)&&y===void 0))return{publisher:n,name:r,version:i,...a===void 0?{}:{description:a},...o===void 0?{}:{license:o},engines:s,displayName:c,...l===void 0?{}:{icon:l},...u===void 0?{}:{designatorPrefix:u},...d===void 0?{}:{entries:d},...f===void 0?{}:{properties:f},...p===void 0?{}:{pins:p},...g===void 0?{}:{model:g},...v===void 0?{}:{view2d:v},...y===void 0?{}:{view:y}}}function pt(e,t,n){let r=F(e,t,[],n,!0,{nonEmpty:!0});if(r!==void 0){if(!re(r))h(n,`package/invalid-manifest`,`Field \"${t}\" must match [a-z0-9]+(?:-[a-z0-9]+)*.`,[t]);else return r}}function mt(e,t){let n=F(e,`version`,[],t,!0,{nonEmpty:!0});if(n!==void 0){if(!oe(n))h(t,`package/invalid-manifest`,`Field \"version\" must be a full SemVer version.`,[`version`]);else return n}}function ht(e,t,n){let r=L(e,`engines`,t,n);if(r===void 0)return;let i=F(r,`mica`,[...t,`engines`],n,!0,{nonEmpty:!0});return i===void 0?void 0:{mica:i}}function gt(e,t,n){return Dt(e,`icon`,t,n,[`.png`,`.svg`],`package/invalid-icon`,!1)}function _t(e,t,n){let r=F(e,`designatorPrefix`,t,n,!1,{nonEmpty:!0});if(r!==void 0){if(!de(r))h(n,`package/invalid-manifest`,`Field \"designatorPrefix\" must be a non-empty alphanumeric prefix.`,[...t,`designatorPrefix`]);else return r}}function vt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"entries\" must be an object.`,t);return}P(e,[`view3d`],t,n);let r=N(e,`view3d`)?Dt(e,`view3d`,t,n,[`.js`],`package/invalid-path`):void 0;if(!(N(e,`view3d`)&&r===void 0))return{...r===void 0?{}:{view3d:r}}}function yt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"pins\" must be an object.`,t);return}let r=Object.create(null),i=!1;for(let[a,o]of Object.entries(e)){let e=[...t,a];if(!le(a)){h(n,`package/invalid-manifest`,`Pin id ${JSON.stringify(a)} is not a legal model pin name.`,e),i=!0;continue}if(!M(o)){h(n,`schema/invalid-type`,`Pin declaration must be an object.`,e),i=!0;continue}P(o,[`label`,`description`],e,n);let s=F(o,`label`,e,n,!1,{nonEmpty:!0}),c=F(o,`description`,e,n,!1,{nonEmpty:!0});N(o,`label`)&&s===void 0||N(o,`description`)&&c===void 0?i=!0:r[a]={...s===void 0?{}:{label:s},...c===void 0?{}:{description:c}}}return i?void 0:r}function bt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"model\" must be an object.`,t);return}P(e,[`entry`,`types`,`methods`,`events`],t,n);let r=Dt(e,`entry`,t,n,[`.js`],`package/invalid-path`),i=/* @__PURE__ */ new Set,a,o=!1,s=N(e,`types`)?L(e,`types`,t,n):void 0;if(N(e,`types`)&&s===void 0)o=!0;else if(s!==void 0){let e=tt(s,[...t,`types`],n);a=e.types;for(let t of e.names)i.add(t)}let c=N(e,`methods`)?xt(e.methods,[...t,`methods`],n,i):void 0;N(e,`methods`)&&c===void 0&&(o=!0);let l=N(e,`events`)?St(e.events,[...t,`events`],n,i):void 0;if(N(e,`events`)&&l===void 0&&(o=!0),!(o||r===void 0))return{entry:r,...a===void 0?{}:{types:a},...c===void 0?{}:{methods:c},...l===void 0?{}:{events:l}}}function xt(e,t,n,r){if(!M(e)){h(n,`schema/invalid-type`,`Field \"methods\" must be an object.`,t);return}let i=Object.create(null),a=!1;for(let[o,s]of Object.entries(e)){let e=[...t,o];if(!se(o)){h(n,`model/invalid-interface`,`Method name ${JSON.stringify(o)} must match [A-Za-z][A-Za-z0-9]*.`,e),a=!0;continue}if(!M(s)){h(n,`schema/invalid-type`,`Method declaration must be an object.`,e),a=!0;continue}P(s,[`params`,`returns`],e,n);let c=Ct(s,`params`,e,n,r),l=Ct(s,`returns`,e,n,r);c===void 0||l===void 0?a=!0:i[o]={params:c,returns:l}}return a?void 0:i}function St(e,t,n,r){if(!M(e)){h(n,`schema/invalid-type`,`Field \"events\" must be an object.`,t);return}let i=Object.create(null),a=!1;for(let[o,s]of Object.entries(e)){let e=[...t,o];if(!ce(o)){h(n,`model/invalid-interface`,`Event name ${JSON.stringify(o)} must use the onDidXxx form.`,e),a=!0;continue}let c=nt(s,e,n,r);c===void 0?a=!0:i[o]=c}return a?void 0:i}function Ct(e,t,n,r,i){let a=[...n,t];if(!N(e,t))h(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);else return nt(e[t],a,r,i)}function wt(e,t,n,r){if(!M(e)){h(n,`schema/invalid-type`,`Field \"view2d\" must be an object.`,t);return}P(e,[`geometry`,`entry`],t,n);let i;N(e,`geometry`)?i=typeof e.geometry==`string`?Dt(e,`geometry`,t,n,[`.json`],`package/invalid-path`):ke(e.geometry,[...t,`geometry`],n,r):h(n,`schema/missing-field`,`Missing required field \"geometry\".`,[...t,`geometry`]);let a=N(e,`entry`)?Dt(e,`entry`,t,n,[`.js`],`package/invalid-path`):void 0;if(!(i===void 0||N(e,`entry`)&&a===void 0))return{geometry:i,...a===void 0?{}:{entry:a}}}function Tt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"view\" must be an object.`,t);return}let r=Object.create(null),i=!1;for(let[a,o]of Object.entries(e)){let e=[...t,a];if(!se(a)){h(n,`package/invalid-manifest`,`View id ${JSON.stringify(a)} must match [A-Za-z][A-Za-z0-9]*.`,e),i=!0;continue}let s=Et(o,e,n);s===void 0?i=!0:r[a]=s}return i?void 0:r}function Et(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`HTML view declaration must be an object.`,t);return}P(e,[`title`,`entry`,`defaultLocation`,`icon`],t,n);let r=F(e,`title`,t,n,!0,{nonEmpty:!0}),i=Dt(e,`entry`,t,n,[`.html`],`package/invalid-path`),a=F(e,`defaultLocation`,t,n,!1,{nonEmpty:!0}),o=F(e,`icon`,t,n,!1,{nonEmpty:!0}),s=!1,c;if(a!==void 0&&(a===`sidebar`||a===`floating`?c=a:(h(n,`package/invalid-manifest`,`Field \"defaultLocation\" must be \"sidebar\" or \"floating\".`,[...t,`defaultLocation`]),s=!0)),o!==void 0&&!ue(o)&&(h(n,`package/invalid-manifest`,`Field \"icon\" must be a Codicons icon name.`,[...t,`icon`]),s=!0),!(s||r===void 0||i===void 0))return{title:r,entry:i,...c===void 0?{}:{defaultLocation:c},...o===void 0?{}:{icon:o}}}function Dt(e,t,n,r,i,a,o=!0){let s=F(e,t,n,r,o,{nonEmpty:!0});if(s===void 0)return;let c=pe(s);if(c!==void 0){h(r,a,`Field \"${t}\" ${c}.`,[...n,t]);return}let l=me(s,i);if(l!==void 0)h(r,a,`Field \"${t}\" ${l}.`,[...n,t]);else return s}let Ot=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function kt(e){return Ot.test(e)}let At=[`asset`,`package`];function jt(e,t,n){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(!Number.isFinite(e)){h(n,`schema/invalid-value`,`Numeric property values must be finite.`,t);return}return e}if(M(e))return Mt(e,t,n);h(n,`schema/invalid-type`,`Property value must be a scalar, a resource reference, a firmware reference or null.`,t)}function Mt(e,t,n){let r=F(e,`mode`,t,n,!0,{nonEmpty:!0});if(r!==void 0){if(r===`project`)return Nt(e,t,n);if(!At.includes(r))h(n,`schema/invalid-value`,`Field \"mode\" must be \"asset\", \"package\" or \"project\".`,[...t,`mode`]);else return Pt(e,r,t,n)}}function Nt(e,t,n){P(e,[`mode`,`projectId`,`name`,`addressSpace`,`loadAddress`],t,n);let r=F(e,`projectId`,t,n,!0,{nonEmpty:!0}),i=Ft(e,t,n);if(r===void 0||i===void 0)return;let a=F(e,`name`,t,n,!1,{nonEmpty:!0});return{mode:`project`,projectId:r,...a===void 0?{}:{name:a},...i}}function Pt(e,t,n,r){let i=N(e,`addressSpace`)||N(e,`loadAddress`),a=t===`asset`?[`assetId`,`name`,`mode`]:[`src`,`mode`];if(P(e,i?[...a,`addressSpace`,`loadAddress`]:a,n,r),t===`asset`){let i=F(e,`assetId`,n,r,!0,{nonEmpty:!0}),a=F(e,`name`,n,r,!0,{nonEmpty:!0}),o=Ft(e,n,r);return i===void 0||a===void 0||o===void 0?void 0:{mode:t,assetId:i,name:a,...o}}let o=F(e,`src`,n,r,!0,{nonEmpty:!0});if(o===void 0)return;let s=It(t,o);if(s!==void 0){h(r,`schema/invalid-value`,`Field \"src\" ${s}.`,[...n,`src`]);return}if(!i)return{src:o,mode:t};let c=Ft(e,n,r);if(c!==void 0)return{src:o,mode:`package`,...c}}function Ft(e,t,n){let r=F(e,`addressSpace`,t,n,!1,{nonEmpty:!0}),i=Ce(e,`loadAddress`,t,n,!1);if(i!==void 0&&i<0)h(n,`schema/invalid-value`,`Field \"loadAddress\" must be a non-negative safe integer.`,[...t,`loadAddress`]);else if(!(N(e,`addressSpace`)&&r===void 0)&&!(N(e,`loadAddress`)&&i===void 0))return{...r===void 0?{}:{addressSpace:r},...i===void 0?{}:{loadAddress:i}}}function It(e,t){switch(e){case`package`:return pe(t);case`asset`:return t.length===0?`must not be empty`:void 0}}let Lt=[`version`,`dependencies`,`instances`,`nodes`,`wires`,`labels`,`references`,`display`];function Rt(e){let t=[],n=Se(e,t);if(!n.ok)throw new m(t);let r=zt(n.value,t);if(r===void 0||xe(t))throw new m(t);return De(r)}function zt(e,t){if(!M(e)){h(t,`json/not-object`,`Fused schematic must be a JSON object.`,[]);return}P(e,Lt,[],t);let n=Bt(e,t),r=Ht(L(e,`dependencies`,[],t),[`dependencies`],t),i=Vt(e,`instances`,[],t,Ut),a=Vt(e,`nodes`,[],t,Zt),o=Vt(e,`wires`,[],t,Qt),s=Vt(e,`labels`,[],t,en),c=Vt(e,`references`,[],t,tn),l=N(e,`display`)?qt(e.display,[`display`],t):void 0;on(i,a,o,s,c,t),sn(i,t);let u=new Set(i.items.map(e=>e.value.id)),d=new Set(a.items.map(e=>e.value.id));if(r!==void 0)for(let e of i.items)Object.prototype.hasOwnProperty.call(r,e.value.device)||h(t,`document/unlocked-device`,`Instance device \"${e.value.device}\" is not locked by \"dependencies\".`,[...e.path,`device`]);for(let e of o.items){let n=[...e.path,`from`],r=[...e.path,`to`];rn(e.value.from,n,u,d,t),rn(e.value.to,r,u,d,t),an(e.value.from,e.value.to)&&h(t,`connection/self-edge`,`A wire must not connect an endpoint to itself.`,r)}for(let e of s.items)rn(e.value.target,[...e.path,`target`],u,d,t);for(let e of c.items)rn(e.value.target,[...e.path,`target`],u,d,t);if(!(n===void 0||r===void 0||i.failed||a.failed||o.failed||s.failed||c.failed||N(e,`display`)&&l===void 0))return{version:n,dependencies:r,instances:i.items.map(e=>e.value),nodes:a.items.map(e=>e.value),wires:o.items.map(e=>e.value),labels:s.items.map(e=>e.value),references:c.items.map(e=>e.value),...l===void 0?{}:{display:l}}}function Bt(e,t){let n=Ce(e,`version`,[],t);if(n!==void 0){if(n!==2)h(t,`schema/unsupported-version`,`Unsupported version ${String(n)}; expected 2.`,[`version`]);else return 2}}function Vt(e,t,n,r,i){let a=Te(e,t,n,r);if(a===void 0)return{items:[],failed:!0};let o=[],s=!1;return a.forEach((e,a)=>{let c=[...n,t,String(a)],l=i(e,c,r);l===void 0?s=!0:o.push({value:l,path:c})}),{items:o,failed:s}}function Ht(e,t,n){if(e===void 0)return;let r=Object.create(null),i=!1;for(let[a,o]of Object.entries(e)){let e=[...t,a],s=ae(a);if(s!==void 0){h(n,`schema/invalid-value`,`Dependency key ${JSON.stringify(a)} ${s}.`,e),i=!0;continue}if(!M(o)){h(n,`schema/invalid-type`,`Dependency must be an object.`,e),i=!0;continue}P(o,[`version`,`integrity`],e,n);let c=F(o,`version`,e,n,!0,{nonEmpty:!0});c!==void 0&&!oe(c)&&(h(n,`schema/invalid-value`,`Dependency \"version\" must be a full SemVer version.`,[...e,`version`]),i=!0);let l=F(o,`integrity`,e,n,!0,{nonEmpty:!0}),u=l===void 0?void 0:he(l);u!==void 0&&(h(n,`schema/invalid-value`,`Dependency \"integrity\" ${u}.`,[...e,`integrity`]),i=!0),c===void 0||l===void 0||u!==void 0?i=!0:r[a]={version:c,integrity:l}}return i?void 0:r}function Ut(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Instance must be an object.`,t);return}P(e,[`id`,`device`,`designator`,`designatorOffset`,`placement`,`properties`,`display`,`viewLayout`],t,n);let r=nn(e,`id`,t,n),i=F(e,`device`,t,n,!0,{nonEmpty:!0}),a=i===void 0?void 0:ae(i);a!==void 0&&h(n,`schema/invalid-value`,`Field \"device\" ${a}.`,[...t,`device`]);let o=F(e,`designator`,t,n,!1,{nonEmpty:!0}),s=N(e,`designatorOffset`)?Fe(e.designatorOffset,[...t,`designatorOffset`],n):void 0,c=N(e,`placement`)?Wt(e.placement,[...t,`placement`],n):void 0;N(e,`placement`)||h(n,`schema/missing-field`,`Missing required field \"placement\".`,[...t,`placement`]);let l=N(e,`properties`)?Gt(e.properties,[...t,`properties`],n):void 0,u=N(e,`display`)?Kt(e.display,[...t,`display`],n):void 0,d=N(e,`viewLayout`)?Jt(e.viewLayout,[...t,`viewLayout`],n):void 0;if(!(r===void 0||i===void 0||a!==void 0||c===void 0||N(e,`properties`)&&l===void 0||N(e,`display`)&&u===void 0||N(e,`viewLayout`)&&d===void 0||N(e,`designatorOffset`)&&s===void 0||N(e,`designator`)&&o===void 0))return{id:r,device:i,...o===void 0?{}:{designator:o},...s===void 0?{}:{designatorOffset:s},placement:c,...l===void 0?{}:{properties:l},...u===void 0?{}:{display:u},...d===void 0?{}:{viewLayout:d}}}function Wt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Placement must be an object.`,t);return}P(e,[`x`,`y`,`rotation`,`width`,`height`],t,n);let r=I(e,`x`,t,n),i=I(e,`y`,t,n),a=I(e,`rotation`,t,n),o=N(e,`width`),s=N(e,`height`),c=I(e,`width`,t,n,o),l=I(e,`height`,t,n,s),u=!1;if(o!==s&&(h(n,`schema/invalid-value`,`Flexible placement must declare \"width\" and \"height\" together.`,t),u=!0),c!==void 0&&c<=0&&(h(n,`schema/invalid-value`,`Field \"width\" must be positive.`,[...t,`width`]),u=!0),l!==void 0&&l<=0&&(h(n,`schema/invalid-value`,`Field \"height\" must be positive.`,[...t,`height`]),u=!0),!(u||r===void 0||i===void 0||a===void 0))return{x:r,y:i,rotation:a,...c===void 0?{}:{width:c},...l===void 0?{}:{height:l}}}function Gt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"properties\" must be an object.`,t);return}let r=Object.create(null),i=!1;for(let[a,o]of Object.entries(e)){let e=[...t,a];if(!se(a)){h(n,`schema/invalid-value`,`Property key ${JSON.stringify(a)} must match [A-Za-z][A-Za-z0-9]*.`,e),i=!0;continue}let s=jt(o,e,n);s===void 0?i=!0:r[a]=s}return i?void 0:r}function Kt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"display\" must be an object.`,t);return}P(e,[`body`],t,n);let r=we(e,`body`,t,n,!1);if(!(N(e,`body`)&&r===void 0))return{...r===void 0?{}:{body:r}}}function qt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"display\" must be an object.`,t);return}P(e,[`body`,`designators`],t,n);let r=we(e,`body`,t,n,!1),i=we(e,`designators`,t,n,!1);if(!(N(e,`body`)&&r===void 0||N(e,`designators`)&&i===void 0))return{...r===void 0?{}:{body:r},...i===void 0?{}:{designators:i}}}function Jt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Field \"viewLayout\" must be an object.`,t);return}P(e,[`properties`,`views`],t,n);let r=[...t,`properties`],i=L(e,`properties`,t,n),a=i===void 0?void 0:Yt(i,r,n),o=Te(e,`views`,t,n),s=!1,c=[],l=/* @__PURE__ */ new Set;if(o!==void 0&&o.forEach((e,r)=>{let i=[...t,`views`,String(r)],a=Xt(e,i,n);a===void 0?s=!0:l.has(a.viewId)?(h(n,`document/invalid-view-layout`,`View id \"${a.viewId}\" is laid out more than once.`,i),s=!0):(l.add(a.viewId),c.push(a))}),!(s||a===void 0||o===void 0))return{properties:a,views:c}}function Yt(e,t,n){P(e,[`height`,`collapsed`],t,n);let r=I(e,`height`,t,n),i=we(e,`collapsed`,t,n),a=!1;if(r!==void 0&&r<=0&&(h(n,`document/invalid-view-layout`,`Layout \"height\" must be a finite positive number.`,[...t,`height`]),a=!0),!(a||r===void 0||i===void 0))return{height:r,collapsed:i}}function Xt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`HTML view layout must be an object.`,t);return}P(e,[`viewId`,`location`,`height`,`collapsed`,`floatingBounds`],t,n);let r=F(e,`viewId`,t,n,!0,{nonEmpty:!0}),i=F(e,`location`,t,n,!0,{nonEmpty:!0}),a=!1,o;i!==void 0&&(i===`sidebar`||i===`floating`?o=i:(h(n,`document/invalid-view-layout`,`Field \"location\" must be \"sidebar\" or \"floating\".`,[...t,`location`]),a=!0));let s=I(e,`height`,t,n),c=we(e,`collapsed`,t,n);s!==void 0&&s<=0&&(h(n,`document/invalid-view-layout`,`Layout \"height\" must be a finite positive number.`,[...t,`height`]),a=!0);let l;if(N(e,`floatingBounds`)){let r=[...t,`floatingBounds`],i=e.floatingBounds;if(!M(i))h(n,`document/invalid-view-layout`,`Field \"floatingBounds\" must be an object.`,r),a=!0;else{P(i,[`x`,`y`,`width`,`height`],r,n);let e=I(i,`x`,r,n),t=I(i,`y`,r,n),o=I(i,`width`,r,n),s=I(i,`height`,r,n);o!==void 0&&o<=0&&(h(n,`document/invalid-view-layout`,`Floating bounds \"width\" must be a finite positive number.`,[...r,`width`]),a=!0),s!==void 0&&s<=0&&(h(n,`document/invalid-view-layout`,`Floating bounds \"height\" must be a finite positive number.`,[...r,`height`]),a=!0),e!==void 0&&t!==void 0&&o!==void 0&&s!==void 0?l={x:e,y:t,width:o,height:s}:a=!0}}if(!(a||r===void 0||o===void 0||s===void 0||c===void 0))return{viewId:r,location:o,height:s,collapsed:c,...l===void 0?{}:{floatingBounds:l}}}function Zt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Node must be an object.`,t);return}P(e,[`id`,`kind`,`x`,`y`],t,n);let r=nn(e,`id`,t,n),i=F(e,`kind`,t,n,!0,{nonEmpty:!0}),a=I(e,`x`,t,n),o=I(e,`y`,t,n),s;if(i!==void 0&&(i===`junction`||i===`free`?s=i:h(n,`schema/invalid-value`,`Field \"kind\" must be \"junction\" or \"free\".`,[...t,`kind`])),r!==void 0&&s!==void 0&&a!==void 0&&o!==void 0)return{id:r,kind:s,x:a,y:o}}function Qt(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Wire must be an object.`,t);return}P(e,[`id`,`from`,`to`,`bends`],t,n);let r=nn(e,`id`,t,n),i=N(e,`from`)?$t(e.from,[...t,`from`],n):void 0,a=N(e,`to`)?$t(e.to,[...t,`to`],n):void 0,o=Te(e,`bends`,t,n),s=[],c=!1;if(o!==void 0&&o.forEach((e,r)=>{let i=Fe(e,[...t,`bends`,String(r)],n);i===void 0?c=!0:s.push(i)}),r!==void 0&&i!==void 0&&a!==void 0&&o!==void 0&&!c)return{id:r,from:i,to:a,bends:s}}function $t(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Endpoint must be an object.`,t);return}let r=F(e,`kind`,t,n,!0,{nonEmpty:!0});if(r===`pin`){P(e,[`kind`,`instance`,`pin`],t,n);let r=F(e,`instance`,t,n,!0,{nonEmpty:!0}),i=F(e,`pin`,t,n,!0,{nonEmpty:!0});return r===void 0||i===void 0?void 0:{kind:`pin`,instance:r,pin:i}}if(r===`node`){P(e,[`kind`,`node`],t,n);let r=F(e,`node`,t,n,!0,{nonEmpty:!0});return r===void 0?void 0:{kind:`node`,node:r}}r!==void 0&&h(n,`schema/invalid-value`,`Field \"kind\" must be \"pin\" or \"node\".`,[...t,`kind`])}function en(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Net label must be an object.`,t);return}P(e,[`id`,`target`,`name`,`offset`],t,n);let r=nn(e,`id`,t,n),i=N(e,`target`)?$t(e.target,[...t,`target`],n):void 0;N(e,`target`)||h(n,`schema/missing-field`,`Missing required field \"target\".`,[...t,`target`]);let a=F(e,`name`,t,n,!0,{nonEmpty:!0}),o=N(e,`offset`)?Fe(e.offset,[...t,`offset`],n):void 0;if(!(r===void 0||i===void 0||a===void 0||N(e,`offset`)&&o===void 0))return{id:r,target:i,name:a,...o===void 0?{}:{offset:o}}}function tn(e,t,n){if(!M(e)){h(n,`schema/invalid-type`,`Voltage reference must be an object.`,t);return}P(e,[`id`,`target`,`voltage`,`symbol`,`rotation`,`label`],t,n);let r=nn(e,`id`,t,n),i=N(e,`target`)?$t(e.target,[...t,`target`],n):void 0;N(e,`target`)||h(n,`schema/missing-field`,`Missing required field \"target\".`,[...t,`target`]);let a=I(e,`voltage`,t,n),o=F(e,`symbol`,t,n,!1,{nonEmpty:!0}),s,c=!1;o!==void 0&&(o===`power`||o===`ground`?s=o:(h(n,`schema/invalid-value`,`Field \"symbol\" must be \"power\" or \"ground\".`,[...t,`symbol`]),c=!0));let l=I(e,`rotation`,t,n,!1);s===`ground`&&a!==void 0&&a!==0&&(h(n,`schema/invalid-value`,`A ground symbol requires \"voltage\": 0.`,[...t,`voltage`]),c=!0);let u;if(N(e,`label`)){if(s===void 0)h(n,`schema/invalid-value`,`Field \"label\" requires a declared \"symbol\".`,[...t,`label`]),c=!0;else{let r=[...t,`label`],i=e.label;if(!M(i))h(n,`schema/invalid-type`,`Field \"label\" must be an object.`,r),c=!0;else{P(i,[`name`,`offset`],r,n);let e=F(i,`name`,r,n,!0,{nonEmpty:!0}),t=N(i,`offset`)?Fe(i.offset,[...r,`offset`],n):void 0;e===void 0||N(i,`offset`)&&t===void 0?c=!0:u={name:e,...t===void 0?{}:{offset:t}}}}}if(!(c||r===void 0||i===void 0||a===void 0||N(e,`rotation`)&&l===void 0))return{id:r,target:i,voltage:a,...s===void 0?{}:{symbol:s},...l===void 0?{}:{rotation:l},...u===void 0?{}:{label:u}}}function nn(e,t,n,r){let i=F(e,t,n,r,!0,{nonEmpty:!0});if(i!==void 0){if(!kt(i))h(r,`schema/invalid-value`,`Field \"${t}\" must be a UUID v4.`,[...n,t]);else return i}}function rn(e,t,n,r,i){e.kind===`pin`?n.has(e.instance)||h(i,`connection/unknown-endpoint`,`Endpoint references unknown instance \"${e.instance}\".`,[...t,`instance`]):r.has(e.node)||h(i,`connection/unknown-endpoint`,`Endpoint references unknown node \"${e.node}\".`,[...t,`node`])}function an(e,t){return e.kind===`pin`?t.kind===`pin`&&e.instance===t.instance&&e.pin===t.pin:t.kind===`node`&&e.node===t.node}function on(e,t,n,r,i,a){let o=/* @__PURE__ */ new Set,s=[e,t,n,r,i];for(let e of s)for(let t of e.items)o.has(t.value.id)?h(a,`document/duplicate-id`,`Id \"${t.value.id}\" is used more than once in the document.`,[...t.path,`id`]):o.add(t.value.id)}function sn(e,t){let n=/* @__PURE__ */ new Set;for(let r of e.items){let e=r.value.designator;e!==void 0&&(n.has(e)?h(t,`document/duplicate-designator`,`Designator ${JSON.stringify(e)} is used more than once.`,[...r.path,`designator`]):n.add(e))}}function cn(e,t){let n=[],r=dn(e,t,n),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=e=>{let t=e;for(;;){let e=i.get(t);if(e===void 0||e===t)return t;t=e}},l=e=>{i.has(e)||i.set(e,e)},u=(e,t)=>{l(e),l(t);let n=c(e),r=c(t);n!==r&&i.set(r,n)},d=new Set(e.nodes.map(e=>e.id)),f=(e,t)=>{let i=ln(e);if(a.has(i)||a.set(i,e),l(i),e.kind===`pin`){if(!r.has(e.instance))return h(n,`connection/unknown-endpoint`,`Pin endpoint references unknown instance \"${e.instance}\".`,[...t,`instance`]),i;let a=r.get(e.instance);return a!==void 0&&!a.has(e.pin)&&h(n,`device/unknown-pin`,`Instance \"${e.instance}\" does not declare pin \"${e.pin}\".`,[...t,`pin`]),i}return d.has(e.node)||h(n,`connection/unknown-endpoint`,`Endpoint references unknown node \"${e.node}\".`,[...t,`node`]),i};if(e.wires.forEach((e,t)=>{let r=[`wires`,String(t)],i=f(e.from,[...r,`from`]),a=f(e.to,[...r,`to`]);i===a?h(n,`connection/self-edge`,`A wire must not connect an endpoint to itself.`,[...r,`to`]):u(i,a)}),e.labels.forEach((e,t)=>{let n=[`labels`,String(t)],r=f(e.target,[...n,`target`]);un(o,r,{name:e.name,path:[...n,`name`],order:t})}),e.references.forEach((e,t)=>{let n=[`references`,String(t)],r=f(e.target,[...n,`target`]);un(s,r,{voltage:e.voltage,path:[...n,`voltage`],order:t}),e.label!==void 0&&un(o,r,{name:e.label.name,path:[...n,`label`,`name`],order:t})}),xe(n))throw new m(n);let p=fn(i,c);pn(p,o,n),mn(p,o,u),p=fn(i,c);for(let e of p.values())gn(e,s,n);if(xe(n))throw new m(n);let g=[];for(let e of p.values()){let t=[...e].sort(Ee),n=[],r,i=!1;for(let e of t){let t=a.get(e);t!==void 0&&t.kind===`pin`&&n.push({instance:t.instance,pin:t.pin}),o.has(e)&&(i=!0);let c=s.get(e)?.[0];c!==void 0&&(r=c.voltage)}n.length!==0&&(!i&&r===void 0&&t.length<2||(n.sort((e,t)=>Ee(e.instance,t.instance)||Ee(e.pin,t.pin)),g.push({id:t.join(`|`),pins:n,...r===void 0?{}:{voltage:r}})))}return{nets:g.sort((e,t)=>Ee(e.id,t.id))}}function ln(e){return e.kind===`pin`?`pin:${e.instance}/${e.pin}`:`node:${e.node}`}function un(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function dn(e,t,n){let r=/* @__PURE__ */ new Map;return e.instances.forEach((e,i)=>{let a=t.get(e.device);a===void 0?h(n,`device/unresolved`,`Instance \"${e.id}\" references device \"${e.device}\", which has no manifest.`,[`instances`,String(i),`device`]):r.set(e.id,new Set(Object.keys(a.pins??{})))}),r}function fn(e,t){let n=/* @__PURE__ */ new Map;for(let r of e.keys()){let e=t(r),i=n.get(e);i===void 0?n.set(e,/* @__PURE__ */ new Set([r])):i.add(r)}return n}function pn(e,t,n){for(let r of e.values()){let e=[];for(let n of r)e.push(...t.get(n)??[]);e.sort((e,t)=>e.order-t.order);let i=/* @__PURE__ */ new Set;for(let t of e)if(!i.has(t.name)&&(i.add(t.name),i.size>1)){h(n,`net/naming-conflict`,`Net has conflicting names: ${[...i].map(e=>JSON.stringify(e)).join(`, `)}.`,t.path);break}}}function mn(e,t,n){let r=/* @__PURE__ */ new Map;for(let[i,a]of e){let e=hn(a,t);if(e===void 0)continue;let o=r.get(e);o===void 0?r.set(e,i):n(o,i)}}function hn(e,t){let n=/* @__PURE__ */ new Set;for(let r of e)for(let e of t.get(r)??[])n.add(e.name);return n.size===1?[...n][0]:void 0}function gn(e,t,n){let r=[];for(let n of e)r.push(...t.get(n)??[]);r.sort((e,t)=>e.order-t.order);let[i,...a]=r;if(i===void 0)return;let o=a.find(e=>e.voltage!==i.voltage);o!==void 0&&h(n,`net/reference-conflict`,`Net has conflicting ideal voltages ${String(i.voltage)} and ${String(o.voltage)}.`,o.path)}let _n=Symbol.for(`mica-js.sdk/method-error`);var vn=class extends Error{code;details;constructor(e,t,n){super(t),this.name=`MethodError`,this.code=e,n!==void 0&&(this.details=n),Object.defineProperty(this,_n,{value:!0})}};function yn(e){if(typeof e!=`object`||!e)return!1;if(e instanceof vn)return!0;let t=e;return typeof t.code==`string`?e[_n]===!0||t.name===`MethodError`&&typeof e.message==`string`:!1}function bn(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,instanceId:n}}var R=class extends Error{problems;constructor(e){let t=e[0];super(t===void 0?`Fused session preparation failed.`:`${t.code}${t.pointer===``?``:` at ${t.pointer}`}: ${t.message}`),this.name=`PreparationError`,this.problems=e}get code(){return this.problems[0]?.code??`runtime/prepare-failed`}},xn=class extends Error{code;diagnostics;constructor(e){let t=e[0];super(t===void 0?`Fused session preparation failed.`:t.message),this.name=`FusedPreparationError`,this.code=t?.code??`runtime/prepare-failed`,this.diagnostics=e}};function z(e,t,n=``){return{code:e,message:t,pointer:n}}function Sn(e,t){if(e instanceof R)return e.problems;if(Cn(e))return[e];if(e instanceof m){let t=e.diagnostics.filter(e=>e.severity===`error`).map(e=>z(e.code,e.message,e.pointer));if(t.length>0)return t}return[z(t,e instanceof Error?e.message:String(e))]}function Cn(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.code==`string`&&typeof t.message==`string`&&typeof t.pointer==`string`}var wn=class{problems=[];instanceIds=[];add(e,t,n){for(let r of Sn(e,t))this.problems.push(r),this.instanceIds.push(n)}addProblem(e,t){this.problems.push(e),this.instanceIds.push(t)}fail(e,t,n){throw this.add(e,t,n),new R(this.problems)}get empty(){return this.problems.length===0}drain(){let e=this.problems.map((e,t)=>bn(e.code,e.pointer===``?e.message:`${e.message} (${e.pointer})`,this.instanceIds[t]));return this.problems.length=0,this.instanceIds.length=0,e}};function Tn(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}function En(e){return e.length===0?`$`:`$${e.map(e=>`[${JSON.stringify(e)}]`).join(``)}`}function Dn(e,t=[]){return kn(e,t,/* @__PURE__ */ new Set)}function On(e){return kn(e,[],/* @__PURE__ */ new Set)}function kn(e,t,n){switch(typeof e){case`string`:case`boolean`:return e;case`number`:if(!Number.isFinite(e))throw TypeError(`${En(t)}: a model value number must be finite`);return e;case`object`:break;default:throw TypeError(`${En(t)}: ${typeof e} is not part of the model value domain`)}if(e===null)return null;if(e instanceof Uint8Array)return e.slice();if(n.has(e))throw TypeError(`${En(t)}: a model value must not contain a cycle`);n.add(e);try{if(Array.isArray(e))return Object.freeze(e.map((e,r)=>kn(e,[...t,String(r)],n)));if(!An(e))throw TypeError(`${En(t)}: only plain objects are part of the model value domain`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,r])=>[e,kn(r,[...t,e],n)])))}finally{n.delete(e)}}function An(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function jn(e,t=[],n=[]){if(e instanceof Uint8Array)return n.push({view:e,path:t}),n;if(Array.isArray(e))return e.forEach((e,r)=>jn(e,[...t,String(r)],n)),n;if(typeof e==`object`&&e&&An(e))for(let[r,i]of Object.entries(e))jn(i,[...t,r],n);return n}var B=class extends Error{code;constructor(e,t){super(t),this.name=`ModelFault`,this.code=e}},Mn=class extends Error{code=`model/disconnected`;constructor(e=`The model client is disconnected from any live model`){super(e),this.name=`ModelDisconnectedError`}},Nn=class{name;#e=new i;#t;constructor(e,t){this.name=e,this.#t=t}event=(e,t,n)=>{let i={},a=!1,o=()=>{a||(a=!0,i.subscription?.dispose())};i.subscription=this.#e.event(n=>{if(a)return;let r;try{r=e.call(t,{value:On(n.value),simTime:n.simTime,sequence:n.sequence})}catch(e){this.#t(e,`listener of event \"${this.name}\"`),o();return}return Tn(r)&&Promise.resolve(r).catch(e=>{this.#t(e,`listener of event \"${this.name}\"`),o()}),r});let s=r(o);return n?.push(s),s};fire(e){this.#e.fire(e)}clear(){this.#e.dispose()}},Pn=class{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Map;#n;#r;#i;#a=0;#o=!0;#s;constructor(e){this.#r=e,this.#n=Object.keys(e.methods);for(let t of Object.keys(e.events))this.#e.set(t,new Nn(t,(t,n)=>{e.report(bn(`runtime/presentation-failed`,`${In(t)} (${n} on ${e.instanceId})`,e.instanceId))}))}get instanceId(){return this.#r.instanceId}get live(){return this.#o}methodDefinition(e){return this.#r.methods[e]}create(e){if(!this.#o)throw new Mn;let t=this.#c(e),n;try{n=this.#r.factory(t)}catch(e){throw this.#m(e,`model/execution-failed`,`Model factory of ${this.instanceId} failed`)}if(Tn(n))throw this.#h(`model/async-handler`,`Model factory of ${this.instanceId} returned a thenable`);let r=this.#l(n);return this.#i=r,{sync:e=>{this.#u(e)},dispose:()=>{this.#d()}}}invoke(e,t){if(!this.#o||this.#i===void 0)throw new Mn;let n=this.#t.get(e);if(n===void 0)throw new B(`model/unknown-method`,`Model ${this.instanceId} has no method \"${e}\".`);let r=n(t);if(Tn(r))throw new B(`model/async-handler`,`Method \"${e}\" of ${this.instanceId} returned a thenable; model hooks must be synchronous.`);return r}prepareParams(e,t){let n=this.methodDefinition(e);if(n===void 0)throw new B(`model/unknown-method`,`Model ${this.instanceId} has no method \"${e}\".`);let r;try{r=Dn(t)}catch(t){throw new B(`model/invalid-params`,`Parameters of \"${e}\" on ${this.instanceId} are not a model value: ${In(t)}`)}try{it(r,n.params,this.#r.types)}catch(t){throw new B(`model/invalid-params`,`Parameters of \"${e}\" on ${this.instanceId} do not match the declared type: ${In(t)}`)}return r}captureResult(e,t){let n=this.methodDefinition(e);if(n===void 0)throw new B(`model/unknown-method`,`Model ${this.instanceId} has no method \"${e}\".`);return this.#p(`model/invalid-result`,`Method \"${e}\" of ${this.instanceId}`,t,n.returns)}client(e){if(this.#s!==void 0)return this.#s;let t={};for(let n of this.#n)t[n]=t=>e(n,t);let n={};for(let[e,t]of this.#e)n[e]=t.event;let r=Object.freeze({methods:Object.freeze(t),events:Object.freeze(n)});return this.#s=r,r}invalidate(){this.#o=!1,this.#i=void 0,this.#t.clear();for(let e of this.#e.values())e.clear();this.#s=void 0}#c(e){let t=this.#r.props,n={};for(let e of this.#e.keys())n[e]=Object.freeze({fire:t=>{this.#f(e,t,void 0)},fireTransferred:(t,n)=>{this.#f(e,t,n)}});let r={get props(){return t},get inputs(){return e.inputs},get memory(){return e.memory},reportError:t=>e.reportError(t),attachJit:t=>e.attachJit(t),loadBytes:(t,n,r)=>r===void 0?e.loadBytes(t,n):e.loadBytes(t,n,r),events:Object.freeze(n)};return Object.freeze(r)}#l(e){if(typeof e!=`object`||!e)throw this.#h(`model/invalid-interface`,`Model ${this.instanceId} factory returned no instance`);let t=e;if(typeof t.sync!=`function`||typeof t.dispose!=`function`)throw this.#h(`model/invalid-interface`,`Model ${this.instanceId} must expose \"sync\" and \"dispose\" functions`);let n=t.methods;if(typeof n!=`object`||!n)throw this.#h(`model/invalid-interface`,`Model ${this.instanceId} exposes no methods object`);let r=Object.getOwnPropertyDescriptors(n),i=Object.keys(r);for(let e of i){let t=r[e];if(!(`value`in t)||typeof t.value!=`function`||!t.enumerable)throw this.#h(`model/invalid-interface`,`Method \"${e}\" of ${this.instanceId} must be an own enumerable function`)}let a=new Set(this.#n);for(let e of i)if(!a.has(e))throw this.#h(`model/invalid-interface`,`Model ${this.instanceId} implements the undeclared method \"${e}\"`);for(let e of a){let t=r[e];if(t===void 0||!(`value`in t))throw this.#h(`model/invalid-interface`,`Model ${this.instanceId} does not implement the declared method \"${e}\"`);let i=t.value;this.#t.set(e,e=>i.call(n,e))}return t}#u(e){let t=this.#i;if(t===void 0||!this.#o)return;let n;try{n=t.sync(e)}catch(e){throw this.#m(e,`model/execution-failed`,`sync of ${this.instanceId} failed`)}if(Tn(n))throw this.#h(`model/async-handler`,`sync of ${this.instanceId} returned a thenable; model hooks must be synchronous.`)}#d(){let e=this.#i;this.#i=void 0,this.#o=!1;let t;try{let n=e?.dispose();Tn(n)&&(Promise.resolve(n).catch(()=>{}),t=new B(`model/async-handler`,`dispose of ${this.instanceId} returned a thenable; model hooks must be synchronous.`))}catch(e){t=e}this.#t.clear();for(let e of this.#e.values())e.clear();if(t!==void 0)throw this.#r.report(bn(t instanceof B?t.code:`model/execution-failed`,`${In(t)} (dispose of ${this.instanceId})`,this.instanceId)),t}#f(e,t,n){let r=this.#r.blocked();if(r!==void 0||!this.#o)throw this.#h(`model/invalid-phase`,`Model ${this.instanceId} fired \"${e}\" outside an allowed phase: ${r??`model is not live`}`);let i=this.#e.get(e),a=this.#r.events[e];if(i===void 0||a===void 0)throw this.#h(`model/unknown-event`,`Model ${this.instanceId} fired the undeclared event \"${e}\"`);let o=t;if(n!==void 0)try{Fn(t,n),o=structuredClone(t,{transfer:[...n]})}catch(t){throw t instanceof B?(this.#r.report(bn(t.code,t.message,this.instanceId)),t):this.#h(`model/invalid-event`,`Event \"${e}\" of ${this.instanceId} cannot transfer its buffers`,t)}let s=this.#p(`model/invalid-event`,`Event \"${e}\" of ${this.instanceId}`,o,a);this.#a+=1;let c=Object.freeze({value:s,simTime:this.#r.now(),sequence:this.#a});i.fire(c);let l=this.#r.observer;if(l!==void 0)try{l({instanceId:this.instanceId,event:e,payload:{value:On(s),simTime:c.simTime,sequence:c.sequence}})}catch(e){this.#r.report(bn(`runtime/presentation-failed`,`${In(e)} (onModelEvent observer of ${this.instanceId})`,this.instanceId))}}#p(e,t,n,r){let i;try{i=Dn(n)}catch(n){throw this.#h(e,`${t} produced an invalid value: ${In(n)}`)}try{it(i,r,this.#r.types)}catch(n){throw this.#h(e,`${t} does not match the declared type: ${In(n)}`)}return i}#m(e,t,n){return e instanceof B||yn(e)?e:this.#h(t,n,e)}#h(e,t,n){let r=new B(e,n===void 0?t:`${t}: ${In(n)}`);return this.#r.report(bn(e,r.message,this.instanceId)),r}};function Fn(e,t){if(!Array.isArray(t))throw new B(`model/invalid-event`,`fireTransferred needs an array of buffers`);let n=/* @__PURE__ */ new Set;for(let e of t){if(!(e instanceof ArrayBuffer))throw new B(`model/invalid-event`,`fireTransferred buffers must be ArrayBuffers`);if(n.has(e))throw new B(`model/invalid-event`,`fireTransferred buffer is listed twice`);n.add(e)}let r=jn(e);for(let e of t){let t=r.filter(t=>t.view.buffer===e);if(t.length===0)throw new B(`model/invalid-event`,`fireTransferred buffer is not part of the event payload`);if(!t.some(t=>t.view.byteOffset===0&&t.view.byteLength===e.byteLength))throw new B(`model/invalid-event`,`fireTransferred buffer must be covered completely by one Uint8Array of the payload`)}}function In(e){return e instanceof Error?e.message:String(e)}let Ln=/* @__PURE__ */ new Map([[`bin`,`bin`],[`hex`,`hex`],[`ihx`,`hex`],[`elf`,`elf`],[`axf`,`elf`]]);function Rn(e){let t=e.lastIndexOf(`.`);if(!(t<0))return Ln.get(e.slice(t+1).toLowerCase())}function zn(e){return e===`bin`}function Bn(e){let t=e.slice(),n=Object.freeze({get length(){return t.length},get byteLength(){return t.length},slice(e,n){return t.slice(e,n)},*[Symbol.iterator](){for(let e of t)yield e}});return new Proxy(n,{get(e,n,r){return typeof n==`string`&&/^(0|[1-9]\\d*)$/.test(n)?t[Number(n)]:Reflect.get(e,n,r)},set(){throw TypeError(`Firmware bytes are read-only`)},defineProperty(){throw TypeError(`Firmware bytes are read-only`)}})}function Vn(e,t,n){return Object.freeze({addressSpace:e,address:t,data:Bn(n)})}function Hn(e){if(e.length===0)throw RangeError(`A firmware image must contain at least one segment`);let t=[...e].sort((e,t)=>e.addressSpace===t.addressSpace?e.address-t.address:e.addressSpace<t.addressSpace?-1:1),n=/* @__PURE__ */ new Map;for(let e of t){if(!Number.isSafeInteger(e.address)||e.address<0)throw RangeError(`Segment address in space \"${e.addressSpace}\" is not a safe integer`);if(e.data.length===0)throw RangeError(`Segment in space \"${e.addressSpace}\" has no bytes`);let t=e.address+e.data.length,r=n.get(e.addressSpace);if(r!==void 0&&e.address<r)throw RangeError(`Segments of space \"${e.addressSpace}\" overlap`);n.set(e.addressSpace,t)}return Object.freeze({segments:Object.freeze(t)})}function Un(e,t,n,r){if(e.length===0)throw RangeError(`A firmware image must not be empty`);let i=n.start+n.size;if(r<n.start||r+e.length>i)throw RangeError(`BIN range [${r}, ${r+e.length}) leaves address space \"${t}\" [${n.start}, ${i})`);return Hn([Vn(t,r,e)])}var Wn=Uint8Array,Gn=Uint16Array,Kn=Int32Array,qn=new Wn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Jn=new Wn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Yn=new Wn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Xn=function(e,t){for(var n=new Gn(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Kn(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Zn=Xn(qn,2),Qn=Zn.b,$n=Zn.r;Qn[28]=258,$n[258]=28;var er=Xn(Jn,0),tr=er.b;er.r;for(var nr=new Gn(32768),V=0;V<32768;++V){var rr=(V&43690)>>1|(V&21845)<<1;rr=(rr&52428)>>2|(rr&13107)<<2,rr=(rr&61680)>>4|(rr&3855)<<4,nr[V]=((rr&65280)>>8|(rr&255)<<8)>>1}for(var ir=(function(e,t,n){for(var r=e.length,i=0,a=new Gn(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Gn(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Gn(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[nr[d]>>c]=l}else for(s=new Gn(r),i=0;i<r;++i)e[i]&&(s[i]=nr[o[e[i]-1]++]>>15-e[i]);return s}),ar=new Wn(288),V=0;V<144;++V)ar[V]=8;for(var V=144;V<256;++V)ar[V]=9;for(var V=256;V<280;++V)ar[V]=7;for(var V=280;V<288;++V)ar[V]=8;for(var or=new Wn(32),V=0;V<32;++V)or[V]=5;var sr=/*#__PURE__*/ ir(ar,9,1),cr=/*#__PURE__*/ ir(or,5,1),lr=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ur=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},dr=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},fr=function(e){return(e+7)/8|0},pr=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Wn(e.subarray(t,n))},mr=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],hr=function(e,t,n){var r=Error(t||mr[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,hr),!n)throw r;return r},gr=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new Wn(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new Wn(i*3));var l=function(e){var t=n.length;if(e>t){var r=new Wn(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=ur(e,d,1);var v=ur(e,d+1,3);if(d+=3,!v){var y=fr(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&hr(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}if(v==1)p=sr,m=cr,h=9,g=5;else if(v==2){var ee=ur(e,d,31)+257,te=ur(e,d+10,15)+4,S=ee+ur(e,d+5,31)+1;d+=14;for(var C=new Wn(S),w=new Wn(19),T=0;T<te;++T)w[Yn[T]]=ur(e,d+T*3,7);d+=te*3;for(var E=lr(w),D=(1<<E)-1,ne=ir(w,E,1),T=0;T<S;){var re=ne[ur(e,d,D)];d+=re&15;var y=re>>4;if(y<16)C[T++]=y;else{var ie=0,ae=0;for(y==16?(ae=3+ur(e,d,3),d+=2,ie=C[T-1]):y==17?(ae=3+ur(e,d,7),d+=3):y==18&&(ae=11+ur(e,d,127),d+=7);ae--;)C[T++]=ie}}var oe=C.subarray(0,ee),O=C.subarray(ee);h=lr(oe),g=lr(O),p=ir(oe,h,1),m=ir(O,g,1)}else hr(1);if(d>_){c&&hr(0);break}}s&&l(f+131072);for(var se=(1<<h)-1,ce=(1<<g)-1,le=d;;le=d){var ie=p[dr(e,d)&se],ue=ie>>4;if(d+=ie&15,d>_){c&&hr(0);break}if(ie||hr(2),ue<256)n[f++]=ue;else if(ue==256){le=d,p=null;break}else{var de=ue-254;if(ue>264){var T=ue-257,fe=qn[T];de=ur(e,d,(1<<fe)-1)+Qn[T],d+=fe}var k=m[dr(e,d)&ce],pe=k>>4;k||hr(3),d+=k&15;var O=tr[pe];if(pe>3){var fe=Jn[pe];O+=dr(e,d)&(1<<fe)-1,d+=fe}if(d>_){c&&hr(0);break}s&&l(f+131072);var A=f+de;if(f<O){var j=a-O,me=Math.min(O,A);for(j+f<0&&hr(3);f<me;++f)n[f]=r[j+f]}for(;f<A;++f)n[f]=n[f-O]}}t.l=p,t.p=le,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?pr(n,0,f):n.subarray(0,f)},_r=/*#__PURE__*/ new Wn(0),vr=function(e,t){return e[t]|e[t+1]<<8},yr=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},br=function(e,t){return yr(e,t)+yr(e,t+4)*4294967296};function xr(e,t){return gr(e,{i:2},t&&t.out,t&&t.dictionary)}var Sr=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{Sr.decode(_r,{stream:!0})}catch{}var Cr=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:pr(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function wr(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(Sr)return Sr.decode(e);var i=Cr(e),a=i.s,n=i.r;return n.length&&hr(8),a}var Tr=function(e,t){return t+30+vr(e,t+26)+vr(e,t+28)},Er=function(e,t,n){var r=vr(e,t+28),i=vr(e,t+30),a=wr(e.subarray(t+46,t+46+r),!(vr(e,t+8)&2048)),o=t+46+r,s=Dr(e,o,i,n,yr(e,t+20),yr(e,t+24),yr(e,t+42)),c=s[0],l=s[1],u=s[2];return[vr(e,t+10),c,l,a,o+i+vr(e,t+32),u]},Dr=function(e,t,n,r,i,a,o){var s=i==4294967295,c=a==4294967295,l=o==4294967295,u=t+n,d=s+c+l;if(r&&d){for(;t+4<u;t+=4+vr(e,t+2))if(vr(e,t)==1)return[s?br(e,t+4+8*c):i,c?br(e,t+4):a,l?br(e,t+4+8*(c+s)):o,1];r<2&&hr(13)}return[i,a,o,0]};function Or(e,t){for(var n={},r=e.length-22;yr(e,r)!=101010256;--r)(!r||e.length-r>65558)&&hr(13);var i=vr(e,r+8);if(!i)return{};var a=yr(e,r+16),o=yr(e,r-20)==117853008;if(o){var s=yr(e,r-12);o=yr(e,s)==101075792,o&&(i=yr(e,s+32),a=yr(e,s+48))}for(var c=t&&t.filter,l=0;l<i;++l){var u=Er(e,a,o),d=u[0],f=u[1],p=u[2],m=u[3],h=u[4],g=u[5],_=Tr(e,g);a=h,(!c||c({name:m,size:f,originalSize:p,compression:d}))&&(d?d==8?n[m]=xr(e.subarray(_,_+f),{out:new Wn(p)}):hr(14,`unknown compression type `+d):n[m]=pr(e,_,_+f))}return n}let kr=Object.freeze({maxFiles:1024,maxFileBytes:33554432,maxTotalBytes:67108864,maxMemoryBytes:67108864,maxPathBytes:1024,maxDepth:32});var H=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`ProgramError`}};function Ar(e){if(e.byteLength>kr.maxTotalBytes)throw new H(`program/resource-limit`,`Program archive exceeds the byte limit.`);let t=/* @__PURE__ */ new Set,n=0;try{let r=Or(e,{filter(e){if(jr(e.name.endsWith(`/`)?e.name.slice(0,-1):e.name),e.name.endsWith(`/`))return!1;if(t.has(e.name))throw new H(`program/invalid-path`,`Duplicate program path ${e.name}.`);if(t.add(e.name),n+=e.originalSize,t.size>kr.maxFiles||e.originalSize>kr.maxFileBytes||n>kr.maxTotalBytes)throw new H(`program/resource-limit`,`Program archive exceeds the file limits.`);return!0}});return Object.entries(r).map(([e,t])=>({path:e,data:t}))}catch(e){throw e instanceof H?e:new H(`program/source-resolve-failed`,`Cannot decode program ZIP: ${e instanceof Error?e.message:String(e)}`)}}function jr(e){let t=A(e);if(t!==void 0)throw new H(`program/invalid-path`,`Program path ${JSON.stringify(e)} ${t}.`);if(new TextEncoder().encode(e).length>kr.maxPathBytes||e.split(`/`).length>kr.maxDepth)throw new H(`program/resource-limit`,`Program path ${JSON.stringify(e)} exceeds the fixed path limits.`)}function Mr(e){if(!Array.isArray(e))throw new H(`program/source-resolve-failed`,`A program file set must be an array.`);if(e.length>kr.maxFiles)throw new H(`program/resource-limit`,`Program file count exceeds the fixed limit.`);let t=/* @__PURE__ */ new Map,n=0;for(let r of e){if(typeof r!=`object`||!r||typeof r.path!=`string`||!(r.data instanceof Uint8Array))throw new H(`program/source-resolve-failed`,`Program files require a path and Uint8Array data.`);if(jr(r.path),t.has(r.path))throw new H(`program/invalid-path`,`Duplicate program path ${r.path}.`);if(n+=r.data.byteLength,r.data.byteLength>kr.maxFileBytes||n>kr.maxTotalBytes)throw new H(`program/resource-limit`,`Program file bytes exceed the fixed limit.`);t.set(r.path,Bn(r.data))}let r=Object.freeze([...t.keys()].sort());for(let e of r){let n=e.split(`/`);for(let r=1;r<n.length;r++)if(t.has(n.slice(0,r).join(`/`)))throw new H(`program/invalid-path`,`Program file ${e} conflicts with a parent file.`)}return Object.freeze({paths:r,read(e){jr(e);let n=t.get(e);if(n===void 0)throw new H(`program/file-not-found`,`Program file ${e} does not exist.`);return n}})}function Nr(e){throw new H(`program/invalid-format`,e)}function Pr(e,t,n,r){if(t.length>kr.maxMemoryBytes)throw new H(`program/resource-limit`,`Program input exceeds the fixed byte limit.`);if(!n.formats?.includes(e))throw new H(`program/unsupported-format`,`This program property does not accept ${e}.`);if(e!==`bin`&&r.loadAddress!==void 0||e===`elf`&&r.addressSpace!==void 0)throw new H(`schema/invalid-value`,`The program format does not accept the saved address overrides.`);let i=n.addressSpaces??{},a=r.addressSpace??n.defaults?.addressSpace;if(e!==`elf`&&(a===void 0||i[a]===void 0))throw new H(`schema/invalid-value`,`The selected program address space does not exist.`);let o=e===`bin`?[{address:r.loadAddress??n.defaults?.loadAddress??-1,data:t}]:e===`hex`?Fr(t):Ir(t),s=0,c=o.map(t=>{let n=t.address+t.data.length;if(!Number.isSafeInteger(t.address)||t.address<0||!Number.isSafeInteger(n))throw new H(`program/out-of-range`,`Program address is outside the safe integer range.`);let r=e===`elf`?Object.entries(i).filter(([,e])=>t.address>=e.start&&n<=e.start+e.size).map(([e])=>e):a===void 0?[]:[a];if(r.length>1)throw new H(`program/ambiguous-address-space`,`ELF load segment matches multiple address spaces.`);let o=r[0],c=o===void 0?void 0:i[o];if(c===void 0||o===void 0||t.address<c.start||n>c.start+c.size)throw new H(`program/out-of-range`,`Program load segment leaves its declared address space.`);if(s+=t.data.length,s>kr.maxMemoryBytes)throw new H(`program/resource-limit`,`Decoded program exceeds the fixed byte limit.`);return{addressSpace:o,address:t.address,data:Bn(t.data)}});try{return Hn(c)}catch(e){throw e instanceof RangeError?new H(`program/invalid-image`,e.message):e}}function Fr(e){let t;try{t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch(e){if(!(e instanceof TypeError))throw e;Nr(`Intel HEX is not valid text.`)}let n=[],r=0,i=!1;for(let e of t.split(/\\r?\\n/)){let t=e.trim();if(t.length===0)continue;(i||!/^:(?:[0-9a-fA-F]{2})+$/.test(t))&&Nr(`Invalid Intel HEX record or data after EOF.`);let a=Uint8Array.from(t.slice(1).match(/../g)??[],e=>Number.parseInt(e,16)),o=a[0];(o===void 0||a.length!==o+5||a.reduce((e,t)=>e+t,0)&255)&&Nr(`Intel HEX length or checksum mismatch.`);let s=(a[1]??0)*256+(a[2]??0),c=a[3],l=a.subarray(4,4+o);switch(c){case 0:s+o>65536&&Nr(`Intel HEX record crosses its address window.`),o>0&&n.push({address:r+s,data:l});break;case 1:(s!==0||o!==0)&&Nr(`Invalid Intel HEX EOF.`),i=!0;break;case 2:case 4:(s!==0||o!==2)&&Nr(`Invalid Intel HEX extended address.`),r=((l[0]??0)*256+(l[1]??0))*(c===2?16:65536);break;case 3:case 5:(s!==0||o!==4)&&Nr(`Invalid Intel HEX start address.`);break;default:Nr(`Unknown Intel HEX record type.`)}}return i||Nr(`Intel HEX has no EOF record.`),n}function Ir(e){(e.length<16||e[0]!==127||e[1]!==69||e[2]!==76||e[3]!==70||e[6]!==1)&&Nr(`Invalid ELF identification.`);let t=e[4]===2,n=t?64:52;(e[4]!==1&&!t||e[5]!==1&&e[5]!==2||e.length<n)&&Nr(`Invalid ELF class, byte order or header.`);let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=e[5]===1,a=e=>r.getUint16(e,i),o=e=>r.getUint32(e,i),s=e=>{if(!t)return o(e);let n=r.getBigUint64(e,i);return n>BigInt(2**53-1)&&Nr(`ELF integer exceeds the safe range.`),Number(n)};(a(16)!==2||o(20)!==1||a(t?52:40)!==n)&&Nr(`ELF must be a linked ET_EXEC image with a valid header.`);let c=s(t?32:28),l=a(t?54:42),u=a(t?56:44);if(u===0)return[];(u===65535||l<(t?56:32)||c<n||!Number.isSafeInteger(c+u*l)||c+u*l>e.length)&&Nr(`Invalid ELF program header table.`);let d=[];for(let n=0;n<u;n++){let r=c+n*l,i=o(r);if((i===2||i===3)&&Nr(`ELF dynamic loading is not supported.`),i!==1)continue;let a=s(r+(t?8:4)),u=s(r+(t?24:12)),f=s(r+(t?32:16));(f>s(r+(t?40:20))||!Number.isSafeInteger(a+f)||a+f>e.length)&&Nr(`Invalid ELF load segment bounds.`),f>0&&d.push({address:u,data:e.subarray(a,a+f)})}return d}let Lr=e=>e/2**32|0,Rr=e=>e>>>0;function zr(e,t,n,r){let i=Lr(n),a=Rr(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Br(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}let Vr=e=>e?`\"${e}\" `:``;function Hr(e,t=``){if(typeof e!=`number`)throw TypeError(Vr(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Vr(t)+`expected integer >= 0, got `+e);return e}function Ur(e,t,n=``){if(Br(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Hr(t,`length`);let r=Br(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=Vr(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}let Wr=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`\"${t}\" `)+`expected object, got type=`+typeof e)},Gr=(e,t)=>{Wr(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`\"${t}\" expected plain object`);if(Object.hasOwn(e,`__proto__`))throw TypeError(`\"${t}.__proto__\" is not allowed`)};function Kr(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function qr(e,t){Ur(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`\"output\" expected length >= `+n)}function Jr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Yr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Xr(e,t){return e<<32-t|e>>>t}function Zr(e,t,n=`opts`){return Gr(e,`defaults`),t!==void 0&&Gr(t,n),Object.assign(Object.create(null),e,t)}function Qr(e,t={}){if(typeof e!=`function`)throw TypeError(`\"hashCons\" expected function, got type=`+typeof e);t=Zr({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}let $r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function ei(e,t,n){return e&t^~e&n}function ti(e,t,n){return e&t^e&n^t&n}var ni=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Yr(this.buffer)}update(e){Kr(this),Ur(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=Yr(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0}else n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){Kr(this),qr(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),zr(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:Yr(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};let ri=/* @__PURE__ */ Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ii=/* @__PURE__ */ Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ai=/* @__PURE__ */ new Uint32Array(64);var oi=class extends ni{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)ai[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=ai[e-15],n=ai[e-2],r=Xr(t,7)^Xr(t,18)^t>>>3,i=Xr(n,17)^Xr(n,19)^n>>>10;ai[e]=i+ai[e-7]+r+ai[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=Xr(o,6)^Xr(o,11)^Xr(o,25),u=l+t+ei(o,s,c)+ii[e]+ai[e]|0,d=(Xr(n,2)^Xr(n,13)^Xr(n,22))+ti(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){Jr(ai)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Jr(this.buffer)}},si=class extends oi{constructor(){super(32,ri)}};let ci=/* @__PURE__ */ Qr(()=>new si,/* @__PURE__ */ $r(1));var li=/* @__PURE__ */ e(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||\n/* istanbul ignore next */9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),ui=/* @__PURE__ */ e(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\\bsemver\\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),di=/* @__PURE__ */ e(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=li(),a=ui();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\\\s`,1],[`\\\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\\\d+`),h(`NONNUMERICIDENTIFIER`,`\\\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\\\.(${c[u.NUMERICIDENTIFIER]})\\\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\\\+(${c[u.BUILDIDENTIFIER]}(?:\\\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\\\*`),h(`XRANGEPLAIN`,`[v=\\\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\\\.(${c[u.XRANGEIDENTIFIER]})(?:\\\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\\\d])(\\\\d{1,${n}})(?:\\\\.(\\\\d{1,${n}}))?(?:\\\\.(\\\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\\\s*)${c[u.LONETILDE]}\\\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\\\^)`),h(`CARETTRIM`,`(\\\\s*)${c[u.LONECARET]}\\\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\\\s*)${c[u.GTLT]}\\\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\\\s*(${c[u.XRANGEPLAIN]})\\\\s+-\\\\s+(${c[u.XRANGEPLAIN]})\\\\s*$`),h(`HYPHENRANGELOOSE`,`^\\\\s*(${c[u.XRANGEPLAINLOOSE]})\\\\s+-\\\\s+(${c[u.XRANGEPLAINLOOSE]})\\\\s*$`),h(`STAR`,`(<|>)?=?\\\\s*\\\\*`),h(`GTE0`,`^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$`),h(`GTE0PRE`,`^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$`)})),fi=/* @__PURE__ */ e(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),pi=/* @__PURE__ */ e(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),mi=/* @__PURE__ */ e(((e,t)=>{let n=ui(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=li(),{safeRe:a,t:o}=di(),s=fi(),{compareIdentifiers:c}=pi(),l=(e,t)=>{let n=t.split(`.`);if(n.length>e.length)return!1;for(let t=0;t<n.length;t++)if(c(e[t],n[t])!==0)return!1;return!0};t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type \"${typeof t}\".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);this.prerelease=l[4]?l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e!==i)return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e!==i)return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];if(n===!1&&(r=[t]),l(this.prerelease,t)){let e=this.prerelease[t.split(`.`).length];isNaN(e)&&(this.prerelease=r)}else this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),hi=/* @__PURE__ */ e(((e,t)=>{let n=mi();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),gi=/* @__PURE__ */ e(((e,t)=>{let n=hi();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),_i=/* @__PURE__ */ e(((e,t)=>{let n=hi();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),vi=/* @__PURE__ */ e(((e,t)=>{let n=mi();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),yi=/* @__PURE__ */ e(((e,t)=>{let n=hi();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),bi=/* @__PURE__ */ e(((e,t)=>{let n=mi();t.exports=(e,t)=>new n(e,t).major})),xi=/* @__PURE__ */ e(((e,t)=>{let n=mi();t.exports=(e,t)=>new n(e,t).minor})),Si=/* @__PURE__ */ e(((e,t)=>{let n=mi();t.exports=(e,t)=>new n(e,t).patch})),Ci=/* @__PURE__ */ e(((e,t)=>{let n=hi();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),wi=/* @__PURE__ */ e(((e,t)=>{let n=mi();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),Ti=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t,r)=>n(t,e,r)})),Ei=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t)=>n(e,t,!0)})),Di=/* @__PURE__ */ e(((e,t)=>{let n=mi();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),Oi=/* @__PURE__ */ e(((e,t)=>{let n=Di();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),ki=/* @__PURE__ */ e(((e,t)=>{let n=Di();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),Ai=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t,r)=>n(e,t,r)>0})),ji=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t,r)=>n(e,t,r)<0})),Mi=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t,r)=>n(e,t,r)===0})),Ni=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t,r)=>n(e,t,r)!==0})),Pi=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t,r)=>n(e,t,r)>=0})),Fi=/* @__PURE__ */ e(((e,t)=>{let n=wi();t.exports=(e,t,r)=>n(e,t,r)<=0})),Ii=/* @__PURE__ */ e(((e,t)=>{let n=Mi(),r=Ni(),i=Ai(),a=Pi(),o=ji(),s=Fi();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),Li=/* @__PURE__ */ e(((e,t)=>{let n=mi(),r=hi(),{safeRe:i,t:a}=di();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2],c=o[3]||`0`,l=o[4]||`0`,u=t.includePrerelease&&o[5]?`-${o[5]}`:``,d=t.includePrerelease&&o[6]?`+${o[6]}`:``;return r(`${s}.${c}.${l}${u}${d}`,t)}})),Ri=/* @__PURE__ */ e(((e,t)=>{let n=hi(),r=li(),i=mi(),a=(e,t,n)=>{if(!r.RELEASE_TYPES.includes(t))return null;let i=o(e,n);return i&&s(i,t)},o=(e,t)=>{let r=e instanceof i?e.version:e;return n(r,t)},s=(e,t)=>{if(c(t))return e.version;switch(e.prerelease=[],t){case`major`:e.minor=0,e.patch=0;break;case`minor`:e.patch=0}return e.format()},c=e=>e.startsWith(`pre`);t.exports=a})),zi=/* @__PURE__ */ e(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=/* @__PURE__ */ new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),Bi=/* @__PURE__ */ e(((e,t)=>{let n=/\\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!_(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&v(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(g,``);let t=((this.options.includePrerelease&&m)|(this.options.loose&&h))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];e=e.replace(s,re(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[u.COMPARATORTRIM],d),o(`comparator trim`,e),e=e.replace(c[u.TILDETRIM],f),o(`tilde trim`,e),e=e.replace(c[u.CARETTRIM],p),o(`caret trim`,e);let l=e.split(` `).map(e=>b(e,this.options)).join(` `).split(/\\s+/).map(e=>ne(e,this.options));i&&(l=l.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[u.COMPARATORLOOSE])))),o(`range list`,l);let v=/* @__PURE__ */ new Map,y=l.map(e=>new a(e,this.options));for(let e of y){if(_(e))return[e];v.set(e.value,e)}v.size>1&&v.has(``)&&v.delete(``);let x=[...v.values()];return r.set(t,x),x}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>y(e,n)&&t.set.some(t=>y(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(ie(this.set[t],e,this.options))return!0;return!1}};let r=new(zi()),i=fi(),a=Vi(),o=ui(),s=mi(),{safeRe:c,src:l,t:u,comparatorTrimReplace:d,tildeTrimReplace:f,caretTrimReplace:p}=di(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:h}=li(),g=new RegExp(l[u.BUILD],`g`),_=e=>e.value===`<0.0.0-0`,v=e=>e.value===``,y=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},b=(e,t)=>(e=e.replace(c[u.BUILD],``),o(`comp`,e,t),e=C(e,t),o(`caret`,e),e=te(e,t),o(`tildes`,e),e=T(e,t),o(`xrange`,e),e=D(e,t),o(`stars`,e),e),x=e=>!e||e.toLowerCase()===`x`||e===`*`,ee=(e,t,n)=>x(e)&&!x(t)||x(t)&&n&&!x(n),te=(e,t)=>e.trim().split(/\\s+/).map(e=>S(e,t)).join(` `),S=(e,t)=>{let n=t.loose?c[u.TILDELOOSE]:c[u.TILDE],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`tilde`,e,t,n,i,a,s);let c;return x(n)?c=``:x(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:x(a)?c=`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:s?(o(`replaceTilde pr`,s),c=`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`):c=`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`,o(`tilde return`,c),c})},C=(e,t)=>e.trim().split(/\\s+/).map(e=>w(e,t)).join(` `),w=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[u.CARETLOOSE]:c[u.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return x(n)?c=``:x(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:x(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},T=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\\s+/).map(e=>E(e,t)).join(` `)),E=(e,t)=>{e=e.trim();let n=t.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{if(o(`xRange`,e,n,r,i,a,s,c),ee(i,a,s))return e;let l=x(i),u=l||x(a),d=u||x(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},D=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[u.STAR],``)),ne=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?u.GTE0PRE:u.GTE0],``)),re=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=x(r)?``:x(i)?`>=${r}.0.0${e?`-0`:``}`:x(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=x(l)?``:x(u)?`<${+l+1}.0.0-0`:x(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),ie=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),Vi=/* @__PURE__ */ e(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.value=this.semver===n?``:this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),this.semver=r[2]?new c(r[2],this.options.loose):n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``||new l(t.value,n).test(this.value):t.operator===``?t.value===``||new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=fi(),{safeRe:i,t:a}=di(),o=Ii(),s=ui(),c=mi(),l=Bi()})),Hi=/* @__PURE__ */ e(((e,t)=>{let n=Bi();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),Ui=/* @__PURE__ */ e(((e,t)=>{let n=Bi();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),Wi=/* @__PURE__ */ e(((e,t)=>{let n=mi(),r=Bi();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),Gi=/* @__PURE__ */ e(((e,t)=>{let n=mi(),r=Bi();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),Ki=/* @__PURE__ */ e(((e,t)=>{let n=mi(),r=Bi(),i=Ai();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;\n/* istanbul ignore next */\ndefault:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),qi=/* @__PURE__ */ e(((e,t)=>{let n=Bi();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),Ji=/* @__PURE__ */ e(((e,t)=>{let n=mi(),r=Vi(),{ANY:i}=r,a=Bi(),o=Hi(),s=Ai(),c=ji(),l=Fi(),u=Pi();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of \"<\" or \">\"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),Yi=/* @__PURE__ */ e(((e,t)=>{let n=Ji();t.exports=(e,t,r)=>n(e,t,`>`,r)})),Xi=/* @__PURE__ */ e(((e,t)=>{let n=Ji();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Zi=/* @__PURE__ */ e(((e,t)=>{let n=Bi();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),Qi=/* @__PURE__ */ e(((e,t)=>{let n=Hi(),r=wi();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),$i=/* @__PURE__ */ e(((e,t)=>{let n=Bi(),r=Vi(),{ANY:i}=r,a=Hi(),o=wi(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=/* @__PURE__ */ new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!e.test(s.semver))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!e.test(u.semver))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),ea=(/* @__PURE__ */ e(((e,t)=>{let n=di(),r=li(),i=mi(),a=pi();t.exports={parse:hi(),valid:gi(),clean:_i(),inc:vi(),diff:yi(),major:bi(),minor:xi(),patch:Si(),prerelease:Ci(),compare:wi(),rcompare:Ti(),compareLoose:Ei(),compareBuild:Di(),sort:Oi(),rsort:ki(),gt:Ai(),lt:ji(),eq:Mi(),neq:Ni(),gte:Pi(),lte:Fi(),cmp:Ii(),coerce:Li(),truncate:Ri(),Comparator:Vi(),Range:Bi(),satisfies:Hi(),toComparators:Ui(),maxSatisfying:Wi(),minSatisfying:Gi(),minVersion:Ki(),validRange:qi(),outside:Ji(),gtr:Yi(),ltr:Xi(),intersects:Zi(),simplifyRange:Qi(),subset:$i(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}})))();let ta=`1.0.0`,na=/^sha256:[0-9a-f]{64}$/,ra=`package.json`;function ia(e){return pe(e)===void 0}async function aa(e,t,n=ta){let r=oa(t),i;try{i=await e.open(r)}catch(e){throw new R([z(`package/not-found`,`Cannot open ${r.id}@${r.version}: ${_a(e)}`)])}let a=i.read,o=sa(i,r);await ca(o,r);let s=async(e,t)=>{let n=o[e];if(n===void 0)throw new R([z(`package/missing-entry`,`Package ${r.id} does not declare ${e}.`)]);if(t!==void 0&&n.size>t)throw new R([z(`package/resource-limit`,`${r.id}/${e} is ${n.size} bytes, above the declared limit of ${t}.`)]);let s=await a.call(i,e);if(!(s instanceof Uint8Array))throw new R([z(`package/not-found`,`Package ${r.id} returned no bytes for ${e}.`)]);let c=s.slice();if(c.length!==n.size)throw new R([z(`package/integrity-mismatch`,`${r.id}/${e} is ${c.length} bytes but the release declares ${n.size}.`)]);if(await pa(c)!==n.integrity)throw new R([z(`package/integrity-mismatch`,`${r.id}/${e} does not match the released digest.`)]);return c.slice()},c=da(new TextDecoder().decode(await s(ra)).replace(/^\\uFEFF/,``));if(fa(c,r),!ga(n,c.engines.mica))throw new R([z(`package/unsupported-engine`,`${r.id}@${r.version} requires mica \"${c.engines.mica}\" but this runtime implements ${n}.`,`/engines/mica`)]);let l=Object.freeze({lock:r,files:o,read:e=>s(e)});return Object.freeze({lock:r,manifest:c,source:l,files:o,read:s})}function oa(e){if(typeof e!=`object`||!e||typeof e.id!=`string`||typeof e.version!=`string`)throw new R([z(`package/invalid-manifest`,`A device lock needs \"id\" and \"version\" strings.`)]);if(!na.test(e.integrity))throw new R([z(`package/integrity-mismatch`,`Lock of \"${e.id}\" does not carry a sha256 release identity.`)]);return Object.freeze({id:e.id,version:e.version,integrity:e.integrity})}function sa(e,t){if(typeof e!=`object`||!e)throw new R([z(`package/not-found`,`Registry returned no package for ${t.id}.`)]);if(e.lock?.id!==t.id||e.lock.version!==t.version||e.lock.integrity!==t.integrity)throw new R([z(`package/integrity-mismatch`,`Registry opened a release that does not match the lock of \"${t.id}\".`)]);if(typeof e.read!=`function`||e.files===null||typeof e.files!=`object`)throw new R([z(`package/not-found`,`Registry returned an unreadable release for \"${t.id}\".`)]);let n=[],r=Object.create(null);for(let[i,a]of Object.entries(e.files))ia(i)?typeof a!=`object`||!a||!Number.isSafeInteger(a.size)||a.size<0||!na.test(a.integrity)?n.push(z(`package/invalid-path`,`Package ${t.id} declares an invalid entry for ${i}.`)):r[i]=Object.freeze({size:a.size,integrity:a.integrity}):n.push(z(`package/invalid-path`,`Package ${t.id} declares the non-normalized path ${JSON.stringify(i)}.`));if(Object.hasOwn(r,ra)||n.push(z(`package/missing-entry`,`Package ${t.id} does not declare ${ra}.`)),n.length>0)throw new R(n);return Object.freeze(r)}async function ca(e,t){let n=await la({id:t.id,version:t.version,files:e});if(n!==t.integrity)throw new R([z(`package/integrity-mismatch`,`The file list of ${t.id}@${t.version} derives the release identity ${n}, but the document locks ${t.integrity}.`)])}async function la(e){return pa(new TextEncoder().encode(ua(e)))}function ua(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>ua(e)).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${ua(t[e])}`).join(`,`)}}`}function da(e){try{return dt(e)}catch(e){throw new R(Sn(e,`package/invalid-manifest`))}}function fa(e,t){let n=`${e.publisher}:${e.name}`;if(n!==t.id)throw new R([z(`package/invalid-manifest`,`package.json declares ${n} but the document locks ${t.id}.`,`/name`)]);if(e.version!==t.version)throw new R([z(`package/invalid-manifest`,`package.json declares version ${e.version} but the document locks ${t.version}.`,`/version`)])}async function pa(e){let t=new Uint8Array(e.byteLength);return t.set(e),`sha256:${ha(await ma(t))}`}async function ma(e){let t=globalThis.crypto?.subtle;if(t===void 0)return ci(e);try{let n=await t.digest(`SHA-256`,e);return new Uint8Array(n)}catch(e){throw new R([z(`package/integrity-mismatch`,`The host WebCrypto refused to compute a SHA-256 digest: ${_a(e)}`)])}}function ha(e){return[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function ga(e,t){if(typeof e!=`string`||typeof t!=`string`||(0,ea.valid)(e)===null)return!1;try{return(0,ea.satisfies)(e,t)}catch{return!1}}function _a(e){return e instanceof Error?e.message:String(e)}async function va(e){let t=[],n={},r=/* @__PURE__ */ new Map,i=e.descriptors;for(let n of Object.keys(e.overrides))Object.hasOwn(i,n)||t.push(z(`schema/invalid-value`,`Instance ${e.instanceId} sets the undeclared property \"${n}\".`,ya(e.pointer,n)));for(let[a,o]of Object.entries(i)){let i=ya(e.pointer,a),s=Object.hasOwn(e.overrides,a)?e.overrides[a]:o.default;if(s===void 0){t.push(z(`schema/missing-field`,`Property \"${a}\" of ${e.instanceId} has neither a default nor an instance value.`,i));continue}if(s===null){if(o.nullable!==!0){t.push(z(`schema/invalid-value`,`Property \"${a}\" of ${e.instanceId} is not nullable.`,i));continue}n[a]=null;continue}if(o.type===`program`){let r=await ka(e,a,o,s,t,i);r!==void 0&&(n[a]=r);continue}if(o.type===`firmware`){let r=await Aa(e,a,o,s,t,i);r!==void 0&&(n[a]=r);continue}if(o.type===`image`||o.type===`binary`){let c=await Oa(e,a,o,s,t,i);c!==void 0&&(n[a]=Bn(c),r.set(a,c));continue}let c=ba(o,s,t,i,e.instanceId);c!==void 0&&(n[a]=c)}let a={};for(let[o,s]of e.irProperties){let c=ya(e.pointer,o),l=i[o];if(l===void 0){t.push(z(`model/invalid-interface`,`The model IR declares the property \"${o}\" but the manifest does not.`,c));continue}if(l.type===`firmware`||l.type===`program`){t.push(z(`model/invalid-interface`,`Property \"${o}\" is a ${l.type} property and must not be declared by the model IR.`,c));continue}let u=s.kind===`optional`?s.inner.kind:s.kind,d=s.kind===`optional`;if(!(u===`number`&&(l.type===`number`||l.type===`integer`)||u===`bool`&&l.type===`boolean`||u===`string`&&(l.type===`string`||l.type===`color`)||u===`enum`&&l.type===`enum`||u===`bytes`&&(l.type===`image`||l.type===`binary`))){t.push(z(`model/invalid-interface`,`Property \"${o}\" is ${l.type} in the manifest but ${u} in the model IR.`,c));continue}if(d!==(l.nullable===!0)){t.push(z(`model/invalid-interface`,`Property \"${o}\" must be declared ${d?`nullable`:`non-nullable`} in the manifest.`,c));continue}if(!Object.hasOwn(n,o))continue;let f=n[o];if(f===null)a[o]=f;else if(u===`bytes`){let e=r.get(o);if(e===void 0){t.push(z(`model/invalid-interface`,`Property \"${o}\" is a byte property the manifest value does not provide.`,c));continue}a[o]=e.slice()}else typeof f==`number`||typeof f==`boolean`||typeof f==`string`?a[o]=f:t.push(z(`model/invalid-interface`,`Property \"${o}\" is not a plain value the core can consume.`,c))}if(t.length>0)throw new R(t);return{props:Object.freeze(n),boardProps:Object.freeze(a)}}function ya(e,t){return`/${[...e,t].map(e=>e.replace(/~/g,`~0`).replace(/\\//g,`~1`)).join(`/`)}`}function ba(e,t,n,r,i){let a=t=>{n.push(z(`schema/invalid-value`,`Property \"${e.type}\" of ${i} must be ${t}.`,r))};switch(e.type){case`string`:return typeof t==`string`?e.maxLength!==void 0&&[...t].length>e.maxLength?a(`at most ${e.maxLength} characters`):t:a(`a string`);case`color`:return typeof t==`string`?(e.alpha===!0?/^#[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$/:/^#[0-9A-Fa-f]{6}$/).test(t)?t:a(e.alpha===!0?`#RRGGBB or #RRGGBBAA`:`#RRGGBB`):a(`a color string`);case`integer`:return typeof t!=`number`||!Number.isSafeInteger(t)?a(`a safe integer`):xa(e,t)??a(Sa(e));case`number`:return typeof t!=`number`||!Number.isFinite(t)?a(`a finite number`):e.exclusiveMin!==void 0&&!(t>e.exclusiveMin)?a(`greater than ${e.exclusiveMin}`):xa(e,t)??a(Sa(e));case`boolean`:return typeof t==`boolean`?t:a(`a boolean`);case`enum`:{let n=e.options??[];return typeof t!=`string`||!n.some(e=>e.value===t)?a(n.length===0?`one of the declared options`:`one of ${n.map(e=>JSON.stringify(e.value)).join(`, `)}`):t}default:return a(e.type)}}function xa(e,t){if(!(e.min!==void 0&&t<e.min)&&!(e.max!==void 0&&t>e.max))return t}function Sa(e){let t=[];return e.min!==void 0&&t.push(`>= ${e.min}`),e.max!==void 0&&t.push(`<= ${e.max}`),t.length===0?`in range`:t.join(` and `)}function Ca(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wa(e){return Ca(e)&&(e.mode===`package`&&typeof e.src==`string`||e.mode===`asset`&&typeof e.assetId==`string`&&typeof e.name==`string`)}function Ta(e){return Ca(e)?e.mode===`project`?typeof e.projectId==`string`:wa(e):!1}function Ea(e){let t=e.split(`/`);return t[t.length-1]}async function Da(e,t,n,r,i,a){let o=n.maxBytes,s=(e,t)=>{i.push(z(e,t,a))},c;switch(r.mode){case`package`:if(!ia(r.src))return s(`package/invalid-path`,`Property \"${t}\" references the non-normalized package path \"${r.src}\".`);try{c=await e.package.read(r.src,o)}catch(e){i.push(...ja(e,`package/not-found`));return}break;case`asset`:{let n=e.resolveResource;if(n===void 0)return s(`runtime/prepare-failed`,`Property \"${t}\" uses a \"${r.mode}\" resource but the runtime was created without a resolveResource function.`);let i;try{i=await n({instanceId:e.instanceId,property:t,reference:r})}catch(e){return s(`package/not-found`,`Property \"${t}\" could not read asset \"${r.assetId}\": ${Ma(e)}`)}if(!(i instanceof Uint8Array))return s(`package/not-found`,`The resolveResource function returned no bytes for property \"${t}\".`);c=i.slice();break}default:return s(`schema/invalid-value`,`Property \"${t}\" uses an unknown resource mode.`)}return o!==void 0&&c.length>o?s(`package/resource-limit`,`Property \"${t}\" is ${c.length} bytes, above the declared limit of ${o}.`):c.slice()}async function Oa(e,t,n,r,i,a){if(wa(r))return Da(e,t,n,r,i,a);i.push(z(`schema/invalid-type`,`Property \"${t}\" of ${e.instanceId} must be a resource reference ({\"src\": ..., \"mode\": ...}).`,a))}async function ka(e,t,n,r,i,a){let o=(e,t)=>{i.push(z(e,t,a))};if(!Ta(r)||n.loader!==`memory`&&n.loader!==`filesystem`)return o(`schema/invalid-value`,`A program requires a valid reference and loader.`);let s={deviceId:e.package.lock.id,property:t,loader:n.loader},c=(e,t)=>{let n=Ca(e)&&typeof e.code==`string`&&[`program/resource-limit`,`program/invalid-path`].includes(e.code)?e.code:t;return o(n,Ma(e))},l;try{if(r.mode===`project`){let t=e.programs?.projects;if(t===void 0)return o(`program/project-resolve-failed`,`No program project provider is configured.`);let i;try{i=e.signal===void 0?await t.resolve(r.projectId,s):await t.resolve(r.projectId,s,e.signal)}catch(e){return c(e,`program/project-resolve-failed`)}if(!Ca(i)||i.kind!==`memory`&&i.kind!==`filesystem`)return o(`program/project-resolve-failed`,`The program project returned no valid artifact.`);if(i.kind!==n.loader)return o(`program/loader-mismatch`,`The project artifact does not match the program loader.`);if(i.kind===`filesystem`){if(!Array.isArray(i.files))return o(`program/project-resolve-failed`,`The program project returned no file set.`);l={kind:`filesystem`,files:i.files}}else{let e=i.format,t=i.data;if(e!==`bin`&&e!==`hex`&&e!==`elf`||!(t instanceof Uint8Array))return o(`program/project-resolve-failed`,`The program project returned an invalid memory artifact.`);l={kind:`memory`,format:e,data:t}}}else if(n.loader===`filesystem`){let s;if(r.mode===`package`){jr(r.src);let t=`${r.src}/`,n=Object.entries(e.package.files).filter(([e])=>e.startsWith(t));if(n.length===0)return o(`package/not-found`,`Package program directory ${r.src} does not exist.`);if(n.length>kr.maxFiles)throw new H(`program/resource-limit`,`Program file count exceeds the fixed limit.`);let i=0;for(let[e,r]of n)if(jr(e.slice(t.length)),i+=r.size,r.size>kr.maxFileBytes||i>kr.maxTotalBytes)throw new H(`program/resource-limit`,`Package program bytes exceed the fixed limits.`);let a=[];for(let[r]of n)a.push({path:r.slice(t.length),data:await e.package.read(r,kr.maxFileBytes)});s=a}else{let o=await Da(e,t,n,r,i,a);if(o===void 0)return;s=Ar(o)}l={kind:`filesystem`,files:s}}else{let s=r.mode===`package`?r.src:r.name,c=Rn(s);if(c===void 0)return o(`program/unknown-format`,`Unknown program file format: ${s}.`);if(!n.formats?.includes(c))return o(`program/unsupported-format`,`The program property does not accept ${c}.`);let u=await Da(e,t,n,r,i,a);if(u===void 0)return;if(!(u instanceof Uint8Array))return o(`program/source-resolve-failed`,`The program file resolver returned no bytes.`);l={kind:`memory`,format:c,data:u}}return l.kind===`filesystem`?r.addressSpace!==void 0||r.loadAddress!==void 0?o(`schema/invalid-value`,`Filesystem programs do not accept address overrides.`):Mr(l.files):Pr(l.format,l.data,n,r)}catch(e){if(e instanceof H)return o(r.mode===`project`&&e.code===`program/source-resolve-failed`?`program/project-resolve-failed`:e.code,e.message);if(e instanceof R){for(let t of e.problems)i.push(z(t.code===`package/resource-limit`?`program/resource-limit`:t.code,t.message,a));return}throw e}}async function Aa(e,t,n,r,i,a){let o=(e,t)=>{i.push(z(e,t,a))};if(!Ta(r)||r.mode===`project`)return o(`schema/invalid-type`,`Property \"${t}\" of ${e.instanceId} must be a firmware reference.`);let s=n.maxBytes,c=n.addressSpaces??{},l=r.mode===`package`?r.src:r.name,u=Rn(Ea(l)??``);if(u===void 0)return o(`firmware/unknown-format`,`Property \"${t}\" names \"${l}\" whose extension is not a known firmware format.`);let d=await Da(e,t,n,r,i,a);if(d===void 0||u===void 0)return;if(s!==void 0&&d.length>s)return o(`package/resource-limit`,`Property \"${t}\" is ${d.length} bytes, above the declared limit of ${s}.`);let f=r.addressSpace??n.addressSpace,p=f===void 0?void 0:c[f];if(f===void 0||p===void 0)return o(`schema/invalid-value`,`Property \"${t}\" selects the unknown address space ${JSON.stringify(f)}.`);if(u!==`bin`&&r.loadAddress!==void 0)return o(`schema/invalid-value`,`Property \"${t}\" sets loadAddress, which only BIN firmware supports.`);if(u===`elf`&&r.addressSpace!==void 0)return o(`schema/invalid-value`,`Property \"${t}\" sets addressSpace, which ELF firmware does not support.`);if(!zn(u))return o(`firmware/unsupported-format`,`${u.toUpperCase()} firmware of property \"${t}\" is not decoded by this runtime yet; provide a BIN source.`);let m=r.loadAddress??n.loadAddress;if(m===void 0)return o(`firmware/out-of-range`,`Property \"${t}\" has no load address for its BIN firmware.`);try{return Un(d,f,p,m)}catch(e){return o(`firmware/out-of-range`,`Property \"${t}\": ${Ma(e)}`)}}function ja(e,t){return e instanceof R?[...e.problems]:[z(t,Ma(e))]}function Ma(e){return e instanceof Error?e.message:String(e)}function Na(e){return Pa(e,/* @__PURE__ */ new Set,[])}function Pa(e,t,n){if(typeof e!=`object`||!e)return(typeof e==`function`||typeof e==`symbol`||typeof e==`bigint`)&&U(`IR_SCHEMA`,`Expected ordinary IR data.`,n.slice()),e;t.has(e)&&U(`IR_SCHEMA`,`Cyclic IR data is not supported.`,n.slice()),t.add(e);let r;if(e instanceof Uint8Array)r=Object.freeze(Array.from(Uint8Array.prototype.values.call(e)));else if(Array.isArray(e)){Object.getPrototypeOf(e)!==Array.prototype&&U(`IR_SCHEMA`,`Expected an ordinary IR array.`);let i=[];for(let t of Reflect.ownKeys(e))t!==`length`&&((typeof t!=`string`||!/^(0|[1-9][0-9]*)$/.test(t)||Number(t)>=e.length)&&U(`IR_SCHEMA`,`IR arrays cannot contain extra properties.`),`value`in Object.getOwnPropertyDescriptor(e,t)||U(`IR_SCHEMA`,`IR arrays cannot contain accessors.`));for(let r=0;r<e.length;r++)Object.hasOwn(e,r)||U(`IR_SCHEMA`,`IR arrays cannot be sparse.`),n.push(r),i.push(Pa(Object.getOwnPropertyDescriptor(e,r).value,t,n)),n.pop();r=Object.freeze(i)}else{let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&U(`IR_SCHEMA`,`Expected an ordinary data object.`);let a={};for(let r of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,r);(typeof r!=`string`||!(`value`in i))&&U(`IR_SCHEMA`,`IR data cannot contain symbols or accessors.`),n.push(r);let o=Pa(i.value,t,n);n.pop(),r===`__proto__`?Object.defineProperty(a,r,{value:o,enumerable:!0}):a[r]=o}r=Object.freeze(a)}return t.delete(e),r}var Fa=class extends Error{diagnostics;constructor(e){if(!e.length)throw TypeError(`BuildError requires at least one diagnostic.`);super(e.map(e=>e.message).join(`\n`)),this.name=`BuildError`,this.diagnostics=Na(e)}};function U(e,t,n=[],r=`finalize`,i){throw new Fa([{code:e,message:t,path:n,phase:r,related:[],...i===void 0?{}:{source:i}}])}let Ia=Object.freeze({Logic:[`low`,`high`,`unknown`],SampleStatus:[`valid`,`floating`],Overflow:[`drop_new`,`drop_oldest`,`error`]}),La=[`positive`,`negate`,`not`,`bitNot`],Ra=[`add`,`subtract`,`multiply`,`divide`,`remainder`,`power`,`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`,`equal`,`notEqual`,`concat`,`bitAnd`,`bitOr`,`bitXor`,`shiftLeft`,`shiftRight`,`shiftRightUnsigned`],za=[`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`],Ba=[`load8`,`load16le`,`load16be`,`load32le`,`load32be`],Va=[`store8`,`store16le`,`store16be`,`store32le`,`store32be`],Ha=[`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`enum`,`record`];function W(e,t){(typeof e!=`object`||!e||Array.isArray(e))&&U(`IR_SCHEMA`,`Expected a data object.`,t)}function G(e,t,n,r,i=!0){for(let n of t)Object.hasOwn(e,n)||U(`IR_SCHEMA`,`Missing field ${n}.`,[...r,n]);for(let a of Object.keys(e))[...t,...n,...i?[`source`]:[]].includes(a)||U(`IR_SCHEMA`,`Unexpected field ${a}.`,[...r,a]);Object.hasOwn(e,`source`)&&Ja(e.source,[...r,`source`])}function K(e,t){typeof e!=`string`&&U(`IR_SCHEMA`,`Expected a string.`,t)}function Ua(e,t){typeof e!=`boolean`&&U(`IR_SCHEMA`,`Expected a boolean.`,t)}function Wa(e,t){typeof e!=`number`&&U(`IR_SCHEMA`,`Expected a number.`,t)}function Ga(e,t){(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)&&U(`IR_SCHEMA`,`Expected a nonnegative safe integer.`,t)}function Ka(e,t,n){t.includes(e)||U(`IR_SCHEMA`,`Expected one of ${t.join(`, `)}.`,n)}function qa(e,t,n){Array.isArray(e)||U(`IR_SCHEMA`,`Expected an array.`,t);for(let r=0;r<e.length;r++)n(e[r],[...t,r])}function Ja(e,t){W(e,t);let n=Object.hasOwn(e,`uri`);for(let n of Object.keys(e))[`uri`,`range`,`label`].includes(n)||U(`IR_SCHEMA`,`Invalid source field.`,[...t,n]);if(Object.hasOwn(e,`label`)&&K(e.label,[...t,`label`]),!n){(!Object.hasOwn(e,`label`)||Object.hasOwn(e,`range`))&&U(`IR_SCHEMA`,`Source requires a label or URI and range.`,t);return}K(e.uri,[...t,`uri`]),W(e.range,[...t,`range`]);let r=e.range;for(let e of Object.keys(r))[`start`,`end`].includes(e)||U(`IR_SCHEMA`,`Invalid range field.`,[...t,`range`,e]);for(let e of[`start`,`end`]){let n=r[e];W(n,[...t,`range`,e]);for(let r of Object.keys(n))[`line`,`column`].includes(r)||U(`IR_SCHEMA`,`Invalid position field.`,[...t,`range`,e,r]);for(let r of[`line`,`column`])(!Number.isSafeInteger(n[r])||n[r]<1)&&U(`IR_SCHEMA`,`Positions start at one.`,[...t,`range`,e,r])}let{start:i,end:a}=r;(a.line<i.line||a.line===i.line&&a.column<i.column)&&U(`IR_SCHEMA`,`Source range is reversed.`,t)}function Ya(e,t,n=!0){W(e,t),e.kind===`optional`&&n?(G(e,[`kind`,`inner`],[],t),Ya(e.inner,[...t,`inner`],!1)):(Ka(e.kind,Ha,[...t,`kind`]),G(e,[`kind`,...[`enum`,`record`].includes(e.kind)?[`name`]:[]],[],t),[`enum`,`record`].includes(e.kind)&&K(e.name,[...t,`name`])),Object.hasOwn(e,`source`)&&U(`IR_SCHEMA`,`Type descriptors cannot carry source information.`,t)}function Xa(e,t,n){W(e,t),Object.hasOwn(e,`source`)&&U(`IR_SCHEMA`,`Resource references cannot carry source information.`,t),Ka(e.kind,[`pin`,`memory`,`parameter`],[...t,`kind`]),e.kind===`parameter`?(G(e,[`kind`,`resource`,`index`],[],t),Ka(e.resource,[`pin`,`memory`],[...t,`resource`]),Ga(e.index,[...t,`index`]),n&&e.resource!==n&&U(`IR_REFERENCE`,`Resource category does not match.`,t)):(G(e,[`kind`,`name`],[],t),K(e.name,[...t,`name`]),n&&e.kind!==n&&U(`IR_REFERENCE`,`Resource category does not match.`,t))}function Za(e,t,n=!1){W(e,t),Object.hasOwn(e,`source`)&&U(`IR_SCHEMA`,`Constants and patterns cannot carry source information.`,t);let r=n?[`number`,`bool`,`string`,`enum`,`none`]:[`number`,`bool`,`string`,`bytes`,`enum`,`record`,`none`];switch(Ka(e.kind,r,[...t,`kind`]),e.kind){case`none`:G(e,[`kind`],[],t);break;case`enum`:G(e,[`kind`,`name`,`member`],[],t),K(e.name,[...t,`name`]),K(e.member,[...t,`member`]);break;case`record`:G(e,[`kind`,`name`,`fields`],[],t),K(e.name,[...t,`name`]),qa(e.fields,[...t,`fields`],(e,t)=>{W(e,t),G(e,[`name`,`value`],[],t),K(e.name,[...t,`name`]),[`number`,`boolean`].includes(typeof e.value)||U(`IR_SCHEMA`,`Expected a number or boolean field.`,[...t,`value`])});break;case`bytes`:G(e,[`kind`,`value`],[],t),qa(e.value,[...t,`value`],(e,t)=>{(!Number.isInteger(e)||e<0||e>255)&&U(`IR_SCHEMA`,`Expected a byte.`,t)});break;default:G(e,[`kind`,`value`],[],t),e.kind===`number`?(Wa(e.value,[...t,`value`]),n&&!Number.isFinite(e.value)&&U(`IR_CONTROL_FLOW`,`Numeric match patterns must be finite.`,t)):e.kind===`bool`?Ua(e.value,[...t,`value`]):K(e.value,[...t,`value`])}}function Qa(e,t){W(e,t),G(e,[`operations`],[],t),qa(e.operations,[...t,`operations`],eo)}function $a(e,t){W(e,t),G(e,[`type`,`body`],[],t),Ya(e.type,[...t,`type`]),Qa(e.body,[...t,`body`])}function eo(e,t){W(e,t),K(e.kind,[...t,`kind`]);let n=[],r=[],i=!1,a=e=>{n=e,i=!0};switch(e.kind){case`constant`:a([`constant`]),Za(e.constant,[...t,`constant`]);break;case`read`:a([`resource`,`name`]),Ka(e.resource,[`property`,`const`,`state`,`derived`],[...t,`resource`]),K(e.name,[...t,`name`]);break;case`parameter`:case`reactionCapture`:a([`index`]),Ga(e.index,[...t,`index`]);break;case`reactionValue`:a([`binding`]),Ka(e.binding,[`previous`,`current`],[...t,`binding`]);break;case`unary`:a([`operator`,`value`]),Ka(e.operator,La,[...t,`operator`]);break;case`binary`:a([`operator`,`left`,`right`]),Ka(e.operator,Ra,[...t,`operator`]);break;case`numeric`:a([`builtin`,`args`]),Ka(e.builtin,za,[...t,`builtin`]),qa(e.args,[...t,`args`],Ga);break;case`record`:a([`fields`]),qa(e.fields,[...t,`fields`],(e,t)=>{W(e,t),G(e,[`name`,`value`],[],t),K(e.name,[...t,`name`]),Ga(e.value,[...t,`value`])});break;case`field`:a([`value`,`field`]),K(e.field,[...t,`field`]);break;case`bytes`:a([`elements`]),qa(e.elements,[...t,`elements`],Ga);break;case`length`:case`optional`:case`isNone`:case`nonNull`:a([`value`]);break;case`index`:a([`value`,`index`]),Ga(e.index,[...t,`index`]);break;case`localRead`:a([`local`]),Ga(e.local,[...t,`local`]);break;case`local`:n=[`local`,`type`,`initial`],Ga(e.local,[...t,`local`]),Ya(e.type,[...t,`type`]);break;case`localWrite`:n=[`local`,`value`],Ga(e.local,[...t,`local`]);break;case`write`:n=[`resource`,`name`,`value`],Ka(e.resource,[`state`],[...t,`resource`]),K(e.name,[...t,`name`]);break;case`memoryLength`:a([`memory`]),Xa(e.memory,[...t,`memory`],`memory`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:a([`memory`,`offset`]),Xa(e.memory,[...t,`memory`],`memory`);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:n=[`memory`,`offset`,`value`],Xa(e.memory,[...t,`memory`],`memory`);break;case`copyBytes`:a([`memory`,`offset`,`length`]),Xa(e.memory,[...t,`memory`],`memory`);break;case`readSample`:a([`pin`]),Xa(e.pin,[...t,`pin`],`pin`);break;case`resistor`:a([`to`,`resistance`]),Xa(e.to,[...t,`to`],`pin`);break;case`combineIntents`:a([`values`]),qa(e.values,[...t,`values`],Ga);break;case`refEqual`:a([`left`,`right`]),Xa(e.left,[...t,`left`]),Xa(e.right,[...t,`right`]);break;case`writeIntent`:n=[`pin`,`value`],Xa(e.pin,[...t,`pin`],`pin`);break;case`call`:case`callValue`:n=[`name`,`pure`,`args`],i=e.kind===`callValue`,K(e.name,[...t,`name`]),Ua(e.pure,[...t,`pure`]),qa(e.args,[...t,`args`],(e,t)=>{W(e,t),e.kind===`value`?(G(e,[`kind`,`value`],[],t),Ga(e.value,[...t,`value`])):Xa(e,t)});break;case`send`:n=[`channel`,`value`],K(e.channel,[...t,`channel`]);break;case`notify`:n=[`notification`],K(e.notification,[...t,`notification`]);break;case`receive`:a([`channel`]),K(e.channel,[...t,`channel`]);break;case`now`:case`random`:a([]);break;case`if`:n=[`condition`,`yes`],r=[`no`],Qa(e.yes,[...t,`yes`]),Object.hasOwn(e,`no`)&&Qa(e.no,[...t,`no`]);break;case`match`:n=[`value`,`arms`],r=[`otherwise`],qa(e.arms,[...t,`arms`],(e,t)=>{W(e,t),G(e,[`pattern`,`body`],[],t),Za(e.pattern,[...t,`pattern`],!0),Qa(e.body,[...t,`body`])}),Object.hasOwn(e,`otherwise`)&&Qa(e.otherwise,[...t,`otherwise`]);break;case`while`:n=[`test`,`body`],$a(e.test,[...t,`test`]),Qa(e.body,[...t,`body`]);break;case`loop`:n=[`body`],Qa(e.body,[...t,`body`]);break;case`and`:case`or`:a([`left`,`right`]),$a(e.right,[...t,`right`]);break;case`select`:a([`condition`,`yes`,`no`]),$a(e.yes,[...t,`yes`]),$a(e.no,[...t,`no`]);break;case`assert`:n=[`condition`],r=[`message`],Object.hasOwn(e,`message`)&&$a(e.message,[...t,`message`]);break;case`wait`:case`elapse`:n=[`duration`];break;case`waitUntil`:n=[`predicate`],K(e.predicate,[...t,`predicate`]);break;case`redirect`:n=[`target`,`delay`];break;case`return`:case`break`:case`continue`:case`stop`:break;case`returnValue`:case`yield`:n=[`value`];break;default:U(`IR_SCHEMA`,`Unknown operation ${e.kind}.`,[...t,`kind`])}G(e,[`kind`,...n,...i?[`result`,`type`]:[]],r,t),i&&(Ga(e.result,[...t,`result`]),Ya(e.type,[...t,`type`]));for(let n of[`value`,`left`,`right`,`condition`,`initial`,`offset`,`length`,`resistance`,`duration`,`target`,`delay`])Object.hasOwn(e,n)&&typeof e[n]!=`object`&&!(n===`value`&&[`constant`,`read`].includes(e.kind))?Ga(e[n],[...t,n]):Object.hasOwn(e,n)&&typeof e[n]==`object`&&![`refEqual`,`and`,`or`].includes(e.kind)&&U(`IR_SCHEMA`,`Expected a result identifier.`,[...t,n])}function to(e){W(e,[]),G(e,[`kind`,`name`,`declarations`],[],[]),Ka(e.kind,[`device`],[`kind`]),K(e.name,[`name`]),qa(e.declarations,[`declarations`],(e,t)=>{W(e,t),K(e.kind,[...t,`kind`]);let n=[`kind`],r=[];switch([`start`,`assert`].includes(e.kind)||(n.push(`name`),K(e.name,[...t,`name`])),e.kind){case`enum`:n.push(`members`),qa(e.members,[...t,`members`],K);break;case`record`:n.push(`fields`),qa(e.fields,[...t,`fields`],(e,t)=>{W(e,t),G(e,[`name`,`type`],[],t),K(e.name,[...t,`name`]),Ka(e.type,[`number`,`bool`],[...t,`type`])});break;case`property`:n.push(`type`),r=[`default`],Object.hasOwn(e,`default`)&&$a(e.default,[...t,`default`]);break;case`const`:case`derived`:n.push(`type`,`value`),$a(e.value,[...t,`value`]);break;case`state`:n.push(`type`,`initial`),$a(e.initial,[...t,`initial`]);break;case`pin`:r=[`initial`,`low`,`high`];for(let n of r)Object.hasOwn(e,n)&&$a(e[n],[...t,n]);Object.hasOwn(e,`low`)!==Object.hasOwn(e,`high`)&&U(`IR_SCHEMA`,`Pin thresholds must be provided together.`,t);break;case`memory`:n.push(`public`,`length`),Ua(e.public,[...t,`public`]),$a(e.length,[...t,`length`]);break;case`channel`:n.push(`direction`,`type`,`capacity`),r=[`maxLength`,`overflow`],$a(e.capacity,[...t,`capacity`]);for(let n of r)Object.hasOwn(e,n)&&$a(e[n],[...t,n]);break;case`notification`:n.push(`direction`);break;case`function`:n.push(`pure`,`params`,`body`),r=[`returns`],Ua(e.pure,[...t,`pure`]),qa(e.params,[...t,`params`],(e,t)=>{W(e,t),G(e,[`name`,`type`],[],t),K(e.name,[...t,`name`]),W(e.type,[...t,`type`]),[`pin`,`memory`].includes(e.type.kind)?G(e.type,[`kind`],[],[...t,`type`]):Ya(e.type,[...t,`type`])}),Object.hasOwn(e,`returns`)&&Ya(e.returns,[...t,`returns`]),Qa(e.body,[...t,`body`]);break;case`start`:case`assert`:n.push(`body`),Qa(e.body,[...t,`body`]);break;case`on`:n.push(`sourcePath`,`body`),qa(e.sourcePath,[...t,`sourcePath`],K),Qa(e.body,[...t,`body`]);break;case`reaction`:n.push(`sourcePath`,`sourceType`,`previous`,`current`,`captures`,`body`),qa(e.sourcePath,[...t,`sourcePath`],K),Ya(e.sourceType,[...t,`sourceType`]),K(e.previous,[...t,`previous`]),K(e.current,[...t,`current`]),qa(e.captures,[...t,`captures`],(e,t)=>{W(e,t),G(e,[`name`,`value`],[],t),K(e.name,[...t,`name`]),$a(e.value,[...t,`value`])}),Qa(e.body,[...t,`body`]);break;default:U(`IR_SCHEMA`,`Unknown declaration ${e.kind}.`,[...t,`kind`])}G(e,n,r,t),Object.hasOwn(e,`type`)&&Ya(e.type,[...t,`type`]),[`channel`,`notification`].includes(e.kind)&&Ka(e.direction,[`input`,`output`],[...t,`direction`])})}function no(e){W(e,[]),G(e,[`kind`,`instructions`],[],[]),Ka(e.kind,[`block`],[`kind`]),qa(e.instructions,[`instructions`],(e,t)=>{W(e,t),G(e,[`pc`,`nextPc`,`body`],[],t);for(let n of[`pc`,`nextPc`])(typeof e[n]!=`number`||!Number.isFinite(e[n]))&&U(`IR_SCHEMA`,`Instruction positions must be finite numbers.`,[...t,n]);Qa(e.body,[...t,`body`])});let t=e.instructions;t.length||U(`IR_JIT_BOUNDARY`,`A block requires at least one instruction.`,[`instructions`]);for(let e=1;e<t.length;e++)t[e-1].nextPc!==t[e].pc&&U(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries do not match.`,[`instructions`,e,`pc`])}let q={kind:`number`},ro={kind:`bool`},io={kind:`string`},ao={kind:`bytes`},oo={kind:`intent`},so={kind:`sample`},co=/* @__PURE__ */ new Set([`device`,`default`,`const`,`let`,`enum`,`record`,`state`,`derived`,`pin`,`memory`,`fn`,`pure`,`process`,`on`,`reaction`,`as`,`capture`,`if`,`else`,`match`,`while`,`loop`,`break`,`continue`,`return`,`await`,`assert`,`redirect`,`true`,`false`,`none`,`start`,`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`NaN`,`Infinity`,...Object.keys(Ia),...za,...Ba,...Va,`resistor`,`copyBytes`,`now`,`random`,`ticks`]);function lo(e,t){let n=e,r=t;return n?.kind===r?.kind&&(n?.kind===`optional`?lo(n.inner,r?.inner):n?.kind===`enum`||n?.kind===`record`?n.name===r?.name:!0)}function uo(e){return e.kind===`optional`?e.inner:e}function fo(e){return uo(e).kind!==`intent`}function po(e){return{facts:new Map(e.facts),locals:new Map(e.locals)}}function mo(e){let t=new Map(e[0]);for(let[n,r]of t)e.some(e=>e.get(n)!==r)&&t.delete(n);return t}function ho(e,t){for(let n of[e.normal,...e.breaks,...e.continues,...e.yieldStates])if(n)for(let e of n.locals.keys())t.has(e)||n.locals.delete(e);return e}function go(e){if(!e.length)return;let t=po(e[0]);t.facts=mo(e.map(e=>e.facts));for(let[n,r]of t.locals){let i=e.map(e=>e.locals.get(n));if(i.some(e=>!e))t.locals.delete(n);else if(i.some(e=>e.value.key!==r.value.key)){let a={type:r.type,key:`join:${n}:${i.map(e=>e.value.key).join(`|`)}`},o=i.map((t,n)=>e[n].facts.get(t.value.key));o.every(e=>e===!0)&&t.facts.set(a.key,!0),o.every(e=>e===!1)&&t.facts.set(a.key,!1),t.locals.set(n,{type:r.type,value:a})}}return t}function _o(e,t,n=[]){e.operations.forEach((e,r)=>{let i=[...n,`operations`,r];t(e,i);for(let n of[`yes`,`no`,`otherwise`,`body`]){let r=n in e?e[n]:void 0;if(r){let e=`body`in r;_o(e?r.body:r,t,[...i,n,...e?[`body`]:[]])}}e.kind===`while`&&_o(e.test.body,t,[...i,`test`,`body`]),e.kind===`assert`&&e.message&&_o(e.message.body,t,[...i,`message`,`body`]),(e.kind===`and`||e.kind===`or`)&&_o(e.right.body,t,[...i,`right`,`body`]),e.kind===`match`&&e.arms.forEach((e,n)=>_o(e.body,t,[...i,`arms`,n,`body`]))})}var vo=class{device;declarations=/* @__PURE__ */ new Map;paths=/* @__PURE__ */ new Map;enums=new Map(Object.entries(Ia));records=/* @__PURE__ */ new Map;functions=/* @__PURE__ */ new Map;effectChecked=/* @__PURE__ */ new Set;receiveOwners=/* @__PURE__ */ new Map;constructor(e){if(this.device=e,!e)return;this.name(e.name,[`name`]);let t=0;e.declarations.forEach((e,n)=>{let r=[`declarations`,n];e.kind===`start`?++t>1&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`,r):e.kind!==`assert`&&(this.name(e.name,[...r,`name`]),this.declarations.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`,r),this.declarations.set(e.name,e),this.paths.set(e.name,r),e.kind===`enum`&&(this.uniqueNames(e.members,[...r,`members`]),e.members.length||this.error(`IR_TYPE`,`An enum must have at least one member.`,r),this.enums.set(e.name,e.members)),e.kind===`record`&&(this.uniqueNames(e.fields.map(e=>e.name),[...r,`fields`]),this.records.set(e.name,e.fields)),e.kind===`function`&&this.functions.set(e.name,e))})}error(e,t,n,r){return U(e,t,n,`finalize`,r?.source)}name(e,t){(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||co.has(e))&&this.error(`IR_REFERENCE`,`Invalid or reserved identifier ${e}.`,t)}uniqueNames(e,t,n=!1){let r=/* @__PURE__ */ new Set;e.forEach((e,i)=>{n?/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||this.error(`IR_REFERENCE`,`Invalid member name.`,[...t,i]):this.name(e,[...t,i]),r.has(e)&&this.error(`IR_REFERENCE`,`Duplicate name ${e}.`,[...t,i]),r.add(e)})}type(e,t){let n=uo(e);n.kind===`enum`&&!this.enums.has(n.name)&&this.device&&this.error(`IR_REFERENCE`,`Unknown enum ${n.name}.`,t),n.kind===`record`&&!this.records.has(n.name)&&this.device&&this.error(`IR_REFERENCE`,`Unknown record ${n.name}.`,t)}expect(e,t,n,r){lo(e,t)||this.error(`IR_TYPE`,`Expected ${this.describe(t)}, received ${this.describe(e)}.`,n,r)}describe(e){let t=e;return t?t.kind===`optional`?`${this.describe(t.inner)}?`:String(t.name??t.kind):`no value`}declaration(e,t,n){if(!this.device)return;let r=this.declarations.get(e);return(!r||r.kind!==t)&&this.error(`IR_REFERENCE`,`Expected ${t} declaration ${e}.`,n),r}ref(e,t,n,r){let i=e.kind===`parameter`?e.resource:e.kind;if(t&&i!==t&&this.error(`IR_REFERENCE`,`Resource category does not match.`,r),e.kind===`parameter`){let t=n.params[e.index];t||this.error(`IR_SCOPE`,`Resource parameter is outside the current function.`,r),t.type.kind!==i&&this.error(`IR_REFERENCE`,`Resource parameter category does not match.`,r)}else this.declaration(e.name,i,r);return i}field(e,t,n){if(e.kind===`sample`){let e={voltage:{kind:`optional`,inner:q},level:{kind:`enum`,name:`Logic`},status:{kind:`enum`,name:`SampleStatus`}};return e[t]||this.error(`IR_REFERENCE`,`Unknown sample field ${t}.`,n),e[t]}e.kind!==`record`&&this.error(`IR_TYPE`,`Field access requires a record or sample.`,n);let r=this.records.get(e.name);if(!r&&!this.device)return q;let i=r?.find(e=>e.name===t);return i||this.error(`IR_REFERENCE`,`Unknown record field ${t}.`,n),{kind:i.type}}constant(e,t,n){if(e.kind===`none`)t.kind!==`optional`&&this.error(`IR_TYPE`,`none requires an optional result type.`,n);else{if(t.kind===`optional`&&this.error(`IR_TYPE`,`Non-null constants require a nonoptional type and explicit optional lift.`,n),(e.kind!==t.kind||(e.kind===`enum`||e.kind===`record`)&&e.name!==(`name`in t?t.name:void 0))&&this.error(`IR_TYPE`,`Constant and result types do not match.`,n),e.kind===`enum`){let t=this.enums.get(e.name);t&&!t.includes(e.member)&&this.error(`IR_REFERENCE`,`Unknown enum member ${e.member}.`,n)}e.kind===`record`&&this.recordFields(e.fields,t,n,e=>({kind:typeof e.value==`boolean`?`bool`:`number`}))}}recordFields(e,t,n,r){t.kind!==`record`&&this.error(`IR_TYPE`,`Record construction requires a named record type.`,n);let i=this.records.get(t.name),a=/* @__PURE__ */ new Set;for(let t=0;t<e.length;t++){let o=e[t];if(a.has(o.name)&&this.error(`IR_REFERENCE`,`Duplicate record field.`,[...n,`fields`,t]),a.add(o.name),i){let e=i.find(e=>e.name===o.name);e||this.error(`IR_REFERENCE`,`Unknown record field ${o.name}.`,[...n,`fields`,t]),this.expect(r(o),{kind:e.type},[...n,`fields`,t])}else r(o)}i&&i.length!==e.length&&this.error(`IR_TYPE`,`Record fields are incomplete.`,n)}context(e,t){return{mode:e,params:[],...t?{returns:t}:{},loop:0,results:/* @__PURE__ */ new Map,resultIds:/* @__PURE__ */ new Set,localIds:/* @__PURE__ */ new Set,tail:!0,finalInstruction:!0,computation:!1}}body(e,t,n){let r=this.region(e,t,{facts:/* @__PURE__ */ new Map,locals:/* @__PURE__ */ new Map},n);t.returns&&r.normal&&this.error(`IR_CONTROL_FLOW`,`A value-returning body has a normal path without returnValue.`,n,e),this.effects(e,t.mode,n)}computation(e,t,n,r){this.type(e.type,[...r,`type`]),this.expect(e.type,t,[...r,`type`]);let i=this.context(n,t);i.computation=!0,this.body(e.body,i,[...r,`body`])}conditioned(e,t,n){let r=po(e),i=n?t.yes:t.no;if(i)for(let[e,t]of i)r.facts.set(e,t);return r}region(e,t,n,r){let i=po(n),a={breaks:[],continues:[],yielded:[],yieldStates:[]},o=new Map(t.results);t={...t,results:o};for(let n=0;n<e.operations.length;n++){let s=e.operations[n],c=[...r,`operations`,n];i||this.error(`IR_CONTROL_FLOW`,`Operation follows an unconditional path terminator.`,c,s);let l=i,u=(e,t)=>{let n=o.get(e);return n||this.error(`IR_SCOPE`,`Result ${e} is not visible or is used before its definition.`,c,s),t&&this.expect(n.type,t,c,s),n},d=(e,t={})=>{let n=s;this.expect(n.type,e,[...c,`type`],s);let r={type:n.type,key:`v:${n.result}`,...t};return o.set(n.result,r),r};`result`in s&&(this.type(s.type,[...c,`type`]),t.resultIds.has(s.result)&&this.error(`IR_SCOPE`,`Duplicate result ${s.result}.`,[...c,`result`],s),t.resultIds.add(s.result));let f=e=>{let t=l.locals.get(e);return t||this.error(`IR_SCOPE`,`Local is not visible or not initialized.`,[...c,`local`],s),t},p=(r,i,a,o={})=>ho(this.region(r,{...t,tail:t.tail&&n===e.operations.length-1,...o},i,[...c,a]),i.locals),m=e=>{a.breaks.push(...e.breaks),a.continues.push(...e.continues),a.yielded.push(...e.yielded),a.yieldStates.push(...e.yieldStates)},h=(e,n,r,i)=>{this.type(e.type,[...c,i,`type`]),this.expect(e.type,n,[...c,i,`type`]);let a=ho(this.region(e.body,{...t,valueRegion:n,loop:0,tail:!1},r,[...c,i,`body`]),r.locals);return a.normal&&this.error(`IR_CONTROL_FLOW`,`A value region has a normal path without yield.`,[...c,i],e),{flow:a,...a.yielded.length?{value:{type:n,key:`region:${`result`in s?s.result:void 0}:${i}`,yes:mo(a.yielded.map(e=>e.yes??/* @__PURE__ */ new Map)),no:mo(a.yielded.map(e=>e.no??/* @__PURE__ */ new Map))}}:{}}};switch(s.kind){case`constant`:{this.constant(s.constant,s.type,[...c,`constant`]);let e=d(s.type,{none:s.constant.kind===`none`});s.constant.kind===`none`&&l.facts.set(e.key,!1);break}case`read`:d(this.declaration(s.name,s.resource,c)?.type??s.type);break;case`parameter`:{let e=t.params[s.index];e||this.error(`IR_SCOPE`,`Parameter index is outside the current function.`,c,s),(e.type.kind===`pin`||e.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource parameters cannot be read as values.`,c,s),d(e.type,{key:`parameter:${s.index}`});break}case`reactionValue`:t.reaction||this.error(`IR_SCOPE`,`Reaction bindings are only visible inside their response body.`,c,s),d(t.reaction.sourceType,{key:`reaction:${s.binding}`});break;case`reactionCapture`:t.reaction||this.error(`IR_SCOPE`,`Reaction captures are only visible inside their response body.`,c,s),t.reaction.captures[s.index]||this.error(`IR_SCOPE`,`Reaction capture index is out of range.`,c,s),d(t.reaction.captures[s.index].value.type,{key:`capture:${s.index}`});break;case`unary`:{let e=u(s.value,s.operator===`not`?ro:q);d(s.operator===`not`?ro:q,s.operator===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{});break}case`binary`:{let e=u(s.left),t=u(s.right);if([`equal`,`notEqual`].includes(s.operator)){this.expect(e.type,t.type,c,s),!fo(e.type)&&(e.type.kind!==`optional`||!e.none&&!t.none)&&this.error(`IR_TYPE`,`Intent values do not support content equality.`,c,s);let n=e.none?t:t.none?e:void 0,r=s.operator===`equal`;d(ro,n?{yes:/* @__PURE__ */ new Map([[n.key,!r]]),no:/* @__PURE__ */ new Map([[n.key,r]])}:{})}else s.operator===`concat`?(u(s.left,io),u(s.right,io),d(io)):(u(s.left,q),u(s.right,q),d([`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(s.operator)?ro:q));break}case`numeric`:s.args.length!==([`min`,`max`,`pow`].includes(s.builtin)?2:1)&&this.error(`IR_TYPE`,`Numeric builtin argument count does not match.`,c,s),s.args.forEach(e=>u(e,q)),d(s.builtin.startsWith(`is`)?ro:q);break;case`record`:this.recordFields(s.fields,s.type,c,e=>u(e.value).type),d(s.type);break;case`field`:{let e=u(s.value),t=e.type;d(t.kind===`record`&&!this.device?s.type:this.field(t,s.field,c),{key:`field:${e.key}:${s.field}`});break}case`bytes`:s.elements.forEach(e=>u(e,q)),d(ao);break;case`length`:{let e=u(s.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`length requires string or bytes.`,c,s),d(q);break}case`index`:{let e=u(s.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`index requires string or bytes.`,c,s),u(s.index,q),d(e.kind===`string`?io:q);break}case`optional`:{let e=u(s.value).type;e.kind===`optional`&&this.error(`IR_TYPE`,`Optional types cannot be nested.`,c,s);let t=d({kind:`optional`,inner:e});l.facts.set(t.key,!0);break}case`isNone`:{let e=u(s.value);e.type.kind!==`optional`&&this.error(`IR_TYPE`,`isNone requires an optional value.`,c,s),d(ro,{yes:/* @__PURE__ */ new Map([[e.key,!1]]),no:/* @__PURE__ */ new Map([[e.key,!0]])});break}case`nonNull`:{let e=u(s.value);(e.type.kind!==`optional`||l.facts.get(e.key)!==!0)&&this.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`,c,s),d(e.type.inner);break}case`local`:{t.localIds.has(s.local)&&this.error(`IR_SCOPE`,`Duplicate local identifier.`,c,s),t.localIds.add(s.local),this.type(s.type,[...c,`type`]);let e=u(s.initial,s.type);l.locals.set(s.local,{type:s.type,value:e});break}case`localRead`:{let e=f(s.local);d(e.type,{...e.value});break}case`localWrite`:{let e=f(s.local),t=u(s.value,e.type);l.locals.set(s.local,{type:e.type,value:t});break}case`write`:{let e=this.declaration(s.name,`state`,c);u(s.value,e?.type);break}case`memoryLength`:this.ref(s.memory,`memory`,t,c),d(q);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:this.ref(s.memory,`memory`,t,c),u(s.offset,q),d(q);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:this.ref(s.memory,`memory`,t,c),u(s.offset,q),u(s.value,q);break;case`copyBytes`:this.ref(s.memory,`memory`,t,c),u(s.offset,q),u(s.length,q),d(ao);break;case`readSample`:this.ref(s.pin,`pin`,t,c),d(so);break;case`resistor`:this.ref(s.to,`pin`,t,c),u(s.resistance,q),d(oo);break;case`combineIntents`:s.values.forEach(e=>u(e,oo)),d(oo);break;case`refEqual`:this.expect({kind:this.ref(s.left,void 0,t,c)},{kind:this.ref(s.right,void 0,t,c)},c),d(ro);break;case`writeIntent`:this.ref(s.pin,`pin`,t,c),u(s.value,oo);break;case`call`:case`callValue`:{let e=this.declaration(s.name,`function`,c);e&&s.pure&&!e.pure&&this.error(`IR_EFFECT`,`A pure call must target an explicitly pure function.`,c,s),e&&s.args.length!==e.params.length&&this.error(`IR_TYPE`,`Call argument count does not match.`,c,s),s.args.forEach((n,r)=>{let i=e?.params[r];n.kind===`value`?(i&&(i.type.kind===`pin`||i.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource argument required.`,c,s),u(n.value,i?.type)):(i&&i.type.kind!==`pin`&&i.type.kind!==`memory`&&this.error(`IR_TYPE`,`Value argument required.`,c,s),this.ref(n,i?.type.kind,t,c))}),s.kind===`callValue`?(e&&!e.returns&&this.error(`IR_TYPE`,`callValue requires a value-returning function.`,c,s),d(e?.returns??s.type)):e?.returns&&this.error(`IR_TYPE`,`call cannot discard the return type of a value-returning function.`,c,s);break}case`send`:{let e=this.declaration(s.channel,`channel`,c);e?.direction===`input`&&this.error(`IR_REFERENCE`,`send requires an output channel.`,c,s),u(s.value,e?.type);break}case`notify`:this.declaration(s.notification,`notification`,c)?.direction===`input`&&this.error(`IR_REFERENCE`,`notify requires an output notification.`,c,s);break;case`receive`:{let e=this.declaration(s.channel,`channel`,c);e?.direction===`output`&&this.error(`IR_REFERENCE`,`receive requires an input channel.`,c,s),d(e?.type??s.type);break}case`now`:case`random`:d(q);break;case`if`:{let e=u(s.condition,ro),t=p(s.yes,this.conditioned(l,e,!0),`yes`),n=s.no?p(s.no,this.conditioned(l,e,!1),`no`):{normal:this.conditioned(l,e,!1),breaks:[],continues:[],yielded:[],yieldStates:[]};m(t),m(n),i=go([t.normal,n.normal].filter(e=>!!e));break}case`match`:{let r=u(s.value),a=uo(r.type),o=/* @__PURE__ */ new Set,d=[];for(let i=0;i<s.arms.length;i++){let u=s.arms[i],f=u.pattern;this.constant(f,f.kind===`none`?r.type:a,[...c,`arms`,i,`pattern`]);let p=f.kind===`enum`?`${f.name}.${f.member}`:`${f.kind}:${String(`value`in f?f.value:void 0)}`;o.has(p)&&this.error(`IR_CONTROL_FLOW`,`Duplicate match pattern.`,[...c,`arms`,i]),o.add(p);let h=po(l);r.type.kind===`optional`&&h.facts.set(r.key,f.kind!==`none`);let g=ho(this.region(u.body,{...t,tail:t.tail&&n===e.operations.length-1},h,[...c,`arms`,i,`body`]),h.locals);m(g),g.normal&&d.push(g.normal)}let f=(a.kind===`bool`?o.has(`bool:true`)&&o.has(`bool:false`):a.kind===`enum`&&this.enums.get(a.name)?.every(e=>o.has(`${a.name}.${e}`)))&&(r.type.kind!==`optional`||o.has(`none:undefined`));if(s.otherwise){let e=po(l);r.type.kind===`optional`&&o.has(`none:undefined`)&&e.facts.set(r.key,!0);let t=p(s.otherwise,e,`otherwise`);m(t),t.normal&&d.push(t.normal)}else f||this.error(`IR_CONTROL_FLOW`,`Match requires exhaustive patterns or a default region.`,c,s);i=go(d);break}case`while`:case`loop`:{let e=/* @__PURE__ */ new Set;_o(s.body,t=>{t.kind===`localWrite`&&l.locals.has(t.local)&&e.add(t.local)}),s.kind===`while`&&_o(s.test.body,t=>{t.kind===`localWrite`&&l.locals.has(t.local)&&e.add(t.local)});let n=t=>{let n=po(l),r=[l,...t];for(let t of e){let e=l.locals.get(t),i={type:e.type,key:`loop:${c.join(`.`)}:${t}`};n.locals.set(t,{type:e.type,value:i});let a=r.map(e=>{let n=e.locals.get(t)?.value;return n?e.facts.get(n.key):void 0});a.every(e=>e===!0)?n.facts.set(i.key,!0):a.every(e=>e===!1)&&n.facts.set(i.key,!1)}return n},r=n([]),o=new Set(t.resultIds),u=new Set(t.localIds),d,f;for(;;){t.resultIds.clear();for(let e of o)t.resultIds.add(e);t.localIds.clear();for(let e of u)t.localIds.add(e);d=s.kind===`while`?h(s.test,ro,r,`test`):void 0;let i=d?go(d.flow.yieldStates)??r:r,a=d?.value?this.conditioned(i,d.value,!0):i;f=p(s.body,a,`body`,{loop:t.loop+1,tail:!1});let c=n([f.normal,...f.continues].filter(e=>!!e));if([...e].every(e=>{let t=c.locals.get(e).value.key;return c.facts.get(t)===r.facts.get(t)}))break;r=c}a.yielded.push(...f.yielded),a.yieldStates.push(...f.yieldStates);let m=[...f.breaks];if(s.kind===`while`&&d?.value){let e=go(d.flow.yieldStates)??r;m.push(this.conditioned(e,d.value,!1))}i=go(m);break}case`and`:case`or`:{let e=u(s.left,ro),t=s.kind===`and`,n=h(s.right,ro,this.conditioned(l,e,t),`right`),r=n.value,a=(e,t)=>new Map([...e??[],...t??[]]),o=t?a(e.yes,r?.yes):mo([e.yes??/* @__PURE__ */ new Map,a(e.no,r?.yes)]),c=t?mo([e.no??/* @__PURE__ */ new Map,a(e.yes,r?.no)]):a(e.no,r?.no);d(ro,{yes:o,no:c}),i=go([this.conditioned(l,e,!t),...n.flow.yieldStates]);break}case`select`:{let e=u(s.condition,ro),t=h(s.yes,s.type,this.conditioned(l,e,!0),`yes`),n=h(s.no,s.type,this.conditioned(l,e,!1),`no`);d(s.type),i=go([...t.flow.yieldStates,...n.flow.yieldStates]);break}case`assert`:{let e=u(s.condition,ro);s.message&&h(s.message,io,this.conditioned(l,e,!1),`message`),i=this.conditioned(l,e,!0);break}case`wait`:(t.valueRegion||t.mode!==`process`)&&this.error(`IR_EFFECT`,`wait is only allowed in a process statement region.`,c,s),u(s.duration,q);break;case`elapse`:(t.valueRegion||t.mode!==`jit`)&&this.error(`IR_EFFECT`,`elapse is only allowed in a JIT statement region.`,c,s),u(s.duration,q);break;case`waitUntil`:t.mode!==`jit`&&this.error(`IR_EFFECT`,`waitUntil requires a JIT instruction.`,c,s),(t.valueRegion||t.loop||!t.tail||n!==e.operations.length-1||!t.finalInstruction)&&this.error(`IR_JIT_BOUNDARY`,`waitUntil must be on the final instruction tail path.`,c,s);{let e=this.declaration(s.predicate,`function`,c);e&&(!e.pure||e.params.length||!lo(e.returns,ro))&&this.error(`IR_TYPE`,`waitUntil requires a zero-parameter pure bool function.`,c,s)}i=void 0;break;case`redirect`:[`jit`,`sync`].includes(t.mode)||this.error(`IR_EFFECT`,`redirect is not permitted in this context.`,c,s),u(s.target,q),u(s.delay,q),i=void 0;break;case`stop`:(t.mode!==`jit`||t.valueRegion)&&this.error(`IR_EFFECT`,`stop requires a JIT statement region.`,c,s),i=void 0;break;case`return`:(t.valueRegion||t.returns||t.mode===`jit`||t.computation||t.mode===`creation`||t.mode===`initial`)&&this.error(`IR_CONTROL_FLOW`,`Void return is not valid in this body.`,c,s),i=void 0;break;case`returnValue`:(t.valueRegion||!t.returns)&&this.error(`IR_CONTROL_FLOW`,`returnValue is not valid in this body.`,c,s),u(s.value,t.returns),i=void 0;break;case`yield`:t.valueRegion||this.error(`IR_CONTROL_FLOW`,`yield requires a value region.`,c,s);{let e=u(s.value,t.valueRegion);a.yielded.push(e),a.yieldStates.push(l)}i=void 0;break;case`break`:case`continue`:t.loop||this.error(`IR_CONTROL_FLOW`,`${s.kind} requires an enclosing loop in this region.`,c,s),(s.kind===`break`?a.breaks:a.continues).push(l),i=void 0}}return i&&(a.normal=i),a}effects(e,t,n){_o(e,(e,n)=>{let r=[`creation`,`initial`,`pure`].includes(t),i=[`creation`,`initial`].includes(t),a=[`write`,`writeIntent`,`send`,`notify`,`now`,`random`,`wait`,`receive`,`elapse`,`waitUntil`,`stop`,`redirect`,...Va].includes(e.kind);if(r&&a&&this.error(`IR_EFFECT`,`${e.kind} is not allowed in ${t} code.`,n,e),i&&(e.kind===`read`&&![`property`,`const`].includes(e.resource)||[`readSample`,`memoryLength`,`copyBytes`,...Ba].includes(e.kind))&&this.error(`IR_EFFECT`,`Creation computations cannot read runtime resources.`,n,e),t===`creation`&&([`resistor`,`combineIntents`,`refEqual`].includes(e.kind)||(e.kind===`call`||e.kind===`callValue`)&&e.args.some(e=>e.kind!==`value`))&&this.error(`IR_EFFECT`,`Ordinary creation computations cannot use resource references or intents.`,n,e),[`reaction`,`process`].includes(t)&&e.kind===`redirect`&&this.error(`IR_EFFECT`,`Control redirection requires a bound JIT entry.`,n,e),[`sync`,`reaction`,`pure`].includes(t)&&[`wait`,`receive`,`elapse`,`waitUntil`,`stop`].includes(e.kind)&&this.error(`IR_EFFECT`,`Synchronous code cannot suspend or use JIT control.`,n,e),t===`process`&&[`elapse`,`waitUntil`,`stop`].includes(e.kind)&&this.error(`IR_EFFECT`,`Process code cannot use JIT control.`,n,e),t===`jit`&&[`wait`,`receive`].includes(e.kind)&&this.error(`IR_EFFECT`,`JIT code cannot use process suspension.`,n,e),e.kind===`call`||e.kind===`callValue`||e.kind===`waitUntil`){let i=e.kind===`waitUntil`?e.predicate:e.name,a=this.functions.get(i);if(a&&r&&!a.pure&&this.error(`IR_EFFECT`,`Pure contexts can only call explicitly pure functions.`,n,e),a){let e=`${t}:${i}`;this.effectChecked.has(e)||(this.effectChecked.add(e),this.effects(a.body,t,[...this.paths.get(i)??[],`body`]))}}},n)}source(e,t,n){e.length||this.error(`IR_SCHEMA`,`An observation source path cannot be empty.`,t);let r=this.declarations.get(e[0]);r||this.error(`IR_REFERENCE`,`Observation source does not exist.`,t);let i,a=1;if(r.kind===`notification`&&n)(r.direction!==`input`||e.length!==1)&&this.error(`IR_REFERENCE`,`Only input notifications can trigger a process.`,t);else{r.kind===`pin`?(e[1]!==`sample`&&this.error(`IR_REFERENCE`,`Pin observation must select sample.`,t),i=so,a=2):r.kind===`state`||r.kind===`derived`?i=r.type:this.error(`IR_REFERENCE`,`An observation source must be state, derived, pin.sample or an input notification.`,t);for(let n=a;n<e.length;n++)i=this.field(i,e[n],[...t,n]);return fo(i)||this.error(`IR_TYPE`,`Observation sources must be comparable.`,t),i}}cycle(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=a=>{if(n.has(a)&&this.error(`IR_DEPENDENCY`,`${t} dependency cycle includes ${a}.`,this.paths.get(a)??[]),!r.has(a)){n.add(a);for(let t of e.get(a)??[])e.has(t)&&i(t);n.delete(a),r.add(a)}};for(let t of e.keys())i(t)}dependencies(e,t,n=/* @__PURE__ */ new Set){let r=/* @__PURE__ */ new Set;return _o(e,e=>{if(e.kind===`read`&&t.includes(e.resource)&&r.add(e.name),(e.kind===`call`||e.kind===`callValue`)&&!n.has(e.name)){n.add(e.name);let i=this.functions.get(e.name);if(i)for(let e of this.dependencies(i.body,t,n))r.add(e)}}),r}validateDevice(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.functions){let r=/* @__PURE__ */ new Set;_o(n.body,e=>{(e.kind===`call`||e.kind===`callValue`)&&r.add(e.name)}),e.set(t,r)}this.cycle(e,`Synchronous call`);let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;this.device.declarations.forEach((e,r)=>{let i=[`declarations`,r];if(`type`in e&&e.type&&this.type(e.type,[...i,`type`]),e.kind===`property`||e.kind===`const`||e.kind===`state`){let n=uo(e.type);([`sample`,`intent`].includes(n.kind)||e.kind===`property`&&n.kind===`record`)&&this.error(`IR_TYPE`,`Type is not valid at this declaration position.`,[...i,`type`],e);let r=e.kind===`property`?`default`:e.kind===`const`?`value`:`initial`,a=e.kind===`property`?e.default:e.kind===`const`?e.value:e.initial;a&&(this.computation(a,e.type,`creation`,[...i,r]),t.set(e.name,this.dependencies(a.body,[`property`,`const`])))}else if(e.kind===`derived`)this.computation(e.value,e.type,`pure`,[...i,`value`]),n.set(e.name,this.dependencies(e.value.body,[`derived`]));else if(e.kind===`pin`){for(let t of[`low`,`high`])e[t]&&this.computation(e[t],q,`creation`,[...i,t]);e.initial&&this.computation(e.initial,oo,`initial`,[...i,`initial`])}else if(e.kind===`memory`)this.computation(e.length,q,`creation`,[...i,`length`]);else if(e.kind===`channel`)[`number`,`bool`,`record`,`bytes`].includes(e.type.kind)||this.error(`IR_TYPE`,`Invalid channel payload type.`,[...i,`type`],e),e.type.kind===`bytes`!=!!e.maxLength&&this.error(`IR_TYPE`,`Only bytes channels require maxLength.`,i,e),this.computation(e.capacity,q,`creation`,[...i,`capacity`]),e.maxLength&&this.computation(e.maxLength,q,`creation`,[...i,`maxLength`]),e.overflow&&this.computation(e.overflow,{kind:`enum`,name:`Overflow`},`creation`,[...i,`overflow`]);else if(e.kind===`function`){this.uniqueNames(e.params.map(e=>e.name),[...i,`params`]),e.params.forEach((e,t)=>{this.declarations.has(e.name)&&this.error(`IR_REFERENCE`,`A parameter cannot shadow a device member.`,[...i,`params`,t]),e.type.kind!==`pin`&&e.type.kind!==`memory`&&this.type(e.type,[...i,`params`,t,`type`])}),e.returns&&this.type(e.returns,[...i,`returns`]);let t=this.context(e.pure?`pure`:`sync`,e.returns);t.params=e.params,this.body(e.body,t,[...i,`body`])}else if(e.kind===`start`||e.kind===`on`)e.kind===`on`&&this.source(e.sourcePath,[...i,`sourcePath`],!0),this.body(e.body,this.context(`process`),[...i,`body`]),_o(e.body,e=>{if(e.kind===`receive`){let t=`${r}`,n=this.receiveOwners.get(e.channel);if(n&&n!==t){let e=new Fa([{code:`IR_REFERENCE`,message:`An input channel cannot have multiple consumer processes.`,phase:`finalize`,path:i,related:[]}]);throw Object.defineProperty(e,\"code\",{value:`CHANNEL_CONSUMER_CONFLICT`}),e}this.receiveOwners.set(e.channel,t)}});else if(e.kind===`reaction`){let t=this.source(e.sourcePath,[...i,`sourcePath`],!1);this.expect(e.sourceType,t,[...i,`sourceType`]),this.type(e.sourceType,[...i,`sourceType`]);let n=[e.previous,e.current,...e.captures.map(e=>e.name)];e.captures.forEach((e,t)=>{fo(e.value.type)||this.error(`IR_TYPE`,`Capture results must be comparable.`,[...i,`captures`,t]),this.computation(e.value,e.value.type,`pure`,[...i,`captures`,t,`value`])});let r=this.context(`reaction`);r.reaction=e,this.body(e.body,r,[...i,`body`]),this.uniqueNames(n,i);for(let e of n)this.declarations.has(e)&&this.error(`IR_REFERENCE`,`Reaction bindings cannot shadow device members.`,i)}else e.kind===`assert`&&this.body(e.body,this.context(`creation`),[...i,`body`])}),this.cycle(t,`Creation`),this.cycle(n,`Derived`)}validateBlock(e){e.instructions.forEach((t,n)=>{let r=this.context(`jit`);r.finalInstruction=n===e.instructions.length-1,this.body(t.body,r,[`instructions`,n,`body`])})}};function yo(e,t){if(!(e instanceof Fa))throw e;let n=new Fa(e.diagnostics.map(e=>{if(e.source)return e;let n=t,r,i=()=>{let e=n?.source;e&&typeof e==`object`&&(typeof e.label==`string`&&e.uri===void 0&&e.range===void 0||typeof e.uri==`string`&&e.range?.start?.line>=1&&e.range?.start?.column>=1&&e.range?.end?.line>=1&&e.range?.end?.column>=1)&&(r=e)};i();for(let t of e.path)n=n?.[t],i();return r?{...e,source:r}:e})),r=Object.getOwnPropertyDescriptor(e,`code`);throw r?.value===`CHANNEL_CONSUMER_CONFLICT`&&Object.defineProperty(n,\"code\",r),n}let bo=/* @__PURE__ */ new WeakMap,xo=/* @__PURE__ */ new WeakMap,So=/* @__PURE__ */ new WeakMap;function Co(e,t){return typeof t==`object`&&t?e.get(t):void 0}function wo(e,t,n){typeof t==`object`&&t&&e.set(t,n),e.set(n,n)}function To(e){let t=Co(bo,e);if(t!==void 0)return t;let n=Na(e);try{to(n),new vo(n).validateDevice();let t=n;return wo(bo,e,t),t}catch(e){return yo(e,n)}}function Eo(e){let t=Co(xo,e);if(t!==void 0)return t;let n=Na(e);try{no(n),new vo().validateBlock(n);let t=n;return wo(xo,e,t),t}catch(e){return yo(e,n)}}function Do(e,t){try{let n=Eo(e),r=To(t);if(So.get(n)?.has(r))return n;new vo(r).validateBlock(n);let i=So.get(n);return i||(i=/* @__PURE__ */ new WeakSet,So.set(n,i)),i.add(r),n}catch(e){if(e instanceof Fa){let t=new Fa(e.diagnostics.map(e=>({...e,phase:`bind`}))),n=Object.getOwnPropertyDescriptor(e,`code`);throw n?.value===`CHANNEL_CONSUMER_CONFLICT`&&Object.defineProperty(t,\"code\",n),t}throw e}}let Oo=/* @__PURE__ */ new WeakMap,ko=/* @__PURE__ */ new WeakMap,Ao=/* @__PURE__ */ new WeakMap,jo=/* @__PURE__ */ new WeakMap,Mo=/* @__PURE__ */ new WeakMap,No=e=>{let t=Object.freeze({});return Oo.set(t,{type:{kind:e}}),t};function Po(e,t,n){let r={};for(let i of t){let t=Object.freeze({});Mo.set(t,{name:e,member:i,...n?{owner:n}:{}}),Object.defineProperty(r,i,{value:t,enumerable:!0})}let i=Object.freeze({name:e,members:Object.freeze(r)});return Oo.set(i,{type:{kind:`enum`,name:e},members:Object.freeze([...t]),...n?{owner:n}:{}}),i}function Fo(e,t,n){let r=Object.freeze({name:e,fields:Object.freeze({...t})});return Oo.set(r,{type:{kind:`record`,name:e},fields:r.fields,...n?{owner:n}:{}}),r}let Io={number:No(`number`),bool:No(`bool`),string:No(`string`),bytes:No(`bytes`),intent:No(`intent`),sample:No(`sample`),pin:Object.freeze({kind:`pin`}),memory:Object.freeze({kind:`memory`}),logic:Po(`Logic`,Ia.Logic),sampleStatus:Po(`SampleStatus`,Ia.SampleStatus),overflow:Po(`Overflow`,Ia.Overflow),optional(e){let t=Oo.get(e);(!t||t.type.kind===`optional`)&&U(`IR_TYPE`,`optional requires a nonoptional value type.`,[],`construct`);let n=Object.freeze({});return Oo.set(n,{...t,type:{kind:`optional`,inner:t.type}}),n},namedEnum(e,t){return(typeof e!=`string`||!Array.isArray(t)||!t.length||t.some(e=>typeof e!=`string`)||new Set(t).size!==t.length)&&U(`IR_TYPE`,`Invalid named enum description.`,[],`construct`),Po(e,t)},namedRecord(e,t){(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))&&U(`IR_TYPE`,`Invalid named record description.`,[],`construct`);for(let e of Object.values(t))[`number`,`bool`].includes(Oo.get(e)?.type.kind??``)||U(`IR_TYPE`,`Record fields must be number or bool types.`,[],`construct`);return Fo(e,t)}};Object.freeze(Io);let J={kind:`number`},Lo={kind:`bool`},Ro={kind:`string`},zo={kind:`bytes`},Bo={kind:`intent`},Vo={kind:`sample`};function Ho(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function Uo(e){return typeof e==`object`&&e?ko.get(e):void 0}function Wo(e){return typeof e==`object`&&e?Mo.get(e):void 0}function Go(e){return typeof e==`object`&&e?jo.get(e):void 0}function Ko(e,t){let n=Object.freeze({});return e.set(n,t),n}function qo(e){return e.alias?qo(e.alias):e}function Jo(e){let t=new Map(e[0]);for(let[n,r]of t)e.some(e=>e.get(n)!==r)&&t.delete(n);return t}let Yo=/* @__PURE__ */ new WeakMap;var Xo=class{options;device;jit;closed=!1;active;source;declarations=[];names=/* @__PURE__ */ new Map;expectedTypes=/* @__PURE__ */ new Set;pending=[];instructions=[];constructor(e,t,n=!1){this.options=e,this.device=t,this.jit=n,e.source!==void 0&&(this.source=Na(e.source))}error(e,t,n=[]){return this.closed=!0,U(e,t,n,`construct`,this.active?.source??this.source)}check(){this.closed&&this.error(`IR_LIFECYCLE`,`This Builder is closed.`)}guard(e){this.check();try{return e()}catch(e){throw this.closed=!0,e instanceof Fa&&e.diagnostics.some(e=>e.phase!==`construct`)?new Fa(e.diagnostics.map(e=>({...e,phase:`construct`}))):e}}type(e){let t=Oo.get(e);if(t||this.error(`IR_TYPE`,`Expected a Builder type descriptor.`),t.owner&&t.owner!==this&&(!this.device||Yo.get(this.device)!==t.owner)&&this.error(`IR_SCOPE`,`Named type belongs to another device definition.`),this.expectedTypes.add(t),t.fields)for(let e of Object.values(t.fields))this.type(e);return t.type}sourceFor(e){let t=e?.source??this.source;return t===void 0?{}:{source:Na(t)}}body(e,t,n,r,i){let a=new Zo(this,e,{result:0,local:0},{},void 0,n);a.source=r===void 0?this.source:Na(r);let o=this.active;this.active=a;try{i?.(a),t(a.view())}finally{a.closed=!0,this.active=o}return this.check(),{operations:a.operations,...a.source?{source:Na(a.source)}:{}}}creation(e,t,n=`creation`,r){return{type:e,body:this.body(n,e=>{typeof t==`function`?t(e):e.returnValue(t)},e,r)}}declarationType(e){let t=this.names.get(e);return t&&`type`in t?t.type:void 0}add(e){e.name!==void 0&&(this.names.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`),this.names.set(e.name,e)),e.kind===`start`&&this.declarations.some(e=>e.kind===`start`)&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`),this.declarations.push(e)}resolve(){for(let e of this.pending){let t=this.names.get(e.call);if(!t||t.kind!==`function`){this.jit&&e.requiresSignature&&U(`IR_TYPE`,`A null or record call argument requires a bound function signature or an explicitly typed Value.`);continue}let n=t.params[e.index];if((!n||n.type.kind===`pin`||n.type.kind===`memory`)&&this.error(`IR_TYPE`,`A value argument requires a value parameter.`),n.type.kind===`optional`&&e.value!==null){let t=e.body.constantData(n.type.inner,e.value),r=e.body.space.result++,i={kind:`constant`,result:r,type:n.type.inner,constant:t,...e.node.source?{source:e.node.source}:{}},a=t=>{if(Array.isArray(t)){let n=t.indexOf(e.node);return n>=0?(t.splice(n,0,i),!0):t.some(a)}return typeof t==`object`&&!!t&&Object.values(t).some(a)};a(this.jit?this.instructions:this.declarations)||U(`IR_SCHEMA`,`Pending call argument is not part of this definition.`),delete e.node.constant,Object.assign(e.node,{kind:`optional`,type:n.type,value:r})}else{let t=e.body.constantData(n.type,e.value);Object.assign(e.node,{type:n.type,constant:t})}}for(let e of this.expectedTypes){let t=e.type.kind===`optional`?e.type.inner:e.type;if(![`enum`,`record`].includes(t.kind))continue;let n=t.name,r=this.names.get(n);if(Ia[n]&&t.kind===`enum`)e.members&&(e.members.length!==Ia[n].length||e.members.some((e,t)=>e!==Ia[n][t]))&&U(`IR_TYPE`,`Builtin enum description does not match its members.`);else if(r&&(r.kind!==t.kind&&U(`IR_REFERENCE`,`Named type category does not match its declaration.`),e.members&&(e.members.length!==r.members.length||e.members.some((e,t)=>e!==r.members[t]))&&U(`IR_TYPE`,`Forward enum description does not match its declaration.`),e.fields)){let t=Object.entries(e.fields);(t.length!==r.fields.length||t.some(([e,t])=>!r.fields.some(n=>n.name===e&&n.type===Oo.get(t)?.type.kind)))&&U(`IR_TYPE`,`Forward record description does not match its declaration.`)}}}},Zo=class e{root;mode;space;scope;parent;returns;closed=!1;ended=!1;endedByWaitUntil=!1;source;operations=[];facts=/* @__PURE__ */ new Map;localValues=/* @__PURE__ */ new Map;loop=0;calculate=!1;yielded=!1;constructor(e,t,n,r,i,a){this.root=e,this.mode=t,this.space=n,this.scope=r,this.parent=i,this.returns=a}view(){return new Proxy(Object.create(null),{get:(e,t)=>typeof t==`string`?(...e)=>this.root.guard(()=>(this.closed&&this.root.error(`IR_LIFECYCLE`,`This body Builder is closed.`),this.root.active!==this&&this.root.error(`IR_SCOPE`,`A captured outer Builder cannot emit into a nested callback.`),this.ended&&this.root.error(this.endedByWaitUntil?`IR_JIT_BOUNDARY`:`IR_CONTROL_FLOW`,`Cannot append an operation after a path terminator.`),this.invoke(t,e))):void 0})}node(e){let t={...e,...e.source===void 0&&this.source!==void 0?{source:Na(this.source)}:{}};eo(t,[]),this.operations.push(t)}result(e,t,n={}){let r=this.space.result++;return this.node({...t,result:r,type:e}),Ko(ko,{root:this.root,scope:this.scope,space:this.space,type:e,id:r,...n})}handle(e,t){let n=Uo(e);return(!n||n.root!==this.root||n.space!==this.space||!Ho(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Value is not visible in the current execution body or scope.`),t&&!lo(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}localHandle(e){let t=Ao.get(e);return(!t||t.root!==this.root||t.space!==this.space||!Ho(this.scope,t.scope))&&this.root.error(`IR_SCOPE`,`Local is not visible in this execution body or scope.`),t}infer(e){if(Uo(e))return this.handle(e).type;let t=Wo(e);if(t)return t.owner&&t.owner!==this.root&&(!this.root.device||Yo.get(this.root.device)!==t.owner)&&this.root.error(`IR_SCOPE`,`Enum member belongs to another device definition.`),{kind:`enum`,name:t.name};if(typeof e==`number`)return J;if(typeof e==`boolean`)return Lo;if(typeof e==`string`)return Ro;if(Array.isArray(e)||e instanceof Uint8Array)return zo;this.root.error(`IR_TYPE`,`A null or record literal requires an explicit target type.`)}constantData(e,t){if(e.kind===`optional`)return t!==null&&this.root.error(`IR_TYPE`,`Optional constants must be lifted from a non-null value.`),{kind:`none`};if(e.kind===`number`||e.kind===`bool`||e.kind===`string`)return typeof t!==(e.kind===`bool`?`boolean`:e.kind)&&this.root.error(`IR_TYPE`,`Constant value does not match its target type.`),{kind:e.kind,value:t};if(e.kind===`enum`){let n=Wo(t);return(!n||n.name!==e.name)&&this.root.error(`IR_TYPE`,`Enum constants require a matching enum member token.`),n.owner&&n.owner!==this.root&&(!this.root.device||Yo.get(this.root.device)!==n.owner)&&this.root.error(`IR_SCOPE`,`Enum member belongs to another definition.`),{kind:`enum`,name:n.name,member:n.member}}if(e.kind===`record`){(typeof t!=`object`||!t||Array.isArray(t))&&this.root.error(`IR_TYPE`,`A record constant requires a field object.`);let n=[...this.root.expectedTypes].find(t=>{let n=t.type.kind===`optional`?t.type.inner:t.type;return n.kind===`record`&&n.name===e.name&&t.fields}),r=this.root.names.get(e.name),i=n?.fields?Object.entries(n.fields).map(([e,t])=>({name:e,type:Oo.get(t).type.kind})):r?.kind===`record`?r.fields:void 0;i||this.root.error(`IR_TYPE`,`Record constants require a complete named type descriptor.`);let a=t;return(Object.keys(a).length!==i.length||i.some(e=>!Object.hasOwn(a,e.name)||typeof a[e.name]!=(e.type===`bool`?`boolean`:`number`)))&&this.root.error(`IR_TYPE`,`Record constant fields do not match the target type.`),{kind:`record`,name:e.name,fields:Object.keys(a).map(e=>({name:e,value:a[e]}))}}if(e.kind===`bytes`){!(t instanceof Uint8Array)&&!Array.isArray(t)&&this.root.error(`IR_TYPE`,`bytes constants require a Uint8Array or number array.`);let e=Array.from(t);return e.some(e=>!Number.isInteger(e)||e<0||e>255)&&this.root.error(`IR_TYPE`,`Every bytes element must be an integer from zero to 255.`),{kind:`bytes`,value:Object.freeze(e)}}this.root.error(`IR_TYPE`,`sample and intent cannot be constructed from host constants.`)}operand(e,t){if(Uo(e)){let n=this.handle(e);if(t&&t.kind===`optional`&&lo(n.type,t.inner)){let e=this.handle(this.result(t,{kind:`optional`,value:n.id}));return this.facts.set(qo(e),!0),e}return t&&!lo(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}let n=t??this.infer(e);if(n.kind===`optional`&&e!==null){let t=this.operand(e,n.inner),r=this.handle(this.result(n,{kind:`optional`,value:t.id}));return this.facts.set(qo(r),!0),r}return this.handle(this.result(n,{kind:`constant`,constant:this.constantData(n,e)},{none:e===null}))}ref(e,t){if(typeof e==`string`)return{kind:t,name:e};let n=Go(e);return(!n||n.root!==this.root||n.space!==this.space||!Ho(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Resource reference is not visible in this body.`),(n.ref.kind===`parameter`?n.ref.resource:n.ref.kind)!==t&&this.root.error(`IR_REFERENCE`,`Resource reference category does not match.`),n.ref}refHandle(e,t){return Ko(jo,{root:this.root,scope:this.scope,space:this.space,ref:{kind:t,name:e}})}requireRead(){[`creation`,`initial`].includes(this.mode)&&this.root.error(`IR_EFFECT`,`Runtime resource reads are not available in creation code.`)}requireEffect(){[`creation`,`initial`,`pure`].includes(this.mode)&&this.root.error(`IR_EFFECT`,`Runtime effects are not available in pure or creation code.`)}branch(t,n,r,i=!1){typeof t!=`function`&&this.root.error(`IR_SCHEMA`,`A body callback is required.`);let a=new e(this.root,this.mode,this.space,{parent:this.scope},this,this.returns);if(a.source=this.source,a.loop=r?0:this.loop+ +!!i,a.calculate=!!r||this.calculate,a.facts=new Map(this.facts),a.localValues=new Map(this.localValues),n)for(let[e,t]of(n.truth?n.info.yes:n.info.no)??[])a.facts.set(qo(e),t);let o=this.root.active;this.root.active=a;let s;try{if(s=t(a.view()),r){if(s===void 0)a.ended||this.root.error(`IR_CONTROL_FLOW`,`A compute callback must produce a value on every normal path.`);else if(!a.ended){let e=a.operand(s,r);a.node({kind:`yield`,value:e.id}),a.yielded=!0,a.ended=!0}}}finally{a.closed=!0,this.root.active=o}return this.root.check(),{body:{operations:a.operations,...a.source?{source:Na(a.source)}:{}},builder:a,returned:s}}merge(e){let t=e.filter(e=>!e.ended);if(!t.length)this.ended=!0,this.endedByWaitUntil=e.some(e=>e.endedByWaitUntil);else{this.facts=Jo(t.map(e=>e.facts));for(let[e,n]of this.localValues){let r=t.map(t=>t.localValues.get(e)??n);if(r.every(e=>e===r[0]))this.localValues.set(e,r[0]);else{let i={...n,alias:void 0};this.localValues.set(e,i),r.every((e,n)=>t[n].facts.get(qo(e))===!0)&&this.facts.set(i,!0)}}}}mergeComputations(e,t=!1){let n=e.filter(e=>e.yielded);if(t&&n.push(this),!n.length)this.ended=!0;else{this.facts=Jo(n.map(e=>e.facts));for(let[e,t]of this.localValues){let r=n.map(n=>n.localValues.get(e)??t);if(r.every(e=>e===r[0]))this.localValues.set(e,r[0]);else{let i={...t,alias:void 0};this.localValues.set(e,i),r.every((e,t)=>n[t].facts.get(qo(e))===!0)&&this.facts.set(i,!0)}}}}invoke(t,n){if(La.includes(t)){let e=this.operand(n[0],t===`not`?Lo:J);return this.result(t===`not`?Lo:J,{kind:`unary`,operator:t,value:e.id},t===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{})}if(Ra.includes(t)){let e=[`equal`,`notEqual`].includes(t),r=e?this.root.type(n.shift()):t===`concat`?Ro:J,i=this.operand(n[0],r),a=this.operand(n[1],r);e&&(r.kind===`intent`||r.kind===`optional`&&r.inner.kind===`intent`&&!i.none&&!a.none)&&this.root.error(`IR_TYPE`,`Intent values do not support content equality.`);let o=i.none?a:a.none?i:void 0,s=e||[`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(t);return this.result(s?Lo:r,{kind:`binary`,operator:t,left:i.id,right:a.id},o?{yes:/* @__PURE__ */ new Map([[qo(o),t!==`equal`]]),no:/* @__PURE__ */ new Map([[qo(o),t===`equal`]])}:{})}if(za.includes(t)){let e=[`min`,`max`,`pow`].includes(t)?2:1;return n.length!==e&&this.root.error(`IR_TYPE`,`Numeric builtin argument count does not match.`),this.result(t.startsWith(`is`)?Lo:J,{kind:`numeric`,builtin:t,args:n.map(e=>this.operand(e,J).id)})}if(Ba.includes(t)||Va.includes(t)){this.requireRead();let e=this.ref(n[0],`memory`),r=this.operand(n[1],J);if(Va.includes(t)){this.requireEffect(),this.node({kind:t,memory:e,offset:r.id,value:this.operand(n[2],J).id});return}return this.result(J,{kind:t,memory:e,offset:r.id})}switch(t){case`withSource`:{let[t,r]=n,i=new e(this.root,this.mode,this.space,this.scope,this.parent,this.returns);i.source=Na(t),i.loop=this.loop,i.calculate=this.calculate,i.facts=this.facts,i.localValues=this.localValues;let a=this.root.active;this.root.active=i;try{r(i.view())}finally{i.closed=!0,this.root.active=a}this.operations.push(...i.operations),this.ended=i.ended,this.endedByWaitUntil=i.endedByWaitUntil,this.facts=i.facts,this.localValues=i.localValues;return}case`constant`:return Uo(n[1])&&this.root.error(`IR_TYPE`,`constant requires a host constant, not a Value handle.`),this.objectOperand(n[1],this.root.type(n[0]));case`readProperty`:case`readConst`:case`readState`:case`readDerived`:{[`readState`,`readDerived`].includes(t)&&this.requireRead();let e=t.slice(4).toLowerCase();return this.result(this.root.type(n[1]),{kind:`read`,resource:e,name:n[0]})}case`local`:{let e=this.root.type(n[0]),t=this.operand(n[1],e),r=this.space.local++;this.node({kind:`local`,local:r,type:e,initial:t.id});let i={root:this.root,space:this.space,scope:this.scope,type:e,id:r};return this.localValues.set(i,t),Ko(Ao,i)}case`getLocal`:{let e=this.localHandle(n[0]),t=this.localValues.get(e);return this.result(e.type,{kind:`localRead`,local:e.id},{alias:qo(t),yes:t.yes??/* @__PURE__ */ new Map,no:t.no??/* @__PURE__ */ new Map,none:t.none??!1})}case`setLocal`:{let e=this.localHandle(n[0]),t=this.operand(n[1],e.type);this.node({kind:`localWrite`,local:e.id,value:t.id}),this.localValues.set(e,t);return}case`record`:{let e=this.root.type(n[0]),t=Oo.get(n[0]),r=n[1];return(e.kind!==`record`||!t.fields||!r||typeof r!=`object`||Object.keys(r).length!==Object.keys(t.fields).length||Object.keys(t.fields).some(e=>!Object.hasOwn(r,e)))&&this.root.error(`IR_TYPE`,`Record fields must exactly match the descriptor.`),this.result(e,{kind:`record`,fields:Object.keys(r).map(e=>({name:e,value:this.operand(r[e],this.root.type(t.fields[e])).id}))})}case`field`:{let e=this.handle(n[0]),t=n[1],r;if(e.type.kind===`sample`)r={voltage:{kind:`optional`,inner:J},level:{kind:`enum`,name:`Logic`},status:{kind:`enum`,name:`SampleStatus`}}[t];else if(e.type.kind===`record`){let n=e.type.name,i=[...this.root.expectedTypes].find(e=>{let t=e.type.kind===`optional`?e.type.inner:e.type;return t.kind===`record`&&t.name===n&&e.fields})?.fields?.[t];if(i)r=this.root.type(i);else{let e=this.root.names.get(n),i=e?.kind===`record`?e.fields.find(e=>e.name===t):void 0;i&&(r={kind:i.type})}}r||this.root.error(`IR_REFERENCE`,`Unknown record or sample field.`);let i=qo(e);i.fields??=/* @__PURE__ */ new Map;let a=i.fields.get(t),o=this.result(r,{kind:`field`,value:e.id,field:t},a?{alias:a}:{});return a||i.fields.set(t,this.handle(o)),o}case`bytes`:return this.result(zo,{kind:`bytes`,elements:n.map(e=>this.operand(e,J).id)});case`length`:{let e=this.handle(n[0]);return[`string`,`bytes`].includes(e.type.kind)||this.root.error(`IR_TYPE`,`length requires string or bytes.`),this.result(J,{kind:`length`,value:e.id})}case`index`:{let e=this.handle(n[0]);return[`string`,`bytes`].includes(e.type.kind)||this.root.error(`IR_TYPE`,`index requires string or bytes.`),this.result(e.type.kind===`string`?Ro:J,{kind:`index`,value:e.id,index:this.operand(n[1],J).id})}case`optional`:{let e=this.handle(n[0]);e.type.kind===`optional`&&this.root.error(`IR_TYPE`,`Optional types cannot be nested.`);let t=this.result({kind:`optional`,inner:e.type},{kind:`optional`,value:e.id});return this.facts.set(qo(this.handle(t)),!0),t}case`isNone`:{let e=this.handle(n[0]);return e.type.kind!==`optional`&&this.root.error(`IR_TYPE`,`isNone requires an optional value.`),this.result(Lo,{kind:`isNone`,value:e.id},{yes:/* @__PURE__ */ new Map([[qo(e),!1]]),no:/* @__PURE__ */ new Map([[qo(e),!0]])})}case`nonNull`:{let e=this.handle(n[0]);return(e.type.kind!==`optional`||this.facts.get(qo(e))!==!0)&&this.root.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`),this.result(e.type.inner,{kind:`nonNull`,value:e.id})}case`pin`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Pin references are not available in ordinary creation computations.`),this.refHandle(n[0],`pin`);case`memory`:return this.requireRead(),this.refHandle(n[0],`memory`);case`memoryLength`:return this.requireRead(),this.result(J,{kind:`memoryLength`,memory:this.ref(n[0],`memory`)});case`copyBytes`:return this.requireRead(),this.result(zo,{kind:`copyBytes`,memory:this.ref(n[0],`memory`),offset:this.operand(n[1],J).id,length:this.operand(n[2],J).id});case`readSample`:return this.requireRead(),this.result(Vo,{kind:`readSample`,pin:this.ref(n[0],`pin`)});case`resistor`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction requires initial-intent or runtime code.`),this.result(Bo,{kind:`resistor`,to:this.ref(n[0],`pin`),resistance:this.operand(n[1],J).id});case`combineIntents`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction is not available here.`),this.result(Bo,{kind:`combineIntents`,values:n.map(e=>this.operand(e,Bo).id)});case`refEqual`:{this.requireRead();let e=Go(n[0]),t=Go(n[1]);(!e||!t)&&this.root.error(`IR_TYPE`,`refEqual requires resource reference handles.`);let r=e.ref.kind===`parameter`?e.ref.resource:e.ref.kind;return this.result(Lo,{kind:`refEqual`,left:this.ref(n[0],r),right:this.ref(n[1],r)})}case`writeState`:this.requireEffect(),this.node({kind:`write`,resource:`state`,name:n[0],value:this.operand(n[1],this.root.declarationType(n[0])).id});return;case`writeIntent`:this.requireEffect(),this.node({kind:`writeIntent`,pin:this.ref(n[0],`pin`),value:this.operand(n[1],Bo).id});return;case`send`:this.requireEffect(),this.node({kind:`send`,channel:n[0],value:this.operand(n[1],this.root.declarationType(n[0])).id});return;case`notify`:this.requireEffect(),this.node({kind:`notify`,notification:n[0]});return;case`now`:case`random`:return this.requireEffect(),this.result(J,{kind:t});case`call`:case`callValue`:case`callPure`:case`callPureValue`:{let e=t.startsWith(`callPure`),r=t.endsWith(`Value`);e||this.requireEffect();let i=n.shift(),a=r?this.root.type(n.shift()):void 0,o=this.root.names.get(i),s=o?.kind===`function`?o.params:void 0,c=n.map((e,t)=>{let n=Go(e);if(n)return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Resource arguments are not available in ordinary creation code.`),this.ref(e,n.ref.kind===`parameter`?n.ref.resource:n.ref.kind);let r=s?.[t]?.type;if(r&&[`pin`,`memory`].includes(r.kind)&&this.root.error(`IR_TYPE`,`A resource reference argument is required.`),!r&&!Uo(e)){let n=e===null||typeof e==`object`&&!Wo(e)&&!Array.isArray(e)&&!(e instanceof Uint8Array),r=n?J:this.infer(e),a={kind:`constant`,result:this.space.result++,type:r,constant:n?{kind:`number`,value:0}:this.constantData(r,e),...this.source?{source:Na(this.source)}:{}};return this.operations.push(a),this.root.pending.push({node:a,call:i,index:t,value:Wo(e)?e:Na(e),body:this,requiresSignature:n}),{kind:`value`,value:a.result}}return{kind:`value`,value:this.operand(e,r).id}}),l={kind:r?`callValue`:`call`,name:i,pure:e,args:c};if(r)return this.result(a,l);this.node(l);return}case`receive`:return(this.calculate||this.mode!==`process`)&&this.root.error(`IR_EFFECT`,`receive requires a process statement region.`),this.result(this.root.type(n[1]),{kind:`receive`,channel:n[0]});case`if`:{let e=this.operand(n[0],Lo),t=this.branch(n[1],{info:e,truth:!0}),r=this.branch(n[2]??(()=>{}),{info:e,truth:!1});this.node({kind:`if`,condition:e.id,yes:t.body,...n[2]?{no:r.body}:{}}),this.merge([t.builder,r.builder]);return}case`match`:{let e=this.handle(n[0]),t=n[1];Array.isArray(t)||this.root.error(`IR_SCHEMA`,`match arms must be an array.`);let r=[],i=t.map(t=>{let n=t.pattern===null?{kind:`none`}:this.constantData(e.type.kind===`optional`?e.type.inner:e.type,t.pattern);[`none`,`number`,`bool`,`string`,`enum`].includes(n.kind)||this.root.error(`IR_TYPE`,`Invalid match pattern.`);let i={...e,yes:/* @__PURE__ */ new Map([[qo(e),n.kind!==`none`]])},a=this.branch(t.emit,{info:i,truth:!0});return r.push(a.builder),{pattern:n,body:a.body}}),a=i.some(e=>e.pattern.kind===`none`)?{info:{...e,yes:/* @__PURE__ */ new Map([[qo(e),!0]])},truth:!0}:void 0,o=n[2]?this.branch(n[2],a):void 0;o&&r.push(o.builder),this.node({kind:`match`,value:e.id,arms:i,...o?{otherwise:o.body}:{}}),this.merge(r.length?r:[this]);return}case`while`:case`loop`:{let e=new Map(this.localValues),r=t===`while`?this.branch(n[0],void 0,Lo):void 0,i=this.branch(n[+(t===`while`)],void 0,void 0,!0);this.node({kind:t,...r?{test:{type:Lo,body:r.body}}:{},body:i.body});for(let[t,n]of e)(i.builder.localValues.get(t)!==n||r&&r.builder.localValues.get(t)!==n)&&this.localValues.set(t,{...n,alias:void 0});r&&!r.builder.yielded&&(this.ended=!0);return}case`and`:case`or`:{let e=this.operand(n[0],Lo),r=t===`and`,i=this.branch(n[1],{info:e,truth:r},Lo),a=Uo(i.returned),o=(e,t)=>new Map([...e??[],...t??[]]),s=r?o(e.yes,a?.yes):Jo([e.yes??/* @__PURE__ */ new Map,o(e.no,a?.yes)]),c=r?Jo([e.no??/* @__PURE__ */ new Map,o(e.yes,a?.no)]):o(e.no,a?.no),l=this.result(Lo,{kind:t,left:e.id,right:{type:Lo,body:i.body}},{yes:s,no:c});return this.mergeComputations([i.builder],!0),l}case`select`:{let e=this.root.type(n[0]),t=this.operand(n[1],Lo),r=this.branch(n[2],{info:t,truth:!0},e),i=this.branch(n[3],{info:t,truth:!1},e),a=this.result(e,{kind:`select`,condition:t.id,yes:{type:e,body:r.body},no:{type:e,body:i.body}});return this.mergeComputations([r.builder,i.builder]),a}case`assert`:{let e=this.operand(n[0],Lo),t=n[1]?this.branch(n[1],{info:e,truth:!1},Ro):void 0;this.node({kind:`assert`,condition:e.id,...t?{message:{type:Ro,body:t.body}}:{}});for(let[t,n]of e.yes??[])this.facts.set(qo(t),n);return}case`wait`:case`elapse`:(this.calculate||(t===`wait`?this.mode!==`process`:this.mode!==`jit`))&&this.root.error(`IR_EFFECT`,`${t} is not permitted in this context.`),this.node({kind:t,duration:this.operand(n[0],J).id});return;case`waitUntil`:(this.mode!==`jit`||this.calculate||this.loop)&&this.root.error(`IR_JIT_BOUNDARY`,`waitUntil requires a JIT tail path outside loops and computations.`),this.node({kind:`waitUntil`,predicate:n[0]}),this.ended=!0,this.endedByWaitUntil=!0;return;case`redirect`:[`jit`,`sync`].includes(this.mode)||this.root.error(`IR_EFFECT`,`redirect requires a JIT-capable context.`),this.node({kind:`redirect`,target:this.operand(n[0],J).id,delay:this.operand(n[1]??0,J).id}),this.ended=!0;return;case`stop`:(this.mode!==`jit`||this.calculate)&&this.root.error(`IR_EFFECT`,`stop requires a JIT statement region.`),this.node({kind:`stop`}),this.ended=!0;return;case`break`:case`continue`:this.loop||this.root.error(`IR_CONTROL_FLOW`,`${t} requires an enclosing loop.`),this.node({kind:t}),this.ended=!0;return;case`return`:(this.calculate||this.returns||[`jit`,`creation`,`initial`].includes(this.mode))&&this.root.error(`IR_CONTROL_FLOW`,`Void return is not permitted in this body.`),this.node({kind:`return`}),this.ended=!0;return;case`returnValue`:(this.calculate||!this.returns)&&this.root.error(`IR_CONTROL_FLOW`,`returnValue is not permitted in this body.`),this.node({kind:`returnValue`,value:this.operand(n[0],this.returns).id}),this.ended=!0;return;default:this.root.error(`IR_SCHEMA`,`Unknown Builder operation ${t}.`)}}objectOperand(e,t){let n=this.operand(e,t);return Ko(ko,n)}};function Qo(e={}){let t=new Xo({name:`JitBlock`,...e.source?{source:e.source}:{}},e.device,!0);if(e.device)for(let n of e.device.declarations)`name`in n&&t.names.set(n.name,n);let n=(r={closed:!1})=>new Proxy(Object.create(null),{get:(i,a)=>typeof a==`string`?(...i)=>{if(a===`finish`){t.check(),r.closed&&t.error(`IR_LIFECYCLE`,`This source view is closed.`),t.active&&t.error(`IR_SCOPE`,`Cannot finish a block inside an instruction callback.`),t.closed=!0,t.resolve();let n={kind:`block`,instructions:t.instructions,...t.sourceFor()};return e.device?Do(n,e.device):Eo(n)}return t.guard(()=>{if(r.closed&&t.error(`IR_LIFECYCLE`,`This source view is closed.`),t.active&&t.error(`IR_SCOPE`,`Cannot add instructions inside an instruction callback.`),a===`withSource`){let e=t.source,r={closed:!1};t.source=Na(i[0]);try{i[1](n(r))}finally{r.closed=!0,t.source=e}return}a!==`instruction`&&t.error(`IR_SCHEMA`,`Unknown block Builder method ${a}.`);let e=i[0];(!e||!Number.isFinite(e.pc)||!Number.isFinite(e.nextPc))&&t.error(`IR_SCHEMA`,`Instruction boundaries require finite pc and nextPc.`);let o=t.instructions.at(-1);o&&o.nextPc!==e.pc&&t.error(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries must match.`);let s=t.body(`jit`,i[1],void 0,e.source??t.source);t.instructions.push({pc:e.pc,nextPc:e.nextPc,body:s,...t.sourceFor(e)})})}:void 0});return n()}function $o(e,t=/* @__PURE__ */ new Map){try{let n=ns(e,t,/* @__PURE__ */ new Set);return n===Y?{known:!1,reason:`it depends on a value that is only known at run time`}:{known:!0,value:n}}catch(e){if(e instanceof es)return{known:!1,reason:e.reason};throw e}}var es=class extends Error{reason;constructor(e){super(e),this.reason=e}};let Y=Symbol(`unverified`);function ts(e){throw new es(e)}function ns(e,t,n){let r=/* @__PURE__ */ new Map,i=Y,a=e.body.operations;for(let e of a){let a=e.kind;if(a===`returnValue`){let t=e.value;i=r.has(t)?r.get(t):Y;continue}if(a===`local`||a===`localWrite`||a===`write`)continue;let o=e.result;typeof o==`number`&&(a===`localRead`?r.set(o,Y):r.set(o,rs(e,r,t,n)))}return i}function rs(e,t,n,r){let i=e=>typeof e==`number`&&t.has(e)?t.get(e):Y;switch(e.kind){case`constant`:return is(e.constant);case`read`:{if(e.resource!==`const`)return Y;let t=e.name;if(typeof t!=`string`)return Y;let i=n.get(t);if(i===void 0)return ts(`constant \"${t}\" is not declared in the model`);if(r.has(t))return ts(`constant \"${t}\" is defined in terms of itself`);r.add(t);try{return ns(i,n,r)}finally{r.delete(t)}}case`unary`:{let t=i(e.value);if(t===Y)return Y;switch(e.operator){case`positive`:return typeof t==`number`?t:Y;case`negate`:return typeof t==`number`?-t:Y;case`not`:return typeof t==`boolean`?!t:Y;case`bitNot`:return typeof t==`number`?~t:Y;default:return Y}}case`binary`:return as(e,i(e.left),i(e.right));case`numeric`:return os(e.builtin,e.args.map(i));case`record`:{let t=e.fields,n={};for(let e of t){let t=i(e.value);if(t===Y)return Y;n[e.name]=t}return n}case`field`:{let t=i(e.value),n=e.field;return t===Y||typeof t!=`object`||!t?Y:t[String(n)]}case`index`:{let t=i(e.value),n=i(e.index);return t===Y||typeof n!=`number`?Y:typeof t==`string`||Array.isArray(t)?t[n]:Y}case`bytes`:{let t=[];for(let n of e.elements){let e=i(n);if(typeof e!=`number`)return Y;t.push(e)}return t}case`length`:{let t=i(e.value);return typeof t==`string`||Array.isArray(t)?t.length:Y}case`optional`:case`nonNull`:return i(e.value);case`isNone`:return i(e.value)===null;default:return Y}}function is(e){if(e===void 0)return Y;switch(e.kind){case`number`:case`bool`:case`string`:return e.value;case`none`:return null;case`enum`:return e.member;case`record`:{let t=e.fields;return Object.fromEntries(t.map(e=>[e.name,e.value]))}case`bytes`:return Array.from(e.value);default:return Y}}function as(e,t,n){if(t===Y||n===Y)return Y;let r=typeof t==`number`&&typeof n==`number`;switch(e.operator){case`add`:return r||typeof t==`string`&&typeof n==`string`?t+n:Y;case`subtract`:return r?t-n:Y;case`multiply`:return r?t*n:Y;case`divide`:return r?t/n:Y;case`remainder`:return r?t%n:Y;case`power`:return r?t**n:Y;case`lessThan`:return r?t<n:Y;case`lessThanOrEqual`:return r?t<=n:Y;case`greaterThan`:return r?t>n:Y;case`greaterThanOrEqual`:return r?t>=n:Y;case`equal`:return t===n;case`notEqual`:return t!==n;case`concat`:return typeof t==`string`&&typeof n==`string`?t+n:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Y;case`bitAnd`:return r?t&n:Y;case`bitOr`:return r?t|n:Y;case`bitXor`:return r?t^n:Y;default:return Y}}function os(e,t){let n=t;if(n.some(e=>typeof e!=`number`))return Y;switch(e){case`isNaN`:return Number.isNaN(n[0]);case`isFinite`:return Number.isFinite(n[0]);case`isInteger`:return Number.isInteger(n[0]);case`isSafeInteger`:return Number.isSafeInteger(n[0]);case`abs`:return Math.abs(n[0]);case`floor`:return Math.floor(n[0]);case`ceil`:return Math.ceil(n[0]);case`trunc`:return Math.trunc(n[0]);case`round`:return Math.round(n[0]);case`sqrt`:return Math.sqrt(n[0]);case`min`:return Math.min(...n);case`max`:return Math.max(...n);case`pow`:return n[0]**n[1];default:return Y}}let ss={number:[`number`,`integer`],string:[`string`,`color`],bool:[`boolean`],bytes:[`binary`,`image`]};function cs(e,t){let n=[],r=(e,t)=>{n.push(z(`model/invalid-interface`,e,t))},i=t.declarations.flatMap(e=>e.kind===`pin`?[e.name]:[]),a=Object.keys(e.pins??{}),o=i.filter(e=>!a.includes(e)),s=a.filter(e=>!i.includes(e));(o.length>0||s.length>0)&&r(`Pins of ${e.publisher}:${e.name} differ between manifest and model IR (model only: ${o.join(`, `)||`none`}; manifest only: ${s.join(`, `)||`none`}).`,`/pins`);let c=e.properties??{},l=new Map(t.declarations.flatMap(e=>e.kind===`const`?[[e.name,e.value]]:[])),u=new Map(t.declarations.flatMap(e=>e.kind===`enum`?[[e.name,e.members]]:[]));for(let e of t.declarations){if(e.kind!==`property`)continue;let t=`/properties/${e.name}`,n=c[e.name];if(n===void 0){r(`The model IR declares the property \"${e.name}\" the manifest does not describe.`,t);continue}let i=e.type.kind===`optional`,a=i?e.type.inner:e.type;a.kind===`enum`?n.type===`enum`?[...u.get(a.name)??[]].sort().join(`\\0`)!==(n.options??[]).map(e=>e.value).sort().join(`\\0`)&&r(`Options of property \"${e.name}\" must match the model enum members.`,t):r(`Property \"${e.name}\" is an enum in the model IR but ${n.type} in the manifest.`,t):ss[a.kind]?.includes(n.type)||r(`Property \"${e.name}\" is ${a.kind} in the model IR but ${n.type} in the manifest.`,t),i!==(n.nullable===!0)&&r(i?`Property \"${e.name}\" is optional in the model IR but the manifest does not set nullable.`:`Property \"${e.name}\" is not optional in the model IR but the manifest sets nullable.`,t);let o=Object.hasOwn(n,`default`);if(e.default===void 0===o){r(e.default===void 0?`The manifest declares a default for \"${e.name}\" the model IR does not.`:`The model IR declares a default for \"${e.name}\" the manifest does not.`,`${t}/default`);continue}if(e.default===void 0)continue;let s=$o(e.default,l);s.known?ls(s.value,n.default)||r(`The manifest default of \"${e.name}\" must equal the model IR default.`,`${t}/default`):r(`The default of \"${e.name}\" cannot be verified before a factory runs: ${s.reason}.`,`${t}/default`)}return n}function ls(e,t){if(typeof e==`number`&&typeof t==`number`)return Object.is(e,t);if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return e===t;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>ls(e,t[n]));let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>ls(e[n],t[n]))}async function us(e){let t=new wn,n=()=>{let n=t.drain();for(let t of n)e.onDiagnostic?.(t);return new xn(n)},r;try{r=Rt(e.document)}catch(e){throw t.add(e,`schema/invalid-value`),n()}let i=[];for(let e of r.instances)i.includes(e.device)||i.push(e.device);let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let n of i){let i=r.dependencies[n];if(i===void 0){t.addProblem(z(`document/unlocked-device`,`Instance device \"${n}\" is not locked.`));continue}let s;try{s=await aa(e.registry,{id:n,version:i.version,integrity:i.integrity},e.hostApiVersion)}catch(e){t.add(e,`package/not-found`);continue}o.set(n,s.manifest),a.set(n,{deviceId:n,lock:s.lock,package:s})}if(!t.empty)throw n();for(let[e,n]of r.instances.entries()){let r=n.viewLayout,i=o.get(n.device);if(r===void 0||i===void 0)continue;let a=i.view??{},s=/* @__PURE__ */ new Set;r.views.forEach((r,i)=>{let o=`/instances/${e}/viewLayout/views/${i}/viewId`;s.has(r.viewId)?t.addProblem(z(`document/invalid-view-layout`,`Instance \"${n.id}\" lists the view \"${r.viewId}\" more than once.`,o),n.id):(s.add(r.viewId),Object.hasOwn(a,r.viewId)||t.addProblem(z(`document/invalid-view-layout`,`Instance \"${n.id}\" references the view \"${r.viewId}\", which ${n.device} does not declare.`,o),n.id))})}if(!t.empty)throw n();let s;try{s=cn(r,o).nets}catch(e){throw t.add(e,`net/reference-conflict`),n()}for(let[n,r]of a){let i=r.package.manifest.model;if(i===void 0)continue;let o=await ds(r,i.entry,e,t);o!==void 0&&a.set(n,{...r,model:o})}if(!t.empty)throw n();let c=[];for(let[n,i]of r.instances.entries()){let r=a.get(i.device),o=r?.model;if(r!==void 0&&o!==void 0)try{let t=await va({instanceId:i.id,package:r.package,descriptors:r.package.manifest.properties??{},overrides:i.properties??{},irProperties:fs(o.ir),pointer:[`instances`,String(n),`properties`],...e.resolveResource===void 0?{}:{resolveResource:e.resolveResource},...e.programs===void 0?{}:{programs:e.programs}});c.push({instanceId:i.id,deviceId:i.device,props:t.props,boardProps:t.boardProps})}catch(e){t.add(e,`runtime/prepare-failed`,i.id)}}if(!t.empty)throw n();let l=new Set(c.map(e=>e.instanceId)),u=s.map(e=>({...e,pins:e.pins.filter(e=>l.has(e.instance))})).filter(e=>e.pins.length>0);return Object.freeze({document:r,devices:a,instances:Object.freeze(c),nets:Object.freeze(u)})}async function ds(e,t,n,r){let i;try{i=await n.loadModule(e.package.source,t)}catch(n){r.addProblem(z(`model/execution-failed`,`Cannot load ${e.deviceId}/${t}: ${ps(n)}`));return}let a=i;if(typeof i!=`object`&&typeof i!=`function`){r.add(z(`model/invalid-interface`,`${e.deviceId}/${t} must export the model IR and a create factory.`),`model/invalid-interface`);return}if(a?.model===void 0||a.create===void 0){r.add(z(`model/invalid-interface`,`${e.deviceId}/${t} must export \"model\" and \"create\".`),`model/invalid-interface`);return}if(typeof a.create!=`function`){r.add(z(`model/invalid-interface`,`${e.deviceId}/${t} exports a non-function \"create\".`),`model/invalid-interface`);return}let o;try{o=To(a.model)}catch(e){r.add(e,`model/invalid-interface`);return}let s=cs(e.package.manifest,o);if(s.length>0)for(let e of s)r.addProblem(e);else return{ir:o,create:a.create}}function fs(e){let t=/* @__PURE__ */ new Map;for(let n of e.declarations)n.kind===`property`&&t.set(n.name,n.type);return t}function ps(e){return e instanceof Error?e.message:String(e)}function ms(e,t){return t}function hs(e){return Object.freeze(Object.fromEntries(e))}function gs(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isInteger(r))throw TypeError(`Byte value must be an integer number`);if(r<0||r>255)throw RangeError(`Byte value must be in [0, 255]`);t[n]=r}return t}let _s=Object.freeze([]);function vs(e){if(e.length===0)return _s;if(e.length===1&&Array.isArray(e[0]))return e[0];let t=[];for(let n of e)if(Array.isArray(n))for(let e of n)t.push(e);else t.push(n);return Object.freeze(t)}function ys(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return e===t;if(bs(e)||bs(t)){if(!bs(e)||!bs(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(let e of i)if(!Object.hasOwn(r,e)||!ys(n[e],r[e]))return!1;return!0}function bs(e){return Array.isArray(e)||ArrayBuffer.isView(e)||`length`in e&&Symbol.iterator in e}function xs(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`Index must be a safe integer number`);if(t<0||t>=e.length)throw RangeError(`Index is outside the value`);return e[t]}function Ss(e){if(e===null)throw TypeError(`Expected a non-null value`);return e}function Cs(e){if(typeof e!=`boolean`)throw TypeError(`Condition must be a boolean`);return e}function ws(e){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`Duration must be a finite integer number`);if(e<0||e>72e14)throw RangeError(`Duration must be in [0, 7200000000000000] picoseconds`);return e}function Ts(e){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`Redirect target must be a finite number`);return e}function Es(e,t){if(!e)throw TypeError(`Reaction value requires a reaction frame`);return e[t]}function Ds(e,t){if(!e||t>=e.captures.length)throw RangeError(`Reaction capture is not available`);return e.captures[t]}let Os=Symbol(`terminated call`);function*ks(e){let t=!1;try{let n=e.next();for(;!n.done;){let t=n.value,r=yield t;if(t.kind===`stop`||t.kind===`redirect`)return Os;n=e.next(r)}return t=!0,n.value}finally{t||e.return(void 0)}}let As=Object.freeze({createEnum:ms,createRecord:hs,createBytes:gs,combineIntents:vs,equalValues:ys,readIndex:xs,nonNull:Ss,checkBoolean:Cs,checkDuration:ws,checkPc:Ts,reactionValue:Es,reactionCapture:Ds,delegate:ks,terminated:Os});function js(e){return e.uri===void 0?Object.freeze({...e}):Object.freeze({...e,range:Object.freeze({start:Object.freeze({...e.range.start}),end:Object.freeze({...e.range.end})})})}function Ms(e){return e.kind===`optional`?Object.freeze({...e,inner:Object.freeze({...e.inner})}):Object.freeze({...e})}function Ns(e){switch(e.kind){case`unary`:case`field`:case`length`:case`optional`:case`isNone`:case`nonNull`:case`localWrite`:case`write`:case`writeIntent`:case`send`:case`match`:case`returnValue`:case`yield`:return[e.value];case`binary`:return[e.left,e.right];case`numeric`:return[...e.args];case`record`:return e.fields.map(e=>e.value);case`bytes`:return[...e.elements];case`index`:return[e.value,e.index];case`local`:return[e.initial];case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:return[e.offset];case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:return[e.offset,e.value];case`copyBytes`:return[e.offset,e.length];case`resistor`:return[e.resistance];case`combineIntents`:return[...e.values];case`call`:case`callValue`:return e.args.flatMap(e=>e.kind===`value`?[e.value]:[]);case`if`:case`select`:case`assert`:return[e.condition];case`and`:case`or`:return[e.left];case`wait`:case`elapse`:return[e.duration];case`redirect`:return[e.target,e.delay];default:return[]}}function Ps(e){let t=[],n=e=>{e.kind===`parameter`&&t.push(`argument:${e.index}`)};return`memory`in e&&n(e.memory),`pin`in e&&n(e.pin),e.kind===`resistor`&&n(e.to),e.kind===`refEqual`&&(n(e.left),n(e.right)),(e.kind===`call`||e.kind===`callValue`)&&e.args.forEach(e=>{e.kind!==`value`&&n(e)}),e.kind===`parameter`&&t.push(`argument:${e.index}`),(e.kind===`reactionValue`||e.kind===`reactionCapture`)&&t.push(`reaction`),t}function Fs(e){return e.kind===`parameter`?`$${e.index}`:e.name}function Is(e){let t=[],n=[],r=[],i=e.kind===`call`||e.kind===`callValue`,a=i||[`wait`,`elapse`,`receive`,`waitUntil`,`redirect`].includes(e.kind),o=i||(/* @__PURE__ */ `read.write.readSample.writeIntent.resistor.bytes.index.nonNull.field.length.memoryLength.copyBytes.send.receive.notify.now.random.reactionValue.reactionCapture.if.select.and.or.assert.wait.elapse.redirect`.split(`.`)).includes(e.kind)||e.kind.startsWith(`load`)||e.kind.startsWith(`store`);return e.kind===`read`&&t.push(`${e.resource}:${e.name}`),e.kind===`write`&&n.push(`state:${e.name}`),`memory`in e&&(e.kind.startsWith(`store`)?n:t).push(`memory:${Fs(e.memory)}`),e.kind===`readSample`&&t.push(`pin:${Fs(e.pin)}`),e.kind===`writeIntent`&&n.push(`pin:${Fs(e.pin)}`),e.kind===`send`&&n.push(`channel:${e.channel}`),e.kind===`receive`&&(t.push(`channel:${e.channel}`),n.push(`channel:${e.channel}`)),e.kind===`notify`&&n.push(`notification:${e.notification}`),e.kind===`waitUntil`&&(t.push(`*`),r.push(e.predicate)),i&&(r.push(e.name),t.push(`*`),n.push(`*`)),Object.freeze({reads:Object.freeze(t),writes:Object.freeze(n),calls:Object.freeze(r),operations:Object.freeze([e.kind]),maySuspend:a,mayThrow:o,mayRedirect:i||e.kind===`redirect`,mayStop:i||e.kind===`stop`,timeDependent:i||e.kind===`now`,random:i||e.kind===`random`})}function Ls(e,t){let n=Ns(e);if(n.some(e=>!t.has(e)))return;let r=t.get(n[0]),i=t.get(n[1]);switch(e.kind){case`constant`:{let t=e.constant;return t.kind===`none`?{value:null}:t.kind===`enum`?{value:t.member}:t.kind===`number`||t.kind===`bool`||t.kind===`string`?{value:t.value}:void 0}case`optional`:return{value:r};case`isNone`:return{value:r===null};case`nonNull`:return r===null?void 0:{value:r};case`unary`:switch(e.operator){case`positive`:return{value:+r};case`negate`:return{value:-r};case`not`:return{value:!r};case`bitNot`:return{value:~r}}break;case`binary`:{let t=r,n=i;switch(e.operator){case`add`:return{value:t+n};case`subtract`:return{value:t-n};case`multiply`:return{value:t*n};case`divide`:return{value:t/n};case`remainder`:return{value:t%n};case`power`:return{value:t**n};case`lessThan`:return{value:t<n};case`lessThanOrEqual`:return{value:t<=n};case`greaterThan`:return{value:t>n};case`greaterThanOrEqual`:return{value:t>=n};case`equal`:return{value:r===i};case`notEqual`:return{value:r!==i};case`concat`:return{value:r+i};case`bitAnd`:return{value:t&n};case`bitOr`:return{value:t|n};case`bitXor`:return{value:t^n};case`shiftLeft`:return{value:t<<n};case`shiftRight`:return{value:t>>n};case`shiftRightUnsigned`:return{value:t>>>n}}break}case`numeric`:{let n=e.args.map(e=>t.get(e));if(e.builtin===`isNaN`)return{value:Number.isNaN(n[0])};if(e.builtin===`isFinite`)return{value:Number.isFinite(n[0])};if(e.builtin===`isInteger`)return{value:Number.isInteger(n[0])};if(e.builtin===`isSafeInteger`)return{value:Number.isSafeInteger(n[0])};let r=Math[e.builtin];return{value:r(...n)}}}}function Rs(e,t,n){switch(e.kind){case`constant`:return e.constant.kind!==`bytes`&&e.constant.kind!==`record`;case`parameter`:case`localRead`:case`optional`:case`isNone`:case`unary`:case`numeric`:return!0;case`nonNull`:return n.has(e.result);case`binary`:{if(e.operator!==`equal`&&e.operator!==`notEqual`)return!0;let n=t.get(e.left);return n?.kind===`optional`&&(n=n.inner),!!n&&[`number`,`string`,`bool`,`enum`].includes(n.kind)}default:return!1}}function zs(e){let t=e=>typeof e!=`object`||!e?e:Object.freeze(Array.isArray(e)?e.map(t):Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,n])=>[e,t(n)])));return Object.freeze(Object.fromEntries(Object.entries(e).flatMap(([n,r])=>[`kind`,`type`,`source`,`body`,`test`,`message`,`yes`,`no`].includes(n)||r===void 0||n===`right`&&typeof r==`object`?[]:[[n,t(n===`arms`?e.arms.map(e=>e.pattern):r)]])))}function Bs(e,t,n=!0){return new Vs(e,t.optimize!==!1,n).analyze()}var Vs=class{optimize;metadata;nodes=[];regions=[];blocks=[];blockSpecs=[];buildingGraph=!1;edges=[];byOperation=/* @__PURE__ */ new Map;folded=/* @__PURE__ */ new Map;eliminated=/* @__PURE__ */ new Set;root;throwExit;stopExit;redirectExit;constructor(e,t,n){this.optimize=t,this.metadata=n,this.root=this.index(e,[],null,e.source),this.throwExit=this.block(0,`throw`),this.stopExit=this.block(0,`stop`),this.redirectExit=this.block(0,`redirect`)}block(e,t,n=null){let r=this.blockSpecs.length,i={id:r,region:e,role:t,position:n};return this.blockSpecs.push(i),this.buildingGraph&&this.blocks.push(this.allocateBlock(i)),r}allocateBlock(e){return{...e,uses:/* @__PURE__ */ new Set,definitions:/* @__PURE__ */ new Set,liveIn:/* @__PURE__ */ new Set,liveOut:/* @__PURE__ */ new Set}}edge(e,t,n,r={}){this.edges.push(Object.freeze({from:e,to:t,kind:n,...r}))}index(e,t,n,r){let i=this.regions.length,a={id:i,parent:n,path:Object.freeze([...t]),entry:this.block(i,`entry`),exit:this.block(i,`exit`),nodes:[]};return this.regions.push(a),e.operations.forEach((n,o)=>{let s=this.nodes.length,c=this.block(i,`operation`,s),l=this.metadata?n.source??e.source??r:void 0,u,d={operation:n,position:s,block:c,definitionBlock:c,region:i,path:Object.freeze([...t,`operations`,o]),inputs:Object.freeze(Ns(n)),get effects(){return u??=Is(n)},children:/* @__PURE__ */ new Map,...l?{source:js(l)}:{}};a.nodes.push(d),this.nodes.push(d),this.byOperation.set(n,d);let f=(e,t,n=[e],r=l)=>{d.children.set(e,this.index(t,[...d.path,...n],i,r))};switch(n.kind){case`if`:f(`yes`,n.yes),n.no&&f(`no`,n.no);break;case`match`:n.arms.forEach((e,t)=>f(`arm${t}`,e.body,[`arms`,t,`body`],e.source??l)),n.otherwise&&f(`otherwise`,n.otherwise);break;case`while`:f(`test`,n.test.body,[`test`,`body`]),f(`body`,n.body);break;case`loop`:f(`body`,n.body);break;case`select`:f(`yes`,n.yes.body,[`yes`,`body`]),f(`no`,n.no.body,[`no`,`body`]);break;case`and`:case`or`:f(`right`,n.right.body,[`right`,`body`]);break;case`assert`:n.message&&f(`message`,n.message.body,[`message`,`body`])}}),a}link(e,t,n,r=`next`){this.edge(e.entry,e.nodes[0]?.block??e.exit,`next`),t!==null&&this.edge(e.exit,t,r),e.nodes.forEach((t,r)=>{let i=t.operation,a=t.block,o=e.nodes[r+1]?.block??e.exit,s=(e,r=o,i=n,a=`next`)=>{let s=t.children.get(e);return this.link(s,r,i,a),s},c=(e,n)=>{let r=t.children.get(e);return this.link(r,n,{yieldTo:r.exit}),r};switch(t.effects.mayThrow&&i.kind!==`assert`&&this.edge(a,this.throwExit,`throw`),i.kind){case`if`:this.edge(a,s(`yes`).entry,`true`),this.edge(a,t.children.has(`no`)?s(`no`).entry:o,`false`);break;case`match`:i.arms.forEach((e,t)=>this.edge(a,s(`arm${t}`).entry,`arm`,{arm:t})),i.otherwise&&this.edge(a,s(`otherwise`).entry,`default`);break;case`while`:{let e=c(`test`,null),t={...n,breakTo:o,continueTo:e.entry},r=s(`body`,e.entry,t,`backedge`);this.edge(a,e.entry,`next`),this.edge(e.exit,r.entry,`true`),this.edge(e.exit,o,`false`);break}case`loop`:{let e=t.children.get(`body`);s(`body`,e.entry,{...n,breakTo:o,continueTo:e.entry},`backedge`),this.edge(a,e.entry,`next`);break}case`select`:case`and`:case`or`:{let n=this.block(e.id,`join`,t.position);if(t.definitionBlock=n,this.edge(n,o,`next`),i.kind===`select`)this.edge(a,c(`yes`,n).entry,`true`),this.edge(a,c(`no`,n).entry,`false`);else{let e=c(`right`,n);this.edge(a,e.entry,i.kind===`and`?`true`:`false`),this.edge(a,n,i.kind===`and`?`false`:`true`,{value:i.left})}break}case`assert`:{let n=this.block(e.id,`throw`,t.position);t.failureBlock=n,this.edge(a,o,`true`),this.edge(n,this.throwExit,`throw`),this.edge(a,i.message?c(`message`,n).entry:n,`false`);break}case`break`:if(n.breakTo===void 0)throw TypeError(`Break has no loop target`);this.edge(a,n.breakTo,`break`);break;case`continue`:if(n.continueTo===void 0)throw TypeError(`Continue has no loop target`);this.edge(a,n.continueTo,`continue`);break;case`yield`:if(n.yieldTo===void 0)throw TypeError(`Yield has no value-region target`);this.edge(a,n.yieldTo,`yield`,{value:i.value});break;case`return`:case`returnValue`:this.edge(a,this.root.exit,`return`);break;case`redirect`:this.edge(a,this.redirectExit,`redirect`);break;case`stop`:this.edge(a,this.stopExit,`stop`);break;case`wait`:case`elapse`:case`receive`:case`waitUntil`:case`call`:case`callValue`:{let n=this.block(e.id,`resume`,t.position);t.resumeBlock=n;let r=i.kind===`call`||i.kind===`callValue`;if(this.edge(a,n,`suspend`),r){let r=this.block(e.id,`join`,t.position);t.completionBlock=r,t.definitionBlock=r,this.edge(a,r,`next`),this.edge(n,n,`suspend`),this.edge(n,r,`resume`),this.edge(r,o,`next`);for(let e of[a,n])this.edge(e,this.redirectExit,`redirect`),this.edge(e,this.stopExit,`stop`);this.edge(n,this.throwExit,`throw`)}else i.kind===`receive`&&(t.definitionBlock=n),this.edge(n,i.kind===`waitUntil`?this.root.exit:o,`resume`),i.kind===`elapse`&&this.edge(a,o,`next`);break}default:this.edge(a,o,`next`)}})}analyze(){let e=/* @__PURE__ */ new Map;for(let t of this.nodes)`result`in t.operation&&e.set(t.operation.result,t.operation.type);let t=/* @__PURE__ */ new Map;if(this.optimize){for(let e of this.nodes){if(!(`result`in e.operation))continue;let n=Ls(e.operation,t);n&&(t.set(e.operation.result,n.value),e.operation.kind!==`constant`&&this.folded.set(e.position,n.value))}let n=/* @__PURE__ */ new Map;for(let e of this.nodes)`result`in e.operation&&this.folded.has(e.position)&&n.set(e.operation.result,this.folded.get(e.position));let r=new Map(this.nodes.flatMap(e=>`result`in e.operation?[[e.operation.result,e]]:[])),i=/* @__PURE__ */ new Set,a=[],o=e=>{i.has(e)||(i.add(e),a.push(e))};for(let e of this.nodes)this.folded.has(e.position)||e.inputs.forEach(o);for(let e=0;e<a.length;e++){let t=r.get(a[e]);t&&!this.folded.has(t.position)&&t.inputs.forEach(o)}for(let t of this.nodes)`result`in t.operation&&!i.has(t.operation.result)&&Rs(t.operation,e,n)&&this.eliminated.add(t.position)}let n,r=()=>n??=this.complete(t);return{nodes:this.nodes,byOperation:this.byOperation,folded:this.folded,constants:t,eliminated:this.eliminated,optimizations:Object.freeze({enabled:this.optimize,foldedPositions:Object.freeze([...this.folded.keys()].filter(e=>!this.eliminated.has(e))),eliminatedPositions:Object.freeze([...this.eliminated])}),get graph(){return r().graph},get effects(){return r().effects},get resources(){return r().resources}}}complete(e){this.buildingGraph=!0,this.blocks=this.blockSpecs.map(e=>this.allocateBlock(e)),this.link(this.root,null,{});for(let e of this.nodes){if(this.eliminated.has(e.position))continue;let t=this.blocks[e.block],n=e.operation;this.folded.has(e.position)||(e.inputs.forEach(e=>t.uses.add(`value:${e}`)),Ps(n).forEach(e=>t.uses.add(e)),n.kind===`localRead`&&t.uses.add(`local:${n.local}`)),`result`in n&&this.blocks[e.definitionBlock].definitions.add(`value:${n.result}`),(n.kind===`local`||n.kind===`localWrite`)&&t.definitions.add(`local:${n.local}`)}let t=/* @__PURE__ */ new Map;for(let e of this.nodes){let n=e.operation.kind===`while`?e.children.get(`test`):e.operation.kind===`assert`?e.children.get(`message`):void 0;if(!n)continue;let r=`region:${n.id}`;t.set(n.exit,r),this.blocks[e.failureBlock??n.exit].uses.add(r)}for(let e of this.edges)e.kind===`yield`&&t.has(e.to)&&this.blocks[e.from].definitions.add(t.get(e.to));let n=this.blocks.map(()=>[]),r=this.blocks.map(()=>[]);this.edges.forEach(e=>{n[e.from].push(e.to),r[e.to].push(e.from)});let i=this.blocks.map(e=>new Set([...e.uses].filter(e=>e.startsWith(`region:`)))),a=this.blocks.map(e=>new Set([...e.definitions].filter(e=>e.startsWith(`region:`))));for(let e of this.nodes){let t=e.operation;e.inputs.forEach(t=>i[e.block].add(`value:${t}`)),Ps(t).forEach(t=>i[e.block].add(t)),t.kind===`localRead`&&i[e.block].add(`local:${t.local}`),`result`in t&&a[e.definitionBlock].add(`value:${t.result}`),(t.kind===`local`||t.kind===`localWrite`)&&a[e.block].add(`local:${t.local}`)}let o=(e,t)=>{let r=this.blocks.map(()=>/* @__PURE__ */ new Set),i=this.blocks.map(()=>/* @__PURE__ */ new Set),a=!0;for(;a;){a=!1;for(let o=this.blocks.length-1;o>=0;o--){let s=new Set(n[o].flatMap(e=>[...r[e]])),c=/* @__PURE__ */ new Set([...e[o],...[...s].filter(e=>!t[o].has(e))]);(s.size!==i[o].size||[...s].some(e=>!i[o].has(e))||c.size!==r[o].size||[...c].some(e=>!r[o].has(e)))&&(a=!0,i[o]=s,r[o]=c)}}return{input:r,output:i}},s=o(this.blocks.map(e=>e.uses),this.blocks.map(e=>e.definitions)),c=o(i,a);this.blocks.forEach((e,t)=>{e.liveIn=s.input[t],e.liveOut=s.output[t]});let l=/* @__PURE__ */ new Map;for(let e of this.edges)if(e.kind===`yield`&&e.value!==void 0){let t=l.get(e.to)??[];t.push(e.value),l.set(e.to,t)}let u=/* @__PURE__ */ new Map;for(let e of this.nodes)for(let t of e.inputs){let n=u.get(t)??[];n.push(e.position),u.set(t,n)}let d=this.nodes.flatMap(e=>{let t=e.operation;if(!(`result`in t))return[];let n=t.kind===`select`||t.kind===`and`||t.kind===`or`,r=n?[...e.children.values()].flatMap(e=>l.get(e.exit)??[]):[];return(t.kind===`and`||t.kind===`or`)&&r.unshift(t.left),[Object.freeze({result:t.result,type:Ms(t.type),position:e.position,region:e.region,block:e.definitionBlock,form:n?`phi`:`operation`,inputs:Object.freeze(n?r:[...e.inputs]),users:Object.freeze(u.get(t.result)??[]),eliminated:this.eliminated.has(e.position),folded:this.folded.has(e.position)})]}),f=Object.freeze({entry:this.root.entry,normalExit:this.root.exit,regions:Object.freeze(this.regions.map(({id:e,parent:t,path:n,entry:r,exit:i})=>Object.freeze({id:e,parent:t,path:n,entry:r,exit:i}))),blocks:Object.freeze(this.blocks.map(e=>Object.freeze({...e,predecessors:Object.freeze([...new Set(r[e.id])]),successors:Object.freeze([...new Set(n[e.id])]),uses:Object.freeze([...e.uses]),definitions:Object.freeze([...e.definitions]),liveIn:Object.freeze([...e.liveIn]),liveOut:Object.freeze([...e.liveOut]),baselineLiveIn:Object.freeze([...c.input[e.id]]),baselineLiveOut:Object.freeze([...c.output[e.id]])}))),edges:Object.freeze([...this.edges]),values:Object.freeze(d),operations:Object.freeze(this.nodes.map(e=>Object.freeze({position:e.position,block:e.block,region:e.region,kind:e.operation.kind,path:e.path,...e.source?{source:e.source}:{},inputs:e.inputs,attributes:zs(e.operation),regions:Object.freeze([...e.children].map(([e,t])=>Object.freeze({role:e,region:t.id}))),effects:e.effects,eliminated:this.eliminated.has(e.position),folded:this.folded.has(e.position)})))}),p=this.nodes.map(e=>e.effects),m=e=>Object.freeze([...new Set(p.flatMap(t=>t[e]))]),h=Object.freeze({reads:m(`reads`),writes:m(`writes`),calls:m(`calls`),operations:m(`operations`),maySuspend:p.some(e=>e.maySuspend),mayRedirect:p.some(e=>e.mayRedirect),mayStop:p.some(e=>e.mayStop),timeDependent:p.some(e=>e.timeDependent),random:p.some(e=>e.random)}),g=new Set([...h.reads,...h.writes].filter(e=>e!==`*`));for(let e of this.nodes){let t=e.operation;if(t.kind===`resistor`&&g.add(`pin:${Fs(t.to)}`),t.kind===`refEqual`)for(let e of[t.left,t.right])g.add(`${e.kind===`parameter`?e.resource:e.kind}:${Fs(e)}`);if(t.kind===`call`||t.kind===`callValue`)for(let e of t.args)e.kind!==`value`&&g.add(`${e.kind===`parameter`?e.resource:e.kind}:${Fs(e)}`)}return{nodes:this.nodes,byOperation:this.byOperation,graph:f,folded:this.folded,constants:e,eliminated:this.eliminated,effects:h,resources:Object.freeze([...g]),optimizations:Object.freeze({enabled:this.optimize,foldedPositions:Object.freeze([...this.folded.keys()].filter(e=>!this.eliminated.has(e))),eliminatedPositions:Object.freeze([...this.eliminated])})}}};function Hs(e,t,n,r,i,a){let o=[],s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let t of e.nodes){let e=t.operation;`result`in e&&c.set(`value:${e.result}`,Ms(e.type)),e.kind===`local`&&c.set(`local:${e.local}`,Ms(e.type)),e.kind===`parameter`&&c.set(`argument:${e.index}`,Ms(e.type));let n=e=>{e.kind===`parameter`&&e.resource&&c.set(`argument:${e.index}`,Object.freeze({kind:e.resource}))};`memory`in e&&n(e.memory),`pin`in e&&n(e.pin),e.kind===`resistor`&&n(e.to),e.kind===`refEqual`&&(n(e.left),n(e.right)),(e.kind===`call`||e.kind===`callValue`)&&e.args.forEach(e=>{e.kind!==`value`&&n(e)})}let l=(e,t,n,r,i,a=!0)=>{s.has(e)||(s.set(e,o.length),o.push(Object.freeze({id:o.length,key:e,kind:t,name:n,region:r,definition:i,materialized:a,...c.has(e)?{type:c.get(e)}:{}})))};for(let t of e.nodes){let n=t.operation;`result`in n&&l(`value:${n.result}`,`value`,`v${n.result}`,t.region,t.position,!e.eliminated.has(t.position)),n.kind===`local`&&l(`local:${n.local}`,`local`,`l${n.local}`,t.region,t.position)}for(let e of a)c.set(e.key,Ms(e.type)),l(e.key,`temporary`,e.name,e.region,e.definition);for(let t of e.graph.blocks)for(let e of[...t.uses,...t.liveIn,...t.baselineLiveIn])e.startsWith(`argument:`)&&l(e,`argument`,`args[${e.slice(9)}]`,0,null),e===`reaction`&&l(e,`reaction`,`reaction`,0,null);let u=Object.freeze([...e.constants].flatMap(([e,t])=>{let n=s.get(`value:${e}`);return n===void 0?[]:[Object.freeze({slot:n,kind:`constant`,value:t})]})),d=new Set(u.map(e=>e.slot)),f=e=>Object.freeze(e.flatMap(e=>{let t=s.get(e);return t===void 0?[]:[t]}).sort((e,t)=>e-t)),p=e=>Object.freeze(f(e).filter(e=>o[e].materialized&&!d.has(e))),m=e=>Object.freeze(e.flatMap(e=>{let t=s.get(e);return t===void 0||!o[t].materialized?[]:[t]}).sort((e,t)=>e-t)),h=(e,t,n=e.block)=>Object.freeze({position:e.position,block:n,phase:t}),g=new Map(e.nodes.map(e=>[JSON.stringify(e.path),e])),_=r.split(`\n`),v=e=>Object.freeze({start:Object.freeze({line:e,column:(_[e-1]?.search(/\\S/)??0)+1}),end:Object.freeze({line:e,column:(_[e-1]?.length??0)+1})}),y=Object.freeze({entries:Object.freeze(n.map(t=>{let n=g.get(JSON.stringify(t.path)),r=n.operation.kind===`redirect`||n.operation.kind===`stop`||n.operation.kind===`waitUntil`,i=r?[]:e.graph.blocks[n.resumeBlock].liveIn;return Object.freeze({id:t.id,kind:t.kind,suspended:h(n,`before`),baseline:h(n,t.delegated?`delegate`:`after`,n.resumeBlock??n.block),generated:v(t.line),continuation:Object.freeze({line:t.delegated?t.line:Math.min(t.line+1,_.length),column:t.delegated?t.column:(_[t.line]?.search(/\\S/)??0)+1}),liveSlots:m(i),delegated:t.delegated,terminal:r})}))}),b=[],x=(t,n,r,i=t.block)=>{b.push(Object.freeze({baseline:h(t,`before`,i),reason:n,generated:r,requiredSlots:f(e.graph.blocks[i].baselineLiveIn),captureSlots:p(e.graph.blocks[i].baselineLiveIn)}))};for(let n of e.nodes){let r=t.get(n.position);if(r){if(x(n,`deopt`,v(r.start.line)),n.effects.mayThrow&&!e.folded.has(n.position)){if(n.operation.kind===`assert`){let e=r.start.line;for(let t=r.start.line;t<=r.end.line;t++)_[t-1]?.includes(`host.assert(`)&&(e=t);x(n,`throw`,v(e),n.failureBlock)}else x(n,`throw`,v(r.start.line))}(n.operation.kind===`return`||n.operation.kind===`returnValue`)&&x(n,`return`,v(r.start.line))}}for(let t of y.entries){let n=t.terminal?[]:e.graph.blocks[t.baseline.block].baselineLiveIn;b.push(Object.freeze({baseline:t.baseline,reason:t.kind===`redirect`?`redirect`:t.kind===`stop`?`stop`:`suspend`,generated:t.generated,requiredSlots:f(n),captureSlots:p(n)}))}for(let e of b)for(let t of e.requiredSlots)if(!o[t].materialized&&!d.has(t))throw Error(`Missing baseline value for frame slot ${t} at position ${e.baseline.position}`);let ee=i.binding?Object.freeze({...i.binding,...i.binding.instruction?{instruction:Object.freeze({...i.binding.instruction})}:{}}):null;return{dependencies:Object.freeze({binding:ee,reads:e.effects.reads,writes:e.effects.writes,calls:e.effects.calls,resources:e.resources,unresolvedCalls:e.effects.calls.length!==0}),sourceMap:Object.freeze({entries:Object.freeze(e.nodes.map(n=>Object.freeze({position:n.position,block:n.block,path:n.path,kind:n.operation.kind,...n.source?{source:n.source}:{},generated:t.get(n.position)??null,eliminated:e.eliminated.has(n.position),folded:e.folded.has(n.position)})))}),frameLayout:Object.freeze({storage:`native-generator`,serializable:!1,slots:Object.freeze(o),materializations:u}),resumeMap:y,exitMap:Object.freeze(b)}}let Us={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},Ws=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),Gs=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function Ks(e,t={}){return new $s(Bs(e,t,!1),t,!1).compileExecutable(e)}function qs(e,t={}){return Js(Ks(e.body,t))}function Js(e){return t=>{let n=e(t),r=n.next();if(!r.done)throw n.return(void 0),TypeError(`Computation unexpectedly suspended with ${r.value.kind}`);return r.value}}function Ys(e,t){if(!Number.isSafeInteger(t)||t<0)throw TypeError(`IR identifiers must be nonnegative safe integers`);return`${e}${t}`}let X=e=>Ys(`v`,e),Xs=e=>Ys(`l`,e),Zs=e=>JSON.stringify(e);function Qs(e){return e.uri===void 0?Object.freeze({...e}):Object.freeze({...e,range:Object.freeze({start:Object.freeze({...e.range.start}),end:Object.freeze({...e.range.end})})})}var $s=class{analysis;options;captureMetadata;constructor(e,t,n=!0){this.analysis=e,this.options=t,this.captureMetadata=n}ranges=/* @__PURE__ */ new Map;temporaries=[];lines=[];constants=[];primitiveConstants=/* @__PURE__ */ new Map;negativeZero=Symbol(`negative zero`);positions=[];resume=[];types=/* @__PURE__ */ new Map;indent=0;serial=0;bindingFor;compileExecutable(e){return this.generate(e).execute}compile(e){let t=this.generate(e),n=this.analysis,r,i=()=>r??=Hs(n,this.ranges,this.resume,t.source,this.options,this.temporaries);return Object.freeze({...t,positions:Object.freeze(this.positions.slice()),resume:Object.freeze(this.resume.slice()),optimizations:n.optimizations,get effects(){return n.effects},get mir(){return n.graph},get dependencies(){return i().dependencies},get sourceMap(){return i().sourceMap},get frameLayout(){return i().frameLayout},get resumeMap(){return i().resumeMap},get exitMap(){return i().exitMap}})}generate(e){this.line(`function* compiledBody(host, args = [], reaction) {`),this.indent++,this.region(e,[]),this.indent--,this.line(`}`);let t=this.lines.join(`\n`),n=Object.freeze(this.constants.slice());return{execute:Function(`C`,`H`,`\"use strict\"; return (${t});`)(n,As),source:t,constants:n}}line(e){this.lines.push(`${` `.repeat(this.indent)}${e}`)}block(e,t){this.line(`${e} {`),this.indent++,t(),this.indent--,this.line(`}`)}capture(e){let t=typeof e!=`object`||!e,n=Object.is(e,-0)?this.negativeZero:e,r=t?this.primitiveConstants.get(n):void 0;if(r!==void 0)return`C[${r}]`;let i=this.constants.push(e)-1;return t&&this.primitiveConstants.set(n,i),`C[${i}]`}ref(e){return e.kind===`parameter`?`args[${e.index}]`:this.capture(e.name)}boundRef(e,t){if(this.bindingFor&&t.kind!==`parameter`)return this.bindingFor(e,t.name)}boundName(e){return this.bindingFor?.(`state`,e)}argument(e){return e.kind===`value`?X(e.value):this.ref(e)}constant(e){switch(e.kind){case`number`:case`bool`:case`string`:return e.value;case`none`:return null;case`enum`:return ms(e.name,e.member);case`bytes`:return Object.freeze(Array.from(gs(e.value)));case`record`:return hs(e.fields.map(e=>[e.name,e.value]));default:return ec(e)}}position(e,t){let n=Object.freeze({path:Object.freeze([...t]),kind:e.kind,line:this.lines.length+1,column:this.indent*2+1,...this.analysis.byOperation.get(e)?.source?{source:Qs(this.analysis.byOperation.get(e).source)}:{}});return this.positions.push(n),n}suspension(e,t=!1){e&&this.resume.push(Object.freeze({...e,line:this.lines.length+1,column:this.indent*2+1,id:this.resume.length,delegated:t}))}region(e,t,n){e.operations.forEach((e,r)=>{this.operation(e,[...t,`operations`,r],n)})}valueRegion(e,t,n){if(this.captureMetadata&&!t.startsWith(`v`)){let r=JSON.stringify([...n,`body`]),i=this.analysis.nodes.find(e=>[...e.children.values()].some(e=>JSON.stringify(e.path)===r)),a=[...i.children.values()].find(e=>JSON.stringify(e.path)===r);this.temporaries.push({key:`region:${a.id}`,name:t,region:i.region,definition:i.position,type:e.type})}let r=`valueRegion${this.serial++}`;this.block(`${r}:`,()=>this.region(e.body,[...n,`body`],{slot:t,label:r}))}equality(e,t){let n=this.types.get(e);return n?.kind===`optional`&&(n=n.inner),n&&(n.kind===`number`||n.kind===`string`||n.kind===`bool`)?`(${X(e)} === ${X(t)})`:`H.equalValues(${X(e)}, ${X(t)})`}operation(e,t,n){`result`in e&&this.types.set(e.result,e.type);let r=this.analysis.byOperation.get(e);if(this.analysis.eliminated.has(r.position))return;let i=this.captureMetadata?this.position(e,t):void 0;try{`result`in e&&this.analysis.folded.has(r.position)?this.line(`const ${X(e.result)} = ${this.capture(this.analysis.folded.get(r.position))};`):this.emitOperation(e,t,i,n)}finally{i&&this.ranges.set(r.position,Object.freeze({start:Object.freeze({line:i.line,column:i.column}),end:Object.freeze({line:this.lines.length,column:this.lines[this.lines.length-1].length+1})}))}}emitOperation(e,t,n,r){let i=t=>{if(!(`result`in e))throw TypeError(`Expected a result-producing operation`);this.line(`const ${X(e.result)} = ${t};`)},a=(e,n)=>this.region(e,[...t,n],r);switch(e.kind){case`constant`:{let t=this.capture(this.constant(e.constant));i(e.constant.kind===`bytes`?`H.createBytes(${t})`:t);break}case`read`:{let t=e.resource===`state`?this.boundName(e.name):void 0;i(t?`${t}.read()`:`host.read(${this.capture(e.resource)}, ${this.capture(e.name)})`);break}case`parameter`:i(`args[${e.index}]`);break;case`reactionValue`:i(`H.reactionValue(reaction, ${Zs(e.binding)})`);break;case`reactionCapture`:i(`H.reactionCapture(reaction, ${e.index})`);break;case`unary`:{let t={positive:`+`,negate:`-`,not:`!`,bitNot:`~`}[e.operator];if(!t)throw TypeError(`Unknown unary operator`);i(`(${t}${X(e.value)})`);break}case`binary`:if(e.operator===`equal`||e.operator===`notEqual`)i(`${e.operator===`notEqual`?`!`:``}${this.equality(e.left,e.right)}`);else{let t=Us[e.operator];if(!t)throw TypeError(`Unknown binary operator`);i(`(${X(e.left)} ${t} ${X(e.right)})`)}break;case`numeric`:if(!Ws.has(e.builtin))throw TypeError(`Unknown numeric builtin`);i(`${Gs.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(X).join(`, `)})`);break;case`record`:i(`H.createRecord([${e.fields.map(e=>`[${this.capture(e.name)}, ${X(e.value)}]`).join(`, `)}])`);break;case`field`:i(`${X(e.value)}[${this.capture(e.field)}]`);break;case`bytes`:i(`H.createBytes([${e.elements.map(X).join(`, `)}])`);break;case`length`:i(`${X(e.value)}.length`);break;case`index`:i(`H.readIndex(${X(e.value)}, ${X(e.index)})`);break;case`optional`:i(X(e.value));break;case`isNone`:i(`(${X(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${X(e.value)})`);break;case`localRead`:i(Xs(e.local));break;case`local`:this.line(`let ${Xs(e.local)} = ${X(e.initial)};`);break;case`localWrite`:this.line(`${Xs(e.local)} = ${X(e.value)};`);break;case`write`:{let t=this.boundName(e.name);t?this.line(`${t}.write(${X(e.value)});`):this.line(`host.write(${this.capture(e.name)}, ${X(e.value)});`);break}case`memoryLength`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.length()`:`host.memoryLength(${this.ref(e.memory)})`);break}case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.${e.kind}(${X(e.offset)})`:`host.load(${Zs(e.kind)}, ${this.ref(e.memory)}, ${X(e.offset)})`);break}case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:{let t=this.boundRef(`memory`,e.memory);t?this.line(`${t}.${e.kind}(${X(e.offset)}, ${X(e.value)});`):this.line(`host.store(${Zs(e.kind)}, ${this.ref(e.memory)}, ${X(e.offset)}, ${X(e.value)});`);break}case`copyBytes`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.copy(${X(e.offset)}, ${X(e.length)})`:`host.copyBytes(${this.ref(e.memory)}, ${X(e.offset)}, ${X(e.length)})`);break}case`readSample`:{let t=this.boundRef(`pin`,e.pin);i(t?`${t}.sample()`:`host.sample(${this.ref(e.pin)})`);break}case`resistor`:{let t=this.boundRef(`pin`,e.to);i(t?`${t}.resistor(${X(e.resistance)})`:`host.resistor(${this.ref(e.to)}, ${X(e.resistance)})`);break}case`combineIntents`:i(`H.combineIntents([${e.values.map(X).join(`, `)}])`);break;case`refEqual`:i(`(${this.ref(e.left)} === ${this.ref(e.right)})`);break;case`writeIntent`:{let t=this.boundRef(`pin`,e.pin);t?this.line(`${t}.intent(${X(e.value)});`):this.line(`host.intent(${this.ref(e.pin)}, ${X(e.value)});`);break}case`call`:case`callValue`:{this.suspension(n,!0);let t=`call${this.serial++}`;this.line(`const ${t} = yield* H.delegate(host.call(${this.capture(e.name)}, [${e.args.map(e=>this.argument(e)).join(`, `)}]));`),this.line(`if (${t} === H.terminated) return;`),e.kind===`callValue`&&i(t);break}case`send`:this.line(`host.send(${this.capture(e.channel)}, ${X(e.value)});`);break;case`notify`:this.line(`host.notify(${this.capture(e.notification)});`);break;case`receive`:this.suspension(n),i(`yield { kind: \"receive\", channel: ${this.capture(e.channel)} }`);break;case`now`:i(`host.now()`);break;case`random`:i(`host.random()`);break;case`if`:this.block(`if (H.checkBoolean(${X(e.condition)}))`,()=>a(e.yes,`yes`)),e.no&&this.block(`else`,()=>a(e.no,`no`));break;case`match`:e.arms.forEach((n,i)=>{let a=n.pattern,o=a.kind===`none`?null:a.kind===`enum`?ms(a.name,a.member):a.value;this.block(`${i?`else if`:`if`} (H.equalValues(${X(e.value)}, ${this.capture(o)}))`,()=>{this.region(n.body,[...t,`arms`,i,`body`],r)})}),e.otherwise&&this.block(e.arms.length?`else`:``,()=>a(e.otherwise,`otherwise`));break;case`while`:this.block(`while (true)`,()=>{let n=`condition${this.serial++}`;this.line(`let ${n};`),this.valueRegion(e.test,n,[...t,`test`]),this.line(`if (!H.checkBoolean(${n})) break;`),this.block(``,()=>a(e.body,`body`))});break;case`loop`:this.block(`while (true)`,()=>a(e.body,`body`));break;case`and`:case`or`:{let n=X(e.result);this.line(`let ${n} = H.checkBoolean(${X(e.left)});`),this.block(`if (${e.kind===`or`?`!`:``}${n})`,()=>{this.valueRegion(e.right,n,[...t,`right`]),this.line(`${n} = H.checkBoolean(${n});`)});break}case`select`:{let n=X(e.result);this.line(`let ${n};`),this.block(`if (H.checkBoolean(${X(e.condition)}))`,()=>this.valueRegion(e.yes,n,[...t,`yes`])),this.block(`else`,()=>this.valueRegion(e.no,n,[...t,`no`]));break}case`assert`:this.block(`if (!H.checkBoolean(${X(e.condition)}))`,()=>{if(e.message){let n=`message${this.serial++}`;this.line(`let ${n};`),this.valueRegion(e.message,n,[...t,`message`]),this.line(`host.assert(false, ${n});`)}else this.line(`host.assert(false, undefined);`)});break;case`wait`:case`elapse`:{let t=`duration${this.serial++}`;this.line(`const ${t} = H.checkDuration(${X(e.duration)});`),this.suspension(n);let r=`yield { kind: ${Zs(e.kind===`wait`?`ticks`:`elapse`)}, duration: ${t} };`;e.kind===`elapse`?this.line(`if (${t} !== 0) ${r}`):this.line(r);break}case`waitUntil`:this.suspension(n),this.line(`yield { kind: \"waitUntil\", predicate: ${this.capture(e.predicate)} };`),this.line(`return;`);break;case`redirect`:this.suspension(n),this.line(`yield { kind: \"redirect\", pc: H.checkPc(${X(e.target)}), delay: H.checkDuration(${X(e.delay)}) };`),this.line(`return;`);break;case`stop`:this.suspension(n),this.line(`yield { kind: \"stop\" };`),this.line(`return;`);break;case`return`:this.line(`return;`);break;case`returnValue`:this.line(`return ${X(e.value)};`);break;case`break`:this.line(`break;`);break;case`continue`:this.line(`continue;`);break;case`yield`:if(!r)throw TypeError(`Value-region yield is outside a value region`);this.line(`${r.slot} = ${X(e.value)};`),this.line(`break ${r.label};`);break;default:ec(e)}}};function ec(e){throw TypeError(`Unsupported IR operation: ${String(e.kind)}`)}let tc={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,equal:`===`,notEqual:`!==`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},nc={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},rc=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),ic=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]),ac=/* @__PURE__ */ new Set([`field`,`optional`,`nonNull`,`readSample`,`resistor`,`combineIntents`,`bytes`,`index`,`select`,`match`]),oc=/* @__PURE__ */ new Set([`bytes`,`record`,`sample`,`intent`,`optional`]),sc=/* @__PURE__ */ new Set([`send`,`notify`,`readSample`,`writeIntent`,`resistor`,`random`,`assert`]);function cc(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`offset must be a safe integer`);if(t<0)throw RangeError(`offset must be nonnegative`);if(t>=e.length)throw RangeError(`Memory range is out of bounds`);return t}function lc(e){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`stored value must be a safe integer`);return e}let uc=/* @__PURE__ */ new WeakMap;function dc(e){let t=uc.get(e);return t===void 0&&(t=new DataView(e.buffer,e.byteOffset,e.byteLength),uc.set(e,t)),t}function fc(e,t,n){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`offset must be a safe integer`);if(t<0)throw RangeError(`offset must be nonnegative`);if(t>e.length||n>e.length-t)throw RangeError(`Memory range is out of bounds`);return t}function pc(e,t){return t??dc(e)}function mc(e,t,n,r){return pc(e,t).getUint16(fc(e,n,2),r)}function hc(e,t,n,r){return pc(e,t).getUint32(fc(e,n,4),r)}function gc(e,t,n,r,i){let a=fc(e,n,2);pc(e,t).setUint16(a,lc(r),i)}function _c(e,t,n,r,i){let a=fc(e,n,4);pc(e,t).setUint32(a,lc(r),i)}let vc=Object.freeze({checkBoolean:Cs,checkDuration:ws,checkPc:Ts,combineIntents:vs,createBytes:gs,equalValues:ys,nonNull:Ss,readIndex:xs,offset:cc,byte:lc,load16:mc,load32:hc,store16:gc,store32:_c}),Z=Symbol(`unsupported direct instruction`),yc=/* @__PURE__ */ new WeakMap;function bc(e){let t=yc.get(e);if(t===void 0){try{t=Bs(e,{},!1).constants}catch{t=/* @__PURE__ */ new Map}yc.set(e,t)}return t}let xc=/* @__PURE__ */ new WeakMap;function Sc(e){let t=xc.get(e);return t===void 0&&(t=Object.freeze({operations:e.operations.length,nestedOperations:Rc(e)}),xc.set(e,t)),t}let Cc=/* @__PURE__ */ new WeakMap;function wc(){let e=Object.freeze({});return Cc.set(e,{entries:/* @__PURE__ */ new Map,constants:[],shards:[],nextResume:1,nextShard:1,stats:{compiledBlocks:0,reusedBlocks:0,invalidatedBlocks:0,compiledShards:0,reusedShards:0,clears:0},binding:void 0}),e}function Tc(e){let t=Cc.get(e);if(t===void 0)throw TypeError(`Invalid direct JIT cache`);return t}function Ec(e){return{states:[...e.states],memories:[...e.memories],pcName:e.pc.name,pcIndex:e.pc.index,host:e.host===!0,blockedStates:e.blockedStates===void 0?void 0:[...e.blockedStates].sort(),blockedMemories:e.blockedMemories===void 0?void 0:[...e.blockedMemories].sort()}}function Dc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r[0]!==i[0]||r[1]!==i[1])return!1}return!0}function Oc(e,t){return e===t?!0:e===void 0||t===void 0||e.length!==t.length?!1:e.every((e,n)=>e===t[n])}function kc(e,t){return e.pcName===t.pcName&&e.pcIndex===t.pcIndex&&e.host===t.host&&Dc(e.states,t.states)&&Dc(e.memories,t.memories)&&Oc(e.blockedStates,t.blockedStates)&&Oc(e.blockedMemories,t.blockedMemories)}function Ac(e){if(e!==void 0)return{counter:e.counter,cycles:e.cycles,...e.pending===void 0?{}:{pending:{...e.pending}}}}function jc(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.counter===t.counter&&e.cycles===t.cycles&&e.pending?.state===t.pending?.state&&e.pending?.period===t.pending?.period&&e.pending?.active===t.pending?.active}function Mc(e){e.entries.clear(),e.constants.length=0,e.shards.length=0,e.nextResume=1,e.nextShard=1,e.binding=void 0,e.stats.clears++}let Nc=36e3;function Pc(e,t,n,r){if(n.length<16){n.forEach((n,r)=>{e.push(`${r?`else if`:`if`} (${t} <= ${n.bound}) ${n.call}`)}),e.push(`else ${r}`);return}let i=[...n.map(e=>e.call),r],a=(r,o)=>{if(r===o){e.push(i[r]);return}let s=r+o>>>1;e.push(`if (${t} <= ${n[s].bound}) {`),a(r,s),e.push(`} else {`),a(s+1,o),e.push(`}`)};a(0,n.length)}function Fc(e,t,n){if(!pl(t.pc.index)||t.states.get(t.pc.name)!==t.pc.index)return;let r=Tc(n??wc()),i=Ec(t);r.binding!==void 0&&!kc(r.binding,i)&&(r.stats.invalidatedBlocks+=r.entries.size,r.entries.clear(),r.constants.length=0,r.shards.length=0,r.nextResume=1,r.nextShard=1),r.binding=i;let a=e=>`C[${r.constants.push(e)-1}]`,o=[],s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set;for(let n of e){if(!Number.isFinite(n.pc)||c.has(n.pc))continue;if(c.add(n.pc),!Number.isFinite(n.nextPc)){r.entries.delete(n.pc)&&r.stats.invalidatedBlocks++;continue}let e=Ac(t.delayLoops?.get(n.pc)),i=r.entries.get(n.pc),l,u=i?.resumeId;if(i!==void 0&&i.body===n.body&&i.nextPc===n.nextPc&&jc(i.delay,e))l=i.instruction,l!==void 0&&(l.resumeId=u??0),r.stats.reusedBlocks++;else{i!==void 0&&r.stats.invalidatedBlocks++;try{l=new ml(t,a).compile(n)}catch(e){if(e!==Z)throw e;l=void 0}l?.duration!==void 0&&u===void 0&&(u=r.nextResume++),l!==void 0&&(l.resumeId=u??0),r.entries.set(n.pc,{body:n.body,nextPc:n.nextPc,delay:e,instruction:l,resumeId:u}),r.stats.compiledBlocks++}l!==void 0&&(o.push(l),s.set(l.pcValue,l))}if(!o.length)return;let l=0;for(let e of o)e.slots.length>l&&(l=e.slots.length);let u=Array.from({length:l},(e,t)=>`v${t}`),d=t,f=pl(d.shardSize)&&d.shardSize>0?d.shardSize:48;if(d.split===!0&&n!==void 0)return ol(r,o,t,f);let p=pl(d.shardSlotLimit)?d.shardSlotLimit:void 0,m=d.split===!0&&(p===void 0?o.reduce((e,t)=>e+t.size,0)>48e3:o.reduce((e,t)=>e+t.slots.length,0)>p),h=m?qc(o,t,f):Kc(o,t,u),g=Function(`C`,`H`,m?`\"use strict\";\\n${h.join(`\n`)}\\nreturn run;`:`\"use strict\"; return (${h.join(`\n`)});`),_=h.filter(e=>e.startsWith(`function stepShard`)).length,v={run:g(Object.freeze([...r.constants]),vc),shards:m?_:1,pcs:Object.freeze(o.map(e=>e.pcValue)),localCount:l,readStates:Wc(o,`readStates`),writeStates:Wc(o,`writeStates`),readMemories:Wc(o,`readMemories`),writeMemories:Wc(o,`writeMemories`)};return Object.defineProperty(v,\"emitStats\",{value:Lc(o)}),Object.freeze(v)}let Ic=Object.assign(Fc,{createCache:wc,clearCache(e){Mc(Tc(e))},cacheStats(e){let t=Tc(e);return Object.freeze({...t.stats,entries:t.entries.size})}});function Lc(e){let t=0,n=0,r=0,i=0,a=0,o=null,s=e=>Number(e.toFixed(3));for(let c of e){t+=c.operations,n+=c.nestedOperations,r+=c.statements,i+=c.foldedOperations,a+=c.selects;let e=c.operations?c.statements/c.operations:0;(o===null||e>o.statementsPerOperation)&&(o=Object.freeze({pc:c.pcValue,operations:c.operations,statements:c.statements,statementsPerOperation:s(e),foldedOperations:c.foldedOperations,selectBlocks:c.selects}))}return Object.freeze({blocks:e.length,operations:t,nestedOperations:n,statements:r,statementsPerOperation:s(t?r/t:0),statementsPerNestedOperation:s(n?r/n:0),foldedOperations:i,selectBlocks:a,worst:o})}function Rc(e){let t=0;for(let n of e.operations)switch(t++,n.kind){case`if`:t+=Rc(n.yes),n.no&&(t+=Rc(n.no));break;case`match`:for(let e of n.arms)t+=Rc(e.body);n.otherwise&&(t+=Rc(n.otherwise));break;case`select`:t+=Rc(n.yes.body)+Rc(n.no.body);break;case`and`:case`or`:t+=Rc(n.right.body);break;case`assert`:n.message&&(t+=Rc(n.message.body))}return t}function zc(e){let t=0,n=!1;for(let r=0;r<e.length;r++){let i=e[r];n?i===`\\\\`?r++:i===`\"`&&(n=!1):i===`\"`?n=!0:i===`;`&&t++}return t}function Bc(e){return e>=48&&e<=57}function Vc(e){return Bc(e)||e>=65&&e<=90||e>=97&&e<=122||e===95}function Hc(e,t){let n=t+1;for(;n<e.length;){let t=e.charCodeAt(n++);if(t===92)n++;else if(t===34)break}return n}function Uc(e){if(!e.startsWith(`select`))return!1;let t=6,n=t;for(;t<e.length&&Bc(e.charCodeAt(t));)t++;return t>n&&e.startsWith(`: {`,t)}function Wc(e,t){let n=/* @__PURE__ */ new Set;for(let r of e)for(let e of r[t])n.add(e);return Object.freeze([...n])}let Gc=e=>[`const S = F.states, M = F.memories, L = F.locals, SD = F.stateDirty, MD = F.memoryDirty, MV = F.memoryViews ?? [];`,`const BS = F.blockedStates ?? [], BM = F.blockedMemories ?? [];`,...e.length?[`let ${e.join(`,`)};`]:[]];function Kc(e,t,n){let r=[`function run(F, deadline) {`,...Gc(n),`while (true) {`,`if (F.time >= deadline) return \"deadline\";`,`if (F.resume !== 0) {`,`if (F.due >= deadline) { F.time = deadline; return \"deadline\"; }`,`F.time = Math.max(F.time, F.due);`,`switch (F.resume) {`];return e.forEach((e,t)=>{r.push(`case ${t+1}: {`),e.slots.forEach((e,t)=>r.push(`${e} = L[${t}];`)),r.push(`F.resume = 0;`,...e.suffix,cl(e.stop),`}`)}),r.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`,`if (F.stopAfterInstruction) return \"invalidated\";`,`switch (H.checkPc(S[${t.pc.index}])) {`),e.forEach((e,n)=>{r.push(`case ${e.pc}: {`,...e.barrier,...e.guard,`S[${t.pc.index}] = ${e.nextPc};`,fl(`SD`,t.pc.index),...e.prefix),e.duration!==void 0&&r.push(...sl(e,n+1)),r.push(...e.suffix,cl(e.stop),`}`)}),r.push(`default: return \"fallback\";`,`}`,`}`,`}`),r}function qc(e,t,n){let r=[...e].sort((e,t)=>e.pcValue-t.pcValue),i=[],a=[],o=0;for(let e of r)a.length&&(a.length>=n||o+e.size>Nc)&&(i.push(a),a=[],o=0),a.push(e),o+=e.size;a.length&&i.push(a);let s=0,c=i.map(e=>{let t={start:s,entries:e,maxSlots:Math.max(...e.map(e=>e.slots.length)),lastPc:e[e.length-1].pc,lastResume:s+e.length,resumable:e.some(e=>e.duration!==void 0)};return s+=e.length,t}),l=e=>Array.from({length:e},(e,t)=>`v${t}`),u=[];c.forEach((e,n)=>{let r=n?c[n-1].lastPc:void 0;u.push(`function stepShard${n}(F, deadline, pc) {`,...Gc(l(e.maxSlots)),`while (true) {`,`switch (pc) {`),e.entries.forEach((n,i)=>{u.push(`case ${n.pc}: {`,...n.barrier,...n.guard,`S[${t.pc.index}] = ${n.nextPc};`,fl(`SD`,t.pc.index),...n.prefix,...sl(n,e.start+i+1),...n.suffix,dl(n.stop,r,e.lastPc,t.pc.index),`}`)}),u.push(`default: return \"fallback\";`,`}`,`}`,`}`)}),c.forEach((e,t)=>{e.resumable&&(u.push(`function resumeShard${t}(F, resume) {`,...Gc(l(e.maxSlots)),`switch (resume) {`),e.entries.forEach((t,n)=>{t.duration!==void 0&&(u.push(`case ${e.start+n+1}: {`),t.slots.forEach((e,t)=>u.push(`${e} = L[${t}];`)),u.push(`F.resume = 0;`,...t.suffix,ll(t.stop),`}`))}),u.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`))}),u.push(`function run(F, deadline) {`,`const S = F.states;`,`while (true) {`,`if (F.time >= deadline) return \"deadline\";`,`let status;`,`if (F.resume !== 0) {`,`if (F.due >= deadline) { F.time = deadline; return \"deadline\"; }`,`F.time = Math.max(F.time, F.due);`,`const resume = F.resume;`);let d=c.map((e,t)=>({shard:e,shardIndex:t})).filter(({shard:e})=>e.resumable);return d.length?Pc(u,`resume`,d.map(({shard:e,shardIndex:t})=>({bound:String(e.lastResume),call:`status = resumeShard${t}(F, resume);`})),`throw new TypeError(\"Unknown direct JIT continuation\");`):u.push(`throw new TypeError(\"Unknown direct JIT continuation\");`),u.push(`} else {`,`if (F.stopAfterInstruction) return \"invalidated\";`,`const pc = S[${t.pc.index}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc);`),Pc(u,`pc`,c.map((e,t)=>({bound:String(e.lastPc),call:`status = stepShard${t}(F, deadline, pc);`})),`return \"fallback\";`),u.push(`}`,`if (status !== \"next\") return status;`,`}`,`}`),u}function Jc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Yc(e){e.entries.sort((e,t)=>e.pcValue-t.pcValue),e.sourceSize=e.entries.reduce((e,t)=>e+t.size,0),e.maxSlots=Math.max(0,...e.entries.map(e=>e.slots.length)),e.resumable=e.entries.some(e=>e.duration!==void 0)}function Xc(e,t,n){return e.entries.length<n&&e.sourceSize+t.size<=Nc}function Zc(e,t){let n=1/0;for(let r of e.entries)n=Math.min(n,Math.abs(r.pcValue-t.pcValue));return n}function Qc(e,t,n){let r,i=1/0;for(let a of e){if(!Xc(a,t,n))continue;let e=Zc(a,t);(e<i||e===i&&(r===void 0||a.entries.length<r.entries.length))&&(r=a,i=e)}return r}function $c(e,t,n){let r=new Map(t.map(e=>[e.pcValue,e])),i=/* @__PURE__ */ new Map;for(let t=e.shards.length-1;t>=0;t--){let n=e.shards[t],a=[],o=!1;for(let e of n.entries){let t=r.get(e.pcValue);t===void 0?o=!0:(t!==e&&(o=!0),a.push(t))}if(o&&(n.entries=a,n.dirty=!0),!a.length)e.shards.splice(t,1);else{Yc(n);for(let e of n.entries)i.set(e.pcValue,n)}}let a=[...r.values()].filter(e=>!i.has(e.pcValue)).sort((e,t)=>e.pcValue-t.pcValue);for(let t of a){let r=Qc(e.shards,t,n);r===void 0&&(r={id:e.nextShard++,entries:[],sourceSize:0,maxSlots:0,resumable:!1,functions:void 0,signature:void 0,dirty:!0},e.shards.push(r)),r.entries.push(t),r.dirty=!0,Yc(r),i.set(t.pcValue,r)}}function el(e){let t=e[0];if(e.length===1)return`pc === ${t.pc}`;let n=e[e.length-1];return`pc >= ${t.pc} && pc <= ${n.pc}`}function tl(e,t,n){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; pc = S[${n}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc); if (${t}) continue; return pc;`}function nl(e,t){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; const pc = S[${t}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc); return pc;`}function rl(e,t){let n=Array.from({length:e.maxSlots},(e,t)=>`v${t}`),r=el(e.entries),i=[`function stepShard${e.id}(F, deadline, pc) {`,...Gc(n),`while (true) {`,`switch (pc) {`];return e.entries.forEach(e=>{i.push(`case ${e.pc}: {`,...e.barrier,...e.guard,`S[${t.pc.index}] = ${e.nextPc};`,fl(`SD`,t.pc.index),...e.prefix,...e.duration===void 0?[]:sl(e,e.resumeId),...e.suffix,tl(e.stop,r,t.pc.index),`}`)}),i.push(`default: return pc;`,`}`,`}`,`}`),e.resumable&&(i.push(`function resumeShard${e.id}(F, resume) {`,...Gc(n),`switch (resume) {`),e.entries.forEach(e=>{e.duration!==void 0&&(i.push(`case ${e.resumeId}: {`),e.slots.forEach((e,t)=>i.push(`${e} = L[${t}];`)),i.push(`F.resume = 0;`,...e.suffix,nl(e.stop,t.pc.index),`}`))}),i.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`)),i}function il(e,t,n){let r=rl(t,n),i=t.resumable?`resumeShard${t.id}`:`undefined`,[a,o]=Function(`C`,`H`,`\"use strict\";\\n${r.join(`\n`)}\\nreturn [stepShard${t.id}, ${i}];`)(Object.freeze([...e.constants]),vc);t.functions={step:a,resume:o},t.signature=Object.freeze([...t.entries]),t.dirty=!1,e.stats.compiledShards++}function al(e,t,n){let r=/* @__PURE__ */ new Map;e.forEach((e,t)=>{for(let n of e.entries)r.set(n.pcValue,t)});let i=[...t].sort((e,t)=>e.pcValue-t.pcValue),a=e.map((e,t)=>`const D${t} = SH[${t}];`);a.push(`function run(F, deadline) {`,`const S = F.states;`,`if (F.time >= deadline) return \"deadline\";`,`let pc;`,`if (F.resume !== 0) {`,`if (F.due >= deadline) { F.time = deadline; return \"deadline\"; }`,`F.time = Math.max(F.time, F.due);`,`const resume = F.resume;`,`const resumed = RES[resume];`,`if (resumed === undefined) throw new TypeError(\"Unknown direct JIT continuation\");`,`const next = resumed(F, resume);`,`if (typeof next !== \"number\") return next;`,`pc = next;`,`} else {`,`if (F.stopAfterInstruction) return \"invalidated\";`,`pc = S[${n.pc.index}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc);`,`}`,`while (true) {`,`let next;`,`switch (pc) {`);let o=-1;for(let e of i){let t=r.get(e.pcValue);t!==o&&(o>=0&&a.push(`next = D${o}(F, deadline, pc); break;`),o=t),a.push(`case ${e.pc}:`)}return o>=0&&a.push(`next = D${o}(F, deadline, pc); break;`),a.push(`default: return \"fallback\";`,`}`,`if (typeof next !== \"number\") return next;`,`pc = next;`,`}`,`}`),a}function ol(e,t,n,r){if($c(e,t,r),!e.shards.length)return;for(let t of e.shards)t.functions!==void 0&&!t.dirty&&Jc(t.signature??[],t.entries)?e.stats.reusedShards++:il(e,t,n);let i=al(e.shards,t,n),a=Function(`SH`,`RES`,`\"use strict\";\\n${i.join(`\n`)}\\nreturn run;`),o=Object.freeze(e.shards.map(e=>e.functions.step)),s=e.nextResume,c=Array(s);for(let t of e.shards)if(t.functions.resume!==void 0)for(let e of t.entries)e.resumeId!==0&&(c[e.resumeId]=t.functions.resume);let l=0;for(let e of t)e.slots.length>l&&(l=e.slots.length);let u={run:a(o,Object.freeze(c)),shards:e.shards.length,pcs:Object.freeze(t.map(e=>e.pcValue)),localCount:l,readStates:Wc(t,`readStates`),writeStates:Wc(t,`writeStates`),readMemories:Wc(t,`readMemories`),writeMemories:Wc(t,`writeMemories`)};return Object.defineProperty(u,\"emitStats\",{value:Lc(t)}),Object.freeze(u)}function sl(e,t){return e.duration===void 0?[]:[`F.due = F.time + ${e.dynamicDuration?`H.checkDuration(${e.duration})`:e.duration};`,`if (F.due > 7200000000000000) throw new RangeError(\"Time out of range\");`,`if ((F.publishPending && F.due > F.time) || F.due >= deadline) {`,...e.slots.map((e,t)=>`L[${t}] = ${e};`),`F.resume = ${t};`,`if (F.publishPending && F.due > F.time) return \"invalidated\";`,`F.time = deadline;`,`return \"deadline\";`,`}`,`F.time = F.due;`]}function cl(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; continue;`}function ll(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; return \"next\";`}function ul(e){return`(typeof ${e} === \"boolean\" ? ${e} : H.checkBoolean(${e}))`}function dl(e,t,n,r){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; pc = S[${r}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc); if (${t===void 0?`pc <= ${n}`:`pc <= ${n} && pc > ${t}`}) continue; return \"next\";`}function fl(e,t){return`${e}[${t>>>5}] |= ${1<<(t&31)};`}function pl(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}var ml=class{binding;capture;readStates=/* @__PURE__ */ new Set;writeStates=/* @__PURE__ */ new Set;readMemories=/* @__PURE__ */ new Set;writeMemories=/* @__PURE__ */ new Set;slots=[];size=0;statements=0;operations=0;selects=0;foldedOperations=0;nestedOperations=0;guard=[];barrier=[];prefix=[];suffix=[];pcValue=0;pc=``;nextPc=``;resumeId=0;duration;dynamicDuration=!1;immediate=!1;stop=!1;values=/* @__PURE__ */ new Map;locals=/* @__PURE__ */ new Map;folded=/* @__PURE__ */ new Map;constants;writtenStates=/* @__PURE__ */ new Set;writtenMemories=/* @__PURE__ */ new Set;references=/* @__PURE__ */ new Set;labels=0;constructor(e,t){this.binding=e,this.capture=t}compile(e){this.pcValue=e.pc,this.constants=bc(e.body);let t=Sc(e.body);this.operations=t.operations,this.nestedOperations=t.nestedOperations,this.pc=this.literal(e.pc),this.nextPc=this.literal(e.nextPc),this.readStates.add(this.binding.pc.name),this.state(this.binding.pc.name,!0);let n=this.binding.delayLoops?.get(e.pc);if(n!==void 0&&pl(n.counter)&&pl(n.cycles)){let e=n.pending,t=e!==void 0&&pl(e.state)&&pl(e.period)&&pl(e.active)?e:void 0;this.guard.push(`if (S[${n.counter}] > 1) {`,`let rounds = Math.min(S[${n.counter}] - 1, Math.floor((deadline - F.time) / ${n.cycles}));`),t!==void 0&&this.guard.push(`if (S[${t.active}]) rounds = Math.min(rounds, Math.floor(Math.max(0, S[${t.period}] - S[${t.state}]) / ${n.cycles}) + 1);`),this.guard.push(`if (rounds > 0) {`,`F.time += rounds * ${n.cycles};`,`if (F.time > 7200000000000000) throw new RangeError(\"Time out of range\");`,`S[${n.counter}] = S[${n.counter}] - rounds;`,fl(`SD`,n.counter),...t===void 0?[]:[`S[${t.state}] += rounds * ${n.cycles};`,fl(`SD`,t.state)],`}`,`if (F.time >= deadline) { F.time = deadline; return \"deadline\"; }`,`}`)}let r=this.prefix,i=!1;for(let t of e.body.operations){if(i)throw Z;if(t.kind===`elapse`){if(this.terminated)throw Z;this.terminate(this.delay(t.duration)),r=this.suffix}else if(t.kind===`redirect`){if(this.terminated)throw Z;let e=this.delay(t.delay);r.push(`S[${this.binding.pc.index}] = H.checkPc(${this.value(t.target)});`,fl(`SD`,this.binding.pc.index)),this.terminate(e),r=this.suffix,i=!0}else if(t.kind===`stop`)this.stop=!0,i=!0;else if(t.kind===`yield`){if(this.terminated)throw Z;this.terminate({value:`0`,zero:!0,dynamic:!1}),i=!0}else this.operation(t,r)}if(!this.terminated&&!this.stop)throw Z;this.compact(),this.barrier=this.emitBarrier();let a=0,o=0,s=0;for(let e of[this.barrier,this.guard,this.prefix,this.suffix])for(let t of e)a+=t.length,o+=zc(t),Uc(t)&&s++;return this.size=a,this.statements=o,this.selects=s,this}emitBarrier(){let e=[],t=(t,n)=>{if(!n.size)return;let r=/* @__PURE__ */ new Map;for(let e of n)r.set(e>>>5,(r.get(e>>>5)??0)|1<<(e&31));for(let[n,i]of[...r].sort(([e],[t])=>e-t))e.push(`if (${t}[${n}] & ${i>>>0}) return \"fallback\";`)};return t(`BS`,this.writtenStates),t(`BM`,this.writtenMemories),e}get terminated(){return this.duration!==void 0||this.immediate}compact(){let e=this.slots.length;if(e<=1)return;let t=this.prefix.length,n=[...this.prefix,...this.suffix],r=n.length,i=new Int32Array(r+1),a=new Int32Array(r).fill(-1),o=new Int32Array(e).fill(-1),s=new Int32Array(e).fill(-1),c=new Int32Array(e).fill(-1),l=new Int32Array(e).fill(-1),u=[];for(let t=0;t<r;t++){i[t]=u.length;let r=n[t],l=0;if(r.charCodeAt(0)===118){let n=1,i=0;for(;n<r.length&&Bc(r.charCodeAt(n));)i=i*10+(r.charCodeAt(n)-48),n++;if(n>1&&r.charCodeAt(n)===32&&r.charCodeAt(n+1)===61&&r.charCodeAt(n+2)===32){if(i>=e)return;a[t]=i,o[i]<0&&(o[i]=t),s[i]=t,l=n+3}}for(;l<r.length;){if(r.charCodeAt(l)===34){l=Hc(r,l);continue}if(r.charCodeAt(l)!==118||l>0&&Vc(r.charCodeAt(l-1))){l++;continue}let n=l+1,i=0;for(;n<r.length&&Bc(r.charCodeAt(n));)i=i*10+(r.charCodeAt(n)-48),n++;if(n===l+1)l++;else if(n<r.length&&Vc(r.charCodeAt(n)))l=n;else{if(i>=e)return;u.push(i),c[i]=t,l=n}}}i[r]=u.length;for(let e=0;e<r;e++)for(let t=i[e];t<i[e+1];t++){let n=u[t];if(o[n]<0||o[n]>e)return}for(let t=0;t<e;t++)s[t]>=0&&(l[t]=Math.max(s[t],c[t]));let d=new Int32Array(e).fill(-1),f=[],p=0;for(let e=0;e<r;e++){let t=a[e];t>=0&&d[t]<0&&(d[t]=f.length>0?f.pop():p++),t>=0&&l[t]===e&&(l[t]=-1,f.push(d[t]));for(let t=i[e];t<i[e+1];t++){let n=u[t];l[n]===e&&(l[n]=-1,f.push(d[n]))}}let m=Array.from({length:p},(e,t)=>`v${t}`),h=t=>{let n=``,r=0,i=0;for(;i<t.length;){if(t.charCodeAt(i)===34){i=Hc(t,i);continue}if(t.charCodeAt(i)!==118||i>0&&Vc(t.charCodeAt(i-1))){i++;continue}let a=i+1,o=0;for(;a<t.length&&Bc(t.charCodeAt(a));)o=o*10+(t.charCodeAt(a)-48),a++;if(a===i+1||a<t.length&&Vc(t.charCodeAt(a))){i=a;continue}let s=o<e?d[o]:-1;s<0||(n+=t.slice(r,i),n+=m[s],r=a),i=a}return r===0?t:n+t.slice(r)};for(let e=0;e<t;e++)this.prefix[e]=h(this.prefix[e]);for(let e=0;e<this.suffix.length;e++)this.suffix[e]=h(this.suffix[e]);this.duration!==void 0&&(this.duration=h(this.duration)),this.slots=m}terminate(e){e.zero?this.immediate=!0:(this.duration=e.value,this.dynamicDuration=e.dynamic)}delay(e){let t=this.folded.get(e);if(t!==void 0&&typeof t.value==`number`){try{ws(t.value)}catch{throw Z}return{value:t.text,zero:t.value===0,dynamic:!1}}let n=this.values.get(e);if(n===void 0)throw Z;return{value:n,zero:!1,dynamic:!0}}literal(e){return typeof e==`boolean`?e?`true`:`false`:typeof e==`number`&&Number.isSafeInteger(e)?Object.is(e,-0)?`-0`:String(e):typeof e==`string`?JSON.stringify(e).replace(/\\u2028/g,`\\\\u2028`).replace(/\\u2029/g,`\\\\u2029`):this.capture(e)}value(e){let t=this.expressionOf(e);if(!t)throw Z;return t}expressionOf(e){return this.values.get(e)??this.folded.get(e)?.text}condition(e){let t=this.folded.get(e);return t!==void 0&&typeof t.value==`boolean`?t.text:ul(this.value(e))}foldResult(e){if(!(`result`in e))return!1;switch(e.kind){case`constant`:{let{constant:t}=e;return t.kind===`string`?this.foldConstant(e.result,t.value):t.kind===`enum`?this.foldConstant(e.result,t.member):t.kind===`number`||t.kind===`bool`?this.foldConstant(e.result,t.value):!1}case`unary`:case`binary`:case`numeric`:{let t=this.constants?.get(e.result);return t!==void 0&&this.foldConstant(e.result,t)}default:return!1}}foldConstant(e,t){return this.folded.set(e,{value:t,text:this.literal(t)}),this.foldedOperations++,!0}slot(){let e=`v${this.slots.length}`;return this.slots.push(e),e}state(e,t){let n=this.binding.states.get(e);if(!pl(n)||t&&this.binding.blockedStates?.has(e))throw Z;return(t?this.writeStates:this.readStates).add(e),t&&this.writtenStates.add(n),n}memory(e){if(e.memory.kind!==`memory`)throw Z;let t=e.memory.name,n=this.binding.memories.get(t),r=e.kind.startsWith(`store`);if(!pl(n)||r&&this.binding.blockedMemories?.has(t))throw Z;return(r?this.writeMemories:this.readMemories).add(t),r&&this.writtenMemories.add(n),n}expression(e){if(e.type.kind!==`number`&&e.type.kind!==`bool`)return;let{operations:t}=e.body,n=t[t.length-1];if(n?.kind!==`yield`)return;let r=/* @__PURE__ */ new Map;for(let e=0;e<t.length-1;e++)if(!this.fold(t[e],r))return;return r.get(n.value)??this.expressionOf(n.value)}fold(e,t){if(!(`result`in e)||!(`type`in e)||e.type.kind!==`number`&&e.type.kind!==`bool`)return!1;let n=e=>t.get(e)??this.expressionOf(e);switch(e.kind){case`constant`:return e.constant.kind!==`number`&&e.constant.kind!==`bool`?!1:(t.set(e.result,this.literal(e.constant.value)),!0);case`read`:return e.resource===`state`&&(t.set(e.result,`S[${this.state(e.name,!1)}]`),!0);case`localRead`:{let n=this.locals.get(e.local);return n?(t.set(e.result,n),!0):!1}case`unary`:{let r=nc[e.operator],i=n(e.value);return!r||i===void 0?!1:(t.set(e.result,`(${r}${i})`),!0)}case`binary`:{let r=tc[e.operator],i=n(e.left),a=n(e.right);return!r||i===void 0||a===void 0?!1:(t.set(e.result,`(${i} ${r} ${a})`),!0)}case`numeric`:{if(!rc.has(e.builtin))return!1;let r=[];for(let t of e.args){let e=n(t);if(e===void 0)return!1;r.push(e)}let i=ic.has(e.builtin)?`Number`:`Math`;return t.set(e.result,`${i}.${e.builtin}(${r.join(`,`)})`),!0}default:return!1}}requireHost(){if(this.binding.host!==!0)throw Z}message(e){let t=e.body.operations,n=t[0],r=t[1];if(t.length!==2||n?.kind!==`constant`||n.constant.kind!==`string`||r?.kind!==`yield`||r.value!==n.result)throw Z;return this.literal(n.constant.value)}pattern(e){switch(e.kind){case`none`:return`null`;case`number`:case`bool`:return this.literal(e.value);case`string`:return this.literal(e.value);case`enum`:return this.literal(e.member)}}region(e,t,n){for(let r of e.operations)if(r.kind===`yield`){if(!n)throw Z;t.push(`${n.slot} = ${this.value(r.value)}; break ${n.label};`)}else this.operation(r,t,n)}operation(e,t,n){let r;if(sc.has(e.kind)&&this.requireHost(),`result`in e){let t=e.type.kind;if(t!==`number`&&t!==`bool`&&!(ac.has(e.kind)||e.kind===`constant`&&(t===`string`||t===`enum`||t===`bytes`)))throw Z;if(this.foldResult(e))return;r=this.slot(),this.values.set(e.result,r),oc.has(t)&&this.references.add(e.result)}let i=e=>{t.push(`${r} = ${e};`)};switch(e.kind){case`constant`:{if(e.constant.kind!==`bytes`)throw Z;let t;try{t=Object.freeze(Array.from(gs(e.constant.value)))}catch{throw Z}i(`H.createBytes(${this.capture(t)})`);break}case`read`:if(e.resource!==`state`)throw Z;i(`S[${this.state(e.name,!1)}]`);break;case`write`:{let n=this.state(e.name,!0);t.push(`S[${n}] = ${this.value(e.value)};`,fl(`SD`,n));break}case`unary`:{let t=nc[e.operator];if(!t)throw Z;i(`(${t}${this.value(e.value)})`);break}case`binary`:{let t=tc[e.operator];if(!t)throw Z;let n=this.value(e.left),r=this.value(e.right);if((e.operator===`equal`||e.operator===`notEqual`)&&(this.references.has(e.left)||this.references.has(e.right))){i(`${e.operator===`notEqual`?`!`:``}H.equalValues(${n},${r})`);break}i(`(${n} ${t} ${r})`);break}case`numeric`:if(!rc.has(e.builtin))throw Z;i(`${ic.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(e=>this.value(e)).join(`,`)})`);break;case`send`:t.push(`F.host.send(${this.capture(e.channel)}, ${this.value(e.value)});`);break;case`notify`:t.push(`F.host.notify(${this.capture(e.notification)});`);break;case`readSample`:if(e.pin.kind!==`pin`)throw Z;i(`F.host.sample(${this.capture(e.pin.name)})`);break;case`writeIntent`:if(e.pin.kind!==`pin`)throw Z;t.push(`F.host.intent(${this.capture(e.pin.name)}, ${this.value(e.value)});`);break;case`resistor`:if(e.to.kind!==`pin`)throw Z;i(`F.host.resistor(${this.capture(e.to.name)}, ${this.value(e.resistance)})`);break;case`combineIntents`:i(`H.combineIntents([${e.values.map(e=>this.value(e)).join(`,`)}])`);break;case`field`:i(`${this.value(e.value)}[${this.capture(e.field)}]`);break;case`bytes`:i(`H.createBytes([${e.elements.map(e=>this.value(e)).join(`,`)}])`);break;case`index`:i(`H.readIndex(${this.value(e.value)},${this.value(e.index)})`);break;case`refEqual`:if(e.left.kind===`parameter`||e.right.kind===`parameter`)throw Z;i(e.left.name===e.right.name?`true`:`false`);break;case`length`:i(`${this.value(e.value)}.length`);break;case`optional`:i(this.value(e.value));break;case`isNone`:i(`(${this.value(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${this.value(e.value)})`);break;case`now`:i(`F.time`);break;case`random`:i(`F.host.random()`);break;case`assert`:{let n=e.message===void 0?`undefined`:this.message(e.message);t.push(`if (!${this.condition(e.condition)}) F.host.assert(false, ${n});`);break}case`local`:{if(e.type.kind!==`number`&&e.type.kind!==`bool`)throw Z;let n=this.slot();this.locals.set(e.local,n),t.push(`${n} = ${this.value(e.initial)};`);break}case`localRead`:{let t=this.locals.get(e.local);if(!t)throw Z;i(t);break}case`localWrite`:{let n=this.locals.get(e.local);if(!n)throw Z;t.push(`${n} = ${this.value(e.value)};`);break}case`load8`:{let t=`M[${this.memory(e)}]`;i(`${t}[H.offset(${t},${this.value(e.offset)})]`);break}case`store8`:{let n=this.memory(e),r=`M[${n}]`;t.push(`${r}[H.offset(${r},${this.value(e.offset)})] = H.byte(${this.value(e.value)});`,fl(`MD`,n));break}case`load16le`:case`load16be`:{let t=this.memory(e),n=`M[${t}]`,r=e.kind.endsWith(`le`)?`true`:`false`;i(`H.load16(${n},MV[${t}],${this.value(e.offset)},${r})`);break}case`load32le`:case`load32be`:{let t=this.memory(e),n=`M[${t}]`,r=e.kind.endsWith(`le`)?`true`:`false`;i(`H.load32(${n},MV[${t}],${this.value(e.offset)},${r})`);break}case`store16le`:case`store16be`:case`store32le`:case`store32be`:{let n=this.memory(e),r=`M[${n}]`,i=e.kind.startsWith(`store16`)?`store16`:`store32`,a=e.kind.endsWith(`le`)?`true`:`false`;t.push(`H.${i}(${r},MV[${n}],${this.value(e.offset)},${this.value(e.value)},${a});`,fl(`MD`,n));break}case`and`:case`or`:{if(e.right.body.operations.at(-1)?.kind!==`yield`)throw Z;let n=`${e.kind}${this.labels++}`;t.push(`${r} = ${this.condition(e.left)};`,`${e.kind===`or`?`if (!`:`if (`}${r}) {`,`${n}: {`),this.region(e.right.body,t,{slot:r,label:n}),t.push(`}`,`${r} = ${ul(r)};`,`}`);break}case`match`:{let r=this.value(e.value);if(!e.arms.length&&!e.otherwise||!e.otherwise&&n)throw Z;e.arms.forEach((e,i)=>{let a=this.pattern(e.pattern);t.push(`${i?`} else if`:`if`} (H.equalValues(${r}, ${a})) {`),this.region(e.body,t,n)}),e.otherwise&&(t.push(e.arms.length?`} else {`:`{`),this.region(e.otherwise,t,n)),t.push(`}`);break}case`if`:t.push(`if (${this.condition(e.condition)}) {`),this.region(e.yes,t,n),e.no&&(t.push(`} else {`),this.region(e.no,t,n)),t.push(`}`);break;case`select`:{let n=this.condition(e.condition),i=this.expression(e.yes),a=i===void 0?void 0:this.expression(e.no);if(i!==void 0&&a!==void 0){t.push(`${r} = ${n} ? ${i} : ${a};`);break}let o=`select${this.labels++}`;t.push(`${o}: {`,`if (${n}) {`),this.region(e.yes.body,t,{slot:r,label:o}),t.push(`} else {`),this.region(e.no.body,t,{slot:r,label:o}),t.push(`}`,`}`);break}default:throw Z}}};let hl=Object.freeze([]),gl=/* @__PURE__ */ new Set([`wait`,`elapse`,`receive`,`waitUntil`,`redirect`,`stop`]);var _l=class{values=[];primitives=/* @__PURE__ */ new Map;negativeZero=Symbol(`negative zero`);capture(e){let t=typeof e!=`object`||!e,n=Object.is(e,-0)?this.negativeZero:e;if(t){let e=this.primitives.get(n);if(e!==void 0)return`C[${e}]`}let r=this.values.push(e)-1;return t&&this.primitives.set(n,r),`C[${r}]`}freeze(){return Object.freeze(this.values.slice())}},vl=class{specs;indices=/* @__PURE__ */ new Map;constructor(e){this.specs=Array.from({length:e},()=>[])}expression(e,t,n){let r=`${e}\\0${t}\\0${n}`,i=this.indices.get(r);return i===void 0&&(i=this.specs[e].length,this.specs[e].push([t,n]),this.indices.set(r,i)),`F.h[${e}][${i}]`}},yl=class extends $s{pool;plan;bodyIndex;functions;emptyArgs;constructor(e,t,n,r,i,a,o,s){super(e,t,!1),this.pool=n,this.plan=r,this.bodyIndex=i,this.functions=a,this.emptyArgs=o,s&&(this.bindingFor=(e,t)=>this.plan.expression(this.bodyIndex,e,t))}capture(e){return this.pool.capture(e)}emitFunction(e,t){return this.lines=[],this.indent=0,this.line(`function f${e}(host, args = [], reaction, F) {`),this.indent++,this.region(t,[]),this.indent--,this.line(`}`),this.lines}emitOperation(e,t,n,r){if(e.kind===`call`||e.kind===`callValue`){let t=this.functions.get(e.name);if(t===void 0)throw new bl;let n=e.args.map(e=>this.argument(e)).join(`, `),r=`f${t}(host, ${n.length?`[${n}]`:this.emptyArgs}, undefined, F)`;e.kind===`callValue`?this.line(`const ${X(e.result)} = ${r};`):this.line(`${r};`)}else super.emitOperation(e,t,n,r)}},bl=class extends Error{};function xl(e,t){try{return Bs(e,t,!1)}catch{return}}function Sl(e,t,n){let r=xl(e,n);if(r===void 0)return;let i=[{name:``,region:e,analysis:r}],a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=e=>{for(let r of e.analysis.nodes){let e=r.operation;if(gl.has(e.kind))return!1;if(e.kind!==`call`&&e.kind!==`callValue`)continue;if(o.has(e.name))return!1;if(a.has(e.name))continue;let c=t?.(e.name);if(c===void 0)return!1;let l=i.length;a.set(e.name,l),o.add(e.name);let u=xl(c,n);if(u===void 0)return!1;let d={name:e.name,region:c,analysis:u};if(i.push(d),!s(d))return!1;o.delete(e.name)}return!0};return s(i[0])?i:void 0}function Cl(e,t={}){try{let n=Sl(e,t.resolveFunction,t);if(n===void 0)return;let r=/* @__PURE__ */ new Map;n.forEach((e,t)=>{t>0&&r.set(e.name,t)});let i=new _l,a=new vl(n.length),o=t.bindResources!==!1,s=i.capture(hl),c=[];for(let e=0;e<n.length;e++){let l=n[e],u=new yl(l.analysis,t,i,a,e,r,s,o);c.push(...u.emitFunction(e,l.region))}c.push(`return f0;`);let l=`\"use strict\";\\n${c.join(`\n`)}`,u=Function(`C`,`H`,l)(i.freeze(),As),d=Object.freeze(a.specs.map(e=>Object.freeze(e.map(([e,t])=>Object.freeze([e,t]))))),f=Object.freeze(n.slice(1).map(e=>e.name));return Object.freeze({source:l,functions:f,resources:d,bind(e){let t={h:d.map(t=>Tl(e,t))};return(n,r)=>u(e,n??hl,r,t)}})}catch{return}}let wl=Object.freeze([]);function Tl(e,t){return t.length?typeof e.bind==`function`?e.bind(t):Object.freeze(t.map(([t,n])=>El(e,t,n))):wl}function El(e,t,n){return Object.freeze(t===`pin`?{sample:()=>e.sample(n),intent:t=>e.intent(n,t),resistor:t=>e.resistor(n,t)}:t===`state`?{read:()=>e.read(`state`,n),write:t=>e.write(n,t)}:{load8:t=>e.load(`load8`,n,t),load16le:t=>e.load(`load16le`,n,t),load16be:t=>e.load(`load16be`,n,t),load32le:t=>e.load(`load32le`,n,t),load32be:t=>e.load(`load32be`,n,t),store8:(t,r)=>e.store(`store8`,n,t,r),store16le:(t,r)=>e.store(`store16le`,n,t,r),store16be:(t,r)=>e.store(`store16be`,n,t,r),store32le:(t,r)=>e.store(`store32le`,n,t,r),store32be:(t,r)=>e.store(`store32be`,n,t,r),length:()=>e.memoryLength(n),copy:(t,r)=>e.copyBytes(n,t,r)})}let Dl=Symbol(`unsupported resumable body`),Ol=/^(\\s*)(?:const|let) (v\\d+|l\\d+)( = |;)/;function kl(e,t={}){if(Il(e))try{return new Al(Bs(e,t,!1),t,!1).compileMachine(e)}catch{return}}var Al=class extends $s{blocks=[];slots=/* @__PURE__ */ new Map;resources=[];resourceIndex=/* @__PURE__ */ new Map;current;graph;constructor(e,t,n){super(e,t,n),t.bindResources&&(this.bindingFor=(e,t)=>this.bindResource(e,t))}bindResource(e,t){let n=`${e}\\0${t}`,r=this.resourceIndex.get(n);return r===void 0&&(r=this.resources.push([e,t])-1,this.resourceIndex.set(n,r)),`F.resources[${r}]`}compileMachine(e){this.graph=this.analysis.graph;for(let e of this.analysis.nodes)`result`in e.operation&&this.types.set(e.operation.result,e.operation.type);let t=this.reserve(),n=this.reserve();this.blocks[n].term={kind:`done`};let r=this.buildRegion(e,n,{},[]);this.blocks[t].term={kind:`jump`,to:r};let i=[...this.locals()].sort(),a=[`function resumableBody(host, args = [], reaction, F) {`,...i.length?[`let ${i.join(`, `)};`]:[],...this.resources.length?[`if (F.resources === void 0) F.resources = host.bind(${this.capture(Object.freeze(this.resources.slice()))});`]:[],`for (;;) {`,`switch (F.pc) {`];for(let e of this.blocks){a.push(`case ${e.id}: {`);for(let t of e.code)a.push(t);a.push(...Ml(e)),a.push(`}`)}a.push(`default: throw new TypeError(\"Unknown resumable continuation\");`,`}`,`}`,`}`);let o=a.join(`\n`),s=Object.freeze(this.constants.slice()),c=Function(`C`,`H`,`\"use strict\"; return (${o});`);return Object.freeze({run:c(s,As),slotCount:this.slots.size,start:0})}locals(){let e=/* @__PURE__ */ new Set;for(let t of this.analysis.nodes){let n=t.operation;`result`in n&&e.add(X(n.result)),(n.kind===`local`||n.kind===`localRead`||n.kind===`localWrite`)&&e.add(`l${n.local}`)}return e}buildRegion(e,t,n,r,i){this.current=void 0;let a=t,o=[];for(let t=e.operations.length-1;t>=0;t--){let i=e.operations[t],s=[...r,`operations`,t];Fl(i)?o.unshift(this.emitStraight(i,s)):(a=this.flush(o,a),o=[],a=this.buildControl(i,a,n,s))}if(i!==void 0){if(o.length){let e=this.blocks[i];for(let t of o)e.code.push(...t);e.term={kind:`jump`,to:a}}else i!==a&&(this.blocks[i].term={kind:`jump`,to:a});return i}return this.flush(o,a)}emitStraight(e,t){let n=this.lines,r=this.indent;this.lines=[],this.indent=0;let i;try{super.operation(e,t),i=this.lines}finally{this.lines=n,this.indent=r}return jl(i)}flush(e,t){if(!e.length)return t;let n=this.open();for(let t of e)n.code.push(...t);return this.current=void 0,n.term={kind:`jump`,to:t},n.id}buildControl(e,t,n,r){switch(e.kind){case`if`:{let i=this.reserve(),a=e.no?this.reserve():t,o=this.open();return o.term={kind:`branch`,test:`H.checkBoolean(${X(e.condition)})`,yes:i,no:a},this.current=void 0,this.buildRegion(e.yes,t,n,[...r,`yes`],i),e.no&&this.buildRegion(e.no,t,n,[...r,`no`],a),o.id}case`match`:{let i=e.otherwise?this.reserve():t,a=i;for(let i=e.arms.length-1;i>=0;i--){let o=e.arms[i],s=this.reserve();this.buildRegion(o.body,t,n,[...r,`arms`,i,`body`],s);let c=o.pattern,l=c.kind===`none`?null:c.kind===`enum`?ms(c.name,c.member):c.value,u=this.open();u.term={kind:`branch`,test:`H.equalValues(${X(e.value)}, ${this.capture(l)})`,yes:s,no:a},this.current=void 0,a=u.id}return e.otherwise&&this.buildRegion(e.otherwise,t,n,[...r,`otherwise`],i),a}case`while`:{let n=this.reserve(),i=this.buildRegion(e.body,n,{breakTo:t,continueTo:n},[...r,`body`]);return this.fillTest(n,e.test,[...r,`test`],e=>({kind:`branch`,test:`H.checkBoolean(${e})`,yes:i,no:t})),n}case`loop`:{let n=this.reserve(),i=this.buildRegion(e.body,n,{breakTo:t,continueTo:n},[...r,`body`]);return this.blocks[n].term={kind:`jump`,to:i},n}case`break`:case`continue`:{let t=e.kind===`break`?n.breakTo:n.continueTo;if(t===void 0)throw Dl;let r=this.open();return r.term={kind:`jump`,to:t},this.current=void 0,r.id}case`return`:case`returnValue`:{let e=this.open();return e.term={kind:`done`},this.current=void 0,e.id}case`wait`:{let n=`duration${this.serial++}`,r=this.open();r.code.push(`const ${n} = H.checkDuration(${X(e.duration)});`);let i=this.resumeBlock(e);return r.code.push(...this.save(e),`F.pc = ${i};`,`F.kind = 1;`,`F.duration = ${n};`),r.term={kind:`suspend`},this.current=void 0,this.link(i,t),r.id}case`receive`:{let n=this.open(),r=this.resumeBlock(e);return n.code.push(...this.save(e),`F.pc = ${r};`,`F.kind = 2;`,`F.channel = ${this.capture(e.channel)};`),n.term={kind:`suspend`},this.current=void 0,this.link(r,t),n.id}default:throw Dl}}fillTest(e,t,n,r){let i=this.blocks[e],a=`condition${this.serial++}`,o=this.lines,s=this.indent;this.lines=i.code,this.indent=0;try{this.line(`let ${a};`),this.valueRegion(t,a,n)}finally{this.lines=o,this.indent=s}this.current=void 0,i.term=r(a)}resumeBlock(e){let t=this.reserve(),n=this.blocks[t],r=this.analysis.byOperation.get(e),i=`result`in e?X(e.result):void 0;for(let e of this.liveIn(r))e!==i&&n.code.push(`${this.slotName(e)} = F.slots[${this.slot(e)}];`);return i&&n.code.push(`${i} = F.value;`),t}link(e,t){let n=this.blocks[e];n.code.push(`F.pc = ${t};`),n.term={kind:`jump`,to:t}}save(e){let t=this.analysis.byOperation.get(e),n=`result`in e?X(e.result):void 0,r=[];for(let e of this.liveIn(t))e!==n&&r.push(`F.slots[${this.slot(e)}] = ${this.slotName(e)};`);return r}liveIn(e){if(e.resumeBlock===void 0)throw Dl;return(this.graph??=this.analysis.graph).blocks[e.resumeBlock].liveIn.filter(e=>e.startsWith(`value:`)||e.startsWith(`local:`))}slotName(e){let t=e.indexOf(`:`),n=Number(e.slice(t+1));if(!Number.isSafeInteger(n)||n<0)throw Dl;return e.startsWith(`value:`)?X(n):Xs(n)}slot(e){let t=this.slots.get(e);if(t!==void 0)return t;let n=this.slots.size;return this.slots.set(e,n),n}reserve(){let e={id:this.blocks.length,code:[]};return this.blocks.push(e),e.id}open(){if(this.current)return this.current;let e={id:this.blocks.length,code:[]};return this.blocks.push(e),this.current=e,e}};function jl(e){let t=[];for(let n of e){let e=Ol.exec(n);e?e[3]!==`;`&&t.push(`${e[1]}${e[2]}${e[3]}${n.slice(e[0].length)}`):t.push(n)}return t}function Ml(e){let t=e.term;if(!t)throw Dl;switch(t.kind){case`jump`:return[`F.pc = ${t.to};`,`break;`];case`branch`:return[`if (${t.test}) F.pc = ${t.yes};`,`else F.pc = ${t.no};`,`break;`];case`suspend`:return[`return true;`];case`done`:return[`F.pc = 0;`,`return false;`];default:throw Dl}}let Nl=/* @__PURE__ */ new Set([`if`,`match`,`while`,`loop`,`break`,`continue`,`return`,`returnValue`,`wait`,`receive`]),Pl=/* @__PURE__ */ new Set([`elapse`,`call`,`callValue`,`waitUntil`,`redirect`,`stop`,`yield`]);function Fl(e){return!Nl.has(e.kind)&&!Pl.has(e.kind)}function Il(e){for(let t of e.operations)switch(t.kind){case`if`:if(!Il(t.yes)||t.no&&!Il(t.no))return!1;break;case`match`:for(let e of t.arms)if(!Il(e.body))return!1;if(t.otherwise&&!Il(t.otherwise))return!1;break;case`while`:if(!Ll(t.test.body)||!Il(t.body))return!1;break;case`loop`:if(!Il(t.body))return!1;break;case`and`:case`or`:if(!Ll(t.right.body))return!1;break;case`select`:if(!Ll(t.yes.body)||!Ll(t.no.body))return!1;break;case`assert`:if(t.message&&!Ll(t.message.body))return!1}return!0}function Ll(e){for(let t of e.operations)if(t.kind!==`yield`&&(Nl.has(t.kind)||Pl.has(t.kind)||!Il({operations:[t]})))return!1;return!0}var Rl=class extends Error{code;instanceId;resource;network;networks;component;reason;constructor(e,t,n={}){super(t),this.name=`ElectricalError`,this.code=e,this.reason=t,this.instanceId=n.instanceId,this.resource=n.resource,this.network=n.network,this.networks=n.networks,this.component=n.component}};function zl(e,t={}){if(!Number.isFinite(e)||e<.001||e>1e9)throw new Rl(`INVALID_ELECTRICAL_PARAMETER`,`Resistance must be finite and in [0.001, 1000000000] ohms.`,t)}let Bl=65536;function Vl(e,t){let n=Math.imul(2166136261^e,16777619);for(let e=0;e<t.length;e++)n=Math.imul(n^t[e].to,16777619);return Math.imul(n^t.length,16777619)>>>0}function Hl(e){let t=0,n=/* @__PURE__ */ new Set;for(let r of e.blocks){t+=r.component.nodes.length+2*r.component.edges.length;let e=r.component.physical;if(e!==void 0&&!n.has(e)&&(n.add(e),t+=e.nodes.length+e.edges.length),t>Bl)break}return t}function Ul(e,t,n){let r;for(let i=0;i<e.component.edges.length;i++){let a=e.component.edges[i],o=(n[a.pin]??t[a.pin])[a.index];(a.from!==o.from||a.to!==o.to||a.resistance!==o.resistance)&&(r??=e.component.edges.slice(),r[i]=o)}return r===void 0?e:{...e,component:{...e.component,edges:r}}}function Wl(e,t,n){let r;for(let i=0;i<e.blocks.length;i++){let a=e.blocks[i],o=Ul(a,t,n);o!==a&&(r??=e.blocks.slice(),r[i]=o)}return r===void 0?e:{...e,blocks:r}}function Gl(e){return{component:e,key:e.nodes.join(`,`)}}function Kl(e,t){let n=new Yl(e.length);for(let e of t)for(let t of e)n.join(t.from,t.to);let r=/* @__PURE__ */ new Map;for(let t=0;t<e.length;t++){let e=n.find(t),i=r.get(e);i===void 0&&(i={nodes:[],edges:[]},r.set(e,i)),i.nodes.push(t)}for(let e of t)for(let t of e)r.get(n.find(t.from)).edges.push(t);let i=0,a=[],o=[],s=Array(e.length),c=Array(e.length),l=0;for(let t of r.values()){let n,r=!0,u=1;for(let i of t.nodes){let t=e[i].reference;t!==void 0&&(r=!1,n===void 0?n=t:t!==n&&(u=0))}r&&i++;for(let e of t.nodes)s[e]=l,c[e]=u;l++;for(let n of Xl(t,e)){let e=a.length;a.push(Gl(n));for(let t of n.edges)(o[t.pin]??=[])[t.index]=e}}return{blocks:a,edgeBlocks:o,components:r.size,floatingComponents:i,nodeComponents:s,nodeUniform:c}}let ql=e=>e===0?0:e;function Jl(e){return{instanceId:e.instance,resource:e.name}}var Yl=class{parents;constructor(e){this.parents=Array(e);for(let t=0;t<e;t++)this.parents[t]=t}find(e){let t=e;for(;this.parents[t]!==t;)t=this.parents[t];for(;e!==t;){let n=this.parents[e];this.parents[e]=t,e=n}return t}join(e,t){let n=this.find(e),r=this.find(t);n!==r&&(this.parents[Math.max(n,r)]=Math.min(n,r))}};function Xl(e,t){let n=0,r,i=!1;for(let a of e.nodes){let e=t[a].reference;e===void 0?n++:r===void 0?r=e:e!==r&&(i=!0)}if(n<2||!i)return[e];let a=/* @__PURE__ */ new Map;for(let n of e.nodes)t[n].reference===void 0&&a.set(n,a.size);let o=new Yl(n),s=!1;for(let t of e.edges){let e=a.get(t.from),n=a.get(t.to);e!==void 0&&n!==void 0&&(o.join(e,n),s=!0)}if(!s&&n<=32)return[e];let c=Array(n),l=[];for(let t=0;t<n;t++){let n=c[o.find(t)];n===void 0&&(n={nodes:[],edges:[],physical:e},l.push(n)),c[t]=n}if(l.length===1)return[e];let u=/* @__PURE__ */ new Map;for(let t of e.edges){let e=a.get(t.from),n=a.get(t.to),r=e??n;if(r===void 0)continue;let i=c[r];i.edges.push(t);let o=e===void 0?t.from:n===void 0?t.to:void 0;if(o===void 0)continue;let s=u.get(o);s===void 0&&(s=[],u.set(o,s)),s.push(i)}for(let t of e.nodes){let e=a.get(t);if(e!==void 0)c[e].nodes.push(t);else{let e=u.get(t);if(e===void 0)continue;for(let n of e)n.nodes[n.nodes.length-1]!==t&&n.nodes.push(t)}}return l}function Zl(e){let t=0,n=0;for(let r of e){let e=t+r;n+=Math.abs(t)>=Math.abs(r)?t-e+r:r-e+t,t=e}return t+n}function Ql(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function $l(e,t,n){let r=t.nodes;if(e.nodes.length!==r.length||e.edges.length!==t.edges.length)return!1;for(let t=0;t<r.length;t++){let i=r[t];if(e.nodes[t]!==i||!Object.is(e.references[t],n[i].reference))return!1}for(let n=0;n<e.edges.length;n++){let r=e.edges[n],i=t.edges[n];if(r.from!==i.from||r.to!==i.to||r.resistance!==i.resistance)return!1}return!0}function eu(e,t,n){let r=t.length;if(e.length===0){for(let e of t)(!(e>0)||!Number.isFinite(e))&&n(`Invalid LDL pivot.`);return{matrix:e,anchors:t,pivots:t,weights:/* @__PURE__ */ new Float64Array}}let i=e.slice(),a=t.slice(),o=new Float64Array(r),s=new Float64Array(r*r);for(let e=0;e<r;e++){let t=e*r,c=[a[e]];for(let n=e+1;n<r;n++)c.push(i[t+n]);let l=Zl(c);(!(l>0)||!Number.isFinite(l))&&n(`Invalid LDL pivot.`),o[e]=l;for(let a=e+1;a<r;a++){let e=i[t+a];if(e===0)continue;let r=e/l;(!(r>0)||!Number.isFinite(r))&&n(`Unrepresentable LDL coefficient.`),s[t+a]=r}for(let o=e+1;o<r;o++){let c=i[t+o];if(c===0)continue;let u=c*(a[e]/l);a[e]>0&&!(u>0)&&n(`Reference coefficient underflow.`),a[o]=a[o]+u;for(let e=o+1;e<r;e++){let a=s[t+e];if(a===0)continue;let l=c*a;l>0||n(`Schur coefficient underflow.`);let u=o*r+e;i[u]=i[u]+l}}}return{matrix:e,anchors:t,pivots:o,weights:s}}function tu(e,t,n){let{weights:r,pivots:i}=e,a=t.length,o=new Float64Array(a);if(r.length===0)for(let e=0;e<a;e++)o[e]=t[e]/i[e],Number.isFinite(o[e])||n(`Non-finite backward substitution.`);else{let e=new Float64Array(a);for(let i=0;i<a;i++){let o=[t[i]];for(let t=0;t<i;t++)o.push(r[t*a+i]*e[t]);e[i]=Zl(o),Number.isFinite(e[i])||n(`Non-finite forward substitution.`)}for(let t=a-1;t>=0;t--){let s=[e[t]/i[t]];for(let e=t+1;e<a;e++)s.push(r[t*a+e]*o[e]);o[t]=Zl(s),Number.isFinite(o[t])||n(`Non-finite backward substitution.`)}}return o}function nu(e,t){return e-t}function ru(e,t){e=0+e;let n=e+t;return n+(Math.abs(e)>=Math.abs(t)?e-n+t:t-n+e)}function iu(e,t,n,r){if(e.length>32||t.length>128)return;let i=Array.from({length:e.length},()=>[]),a=[`unknown.length === ${e.length}`,`edges.length === ${t.length}`],o=[];for(let e=0;e<t.length;e++){let r=t[e],s=n.get(r.from),c=n.get(r.to);if(s!==void 0&&c!==void 0)return;if(s===void 0&&c===void 0){a.push(`nodes[edges[${e}].from].reference !== undefined`,`nodes[edges[${e}].to].reference !== undefined`);continue}let l=s??c;if(i[l].length===2)return;i[l].push(e);let u=s===void 0?`from`:`to`,d=s===void 0?`to`:`from`;o[e]=`nodes[edges[${e}].${u}].reference`,a.push(`edges[${e}].${d} === unknown[${l}]`,`${o[e]} !== undefined`)}if(i.some(e=>e.length===0))return;let s=[];for(let e=0;e<i.length;e++){let t=i[e],n=e=>e.length===1?`(0 + ${e[0]})`:`pair(${e.join(`,`)})`;for(let e of t)s.push(`const g${e} = edges[${e}].conductance / gScale;`);s.push(`anchors[${e}] = ${n(t.map(e=>`g${e}`))};`,`right[${e}] = ${n(t.map(e=>`g${e} * (${o[e]} / vScale)`))};`)}return Function(`pair`,`nodes`,`\"use strict\"; return {\n matches(edges, unknown) { return ${a.join(` && `)}; },\n assemble(edges, gScale, vScale) {\n const anchors = new Float64Array(${e.length});\n const right = new Float64Array(${e.length});\n ${s.join(`\n`)}\n return { anchors, right };\n }\n };`)(ru,r)}function au(e,t){let n=[...e],r=new Map(n.map((e,t)=>[e,t])),i=new Yl(n.length),a=t.map(e=>({id:e.id,pins:[...e.pins],voltage:e.voltage}));for(let e of n)if(e.low===void 0!=(e.high===void 0)||e.low!==void 0&&(!Number.isFinite(e.low)||!Number.isFinite(e.high)||!(e.low<e.high)))throw new Rl(`INVALID_ELECTRICAL_PARAMETER`,`Pin thresholds must both be omitted or finite with low < high.`,Jl(e));let o=(e,t)=>{let n=r.get(e);if(n===void 0)throw new Rl(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,t===void 0?Jl(e):{network:t});return n},s=(e,t)=>{let n=r.get(e);if(n===void 0)throw new Rl(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,Jl(t));return n},c=e=>Number.isFinite(e)&&e>=.001&&e<=1e9;for(let e of a){if(e.voltage!==void 0&&!Number.isFinite(e.voltage))throw new Rl(`INVALID_ELECTRICAL_PARAMETER`,`Reference must be finite.`,{network:e.id});let t;for(let n of e.pins){let r=o(n,e.id);t===void 0?t=r:i.join(t,r)}}let l=[],u=[],d=/* @__PURE__ */ new Map,f=n.map((e,t)=>{let n=i.find(t),r=d.get(n);return r===void 0&&(r=l.length,d.set(n,r),l.push({pins:[],networks:[],reference:void 0}),u.push([])),l[r].pins.push(e),u[r].push(t),r});for(let e of a){if(e.pins.length===0)continue;let t=l[f[o(e.pins[0],e.id)]];if(t.networks.push(e.id),e.voltage===void 0)continue;let n=ql(e.voltage);if(t.reference!==void 0&&t.reference!==n)throw new Rl(`CONFLICTING_REFERENCE`,`Conflicting fixed potentials on a net.`,{network:e.id,networks:Object.freeze([...t.networks])});t.reference=n}let p=/* @__PURE__ */ new Map,m=[],h,g=0,_=/* @__PURE__ */ new Map,v=new Uint32Array(n.length),y=0,b=0;for(let e=0;e<n.length;e++){let t=Vl(e,[]);v[e]=t,y+=t,b^=t}let x=(e,t)=>{let n=Vl(e,t),r=v[e];n!==r&&(v[e]=n,y+=n-r,b^=r^n)},ee=(e,t)=>{let n=_.get(e);if(n===void 0)return;let r=n.hashes;if(r.length===v.length){for(let e=0;e<r.length;e++){let n=t[e],i=n===void 0?v[e]:Vl(e,n);if(r[e]!==i)return}return n}},te=(e,t)=>{if(!(t.cost>Bl))for(_.has(e)?_.get(e)!==t&&_.set(e,t):_.set(e,void 0);_.size>4096;){let e=_.keys().next().value;if(e===void 0)break;_.delete(e)}},S=Array(l.length),C=Array(n.length),w=Array.from({length:n.length},()=>[]),T=Object.freeze([]),E=new Int32Array(l.length),D=[],ne=[],re=[],ie=Array(n.length),ae=[],oe=[],O=[],se=[],ce=new Int32Array(n.length),le=0,ue=!1,de=!1,fe=(e,t)=>{for(let n of e)t.indexOf(n)===-1&&(E[n.from]=E[n.from]-1,E[n.to]=E[n.to]-1);for(let n of t)e.indexOf(n)===-1&&(E[n.from]=E[n.from]+1,E[n.to]=E[n.to]+1)},k={solves:0,components:0,floatingComponents:0,factorizations:0,factorizationReuses:0,cacheHits:0,leafPlans:0,leafPropagations:0,topologyPrepares:0},pe=Object.freeze([]),A=[],j=[],me=Array(n.length),he=[],ge=[],_e=[],ve=[],ye=[],be=[],M=/* @__PURE__ */ new Map,N=()=>(++le===2147483647&&(ce.fill(0),le=1),le),xe=(e,t)=>{let n=M.get(e);n===void 0&&(M.size>=256&&M.clear(),n={},M.set(e,n));let r=n[t];return r===void 0&&(r=Object.freeze({voltage:ql(e),level:t,status:`valid`}),n[t]=r),r},P=(e,t)=>e.low===void 0?`unknown`:t<=e.low?`low`:t>=e.high?`high`:`unknown`,Se=(e,t,r,i)=>{let a=f[e],o=u[a],s=l[r].reference,c=[],d=[],p=[];for(let e=0;e<o.length;e++){let t=o[e],r=n[t];c.push(t),d.push(r),p.push(xe(s,P(r,s)))}return Object.freeze({targetPin:t.to,resistance:t.resistance,target:r,edges:i,node:a,voltage:s,slots:Object.freeze(c),pins:Object.freeze(d),samples:Object.freeze(p)})},F=(e,t,n,r)=>{let i=Se(e,t,n,r),a=me[e];if(a===void 0)me[e]=[i],k.leafPlans++;else{for(let e of a)if(e.targetPin===t.to&&e.resistance===t.resistance)return;a.length<2?a.push(i):a[a.length-1]=i,k.leafPlans++}},I=()=>{for(let e=0;e<be.length;e++){let t=be[e];F(t.slot,t.branch,t.target,t.edges)}be.length=0},Ce=(e,t)=>{if(h===void 0||t.length!==1)return;let n=me[e];if(n===void 0)return;let r=w[e];if(r.length!==1||l[r[0].to].reference===void 0)return;let i=f[e];if(E[i]!==1||l[i].reference!==void 0)return;let a=t[0];for(let e=0;e<n.length;e++){let t=n[e];if(t.targetPin===a.to&&t.resistance===a.resistance)return l[t.target].reference===void 0?void 0:t}},we=(e,t)=>{let n=e.length;for(;n>0&&e[n-1]>t;)e[n]=e[n-1],n--;e[n]=t},L=e=>{de||=(h={...h,nodeComponents:h.nodeComponents.slice(),nodeUniform:h.nodeUniform.slice()},!0);let t=h.nodeComponents,r=h.nodeUniform;j.length=0,O.length=0,se.length=0;for(let i=0;i<e;i++){let e=f[he[i]],a=ve[i];t[e]=t[a],r[e]=r[a];let o=ye[i];if(o!==void 0){if(S[e]===o.voltage)continue;let t=o.slots;for(let e=0;e<t.length;e++){let n=o.pins[e],r=o.samples[e];n.sample!==r&&(we(j,t[e]),O.push(n),se.push(r))}continue}let s=l[a].reference;if(S[e]===s)continue;let c=u[e];for(let e=0;e<c.length;e++){let t=c[e],r=n[t],i=r.low===void 0?`unknown`:s<=r.low?`low`:s>=r.high?`high`:`unknown`,a=r.sample;(a.voltage!==s||a.level!==i||a.status!==`valid`)&&(we(j,t),O.push(r),se.push(xe(s,i)))}}for(let e=0;e<O.length;e++)O[e].sample=se[e];for(let t=0;t<e;t++){let e=he[t],n=ve[t],r=w[e][0].to;S[f[e]]=l[n].reference,r!==n&&(E[r]=E[r]-1,E[n]=E[n]+1),C[e]=ge[t];let i=_e[t];w[e]=i,x(e,i)}ue=!0,k.solves++,k.leafPropagations++};return{get stats(){return Object.freeze({...k})},solve(e){let t=De(Te(e));if(t.length===0)return T;let r=[];for(let e=0;e<t.length;e++)r.push(n[t[e]]);return Object.freeze(r)},solveSlots(e){if(e===void 0)return De(void 0);let t=e instanceof Set||Array.isArray(e)||ArrayBuffer.isView(e)&&Symbol.iterator in e;if(!t){A.length=0;for(let t of e)A.push(t)}let r=t?e:A,i=()=>t?Ee(e):A;if(h!==void 0){let e=N(),t=0,a=!0;for(let i of r){if(ce[i]===e)continue;ce[i]=e;let r=n[i].intent;if(r===C[i])continue;let o=Ce(i,r);if(o===void 0){a=!1;break}he[t]=i,ge[t]=r,_e[t]=o.edges,ve[t]=o.target,ye[t]=o,t++}if(a)return t===0?De(i()):(L(t),j.length===0?pe:j)}return De(i())}};function Te(e){if(e!==void 0){A.length=0;for(let t of e)A.push(o(t));return A}}function Ee(e){if(e!==void 0){A.length=0;for(let t of e)A.push(t);return A}}function De(e){let t=h===void 0;if(be.length=0,h!==void 0&&!ue&&e!==void 0&&e.length===0)return k.solves++,k.cacheHits+=h.blocks.length,pe;D.length=0,ne.length=0,re.length=0,oe.length=0;let r=N(),i=t,a=h!==void 0&&e!==void 0;if(a){let t=0;for(let i=0;i<e.length;i++){let a=e[i];if(ce[a]===r)continue;ce[a]=r;let o=n[a].intent;if(o===C[a])continue;let s=Ce(a,o);if(s===void 0){t=-1;break}he[t]=a,ge[t]=o,_e[t]=s.edges,ve[t]=s.target,ye[t]=s,t++}if(t>0)return L(t),j.length===0?pe:j;r=N()}let o=t||e===void 0;for(let t=0;t<(o?n.length:e.length);t++){let u=o?t:e[t];if(!o){if(ce[u]===r)continue;ce[u]=r}let d=n[u],p=d.intent;if(p===C[u])continue;let m=f[u],h=w[u],g=[];for(let e of p){c(e.resistance)||zl(e.resistance,Jl(d));let t=f[s(e.to,d)];if(m===t)continue;let n=h[g.length];if(n?.to===t&&n.resistance===e.resistance)g.push(n);else{let r={pin:u,index:g.length,from:m,to:t,resistance:e.resistance,conductance:1/e.resistance};g.push(r),n?.to===t?oe.push(n):i=!0}}g.length!==h.length&&(i=!0);let _=h.length===1&&g.length===1&&E[m]===1&&l[m].reference===void 0&&l[h[0].to].reference!==void 0&&l[g[0].to].reference!==void 0;a&&!_&&(a=!1),_&&p.length===1&&g[0]!==h[0]&&be.push({slot:u,branch:p[0],target:g[0].to,edges:g}),D.push(u),ne.push(p),re.push(g)}if(a&&i){for(let e=0;e<D.length;e++)he[e]=D[e],ge[e]=ne[e],_e[e]=re[e],ve[e]=re[e][0].to,ye[e]=void 0;return I(),L(D.length),j.length===0?pe:j}ue&&(i=!0);let d=D.length;if(h!==void 0&&!i&&oe.length===0){for(let e=0;e<d;e++){let t=D[e];C[t]=ne[e],w[t]=re[e]}return k.solves++,k.cacheHits+=h.blocks.length,I(),pe}let _=h,T,O,se=0,le=/* @__PURE__ */ new Map;for(let e=0;e<ae.length;e++)ie[ae[e]]=void 0;ae.length=0;for(let e=0;e<d;e++){let t=D[e];ie[t]=re[e],ae.push(t)}if(i){let e=y,t=b;for(let n=0;n<d;n++){let r=D[n],i=Vl(r,re[n]),a=v[r];i!==a&&(e+=i-a,t^=a^i)}if(T=`${e}:${t}`,O=ee(T,ie),O!==void 0)_=Wl(O.topology,w,ie);else{let e=w.slice();for(let t=0;t<d;t++)e[D[t]]=re[t];_=Kl(l,e),se++}}else{let e=/* @__PURE__ */ new Set;for(let t of oe){let n=_.edgeBlocks[t.pin]?.[t.index];n!==void 0&&e.add(n)}for(let t of e)le.set(t,Ul(_.blocks[t],w,ie))}let A,me=/* @__PURE__ */ new Map,M=0,xe=0,P=i?0:_.blocks.length-le.size;for(let e of i?_.blocks:le.values()){let{component:t,key:n}=e,r=p.get(n);if(r!==void 0&&$l(r,t,l)){P++,(A??=/* @__PURE__ */ new Map).set(n,r);continue}let i=new Map(t.nodes.map(e=>[e,l[e].reference??null])),a=t.nodes.filter(e=>l[e].reference!==void 0),o=t.physical??t,s=e=>{let t=o.nodes.flatMap(e=>[...l[e].networks]),n=o.nodes.flatMap(e=>l[e].pins.map(e=>e.id)),r=l[o.nodes[0]].pins[0];throw new Rl(`ELECTRICAL_SOLVE_FAILED`,e,{...Jl(r),...t[0]===void 0?{}:{network:t[0]},networks:Object.freeze(t),component:Object.freeze(n)})},c,u;if(a.length!==0){let e=t.nodes.filter(e=>l[e].reference===void 0);for(let e of a)i.set(e,l[e].reference);let n=l[a[0]].reference;if(a.every(e=>l[e].reference===n))for(let t of e)i.set(t,n);else if(e.length!==0){let n=e.length,o=new Map(e.map((e,t)=>[e,t])),d=0,f=0,p=!1;for(let e of a)f=Math.max(f,Math.abs(l[e].reference));for(let e of t.edges){let t=o.has(e.from),n=o.has(e.to);(t||n)&&(d=Math.max(d,e.conductance)),t&&n&&(p=!0)}(!(d>0)||!(f>0))&&s(`Invalid equation scaling.`),p||(u=m.find(n=>n.matches(t.edges,e)),u===void 0&&(u=iu(e,t.edges,o,l),u!==void 0&&(m.push(u),m.length>8&&m.shift())));let h=new Float64Array(p?n*n:0),g,_;if(u!==void 0)({anchors:g,right:_}=u.assemble(t.edges,d,f));else{let e=Array.from({length:n},()=>[]),r=Array.from({length:n},()=>[]);for(let i of t.edges){let t=o.get(i.from),a=o.get(i.to),s=i.conductance/d;if(t!==void 0&&a!==void 0){let e=Math.min(t,a)*n+Math.max(t,a);h[e]=h[e]+s}else if(t!==void 0||a!==void 0){let n=t??a,o=l[t===void 0?i.from:i.to].reference;e[n].push(s),r[n].push(o/f*s)}}g=Float64Array.from(e,e=>Zl(e)),_=Float64Array.from(r,e=>Zl(e))}r?.factorization!==void 0&&Ql(r.factorization.matrix,h)&&Ql(r.factorization.anchors,g)?(c=r.factorization,xe++):(c=eu(h,g,s),M++);let v=tu(c,_,s);e.forEach((e,t)=>{let n=ql(v[t]*f);Number.isFinite(n)||s(`Non-finite node voltage.`),i.set(e,n)})}}let d={nodes:t.nodes,references:t.nodes.map(e=>l[e].reference),edges:t.edges,voltages:t.nodes.map(e=>i.get(e)),factorization:c};(A??=/* @__PURE__ */ new Map).set(n,d);for(let[e,t]of i)S[e]!==t&&me.set(e,t)}let Se=/* @__PURE__ */ new Map;j.length=0;for(let[e,t]of me){let r=u[e];for(let e=0;e<r.length;e++){let i=r[e],a=n[i],o=t===null||a.low===void 0?`unknown`:t<=a.low?`low`:t>=a.high?`high`:`unknown`,s=t===null?`floating`:`valid`,c=a.sample,l=c.voltage!==t||c.level!==o||c.status!==s;l&&j.push(i),(l||k.solves===0)&&Se.set(a,Object.freeze({voltage:t===null?null:ql(t),level:o,status:s}))}}j.length>1&&j.sort(nu);for(let[e,t]of Se)e.sample=t;for(let[e,t]of me)S[e]=t;for(let e=0;e<d;e++){let t=D[e],n=re[e];fe(w[t],n),C[t]=ne[e],w[t]=n,x(t,n)}if(i)p=A??/* @__PURE__ */ new Map;else{if(A!==void 0)for(let[e,t]of A)p.set(e,t);for(let[e,t]of le)_.blocks[e]=t}if(h=_,de=!1,ue=!1,i){let e=O!==void 0&&_===O.topology?O:{id:O?.id??g++,cost:O?.cost??Hl(_),topology:_,hashes:O?.hashes??v.slice()};te(T,e)}return k.solves++,k.components=_.components,k.floatingComponents=_.floatingComponents,k.factorizations+=M,k.factorizationReuses+=xe,k.cacheHits+=P,k.topologyPrepares+=se,I(),j.length===0?pe:j}}var ou=class{heap=[];sequence=0;get time(){return this.heap[0]?.time??1/0}push(e,t){let n={time:e,order:this.sequence++,value:t},r=this.heap.length;for(this.heap.push(n);r>0;){let e=r-1>>>1;if(!this.before(n,this.heap[e]))break;this.heap[r]=this.heap[e],r=e}this.heap[r]=n}pop(){let e=this.heap[0],t=this.heap.pop();if(this.heap.length){let e=0;for(;e*2+1<this.heap.length;){let n=e*2+1;if(n+1<this.heap.length&&this.before(this.heap[n+1],this.heap[n])&&n++,!this.before(this.heap[n],t))break;this.heap[e]=this.heap[n],e=n}this.heap[e]=t}return e.value}clear(){this.heap.length=0}before(e,t){return e.time<t.time||e.time===t.time&&e.order<t.order}},su=class{entries=[];words=[];activeWords=[];batch=[];get size(){return this.activeWords.length}register(e){return this.entries.push(e)-1}add(e){let t=e>>>5,n=this.words[t]??0;n===0&&this.activeWords.push(t),this.words[t]=n|1<<(e&31)}take(){let e=this.batch;e.length=0,this.activeWords.length>1&&this.activeWords.sort((e,t)=>e-t);for(let t of this.activeWords){let n=this.words[t];for(this.words[t]=0;n!==0;){let r=31-Math.clz32(n&-n);e.push(this.entries[t*32+r]),n&=n-1}}return this.activeWords.length=0,e}clear(){this.entries.length=0,this.words.length=0,this.activeWords.length=0,this.batch.length=0}},cu=class{values=[];head=0;get length(){return this.values.length-this.head}push(e){this.values.push(e)}shift(){let e=this.values[this.head];return this.values[this.head++]=void 0,this.head===this.values.length&&this.clear(),e}clear(){this.values.length=0,this.head=0}drain(){let e=this.values.slice(this.head);return this.clear(),e}};function lu(e,t){if(typeof e!=`object`||!e||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Expected a plain data object`);for(let n of Reflect.ownKeys(e)){if(!(`value`in Object.getOwnPropertyDescriptor(e,n)))throw TypeError(`Accessor properties are not allowed`);if(typeof n!=`string`||t&&!t.includes(n))throw TypeError(`Unknown field ${String(n)}`)}}function uu(e,t=`value`){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`${t} must be finite`);return e}function du(e,t=`value`){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`${t} must be a safe integer`);return e}function fu(e,t=`value`){let n=du(e,t);if(n<0)throw RangeError(`${t} must be nonnegative`);return n}function pu(e){if(typeof e!=`string`||e.length===0)throw TypeError(`Expected a nonempty identifier`);return e}function mu(e,t,n){let r=fu(t,`offset`),i=fu(n,`length`);if(r>e.length||i>e.length-r)throw RangeError(`Memory range is out of bounds`);return r}function hu(e,t){if(e===t||typeof e==`number`&&typeof t==`number`&&Number.isNaN(e)&&Number.isNaN(t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&hu(e[n],t[n]))}function gu(e){return typeof e!=`object`||!e?e:e instanceof Uint8Array?e.slice():Object.freeze(Array.isArray(e)?e.map(gu):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,gu(t)])))}let _u=/* @__PURE__ */ new WeakSet;function vu(e,t=()=>{}){let n=Object.freeze({get length(){return t(),e.length},get byteLength(){return t(),e.length},slice(n,r){return t(),e.slice(n,r)},*[Symbol.iterator](){for(let n=0;n<e.length;n++)t(),yield e[n];t()}}),r=new Proxy(n,{get(n,r,i){return t(),typeof r==`string`&&/^(0|[1-9]\\d*)$/.test(r)?e[Number(r)]:Reflect.get(n,r,i)},set(){throw TypeError(`Bytes are read-only`)},defineProperty(){throw TypeError(`Bytes are read-only`)}});return _u.add(r),r}function yu(e,t,n,r=!1){if(e.kind===`optional`)return t===null?null:yu(e.inner,t,n,r);switch(e.kind){case`number`:if(typeof t!=`number`)throw TypeError(`Expected number`);if(r&&!Number.isFinite(t))throw TypeError(`Property must be finite`);return t;case`bool`:if(typeof t!=`boolean`)throw TypeError(`Expected boolean`);return t;case`string`:if(typeof t!=`string`)throw TypeError(`Expected string`);return t;case`bytes`:if(!(t instanceof Uint8Array))throw TypeError(`Expected Uint8Array`);return t.slice();case`enum`:{let r=e.name===`Logic`?[`low`,`high`,`unknown`]:e.name===`SampleStatus`?[`valid`,`floating`]:e.name===`Overflow`?[`drop_new`,`drop_oldest`,`error`]:n.get(e.name)?.members;if(typeof t!=`string`||!r?.includes(t))throw TypeError(`Invalid ${e.name} member`);return t}case`record`:{lu(t);let r=n.get(e.name);return Object.freeze(Object.fromEntries(r.fields.map(e=>[e.name,yu({kind:e.type},t[e.name],n)])))}case`sample`:case`intent`:return t}}function bu(e){return e instanceof Uint8Array?vu(e.slice()):gu(e)}function xu(e,t,n){if(n!==void 0){if(!Array.isArray(n)||n.length!==4)throw TypeError(`randomState must contain four words`);for(let e of n)if(du(e),e<0||e>4294967295)throw RangeError(`randomState word out of range`);if(!n.some(Boolean))throw RangeError(`randomState cannot be zero`);return Uint32Array.from(n)}let r=2166136261,i=new TextEncoder().encode(t),a=new Uint8Array(4+i.length);new DataView(a.buffer).setUint32(0,e,!0),a.set(i,4);for(let e of a)r=Math.imul(r^e,16777619)>>>0;let o=/* @__PURE__ */ new Uint32Array(4);for(let e=0;e<4;e++){r=r+2654435769>>>0;let t=Math.imul(r^r>>>16,2246822507)>>>0;t=Math.imul(t^t>>>13,3266489909)>>>0,o[e]=(t^t>>>16)>>>0}return o.some(Boolean)||(o[0]=1),o}function Su(e){let t=(e,t)=>(e<<t|e>>>32-t)>>>0,n=Math.imul(t(Math.imul(e[1],5),7),9)>>>0,r=e[1]<<9;return e[2]^=e[0],e[3]^=e[1],e[1]^=e[2],e[0]^=e[3],e[2]^=r,e[3]=t(e[3],11),n/4294967296}let Cu={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},wu={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},Tu=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),Eu=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function Du(e,t,n){let r=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,i=mu(t.bytes,n,r);return r===1?t.bytes[i]:r===2?t.view.getUint16(i,e.endsWith(`le`)):t.view.getUint32(i,e.endsWith(`le`))}function Ou(e,t,n){let r=mu(e.bytes,t,n);return e.bytes.slice(r,r+Number(n))}function ku(e){throw Error(e===void 0?`Assertion failed`:String(e))}function Au(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let ju=Object.freeze({checkBoolean:Cs,createBytes:gs,createEnum:ms,createRecord:hs,equalValues:ys,nonNull:Ss,readIndex:xs,load:Du,copyBytes:Ou,assertFalse:ku,sameBytes:Au});var Mu=class extends Error{};function Q(e){throw new Mu(e)}var Nu=class{target;bindings=[];bindingIds=/* @__PURE__ */ new Map;slots=[];nested=[];named=/* @__PURE__ */ new Map;visiting=/* @__PURE__ */ new Set;results=/* @__PURE__ */ new Set;buffers=[[]];depth=0;serial=0;constructor(e){this.target=e,this.bindings.push(e),this.bindingIds.set(e,0)}build(e,t){let n=this.nestedDerived(e);if(t.length===1)this.line(`return ${n}();`);else{this.line(`let projected = ${n}();`);for(let e=1;e<t.length;e++)this.line(`projected = projected[${this.ref(t[e])}];`);this.line(`return projected;`)}return[`function () {`,...this.nested.map(e=>e),...this.buffers[0].map(e=>` ${e}`),`}`].join(`\n`)}slotsUsed(){return this.slots}bindingTable(){return this.bindings}get lines(){return this.buffers[this.buffers.length-1]}line(e){this.lines.push(`${` `.repeat(this.depth)}${e}`)}block(e,t){this.line(`${e} {`),this.depth++,t(),this.depth--,this.line(`}`)}bind(e){if(!(typeof e==`object`&&e)&&Object.is(e,-0))return this.bindings.push(e)-1;let t=this.bindingIds.get(e);if(t!==void 0)return t;let n=this.bindings.push(e)-1;return this.bindingIds.set(e,n),n}ref(e){return`B[${this.bind(e)}]`}slot(e){this.slots.includes(e)||this.slots.push(e)}nestedSource(e,t,n){this.buffers.push([]);let r=this.depth;this.depth=0;try{n()}finally{this.depth=r}let i=this.buffers.pop(),a=[`function ${e}(${t.join(`, `)}) {`,...i,`}`].join(`\n`);return this.nested.push(a),e}nestedDerived(e){let t=`derived:${e.name}`,n=this.named.get(t);if(n)return n;this.visiting.has(t)&&Q(`recursive derived ${e.name}`);let r=`d${this.serial++}`;this.named.set(t,r),this.visiting.add(t);try{this.nestedSource(r,[],()=>this.region(e.value.body,void 0))}finally{this.visiting.delete(t)}return r}nestedFunction(e,t){let n=`function:${e}`,r=this.named.get(n);if(r)return r;this.visiting.has(n)&&Q(`recursive pure call ${e}`);let i=`f${this.serial++}`;this.named.set(n,i),this.visiting.add(n);try{let e=t.params.map((e,t)=>`p${t}`);this.nestedSource(i,e,()=>{let n=this.params;this.params=e;try{this.region(t.body,void 0)}finally{this.params=n}})}finally{this.visiting.delete(n)}return i}params;value(e){return this.results.has(e)||Q(`result ${e} is used before it is defined`),`v${e}`}defineResult(e){return this.results.add(e),`v${e}`}region(e,t){for(let n of e.operations)this.operation(n,t)}valueRegion(e,t){let n=`s${this.serial++}`;this.line(`${n}: {`),this.depth++,this.region(e.body,{slot:t,label:n}),this.depth--,this.line(`}`)}argument(e){return e.kind!==`value`&&Q(`resource argument`),this.value(e.value)}memoryRef(e,t){e.kind===`parameter`&&Q(`parameterised memory ${t}`);let n=this.target.memoryPlan(e.name);return this.slot(n.slot),n}pinRef(e,t){e.kind===`parameter`&&Q(`parameterised pin ${t}`);let n=this.target.pins.get(e.name),r=this.target.sampleResources.get(e.name);return(!n||!r)&&Q(`unknown pin ${e.name}`),this.slot(r),n}operation(e,t){let n=t=>{`result`in e||Q(`resultless operation`),this.line(`const ${this.defineResult(e.result)} = ${t};`)},r=e=>this.region(e,t);switch(e.kind){case`constant`:{let t=e.constant;t.kind===`bytes`?n(`H.createBytes(${this.ref(Object.freeze(Array.from(gs(t.value))))})`):t.kind===`enum`?n(this.ref(ms(t.name,t.member))):t.kind===`record`?n(this.ref(hs(t.fields.map(e=>[e.name,e.value])))):t.kind===`none`?n(`null`):n(this.ref(t.value));break}case`read`:if(e.resource===`state`){let t=this.target.stateResources.get(e.name);(!t||!this.target.states.has(e.name))&&Q(`unknown state ${e.name}`),this.slot(t),n(`${this.ref(this.target.states)}.get(${this.ref(e.name)})`)}else if(e.resource===`derived`){let t=this.target.declarations.get(e.name);t?.kind!==`derived`&&Q(`unknown derived ${e.name}`),n(`${this.nestedDerived(t)}()`)}else n(`${this.ref(this.target)}.read(${this.ref(e.resource)}, ${this.ref(e.name)})`);break;case`parameter`:{let t=this.params;(!t||e.index>=t.length)&&Q(`value parameter outside a call`),n(t[e.index]);break}case`unary`:{let t=Cu[e.operator];t||Q(`unsupported unary ${e.operator}`),n(`(${t}${this.value(e.value)})`);break}case`binary`:if(e.operator===`equal`||e.operator===`notEqual`)n(`${e.operator===`notEqual`?`!`:``}H.equalValues(${this.value(e.left)}, ${this.value(e.right)})`);else{let t=wu[e.operator];t||Q(`unsupported binary ${e.operator}`),n(`(${this.value(e.left)} ${t} ${this.value(e.right)})`)}break;case`numeric`:Tu.has(e.builtin)||Q(`unsupported builtin ${e.builtin}`),n(`${Eu.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(e=>this.value(e)).join(`, `)})`);break;case`record`:n(`H.createRecord([${e.fields.map(e=>`[${this.ref(e.name)}, ${this.value(e.value)}]`).join(`, `)}])`);break;case`field`:n(`${this.value(e.value)}[${this.ref(e.field)}]`);break;case`bytes`:n(`H.createBytes([${e.elements.map(e=>this.value(e)).join(`, `)}])`);break;case`length`:n(`${this.value(e.value)}.length`);break;case`index`:n(`H.readIndex(${this.value(e.value)}, ${this.value(e.index)})`);break;case`optional`:n(this.value(e.value));break;case`isNone`:n(`(${this.value(e.value)} === null)`);break;case`nonNull`:n(`H.nonNull(${this.value(e.value)})`);break;case`localRead`:n(`l${e.local}`);break;case`local`:this.line(`let l${e.local} = ${this.value(e.initial)};`);break;case`localWrite`:this.line(`l${e.local} = ${this.value(e.value)};`);break;case`memoryLength`:n(`${this.ref(this.memoryRef(e.memory,e.kind))}.bytes.length`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:n(`H.load(${this.ref(e.kind)}, ${this.ref(this.memoryRef(e.memory,e.kind))}, ${this.value(e.offset)})`);break;case`copyBytes`:{let t=this.memoryRef(e.memory,e.kind);n(`H.copyBytes(${this.ref(t)}, ${this.value(e.offset)}, ${this.value(e.length)})`);break}case`readSample`:n(`${this.ref(this.pinRef(e.pin,e.kind))}.sample`);break;case`callValue`:{e.pure||Q(`impure call`);let t=this.target.declarations.get(e.name);(t?.kind!==`function`||!t.pure)&&Q(`unknown pure function ${e.name}`),n(`${this.nestedFunction(e.name,t)}(${e.args.map(e=>this.argument(e)).join(`, `)})`);break}case`if`:this.block(`if (H.checkBoolean(${this.value(e.condition)}))`,()=>r(e.yes)),e.no&&this.block(`else`,()=>r(e.no));break;case`match`:e.arms.forEach((t,n)=>{let i=t.pattern,a=i.kind===`none`?null:i.kind===`enum`?ms(i.name,i.member):i.value;this.block(`${n?`else if`:`if`} (H.equalValues(${this.value(e.value)}, ${this.ref(a)}))`,()=>r(t.body))}),e.otherwise&&this.block(e.arms.length?`else`:``,()=>r(e.otherwise));break;case`while`:this.block(`while (true)`,()=>{let t=`s${this.serial++}`;this.line(`let ${t};`),this.valueRegion(e.test,t),this.line(`if (!H.checkBoolean(${t})) break;`),this.block(``,()=>r(e.body))});break;case`loop`:this.block(`while (true)`,()=>r(e.body));break;case`and`:case`or`:{let t=this.defineResult(e.result);this.line(`let ${t} = H.checkBoolean(${this.value(e.left)});`),this.block(`if (${e.kind===`or`?`!`:``}${t})`,()=>{this.valueRegion(e.right,t),this.line(`${t} = H.checkBoolean(${t});`)});break}case`select`:{let t=this.defineResult(e.result);this.line(`let ${t};`),this.block(`if (H.checkBoolean(${this.value(e.condition)}))`,()=>this.valueRegion(e.yes,t)),this.block(`else`,()=>this.valueRegion(e.no,t));break}case`assert`:this.block(`if (!H.checkBoolean(${this.value(e.condition)}))`,()=>{if(e.message){let t=`s${this.serial++}`;this.line(`let ${t};`),this.valueRegion(e.message,t),this.line(`H.assertFalse(${t});`)}else this.line(`H.assertFalse(undefined);`)});break;case`return`:this.line(`return;`);break;case`returnValue`:this.line(`return ${this.value(e.value)};`);break;case`break`:this.line(`break;`);break;case`continue`:this.line(`continue;`);break;case`yield`:t||Q(`yield outside a value region`),this.line(`${t.slot} = ${this.value(e.value)};`),this.line(`break ${t.label};`);break;default:{let t=e.kind;Q(`unsupported operation ${String(t)}`)}}}};function Pu(e,t,n){if(t&&t.kind!==`optional`){if(t.kind===`record`){let r=e.get(t.name);if(r?.kind!==`record`)return;let i=r.fields.find(e=>e.name===n);return i?{kind:i.type}:void 0}if(t.kind===`sample`){if(n===`voltage`)return{kind:`optional`,inner:{kind:`number`}};if(n===`level`||n===`status`)return{kind:`enum`,name:`Logic`}}}}function Fu(e,t,n){let r=t;for(let t=1;t<n.length;t++)r=Pu(e,r,n[t]);return{type:r}}function Iu(e){return e?e.kind===`optional`?Iu(e.inner):[`number`,`bool`,`string`,`enum`].includes(e.kind):!1}function Lu(e,t,n,r){if(t)switch(t.kind){case`number`:return`(${n} === ${r} || (${n} !== ${n} && ${r} !== ${r}))`;case`bool`:case`string`:case`enum`:return`(${n} === ${r})`;case`bytes`:return`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${n}.length === ${r}.length && H.sameBytes(${n}, ${r})))`;case`sample`:{let i=[`voltage`,`level`,`status`].map(i=>Lu(e,Pu(e,t,i),`${n}[${JSON.stringify(i)}]`,`${r}[${JSON.stringify(i)}]`));return i.some(e=>e===void 0)?void 0:`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${i.join(` && `)}))`}case`record`:{let i=e.get(t.name);if(i?.kind!==`record`||!i.fields.length)return;let a=i.fields.map(t=>Lu(e,{kind:t.type},`${n}[${JSON.stringify(t.name)}]`,`${r}[${JSON.stringify(t.name)}]`));return a.some(e=>e===void 0)?void 0:`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${a.join(` && `)}))`}case`optional`:{let i=Lu(e,t.inner,n,r);return i===void 0?void 0:`(${n} === ${r} || (${n} === null ? ${r} === null : (${r} !== null && ${i})))`}default:return}}function Ru(e,t,n){let r=e.declarations.get(n[0]);if(r?.kind!==`derived`)return{ok:!1,reason:`source root is not a derived declaration`};let{type:i}=Fu(e.declarations,r.type,n);if(i===void 0)return{ok:!1,reason:`source field type is not resolvable`};if(i.kind===`intent`)return{ok:!1,reason:`intent has no stable content comparison`};try{let a=new Nu(e),o=a.build(r,n),s=Function(`B`,`H`,`\"use strict\"; return (${o});`)(a.bindingTable(),ju),c=`function (a, b) { return ${Lu(e.declarations,i,`a`,`b`)??`H.same(a, b)`}; }`,l=Function(`H`,`\"use strict\"; return (${c});`)({...ju,same:hu});return{ok:!0,plan:{key:t,path:[...n],source:o,comparison:c,slots:a.slotsUsed(),evaluate:s,equals:l,needsSnapshot:!Iu(i)}}}catch(e){return{ok:!1,reason:e instanceof Mu?e.message:`unexpected code generation failure: ${e instanceof Error?e.message:String(e)}`}}}let zu=/* @__PURE__ */ new WeakMap,Bu=/* @__PURE__ */ new WeakMap,Vu=/* @__PURE__ */ new WeakMap,Hu=/* @__PURE__ */ new WeakMap,Uu=72e14;function Wu(e){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`Time must be a finite integer`);if(e<0||e>72e14)throw RangeError(`Time out of range`);return e===0?0:e}function Gu(e){let t=zu.get(e);return t||(t=Ks(e),zu.set(e,t)),t}function Ku(e,t){let n=e.entry.model,r=Hu.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,Hu.set(n,r));let i=r.get(t);if(i!==void 0)return i??void 0;let a=Cl(t,{bindResources:!0,resolveFunction:t=>{let n=e.declarations.get(t);return n?.kind===`function`?n.body:void 0}});return r.set(t,a??null),a}function qu(e){let t=Bu.get(e);return t===void 0&&(t=kl(e,{bindResources:!0})??null,Bu.set(e,t)),t??void 0}function Ju(e){return{pc:e.start,slots:Array(e.slotCount),kind:0,duration:0,channel:``,value:void 0}}function Yu(e,t){let n=Vu.get(e);return n||(n=qs(e),Vu.set(e,n)),n(t)}var Xu=class extends Error{code;diagnostic;related;constructor(e){super(e.message),this.name=`SimulationError`,this.code=e.code,this.diagnostic=e,this.related=e.related}};function Zu(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var Qu=class extends TypeError{code=`ASYNC_HOOK_RESULT`;constructor(){super(`Device hooks must return synchronously`)}},$u=class extends RangeError{code=`INVALID_ELECTRICAL_PARAMETER`};function ed(e){if(typeof e!=`number`||!Number.isFinite(e))throw new $u(`Electrical parameters must be finite numbers`);return e}function td(e){if(Zu(e))throw Promise.resolve(e).catch(()=>{}),new Qu}function nd(e){if(!(e instanceof Fa))return{};let t=e.diagnostics[0];return t?{...t.path?{path:Object.freeze([...t.path])}:{},...t.source?{source:gu(t.source)}:{}}:{}}function rd(e,t,n){return new Xu(Object.freeze({code:e,message:t instanceof Error?t.message:String(t),phase:n,time:null,cause:t,...nd(t),related:Object.freeze([])}))}let id=Object.freeze([]);function ad(e,t){for(let n of t.keys())if(!e.has(n))return!1;return!0}function od(e,t){return Object.freeze({get props(){return t.assertReadAllowed(e),Object.freeze(Object.fromEntries([...e.props].map(([e,t])=>[e,bu(t)])))},get inputs(){return e.assertCallAllowed(),e.inputs()},get memory(){return t.assertReadAllowed(e),e.publicMemory()},topics:t.topicBridge(e),reportError:n=>t.report(e,n),attachJit:t=>e.attach(t),loadBytes:(t,n,...r)=>e.loadBytes(t,n,r.length?r[0]:0)})}var sd=class{board;entry;id;declarations=/* @__PURE__ */ new Map;props=/* @__PURE__ */ new Map;constants=/* @__PURE__ */ new Map;states=/* @__PURE__ */ new Map;directBank;memories=/* @__PURE__ */ new Map;memoryViews=/* @__PURE__ */ new Map;memorySizes=/* @__PURE__ */ new Map;pins=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;notificationInputs=/* @__PURE__ */ new Set;notificationOutputs=/* @__PURE__ */ new Map;batchInputs=[];batchOutputs=[];batchNotifications=[];emptyOutputs=Object.create(null);resources=[];jits=[];processes=[];reactions=[];derived=/* @__PURE__ */ new Map;derivedBuffers=/* @__PURE__ */ new Map;stateResources=/* @__PURE__ */ new Map;memoryResources=/* @__PURE__ */ new Map;sampleResources=/* @__PURE__ */ new Map;observerRevision=0;dependencyStack=[];observations=/* @__PURE__ */ new WeakMap;staticObservations=/* @__PURE__ */ new WeakMap;resistorIntents=/* @__PURE__ */ new Map;sampleEntries=/* @__PURE__ */ new Map;stateSlots=/* @__PURE__ */ new Map;resourceHandles=/* @__PURE__ */ new Map;memoryPlans=/* @__PURE__ */ new Map;observationFrames=/* @__PURE__ */ new WeakMap;evaluating=/* @__PURE__ */ new Set;random;host;context;adapter;valid=!0;rawProps;constructor(e,t,n,r,i,a){this.board=e,this.entry=t,this.id=n;for(let e of t.model.declarations)`name`in e&&this.declarations.set(e.name,e),(e.kind===`state`||e.kind===`memory`||e.kind===`pin`)&&(e.kind===`state`?this.stateResources:e.kind===`memory`?this.memoryResources:this.sampleResources).set(e.name,{version:0,subscribers:/* @__PURE__ */ new Set});lu(r),this.rawProps=r;for(let e of Object.keys(r))if(this.declarations.get(e)?.kind!==`property`)throw TypeError(`Unknown property ${e}`);this.random=xu(i,n,a),this.host={read:(e,t)=>this.read(e,t),write:(e,t)=>this.writeState(e,t,this.stateSlot(e)),sample:e=>this.readSample(e),intent:(t,n)=>{let r=this.pin(t);r.intent!==n&&(r.intent=n,e.dirtyElectricalSlots.add(e.electricalSlot(r)),e.electricalDirty=!0)},resistor:(e,t)=>{let n=ed(t);if(n<.001||n>1e9)throw new $u(`Resistance outside [0.001, 1e9]`);return this.resistorIntent(e,n)},memoryLength:e=>this.memory(e).length,load:(e,t,n)=>{let r=this.memoryPlan(t),i=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,a=mu(r.bytes,n,i),o=this.dependencyStack.at(-1);return o&&o.set(r.slot,r.slot.version),i===1?r.bytes[a]:i===2?r.view.getUint16(a,e.endsWith(`le`)):r.view.getUint32(a,e.endsWith(`le`))},store:(e,t,n,r)=>{let i=this.memoryPlan(t),a=e.startsWith(`store8`)?1:e.startsWith(`store16`)?2:4,o=mu(i.bytes,n,a),s=du(r,`stored value`);a===1?i.bytes[o]=s:a===2?i.view.setUint16(o,s,e.endsWith(`le`)):i.view.setUint32(o,s,e.endsWith(`le`)),this.memoryChangedPlan(i)},copyBytes:(e,t,n)=>{this.track(this.memoryResources,String(e));let r=this.memory(e),i=mu(r,t,n);return r.slice(i,i+Number(n))},send:(e,t)=>this.send(e,t,!1),notify:t=>{if(!this.notificationOutputs.has(t))throw TypeError(`Unknown notification ${t}`);this.notificationOutputs.set(t,e.time)},now:()=>e.time,random:()=>Su(this.random),call:(e,t)=>this.invoke(e,t),assert:(e,t)=>{if(e!==!0)throw Error(t===void 0?`Assertion failed`:String(t))},bind:e=>this.bindResources(e)},this.context=od(this,e)}track(e,t){this.trackSlot(e.get(t))}trackSlot(e){let t=this.dependencyStack.at(-1);t&&t.set(e,e.version)}bindingReport(){return Object.freeze({instance:this.id,handles:this.resourceHandles.size,bound:Object.freeze([...this.resourceHandles.keys()].sort()),processes:Object.freeze(this.processes.map(e=>Object.freeze({name:e.declaration.kind===`on`?e.declaration.name:`start`,bound:e.frame?.resources?.length??0})))})}dependenciesCurrent(e){if(!e)return!1;for(let[t,n]of e)if(t.version!==n)return!1;return!0}evaluate(e,t){let n=t??/* @__PURE__ */ new Map;this.dependencyStack.push(n);try{return{value:e(),dependencies:n}}finally{this.dependencyStack.pop();let e=this.dependencyStack.at(-1);if(e)for(let[t,r]of n)e.set(t,r)}}evaluateSource(e,t){this.dependencyStack.push(t);try{return gu(this.source(e))}finally{this.dependencyStack.pop();let e=this.dependencyStack.at(-1);if(e)for(let[n,r]of t)e.set(n,r)}}observe(e,t){let n=this.staticObservations.get(e);if(n)return n();let r=this.declarations.get(t[0]);if(r?.kind===`pin`||r?.kind===`state`){let n=r.kind===`pin`?this.sampleResources:this.stateResources,i=r.kind===`pin`?this.pin(r.name):void 0;if(i&&t[1]!==`sample`)throw TypeError(`Invalid source ${t.join(`.`)}`);let a=()=>{let e=i?i.sample:this.states.get(r.name);for(let n=i?2:1;n<t.length;n++)e=e[t[n]];return i?e:gu(e)},o=a(),s=n.get(r.name);return s.subscribers.size||this.observerRevision++,s.subscribers.add(e),this.staticObservations.set(e,a),o}let i=this.observationFrames.get(e),a;i===void 0?(a=/* @__PURE__ */ new Map,this.observationFrames.set(e,{first:a,second:/* @__PURE__ */ new Map,alternate:!0})):(a=i.alternate?i.second:i.first,i.alternate=!i.alternate,a.clear());let o=this.evaluateSource(t,a),s=this.observations.get(e);if(s===void 0||s.size!==a.size||!ad(s,a)){if(s)for(let t of s.keys())!a.has(t)&&t.subscribers.delete(e)&&!t.subscribers.size&&this.observerRevision++;for(let t of a.keys())s?.has(t)||(t.subscribers.size||this.observerRevision++,t.subscribers.add(e))}return this.observations.set(e,a),o}observationReader(e,t){return this.staticObservations.get(e)??(()=>this.observe(e,t))}read(e,t){if(e===`state`)return this.trackSlot(this.stateSlot(t)),this.states.get(t);if(e===`derived`){let e=this.derived.get(t);if(!e||!this.dependenciesCurrent(e.dependencies)){let n=this.declarations.get(t);if(n?.kind!==`derived`)throw TypeError(`Unknown derived ${t}`);let r=this.derivedBuffers.get(t);r===void 0?(r=/* @__PURE__ */ new Map,this.derivedBuffers.set(t,r)):r.clear(),e=this.evaluate(()=>Yu(n.value,this.host),r),this.derived.set(t,e)}let n=this.dependencyStack.at(-1);if(n)for(let[t,r]of e.dependencies)n.set(t,r);return e.value}let n=e===`property`?this.props:this.constants;if(n.has(t))return n.get(t);if(this.evaluating.has(t))throw TypeError(`Circular creation dependency ${t}`);this.evaluating.add(t);try{let e=this.declarations.get(t);if(e?.kind!==`property`&&e?.kind!==`const`)throw TypeError(`Invalid creation reference ${t}`);let r;if(e.kind===`property`){if(Object.hasOwn(this.rawProps,t))r=yu(e.type,this.rawProps[t],this.declarations,!0);else if(e.default)r=yu(e.type,Yu(e.default,this.host),this.declarations,!0);else throw TypeError(`Missing property ${t}`)}else r=Yu(e.value,this.host);return n.set(t,r),r}finally{this.evaluating.delete(t)}}invoke(e,t=[]){let n=this.declarations.get(e);if(n?.kind!==`function`)throw TypeError(`Unknown function ${e}`);return Gu(n.body)(this.host,t)}syncCall(e,t=[]){let n=this.invoke(e,t).next();if(!n.done)throw TypeError(`Unexpected suspension in synchronous function`);return n.value}pin(e){let t=this.pins.get(String(e));if(!t)throw TypeError(`Unknown pin ${String(e)}`);return t}resistorIntent(e,t){let n=typeof e==`string`?e:String(e),r=this.resistorIntents.get(n);r===void 0&&(this.resistorIntents.size>=64&&this.resistorIntents.clear(),r=/* @__PURE__ */ new Map,this.resistorIntents.set(n,r));let i=r.get(t);return i===void 0&&(r.size>=8&&r.clear(),i=Object.freeze([Object.freeze({to:this.pin(n),resistance:t})]),r.set(t,i)),i}readSample(e){let t=typeof e==`string`?e:String(e),n=this.sampleEntries.get(t);if(n===void 0){let e=this.pin(t);n={pin:e,slot:this.sampleResources.get(e.name)},this.sampleEntries.size>=512&&this.sampleEntries.clear(),this.sampleEntries.set(t,n)}let r=this.dependencyStack.at(-1);return r&&r.set(n.slot,n.slot.version),n.pin.sample}memory(e){let t=this.memories.get(String(e));if(!t)throw TypeError(`Unknown memory ${String(e)}`);return t}directStateBank(){if(this.directBank===void 0){let e=[...this.states.keys()].filter(e=>{let t=this.declarations.get(e);return t.type.kind===`number`||t.type.kind===`bool`});this.directBank={stateNames:Object.freeze(e),states:new Map(e.map((e,t)=>[e,t])),stateValues:e.map(e=>this.states.get(e))}}return this.directBank}writeState(e,t,n){let r=gu(t);this.states.set(e,r);let i=this.directBank?.states.get(e);i!==void 0&&(this.directBank.stateValues[i]=r),this.board.invalidate(n)}stateSlot(e){let t=this.stateSlots.get(e);if(t===void 0){if(!this.states.has(e))throw TypeError(`Unknown state ${e}`);t=this.stateResources.get(e),this.stateSlots.set(e,t)}return t}memoryPlan(e){let t=typeof e==`string`?e:String(e),n=this.memoryPlans.get(t);if(n===void 0){let e=this.memories.get(t);if(!e)throw TypeError(`Unknown memory ${t}`);n={name:t,bytes:e,view:this.memoryViews.get(t),slot:this.memoryResources.get(t)},this.memoryPlans.set(t,n)}return n}memoryChanged(e){this.memoryChangedSlot(e,this.memoryPlan(e).slot)}memoryChangedPlan(e){this.memoryChangedSlot(e.name,e.slot)}memoryChangedSlot(e,t){this.board.invalidate(t);for(let t of this.jits)t.options.code===e&&(t.cache.clear(),t.revision++,t.directPrograms.clear(),t.directProgramRevision=-1,t.directSkip=void 0,t.directMisses=0,t.direct?.frame.resume?t.direct.frame.stopAfterInstruction=!0:t.direct=void 0)}bindResources(e){let t=Array(e.length);for(let n=0;n<e.length;n++){let r=e[n],i=`${r[0]}\\0${r[1]}`,a=this.resourceHandles.get(i);a===void 0&&(a=this.resourceHandle(r[0],r[1]),this.resourceHandles.set(i,a)),t[n]=a}return t}resourceHandle(e,t){if(e===`pin`){let e,n=-1,r,i=()=>(e===void 0&&(e=this.pin(t),n=this.board.electricalSlot(e),r=this.sampleResources.get(t)),e);return Object.freeze({sample:()=>{let e=i(),t=this.dependencyStack.at(-1);return t&&t.set(r,r.version),e.sample},intent:e=>{let t=i();t.intent!==e&&(t.intent=e,this.board.dirtyElectricalSlots.add(n),this.board.electricalDirty=!0)},resistor:e=>{let n=ed(e);if(n<.001||n>1e9)throw new $u(`Resistance outside [0.001, 1e9]`);return this.resistorIntent(t,n)}})}if(e===`state`){let e,n=()=>e??=this.stateSlot(t),r=this.states;return Object.freeze({read:()=>{let e=n(),i=this.dependencyStack.at(-1);return i&&i.set(e,e.version),r.get(t)},write:e=>{let r=n();this.writeState(t,e,r)}})}let n,r=()=>n??=this.memoryPlan(t),i=(e,t,n)=>{let i=r(),a=mu(i.bytes,n,e),o=this.dependencyStack.at(-1);return o&&o.set(i.slot,i.slot.version),e===1?i.bytes[a]:e===2?i.view.getUint16(a,t):i.view.getUint32(a,t)},a=(e,n,i,a)=>{let o=r(),s=mu(o.bytes,i,e),c=du(a,`stored value`);e===1?o.bytes[s]=c:e===2?o.view.setUint16(s,c,n):o.view.setUint32(s,c,n),this.memoryChangedSlot(t,o.slot)};return Object.freeze({load8:e=>i(1,!1,e),load16le:e=>i(2,!0,e),load16be:e=>i(2,!1,e),load32le:e=>i(4,!0,e),load32be:e=>i(4,!1,e),store8:(e,t)=>a(1,!1,e,t),store16le:(e,t)=>a(2,!0,e,t),store16be:(e,t)=>a(2,!1,e,t),store32le:(e,t)=>a(4,!0,e,t),store32be:(e,t)=>a(4,!1,e,t),length:()=>this.memory(t).length,copy:(e,n)=>{this.track(this.memoryResources,t);let r=this.memory(t),i=mu(r,e,n);return r.slice(i,i+Number(n))}})}prepare(){for(let e of this.entry.model.declarations)e.kind===`pin`&&this.pins.set(e.name,{id:`${this.id}\\0${e.name}`,instance:this.id,name:e.name,intent:[],sample:{voltage:null,level:`unknown`,status:`floating`}});for(let e of this.entry.model.declarations)switch(e.kind){case`property`:case`const`:this.read(e.kind,e.name);break;case`state`:this.states.set(e.name,gu(Yu(e.initial,this.host)));break;case`memory`:{let t=fu(Yu(e.length,this.host),`memory length`);this.memorySizes.set(e.name,t);break}case`pin`:{let t=this.pins.get(e.name);if(e.low&&e.high){let n=ed(Yu(e.low,this.host)),r=ed(Yu(e.high,this.host));if(n>=r)throw new $u(`Pin thresholds must satisfy low < high`);Object.assign(t,{low:n,high:r})}e.initial&&(t.intent=Yu(e.initial,this.host));break}case`channel`:{let t=fu(Yu(e.capacity,this.host),`capacity`);if(t===0)throw RangeError(`Capacity must be positive`);let n;if(e.maxLength&&(n=fu(Yu(e.maxLength,this.host),`maxLength`),n===0))throw RangeError(`maxLength must be positive`);this.channels.set(e.name,{declaration:e,capacity:t,...n===void 0?{}:{maxLength:n},overflow:e.overflow?String(Yu(e.overflow,this.host)):`drop_new`,incoming:new cu,pending:new cu,outgoing:new cu});break}case`notification`:e.direction===`output`&&this.notificationOutputs.set(e.name,null);break;case`start`:case`on`:this.processes.push({instance:this,declaration:e,resumable:qu(e.body),...e.kind===`on`?{source:e.sourcePath}:{},state:`idle`,pending:!1});break;case`reaction`:this.reactions.push({instance:this,declaration:e,previous:void 0,synchronousProgram:Ku(this,e.body)??null,frame:void 0})}for(let[e,t]of this.channels)t.declaration.direction===`input`?this.batchInputs.push(t):(this.batchOutputs.push([e,t]),this.emptyOutputs[e]=id);for(let e of this.notificationOutputs.keys())this.batchNotifications.push(e),this.emptyOutputs[e]=null;Object.freeze(this.emptyOutputs)}captureBatch(e,t){for(let e of this.batchInputs)e.incoming.length&&e.incoming.clear();let n=this.emptyOutputs;for(let[e,t]of this.batchOutputs)t.outgoing.length&&(n===this.emptyOutputs&&(n=Object.assign(Object.create(null),this.emptyOutputs)),n[e]=Object.freeze(t.outgoing.drain().map(e=>Object.freeze({time:e.time,value:bu(e.value)}))));for(let e of this.batchNotifications){let t=this.notificationOutputs.get(e);t!==null&&(n===this.emptyOutputs&&(n=Object.assign(Object.create(null),this.emptyOutputs)),n[e]=Object.freeze({time:t}),this.notificationOutputs.set(e,null))}return Object.freeze({from:e,to:t,outputs:n===this.emptyOutputs?n:Object.freeze(n)})}assertCreation(){for(let e of this.entry.model.declarations)if(e.kind===`assert`&&!Gu(e.body)(this.host).next().done)throw TypeError(`Creation assertion suspended`)}allocate(){for(let[e,t]of this.memorySizes){let n=new Uint8Array(t);this.memories.set(e,n),this.memoryViews.set(e,new DataView(n.buffer))}this.memorySizes.clear()}assertCallAllowed(){this.board.assertCallAllowed(this)}inputs(){let e=Object.create(null);for(let t of this.entry.model.declarations)t.kind===`channel`&&t.direction===`input`&&(e[t.name]=Object.freeze({send:e=>{this.assertCallAllowed(),this.send(t.name,e,!0)}})),t.kind===`notification`&&t.direction===`input`&&(e[t.name]=Object.freeze({notify:()=>{this.assertCallAllowed(),this.notificationInputs.add(t.name)}}));return Object.freeze(e)}publicMemory(){let e=Object.create(null);for(let t of this.entry.model.declarations)t.kind===`memory`&&t.public&&(e[t.name]=vu(this.memory(t.name),()=>{if(this.board.assertAlive(this),![`idle`,`initialize`,`sync`].includes(this.board.phase))throw this.board.error(`INVALID_CALL_STATE`,`Memory cannot be borrowed in this phase`,this);if(this.board.phase===`initialize`&&this.board.current!==this)throw this.board.error(`INVALID_CALL_STATE`,`Another factory is initializing`,this)}));return Object.freeze(e)}send(e,t,n){let r=this.channels.get(e);if(!r||r.declaration.direction!==(n?`input`:`output`))throw TypeError(`Unknown channel ${e}`);let i=yu(r.declaration.type,t,this.declarations);if(r.maxLength!==void 0&&i.length>r.maxLength)throw RangeError(`Message exceeds maxLength`);let a=n?r.pending:r.outgoing;if(a.length===r.capacity){if(r.overflow===`drop_new`)return;if(r.overflow===`error`){let t=this.board.error(`CHANNEL_OVERFLOW`,`Channel ${e} overflow`,this);throw this.board.fault(t),t}a.shift()}a.push({time:this.board.time,value:i})}attach(e){if(this.assertCallAllowed(),this.board.phase!==`initialize`||this.board.current!==this)throw this.board.error(`INVALID_CALL_STATE`,`attachJit is initialization-only`,this);if(lu(e,[`entry`,`code`,`pc`,`beforeInstruction`,`polling`,`delays`,`translate`]),pu(e.entry),pu(e.code),pu(e.pc),this.jits.some(t=>t.active&&t.options.entry===e.entry))throw this.board.error(`INVALID_BINDING`,`Duplicate JIT entry`,this);if(!this.memories.has(e.code)||this.declarations.get(e.pc)?.kind!==`state`||this.declarations.get(e.pc).type.kind!==`number`||typeof e.translate!=`function`)throw this.board.error(`INVALID_BINDING`,`Invalid JIT binding`,this);if(e.beforeInstruction!==void 0){lu(e.beforeInstruction,[`when`,`call`]);let t=this.declarations.get(e.beforeInstruction.when),n=this.declarations.get(e.beforeInstruction.call);if(!t||![`state`,`derived`].includes(t.kind)||!(`type`in t)||t.type.kind!==`bool`||n?.kind!==`function`||n.params.length||n.returns)throw this.board.error(`INVALID_BINDING`,`Invalid instruction hook`,this)}else if(Object.hasOwn(e,`beforeInstruction`))throw TypeError(`Invalid beforeInstruction`);let t=/* @__PURE__ */ new Map;if(Object.hasOwn(e,`polling`)){if(!Array.isArray(e.polling))throw TypeError(`polling must be an array`);for(let n of e.polling){lu(n,[`pc`,`predicate`,`consume`,`wait`]);let e=uu(n.pc,`polling pc`),r=pu(n.predicate),i=this.declarations.get(r);if(t.has(e)||i?.kind!==`function`||!i.pure||i.params.length||i.returns?.kind!==`bool`)throw this.board.error(`INVALID_BINDING`,`Invalid polling declaration`,this);let a;if(Object.hasOwn(n,`consume`)){a=pu(n.consume);let e=this.declarations.get(a);if(e?.kind!==`function`||e.params.length!==0||e.returns!==void 0)throw this.board.error(`INVALID_BINDING`,`Invalid polling consume function`,this)}let o;if(Object.hasOwn(n,`wait`)){lu(n.wait,[`delay`,`advance`]);let e=pu(n.wait.delay),t=pu(n.wait.advance),r=this.declarations.get(e),i=this.declarations.get(t);if(r?.kind!==`function`||!r.pure||r.params.length!==0||r.returns?.kind!==`number`||i?.kind!==`function`||i.params.length!==1||i.params[0].type.kind!==`number`||i.returns!==void 0)throw this.board.error(`INVALID_BINDING`,`Invalid polling wait functions`,this);o=Object.freeze({delay:e,advance:t})}t.set(e,Object.freeze({predicate:r,...a===void 0?{}:{consume:a},...o===void 0?{}:{wait:o}}))}}if(Object.hasOwn(e,`delays`)&&!(e.delays instanceof Map))throw TypeError(`delays must be a Map`);let n={instance:this,options:Object.freeze({...e,...e.beforeInstruction?{beforeInstruction:Object.freeze({...e.beforeInstruction})}:{}}),cache:/* @__PURE__ */ new Map,polling:t,delays:e.delays??/* @__PURE__ */ new Map,revision:0,directRevision:-1,directObserverRevision:-1,directStateGuards:/* @__PURE__ */ new Set,directMemoryGuards:/* @__PURE__ */ new Set,directHookReads:/* @__PURE__ */ new Set,directPrograms:/* @__PURE__ */ new Map,directProgramRevision:-1,direct:void 0,directSkip:void 0,directMisses:0,pollReads:void 0,currentPc:void 0,automaticPolling:!1,pollingWait:!1,pollingPeriod:0,pollingOrigin:0,pollingToken:0,active:!0,stopped:!1,queued:!1,execution:void 0};this.jits.push(n),this.board.jits.push(n);let r={dispose:()=>{n.active&&(n.active=!1,n.execution=void 0,delete n.predicate,n.pollingToken++,this.board.waitingJits.delete(n),n.cache.clear(),n.directPrograms.clear(),n.direct=void 0,n.pollReads=void 0)}};return this.resources.push(r),r}loadBytes(e,t,n){if(this.assertCallAllowed(),this.board.phase!==`idle`&&(this.board.phase!==`initialize`||this.board.current!==this))throw this.board.error(`INVALID_CALL_STATE`,`Code loading is not allowed in this phase`,this);if(typeof e!=`string`||!this.jits.some(t=>t.active&&t.options.code===e))throw this.board.error(`INVALID_BINDING`,`Memory is not bound as code`,this);if(!(t instanceof Uint8Array))throw TypeError(`Code must be Uint8Array`);let r=this.memory(e),i=mu(r,n,t.length);t.length&&(r.set(t.slice(),i),this.memoryChanged(e))}source(e){let t=this.declarations.get(e[0]),n,r=1;if(t?.kind===`pin`){if(this.track(this.sampleResources,t.name),e[1]!==`sample`)throw TypeError(`Invalid source ${e.join(`.`)}`);n=this.pin(t.name).sample,r=2}else if(t?.kind===`state`||t?.kind===`derived`)n=this.read(t.kind,t.name);else throw TypeError(`Invalid source ${e.join(`.`)}`);for(let t=r;t<e.length;t++)n=n[e[t]];return n}};let cd=/* @__PURE__ */ new WeakMap;function ld(e,t){cd.set(e,t)}function ud(e,t,n){let r=/* @__PURE__ */ new Map,i=[],a=e=>{for(let t of e.operations)switch(`result`in t&&r.set(t.result,t),t.kind){case`constant`:case`unary`:case`binary`:case`numeric`:case`field`:case`length`:case`index`:case`isNone`:case`nonNull`:case`optional`:case`local`:case`localRead`:case`localWrite`:case`memoryLength`:case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:case`readSample`:case`yield`:break;case`read`:if(t.resource===`derived`||t.name===n)return!1;break;case`if`:if(!a(t.yes)||t.no&&!a(t.no))return!1;break;case`select`:if(!a(t.yes.body)||!a(t.no.body))return!1;break;case`and`:case`or`:if(!a(t.right.body))return!1;break;case`match`:if(t.arms.some(e=>!a(e.body))||t.otherwise&&!a(t.otherwise))return!1;break;case`redirect`:i.push(t.target);break;default:return!1}return!0};return a(e)?i.some(e=>{let n=r.get(e);return n?.kind!==`constant`||n.constant.kind===`number`&&n.constant.value===t}):!1}let dd=/* @__PURE__ */ new WeakMap;function fd(e){let t=dd.get(e);return t===void 0&&(t={stateMask:[],memoryMask:[]},dd.set(e,t)),t}function pd(e){let t=e;return t.directStats??={directCompiles:0,directShards:0,directCalls:0,directFallbacks:0,directDeadlines:0,directStopped:0}}function md(e){let t=fd(e),{stateIndex:n,memoryIndex:r}=t;if(n===void 0||r===void 0)return;let i=(e,t,n)=>{e.fill(0);for(let r of n){let n=t.get(r);n!==void 0&&(e[n>>>5]=(e[n>>>5]??0)|1<<(n&31))}};i(t.stateMask,n,e.directStateGuards),i(t.memoryMask,r,e.directMemoryGuards)}function hd(e,t){let n=!1,r=e.instance,i=e.directHookReads.size;if(t)for(let n of t.keys())e.directHookReads.add(n);if(e.directObserverRevision!==r.observerRevision||i!==e.directHookReads.size){e.directObserverRevision=r.observerRevision;for(let[t,i]of r.stateResources){let r=i.subscribers.size>0||e.directHookReads.has(i);e.directStateGuards.has(t)!==r&&(r?e.directStateGuards.add(t):e.directStateGuards.delete(t),n=!0)}for(let[t,i]of r.memoryResources){let r=i.subscribers.size>0||e.directHookReads.has(i)||t===e.options.code;e.directMemoryGuards.has(t)!==r&&(r?e.directMemoryGuards.add(t):e.directMemoryGuards.delete(t),n=!0)}n&&(md(e),e.directSkip=void 0)}}function gd(e,t,n){let r=()=>{e.time=n.time};return{send:(e,n)=>{r(),t.host.send(e,n)},sample:e=>(r(),t.host.sample(e)),intent:(e,i)=>{r();let a=t.pin(e).intent!==i;t.host.intent(e,i),a&&(n.publishPending=!0)},resistor:(e,n)=>(r(),t.host.resistor(e,n)),notify:e=>{r(),t.host.notify(e)},now:()=>(r(),t.host.now()),random:()=>(r(),t.host.random()),assert:(e,n)=>{r(),t.host.assert(e,n)}}}function _d(e){if(e.directLayout!==void 0)return e.directLayout;let t=e.instance,n=t.directStateBank(),r=[...t.memories.keys()],i=new Map(r.map((e,t)=>[e,t])),a=r.map(e=>t.memory(e)),o=a.map(e=>new DataView(e.buffer,e.byteOffset,e.byteLength));return e.directLayout={...n,memoryNames:Object.freeze(r),memories:i,memoryBanks:Object.freeze(a),memoryViews:Object.freeze(o)},e.directLayout}function vd(e,t,n,r,i){let a={states:n.stateValues,memories:[...n.memoryBanks],memoryViews:n.memoryViews,locals:Array(r.localCount),stateDirty:Array(Math.ceil(n.stateNames.length/32)).fill(0),memoryDirty:Array(Math.ceil(n.memoryNames.length/32)).fill(0),time:e.time,due:e.time,resume:0};return a.host=gd(e,t,a),a.blockedStates=i.stateMask,a.blockedMemories=i.memoryMask,a}function yd(e,t,n){let r=t.instance,i=!!t.direct?.frame.resume;if(!i){let i=uu(r.states.get(t.options.pc),`pc`);if(e.execution!==`throughput`||e.jits.length!==1||t.polling.has(i)||t.cache.get(i)?.polling||(hd(t,n),t.directSkip===i))return!1;if(t.directRevision!==t.revision){let n=t.direct?.pcs.size??0,a=t.revision-t.directRevision,o=n<16?1:Math.max(64,n),s=t.direct?.pcs.has(i)===!0;if(t.direct===void 0||a>=o||!s&&t.directMisses>=512){t.directProgramRevision!==t.revision&&(t.directProgramRevision===-1&&t.directCache!==void 0&&Ic.clearCache(t.directCache),t.directPrograms.clear(),t.directProgramRevision=t.revision);let n=_d(t),i=[...t.cache.values()].filter(e=>!e.polling&&!t.polling.has(e.pc)),a=/* @__PURE__ */ new Map;for(let[e,r]of t.delays){let t=n.states.get(r.counter);if(t===void 0)continue;let i=r.pending===void 0?void 0:{state:n.states.get(r.pending.state),period:n.states.get(r.pending.period),active:n.states.get(r.pending.active)};a.set(e,i!==void 0&&i.state!==void 0&&i.period!==void 0&&i.active!==void 0?{counter:t,cycles:r.cycles,pending:i}:{counter:t,cycles:r.cycles})}let o=JSON.stringify([...a].sort(([e],[t])=>e-t)),s=t.directPrograms.get(o);if(s)t.direct=s,t.directRevision=t.revision;else{let{states:s,memories:c}=n,l=t.directCache??=Ic.createCache(),u=Ic(i,{states:s,memories:c,pc:{name:t.options.pc,index:s.get(t.options.pc)},host:!0,split:!0,shardSize:8,delayLoops:a},l);t.directRevision=t.revision,t.directMisses=0;let d=pd(t);d.directShards=u?.shards??0,u&&d.directCompiles++;let f=fd(t);f.stateIndex=s,f.memoryIndex=c,f.stateMask.length=Math.ceil(n.stateNames.length/32),f.memoryMask.length=Math.ceil(n.memoryNames.length/32),md(t),t.direct=u?{program:u,pcs:new Set(u.pcs),revision:t.revision,frame:vd(e,r,n,u,f)}:void 0,t.direct?t.directPrograms.set(o,t.direct):t.directPrograms.delete(o)}}else if(!s){let e=pd(t);return e.directCalls++,e.directFallbacks++,t.directMisses+=1,!1}}if(!t.direct)return!1}let a=t.direct,o=a.frame;i&&(o.stopAfterInstruction=!0),o.time=e.time,o.stateDirty.fill(0),o.memoryDirty.fill(0);let s=e.time,c,l=!1,u=pd(t);u.directCalls++;try{c=a.program.run(o,Math.min(e.executionEnd,e.events.time))}finally{e.time=o.time,o.publishPending=!1;let n=t.directLayout;for(let e=0;e<o.stateDirty.length;e++){let t=o.stateDirty[e];for(;t!==0;){let i=e*32+31-Math.clz32(t&-t);r.host.write(n.stateNames[i],o.states[i]),t&=t-1,l=!0}}for(let e=0;e<o.memoryDirty.length;e++){let t=o.memoryDirty[e];for(;t!==0;){let i=e*32+31-Math.clz32(t&-t);r.memoryChanged(n.memoryNames[i]),t&=t-1,l=!0}}}if((c!==`fallback`||l||e.time!==s)&&e.boundary(),c===`fallback`){let n=uu(r.states.get(t.options.pc),`pc`);if(t.polling.has(n)||t.cache.get(n)?.polling||(u.directFallbacks++,t.directSkip=n),e.time===s&&e.time<e.executionEnd)return!1}else if(c===`stopped`)return u.directStopped++,t.stopped=!0,!0;else c===`invalidated`?(o.stopAfterInstruction=!1,a.revision!==t.revision&&(t.direct=void 0,t.directRevision=-1)):u.directDeadlines++;return o.resume&&o.due>e.time?e.events.push(o.due,()=>e.queueJit(t)):e.queueJit(t),!0}function bd(e,t){let n=new Map(t),r=e.instance;for(let t of[r.stateResources.get(e.options.pc),r.memoryResources.get(e.options.code)])n.set(t,t.version);return n}function xd(e,t,n,r,i){t.dependencies=n,t.pollingWait=!0,t.pollingPeriod=0,e.waitingJits.add(t);let a=++t.pollingToken;if(e.boundary(),r===0||i===void 0)return;let o=Wu(e.time+r);e.events.push(o,()=>{if(a!==t.pollingToken||!t.active||t.stopped||!e.waitingJits.has(t))return;let n=t.dependencies;t.pollingWait=!1,delete t.dependencies,e.waitingJits.delete(t),t.pollingToken++,e.current=t.instance,t.instance.dependenciesCurrent(n)&&(t.instance.syncCall(i,[r]),e.boundary()),e.queueJit(t)})}function Sd(e,t,n){if(n.kind===`elapse`){let r=Wu(n.duration);if(r===0)return!1;let i=Wu(e.time+r);return e.events.push(i,()=>e.queueJit(t)),e.boundary(),!0}if(n.kind===`waitUntil`){let r=t.instance.evaluate(()=>t.instance.syncCall(n.predicate));return r.value!==!0&&(t.predicate=n.predicate,t.pollingWait=!1,t.dependencies=r.dependencies,e.waitingJits.add(t),e.boundary(),!0)}if(n.kind===`stop`)return t.stopped=!0,t.execution=void 0,e.boundary(),!0;if(n.kind===`redirect`){uu(n.pc,`redirect target`);let r=Wu(n.delay);t.instance.host.write(t.options.pc,n.pc),t.execution=void 0;let i=t.automaticPolling&&r>0&&n.pc===t.currentPc&&t.pollReads,a=i?bd(t,i):void 0;return t.automaticPolling=!1,t.pollReads=void 0,e.boundary(),r===0?e.queueJit(t):e.events.push(Wu(e.time+r),()=>{t.active&&!t.stopped&&(a&&t.instance.dependenciesCurrent(a)?(t.dependencies=a,t.pollingWait=!0,t.pollingPeriod=r,t.pollingOrigin=e.time,e.waitingJits.add(t)):e.queueJit(t))}),!0}throw TypeError(`Invalid JIT suspension`)}function Cd(e,t){if(t.queued=!1,t.active&&!t.stopped){if(e.current=t.instance,t.direct?.frame.resume)yd(e,t);else{if(!t.execution){t.automaticPolling=!1,t.pollReads=void 0;let n,r=!1,i=t.options.beforeInstruction;if(i){let a=t.instance.declarations.get(i.when).kind,o=t.instance.states.get(t.options.pc),s=e.execution===`throughput`&&(e.jits.length===1||t.polling.has(o))?t.instance.evaluate(()=>t.instance.read(a,i.when)):void 0,c=(s?s.value:t.instance.read(a,i.when))===!0;if(c){let n=t.instance.invoke(i.call),r=n.next();if(!r.done){if(t.execution=n,Sd(e,t,r.value))return;throw TypeError(`Invalid hook suspension`)}}n=s?.dependencies,r=c}let a=uu(t.instance.states.get(t.options.pc),`pc`);if(e.execution===`throughput`){let i=t.polling.get(a);if(i){let r=t.instance.evaluate(()=>t.instance.syncCall(i.predicate));if(r.value!==!0){let a=new Map([...n??[],...r.dependencies]),o=0,s=i.wait;s&&(o=Wu(t.instance.evaluate(()=>t.instance.syncCall(s.delay),a).value)),xd(e,t,bd(t,a),o,s?.advance);return}i.consume&&t.instance.syncCall(i.consume)}if(!r&&e.jits.length===1&&yd(e,t,n))return}let o=t.cache.get(a);if(!o){let n=e.phase;e.phase=`translate`;let r=!0;try{let n=vu(t.instance.memory(t.options.code),()=>{if(!r)throw e.error(`OBJECT_DISPOSED`,`Translation view expired`,t.instance)}),i=t.options.translate(Object.freeze({pc:a,code:n}),Qo({device:t.instance.entry.model}));td(i);let s=Do(i,t.instance.entry.model);if(s.instructions[0]?.pc!==a)throw TypeError(`Translated first pc does not match`);let c=s.instructions.map(e=>({pc:e.pc,nextPc:e.nextPc,body:e.body,polling:ud(e.body,e.pc,t.options.pc),execute:Gu(e.body)}));for(let e=c.length-1;e>=0;e--){let n=c[e];t.cache.set(n.pc,n)}t.revision++,t.directSkip=void 0,o=c[0]}catch(n){throw e.wrap(n,`JIT_FAILED`,`translate`,t.instance)}finally{r=!1,e.phase=n}}t.currentPc=a,t.automaticPolling=e.execution===`throughput`&&e.jits.length===1&&o.polling&&!r&&(!i||n!==void 0),t.pollReads=n,t.instance.host.write(t.options.pc,o.nextPc),t.execution=o.execute(t.instance.host)}for(;;){let n=t.automaticPolling?(()=>{let e=t.instance.evaluate(()=>t.execution.next());return t.pollReads=new Map([...t.pollReads??[],...e.dependencies]),e.value})():t.execution.next();if(n.done){t.execution=void 0,e.boundary(),e.queueJit(t);return}if(Sd(e,t,n.value))return}}}}let wd=Symbol.for(`mica-js.simulator/observations`),Td=Symbol.for(`mica-js.simulator/processes`),Ed=Object.freeze({}),Dd=/* @__PURE__ */ new WeakMap;function Od(e){try{if(!Array.isArray(e))throw TypeError(`Expected device entries`);let t=/* @__PURE__ */ new Set,n=e.map(e=>{lu(e,[`id`,`model`,`create`]);let n=pu(e.id);if(t.has(n))throw TypeError(`Duplicate device type ${n}`);if(t.add(n),typeof e.create!=`function`)throw TypeError(`Expected device factory`);let r;try{r=To(e.model)}catch(e){throw rd(e instanceof Fa&&Object.getOwnPropertyDescriptor(e,`code`)?.value===`CHANNEL_CONSUMER_CONFLICT`?`CHANNEL_CONSUMER_CONFLICT`:`MODEL_VALIDATION_FAILED`,e,`library`)}return Object.freeze({id:n,model:r,create:e.create})}),r=Object.freeze({});return Dd.set(r,n),r}catch(e){throw e instanceof Xu?e:rd(`INVALID_CONFIGURATION`,e,`library`)}}var kd=class{time=0;status=`ready`;phase=`assembly`;current;electricalDirty=!0;dirtyElectricalSlots=/* @__PURE__ */ new Set;observations=new su;reactionBatch=[];changeObservations=[];changePrevious=[];changeCurrent=[];plans=[];skippedPlans=[];sampleSlots=/* @__PURE__ */ new Map;sampleSlotsBySlot=[];electricalSlots=/* @__PURE__ */ new Map;byId=/* @__PURE__ */ new Map;dispatchDepth=0;initialized=!1;errors=new i;diagnostics=new i;listeners=/* @__PURE__ */ new Set;hostListeners=0;models=new cu;events=new ou;readyJits=new cu;waitingJits=/* @__PURE__ */ new Set;jits=[];instances=[];network;primary;execution;executionEnd=0;onDidError=(e,t,n)=>this.errors.event(n=>{try{e.call(t,n)}catch(e){this.diagnostic(`HOST_LISTENER_FAILED`,e)}},void 0,n);onDidDiagnostic=(e,t,n)=>this.diagnostics.event(n=>{try{e.call(t,n)}catch(e){this.fallback(e)}},void 0,n);topics=this.topicBridge();constructor(e,t,n){try{lu(t,[`instances`,`nets`]),lu(n,[`seed`,`execution`,`cpuQuantum`]);let r=Object.hasOwn(n,`execution`)?n.execution:`throughput`;if(r!==`throughput`&&r!==`precise`)throw TypeError(`Invalid execution mode`);this.execution=r;let i=Object.hasOwn(n,`cpuQuantum`)?du(n.cpuQuantum,`cpuQuantum`):1e7;if(i<1||i>1e7)throw RangeError(`cpuQuantum outside [1, 10000000]`);if(!Array.isArray(t.instances)||!Array.isArray(t.nets))throw TypeError(`instances and nets are required arrays`);let a=Object.hasOwn(n,`seed`)?du(n.seed,`seed`):0;if(a<0||a>4294967295)throw RangeError(`seed out of uint32 range`);let o=new Map(e.map(e=>[e.id,e])),s=/* @__PURE__ */ new Set;for(let e of t.instances){lu(e,[`id`,`type`,`props`,`randomState`]);let t=pu(e.id),n=pu(e.type);if(s.has(t))throw TypeError(`Duplicate instance ${t}`);s.add(t);let r=o.get(n);if(!r)throw TypeError(`Unknown device type ${n}`);let i=Object.hasOwn(e,`props`)?e.props:{};if(Object.hasOwn(e,`randomState`)&&e.randomState===void 0)throw TypeError(`Invalid randomState`);this.instances.push(new sd(this,r,t,i,a,e.randomState))}for(let e of this.instances)this.byId.set(e.id,e);let c=this.byId,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set;for(let e of t.nets){lu(e,[`id`,`pins`,`voltage`]);let t=pu(e.id);if(l.has(t))throw TypeError(`Duplicate network ${t}`);if(l.add(t),!Array.isArray(e.pins))throw TypeError(`Network pins must be an array`);Object.hasOwn(e,`voltage`)&&uu(e.voltage,`voltage`);for(let t of e.pins){lu(t,[`instance`,`pin`]);let e=pu(t.instance),n=pu(t.pin);if(c.get(e)?.declarations.get(n)?.kind!==`pin`)throw TypeError(`Unknown pin endpoint`);let r=`${e}\\0${n}`;if(u.has(r))throw TypeError(`Duplicate connected endpoint`);u.add(r)}}try{for(let e of this.instances)this.current=e,e.prepare();for(let e of this.instances)this.current=e,e.assertCreation();for(let e of this.instances)this.current=e,e.allocate()}catch(e){throw this.wrap(e,`MODEL_EXECUTION_FAILED`,`assembly`,this.current)}let d=t.nets.map(e=>({id:e.id,pins:e.pins.map(e=>c.get(e.instance).pin(e.pin)),...Object.hasOwn(e,`voltage`)?{voltage:e.voltage}:{}})),f=[];for(let e of this.instances)for(let t of e.pins.values()){let n=e.sampleResources.get(t.name);f.push(t),this.sampleSlots.set(t,n),this.electricalSlots.set(t,this.sampleSlotsBySlot.length),this.sampleSlotsBySlot.push(n)}this.network=au(f,d),this.phase=`initialize`;for(let e of this.instances){this.current=e;let t;try{if(t=e.entry.create(e.context),td(t),typeof t!=`object`||!t||typeof t.sync!=`function`||typeof t.dispose!=`function`)throw TypeError(`Invalid device adapter`)}catch(t){throw this.wrap(t,`DEVICE_CALLBACK_FAILED`,`initialize`,e)}if(e.adapter=t,this.isFaulted)throw this.primary}this.current=void 0,this.phase=`idle`,Object.defineProperty(this,wd,{value:()=>this.observationReport(),enumerable:!1}),Object.defineProperty(this,Td,{value:()=>this.processReport(),enumerable:!1})}catch(e){let t=e instanceof Xu?e:this.wrap(e,`INVALID_CONFIGURATION`,`assembly`,this.current);this.primary=t;let n=this.cleanup();throw n.length?this.aggregate(t,n):t}}get isFaulted(){return this.status===`faulted`}observationReport(){return Object.freeze({plans:Object.freeze(this.plans.map(e=>Object.freeze({key:e.plan.key,path:Object.freeze([...e.plan.path]),receivers:e.members.length,slots:e.plan.slots.length,source:e.plan.source,comparison:e.plan.comparison}))),skipped:Object.freeze(this.skippedPlans.map(e=>Object.freeze({...e}))),reactions:Object.freeze(this.instances.flatMap(e=>e.reactions.map(t=>Object.freeze({instance:e.id,name:t.declaration.name,mode:t.synchronousProgram===void 0?`pending`:t.synchronousProgram===null?`generic`:t.synchronous!==void 0&&t.synchronous!==null?`sync`:`ready`,functions:t.synchronousProgram?.functions.length??0}))))})}processReport(){let e=[],t=[];for(let n of this.instances)for(let r of n.processes){let i=`${n.id}/${r.declaration.kind===`on`?r.declaration.name:`start`}`;(r.resumable?e:t).push(i)}return Object.freeze({resumable:Object.freeze(e),generic:Object.freeze(t),bindings:Object.freeze(this.instances.map(e=>e.bindingReport()))})}assertAlive(e){if(this.status===`disposed`||e&&!e.valid)throw this.error(`OBJECT_DISPOSED`,`Object is disposed`,e)}assertCallAllowed(e){this.admit(e,!1)}assertReadAllowed(e){this.admit(e,!0)}admit(e,t){if(this.assertAlive(e),e&&[`execute`,`translate`,`dispose`,`assembly`].includes(this.phase))throw this.error(`INVALID_CALL_STATE`,`Operation is not allowed in this phase`,e);if(!t&&this.status===`faulted`)throw this.error(`BOARD_FAULTED`,`Board is faulted`,e)}error(e,t,n,r,i){let a=r instanceof Rl?r:void 0;return new Xu(Object.freeze({code:e,message:t,phase:i??(this.phase===`idle`?`host`:this.phase),time:this.time,...a?.instanceId===void 0?n?{instanceId:n.id}:{}:{instanceId:a.instanceId},...a?.resource===void 0?{}:{resource:a.resource},...nd(r),...r===void 0?{}:{cause:r},related:Object.freeze([])}))}wrap(e,t,n,r){if(e instanceof Xu&&![`DEVICE_CALLBACK_FAILED`,`JIT_FAILED`,`CLEANUP_FAILED`].includes(t))return e;let i=e instanceof Rl||e instanceof $u||e instanceof Qu?e.code:void 0;return this.error(n!==`dispose`&&i?i:t,e instanceof Error?e.message:String(e),r,e,n)}fault(e){if(this.status===`ready`){this.status=`faulted`,this.primary=e,this.dispatchDepth++;try{this.errors.fire(e.diagnostic)}finally{this.dispatchDepth--}}}diagnostic(e,t,n){let r=this.error(e,t instanceof Error?t.message:String(t),n,t).diagnostic;this.dispatchDepth++;try{this.diagnostics.fire(r)}finally{this.dispatchDepth--}}fallback(e){try{console.error(e)}catch{}}report(e,t){this.status===`disposed`?this.fallback(t):e.valid?this.status===`faulted`?this.diagnostic(`REPORTED_ERROR`,t,e):this.fault(this.error(`REPORTED_ERROR`,t instanceof Error?t.message:String(t),e,t,`report`)):this.diagnostic(`STALE_REPORT`,t,e)}topicBridge(e){let t=Object.freeze({onDidReceive:((t,n,r)=>{this.assertCallAllowed(e);let i={...e?{owner:e}:{},call:e=>t.call(n,e)};this.listeners.add(i),e||this.hostListeners++;let a=!0,o={dispose:()=>{a&&(a=!1,this.listeners.delete(i)&&!e&&this.hostListeners--)}};return r?.push(o),e?.resources.push(o),o}),publish:(t,n)=>{if(this.assertCallAllowed(e),typeof t!=`string`)throw TypeError(`Topic must be a string`);this.dispatchDepth++;try{let e=Object.freeze({topic:t,payload:n});for(let t of[...this.listeners])if(!(t.owner&&this.status!==`ready`))try{let n=t.call(e);t.owner&&td(n)}catch(e){t.owner?this.fault(this.wrap(e,`DEVICE_CALLBACK_FAILED`,`topic`,t.owner)):this.diagnostic(`HOST_LISTENER_FAILED`,e)}}finally{this.dispatchDepth--}}});return ld(t,{assertPublishAllowed:()=>this.assertCallAllowed(e),hostListeners:()=>this.hostListeners}),t}enqueue(e){e.state===`idle`?(e.state=`queued`,this.models.push(e)):e.state!==`queued`&&(e.pending=!0)}queueJit(e){e.active&&!e.stopped&&!e.queued&&(e.queued=!0,this.readyJits.push(e))}canContinueDirect(e,t){return this.status===`ready`&&this.phase===`execute`&&!this.isFaulted&&this.execution===`throughput`&&this.jits.length===1&&this.jits[0]===e&&e.active&&!e.stopped&&!e.queued&&this.readyJits.length===0&&this.models.length===0&&this.waitingJits.size===0&&this.time<this.executionEnd&&t>=this.time&&t<this.executionEnd&&this.events.time>t}invalidate(e){if(e.version++,e.subscribers.size!==0)for(let t of e.subscribers)this.observations.add(t.order)}electricalSlot(e){return this.electricalSlots.get(e)}publish(){if(!this.electricalDirty)return;let e=this.network.solveSlots(this.dirtyElectricalSlots);this.dirtyElectricalSlots.clear(),this.electricalDirty=!1;for(let t=0;t<e.length;t++)this.invalidate(this.sampleSlotsBySlot[e[t]])}bindObservation(e,t){let n=e.instance;e.previous=n.observe(e,t),e.readSource=n.observationReader(e,t),e.order=this.observations.register(e)}baseline(){this.publish();let e=[];for(let t of this.instances){let n=`${t.id}\\0`;for(let r of t.processes)r.source&&t.declarations.get(r.source[0])?.kind!==`notification`&&e.push({observation:r,path:r.source,key:n+r.source.join(`\\0`),instance:t});for(let r of t.reactions){let i=r.declaration.sourcePath;e.push({observation:r,path:i,key:n+i.join(`\\0`),instance:t})}}let t=/* @__PURE__ */ new Map;for(let n of e){if(t.has(n.key))continue;let e=Ru(n.instance,n.key,n.path);if(!e.ok){this.skippedPlans.push({key:n.key,reason:e.reason}),t.set(n.key,void 0);continue}let r={plan:e.plan,instance:n.instance,members:[],dependencies:/* @__PURE__ */ new Map,entry:{dependencies:/* @__PURE__ */ new Map,value:void 0},order:0,previous:void 0,bound:!1};t.set(n.key,r),this.plans.push(r)}for(let n of e){let e=t.get(n.key);e===void 0?this.bindObservation(n.observation,n.path):(e.bound?n.observation.order=this.observations.register(Ed):(e.bound=!0,e.order=this.observations.register(e),n.observation.order=e.order,this.bindChain(e)),e.members.push(n.observation),n.observation.previous=e.previous)}}bindChain(e){let t=e.instance;for(let n of e.plan.slots)n.subscribers.size||t.observerRevision++,n.subscribers.add(e);let n=e.plan.evaluate();e.previous=e.plan.needsSnapshot?gu(n):n,this.commitChain(e,n)}commitChain(e,t){let n=e.plan.path;if(n.length!==1)return;for(let t of e.plan.slots)e.dependencies.set(t,t.version);let r=e.entry;r.value!==t&&(r.value=t),r.dependencies=e.dependencies,e.instance.derived.get(n[0])!==r&&e.instance.derived.set(n[0],r)}collectChain(e){let t=e.plan.evaluate(),n=e.plan.needsSnapshot?gu(t):t;if(this.commitChain(e,t),e.plan.equals(e.previous,n))return;let r=e.previous;e.previous=n;let i=e.members,a=i[0];if(i.length===1&&!this.changeObservations.length)a.previous=n,this.applyChange(a,r,n);else for(let e of i)e.previous=n,this.recordChange(e,r,n)}applyChange(e,t,n){if(e.declaration.kind===`reaction`){let r=e,i=r.frame;i===void 0?r.frame={previous:t,current:n,captures:[]}:(i.previous=t,i.current=n,i.captures.length=0),this.reactionBatch.push(r)}else this.enqueue(e)}recordChange(e,t,n){this.insertOrderedChange(this.changeObservations,this.changePrevious,this.changeCurrent,e,t,n)}insertOrderedChange(e,t,n,r,i,a){let o=e.length,s=r.order;for(;o>0&&e[o-1].order>s;)o--;o===e.length?(e.push(r),t.push(i),n.push(a)):(e.splice(o,0,r),t.splice(o,0,i),n.splice(o,0,a))}boundary(){for(;;){if(this.publish(),!this.observations.size)return;let e=this.reactionBatch;e.length=0;let t=this.changeObservations;t.length=0,this.changePrevious.length=0,this.changeCurrent.length=0;let n=this.observations.take();for(let e=0;e<n.length;e++){let r=n[e];if(`plan`in r){this.collectChain(r);continue}let i=r.readSource();if(hu(r.previous,i))continue;let a=r.previous;r.previous=i,t.length?this.recordChange(r,a,i):this.applyChange(r,a,i)}let r=t.length;if(r){for(let e=0;e<r;e++)this.applyChange(t[e],this.changePrevious[e],this.changeCurrent[e]);t.length=0,this.changePrevious.length=0,this.changeCurrent.length=0}if(e.length)this.runBoundaryReactions(e);else return}}runBoundaryReactions(e){try{for(let t of e)if(t.declaration.captures.length){let e=t.frame;e.captures=t.declaration.captures.map(e=>gu(Yu(e.value,t.instance.host)))}for(let t of e)this.current=t.instance,this.runReaction(t)}finally{this.clearReactionFrames(e)}}clearReactionFrames(e){for(let t of e){let e=t.frame;e!==void 0&&(e.previous=void 0,e.current=void 0,e.captures.length=0)}}runReaction(e){let t=e.instance,n=e.synchronousProgram;if(n===void 0&&(n=Ku(t,e.declaration.body)??null,e.synchronousProgram=n),n!==null){let r=e.synchronous;r??(r=n.bind(t.host),e.synchronous=r),r(void 0,e.frame)}else if(e.execute??=Gu(e.declaration.body),!e.execute(t.host,[],e.frame).next().done)throw TypeError(`Reaction cannot suspend`)}drive(e,t){let n=e.resumable;if(n)this.driveResumable(e,n,t);else for(this.current=e.instance,e.state=`running`,e.execution??=Gu(e.declaration.body)(e.instance.host);;){let n=e.execution.next(t);if(n.done){this.boundary(),e.execution=void 0,e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}let r=n.value;if(r.kind===`receive`){let n=e.instance.channels.get(r.channel);if(n.incoming.length){t=n.incoming.shift().value;continue}e.state=`waiting`,n.receiver=e,this.boundary();return}if(r.kind!==`ticks`)throw TypeError(`Invalid process suspension`);let i=Wu(r.duration),a=Wu(this.time+i);e.state=`waiting`,this.boundary(),i===0?(e.state=`queued`,this.models.push(e)):(e.wake??=()=>{e.state=`queued`,this.models.push(e)},this.events.push(a,e.wake));return}}driveResumable(e,t,n){this.current=e.instance,e.state=`running`;let r=e.frame??=Ju(t),i=n;for(;;){if(r.value=i,!t.run(e.instance.host,void 0,void 0,r)){this.boundary(),e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}if(r.kind===2){let t=e.instance.channels.get(r.channel);if(t.incoming.length){i=t.incoming.shift().value;continue}e.state=`waiting`,t.receiver=e,this.boundary();return}let n=r.duration,a=Wu(this.time+n);e.state=`waiting`,this.boundary(),n===0?(e.state=`queued`,this.models.push(e)):(e.wake??=()=>{e.state=`queued`,this.models.push(e)},this.events.push(a,e.wake));return}}runUntil(e){if(this.assertAlive(),this.phase!==`idle`||this.dispatchDepth)throw this.error(`INVALID_CALL_STATE`,`Board is busy`);if(this.status===`faulted`)throw this.error(`BOARD_FAULTED`,`Board is faulted`);let t=Wu(e);if(t<this.time)throw RangeError(`Cannot run backwards`);let n=this.time;this.phase=`execute`,this.executionEnd=t;try{if(!this.initialized){this.baseline(),this.initialized=!0;for(let e of this.instances)for(let t of e.processes)t.declaration.kind===`start`&&this.enqueue(t);for(let e of this.jits)this.queueJit(e)}for(let e of this.instances){for(let t of e.channels.values()){if(t.pending.length)for(let e of t.pending.drain())t.incoming.push(e);if(t.receiver&&t.incoming.length){let e=t.receiver;t.receiver=void 0;let n=t.incoming.shift().value;this.events.push(this.time,()=>{e.state=`queued`,e.resumeValue=n,this.models.push(e)})}}for(let t of e.notificationInputs)for(let n of e.processes)n.source?.[0]===t&&this.enqueue(n);e.notificationInputs.clear()}for(;;){for(;this.events.time===this.time;)this.events.pop()();if(this.models.length){let e=this.models.shift(),t=e.resumeValue;if(e.resumeValue=void 0,this.drive(e,t),this.isFaulted)throw this.primary;continue}let e=1/0;if(this.waitingJits.size)for(let n=0;n<this.jits.length;n++){let r=this.jits[n];if(r.active&&!r.stopped&&this.waitingJits.has(r)){if(r.instance.dependenciesCurrent(r.dependencies)){if(r.pollingWait&&r.pollingPeriod>0){let n=Uu-(Uu-r.pollingOrigin)%r.pollingPeriod;n<72e14&&n<t&&(n===this.time?(r.pollingWait=!1,r.pollingToken++,delete r.dependencies,this.waitingJits.delete(r),this.queueJit(r)):e=Math.min(e,n))}}else if(r.pollingWait){r.pollingWait=!1,r.pollingToken++,delete r.dependencies,this.waitingJits.delete(r);let e=r.pollingPeriod>0?(this.time-r.pollingOrigin)%r.pollingPeriod:0;e?this.events.push(Wu(this.time+(r.pollingPeriod-e)),()=>this.queueJit(r)):this.queueJit(r)}else if(r.predicate){let e=r.instance.evaluate(()=>r.instance.syncCall(r.predicate));r.dependencies=e.dependencies,e.value===!0&&(delete r.predicate,delete r.dependencies,this.waitingJits.delete(r),this.queueJit(r))}}}if(this.time<t&&this.readyJits.length){if(Cd(this,this.readyJits.shift()),this.isFaulted)throw this.primary}else if(e<this.events.time&&e<=t)this.time=e;else if(this.events.time<=t)this.time=this.events.time;else{this.time=t;break}}let e=this.instances.map(e=>e.captureBatch(n,t));this.phase=`sync`;for(let t=0;t<this.instances.length;t++){let n=this.instances[t];this.current=n;try{td(n.adapter.sync(e[t]))}catch(e){throw this.wrap(e,`DEVICE_CALLBACK_FAILED`,`sync`,n)}if(this.isFaulted)throw this.primary}}catch(e){let t=this.wrap(e,`MODEL_EXECUTION_FAILED`,this.phase===`sync`?`sync`:`execute`,this.current);throw this.fault(t),t}finally{this.current=void 0,this.phase=`idle`}}dispose(){if(this.status===`disposed`)return;if(this.phase!==`idle`||this.dispatchDepth)throw this.error(`INVALID_CALL_STATE`,`Board is busy`);let e=this.cleanup();if(e.length)throw this.primary?this.aggregate(this.primary,e):this.aggregate(e[0],e.slice(1))}aggregate(e,t){return new Xu(Object.freeze({...e.diagnostic,related:Object.freeze([...e.related,...t.map(e=>e.diagnostic)])}))}cleanup(){this.phase=`dispose`;for(let e of this.instances)e.valid=!1;let e=[];for(let t of[...this.instances].reverse()){if(t.adapter)try{td(t.adapter.dispose())}catch(n){e.push(this.wrap(n,`CLEANUP_FAILED`,`dispose`,t))}for(let n of[...t.resources].reverse())try{n.dispose()}catch(n){e.push(this.wrap(n,`CLEANUP_FAILED`,`dispose`,t))}t.resources.length=0}return this.events.clear(),this.models.clear(),this.readyJits.clear(),this.observations.clear(),this.reactionBatch.length=0,this.plans.length=0,this.skippedPlans.length=0,this.changeObservations.length=0,this.changePrevious.length=0,this.changeCurrent.length=0,this.sampleSlots.clear(),this.listeners.clear(),this.hostListeners=0,this.errors.dispose(),this.diagnostics.dispose(),this.status=`disposed`,this.phase=`idle`,e}};function Ad(e,t,n){let r=Dd.get(e);if(!r)throw rd(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Unknown device library`),`assembly`);if(arguments.length>=3&&n===void 0)throw rd(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Explicit undefined options`),`assembly`);return new kd(r,t,n??{})}var $=class extends Error{code;instanceId;constructor(e,t,n){super(t),this.name=`FusedRuntimeError`,this.code=e,n!==void 0&&(this.instanceId=n)}};let jd=`model/disconnected`;var Md=class{board;#e=/* @__PURE__ */ new Map;constructor(e,t){let n=/* @__PURE__ */ new Map;for(let r of e.instances){let i=e.devices.get(r.deviceId),a=i?.package.manifest.model;if(i?.model===void 0||a===void 0)continue;let o=new Pn({instanceId:r.instanceId,methods:a.methods??{},events:a.events??{},types:a.types??{},props:r.props,factory:i.model.create,report:t.report,blocked:t.blocked,now:t.now,...t.observer===void 0?{}:{observer:t.observer}});this.#e.set(r.instanceId,o);let s=n.get(r.deviceId);s===void 0?n.set(r.deviceId,[o]):s.push(o)}let r=[];for(let[t,i]of e.devices)i.model!==void 0&&r.push({id:t,model:i.model.ir,create:e=>{let r=n.get(t)?.shift();if(r===void 0)throw Error(`Unexpected model factory call for \"${t}\"`);return r.create(e)}});let i={instances:e.instances.map(e=>({id:e.instanceId,type:e.deviceId,props:{...e.boardProps}})),nets:e.nets.map(e=>({id:e.id,pins:e.pins.map(e=>({instance:e.instance,pin:e.pin})),...e.voltage===void 0?{}:{voltage:e.voltage}}))};this.board=Ad(Od(r),i)}binding(e){return this.#e.get(e)}invalidate(){for(let e of this.#e.values())e.invalidate();this.#e.clear()}},Nd=class{#e;#t;#n;#r;#i=new i;#a=new i;#o=[];#s=`paused`;#c;#l=!1;#u;#d=!1;onDidChangeState=this.#i.event;onDidReportDiagnostic=this.#a.event;constructor(e,t,n){this.#e=e,this.#t=n,this.#n=t.onModelEvent,this.#r=t.onDiagnostic,this.#c=this.#f()}getState(){let e=n(this.#c?.board.time??0);return Object.freeze({status:this.#s,simTime:e})}getModel(e){if(this.#s===`disposed`)throw new $(jd,`The runtime is disposed; no model client is available.`,e);let t=this.#c?.binding(e);if(t===void 0)throw new $(`model/unknown-instance`,`No live model for instance \"${e}\"; modeled instance ids are declared by the document.`,e);return t.client((e,n)=>this.#h(t,e,n))}async step(){if(this.#p(`step`),this.#s===`running`)throw new $(`runtime/unavailable-state`,`step requires the paused state; pause the runtime first.`);await this.#T(()=>this.#m())}async resume(){this.#p(`resume`),this.#s!==`running`&&(this.#C(`running`),await this.#T(()=>{this.#s===`running`&&this.#m()}))}pause(){this.#s===`running`&&this.#C(`paused`)}async reset(){if(this.#s===`disposed`)throw new $(`runtime/unavailable-state`,`The runtime is disposed.`);this.#C(`paused`),await this.#O();let e=this.#c;if(this.#c=void 0,e!==void 0){let t;try{e.board.dispose()}catch(e){t=new $(`runtime/model-failed`,`Board cleanup failed during reset: ${Ld(e)}`,e instanceof Xu?e.diagnostic.instanceId:void 0)}finally{e.invalidate()}if(t!==void 0)throw this.#b(t,!0),t}this.#c=this.#f(),this.#w()}async dispose(){if(this.#s===`disposed`)return;this.#C(`disposed`),await this.#O();let e=this.#c;this.#c=void 0;let t=[];if(e!==void 0){try{e.board.dispose()}catch(e){let n=Pd(e);t.push(bn(n?.code??`runtime/model-failed`,`Board cleanup failed: ${Ld(e)}`))}e.invalidate()}this.#i.dispose(),this.#a.dispose();for(let e of t)this.#r?.(e);if(t.length>0)throw new $(t[0].code,t.map(e=>e.message).join(`; `))}#f(){this.#d=!0;try{return new Md(this.#e,{report:e=>this.#x(e),blocked:()=>this.#d&&(this.#s===`paused`||this.#s===`running`)?void 0:`model input is only allowed during initialization, method calls, sync and advance`,now:()=>n(this.#c?.board.time??0),...this.#n===void 0?{}:{observer:this.#n}})}finally{this.#d=!1}}#p(e){if(this.#s===`disposed`)throw new $(`runtime/unavailable-state`,`${e} is not allowed after dispose.`);if(this.#s===`faulted`)throw new $(`runtime/model-failed`,`${e} is not allowed while the runtime is faulted; call reset first.`)}#m(){let e=this.#c;if(e===void 0)throw new $(`runtime/unavailable-state`,`No session is prepared.`);let t=e.board.time,n=t+this.#t;if(n>72e14){let e=new $(`runtime/invalid-time`,`Advancing ${this.#t} ps from ${t} ps exceeds the supported simulation time range.`);throw this.#x(bn(e.code,e.message)),this.#s===`running`&&this.#C(`paused`),e}this.#d=!0;try{e.board.runUntil(n)}catch(e){throw this.#y(e)}finally{this.#d=!1}this.#w()}#h(e,t,n){if(!e.live)return Promise.reject(new Mn);let r;try{r=e.prepareParams(t,n)}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return this.#s===`disposed`?Promise.reject(new $(jd,`The runtime is disposed.`,e.instanceId)):this.#T(()=>this.#g(e,t,r))}#g(e,t,n){if(!e.live)throw new Mn;if(this.#s===`faulted`)throw new $(`runtime/model-failed`,`The runtime is faulted; method calls are rejected until reset.`,e.instanceId);this.#d=!0;try{let r=e.invoke(t,n);return e.captureResult(t,r)}catch(n){throw this.#_(e,t,n)}finally{this.#d=!1}}#_(e,t,n){if(yn(n))return this.#v(e,t,n);if(n instanceof Mn||n instanceof $)return n;if(n instanceof B){let t=new $(n.code,n.message,e.instanceId);return this.#b(t,!1),t}let r=new $(`model/execution-failed`,`Method \"${t}\" failed: ${Ld(n)}`,e.instanceId);return this.#b(r,!0),r}#v(e,t,n){let r=n.details;if(r===void 0)return new vn(n.code,n.message);try{return new vn(n.code,n.message,Dn(r))}catch(r){return this.#x(bn(`model/invalid-result`,`Details of the rejection \"${n.code}\" of method \"${t}\" are not a model value: ${Ld(r)}`,e.instanceId)),new vn(n.code,n.message)}}#y(e){let t=Pd(e),n=e instanceof Xu?e.diagnostic:void 0,r=n?.instanceId,i=new $(`runtime/model-failed`,n===void 0?Ld(e):`${n.code} at ${String(n.time)} ps: ${n.message}`,r);return this.#b(i,t===void 0),i}#b(e,t){t&&this.#x(bn(e.code,e.message,e.instanceId)),(this.#s===`running`||this.#s===`paused`)&&this.#C(`faulted`)}#x(e){let t=this.#r;if(t!==void 0)try{t(e)}catch(e){this.#S(`the onDiagnostic sink`,e)}try{this.#a.fire(e)}catch(n){let r=bn(`runtime/presentation-failed`,`A diagnostic listener failed: ${Ld(n)}`,e.instanceId);if(t===void 0){this.#S(`a diagnostic listener`,n);return}try{t(r)}catch(e){this.#S(`the onDiagnostic sink`,e)}}}#S(e,t){try{console.error(`[mica fused] ${e} failed:`,t)}catch{}}#C(e){this.#s!==e&&(this.#s=e,this.#w())}#w(){let e=this.getState();try{this.#i.fire(e)}catch(e){this.#x(bn(`runtime/presentation-failed`,`A state listener failed: ${Ld(e)}`))}}#T(e){return this.#s===`disposed`?Promise.reject(new $(jd,`The runtime is disposed.`)):new Promise((t,n)=>{this.#o.push(()=>{try{t(e())}catch(e){n(e instanceof Error?e:Error(String(e)))}}),this.#E()})}#E(){if(this.#l||this.#s===`disposed`)return;this.#l=!0;let e=()=>{};this.#u=new Promise(t=>{e=t});let t=e;this.#D(t)}async#D(e){try{for(;;){let e=this.#o.shift();if(e!==void 0)e(),await Fd();else{if(this.#s!==`running`||this.#c===void 0)break;try{this.#m()}catch{if(this.#s!==`running`)break}await Id()}}}finally{this.#l=!1,this.#u=void 0,e()}}async#O(){for(;this.#l;){let e=this.#u;if(e===void 0)break;await e}}};function Pd(e){if(e instanceof B)return e;if(e instanceof Xu)return Pd(e.diagnostic.cause)}function Fd(){return new Promise(e=>{queueMicrotask(e)})}function Id(){return new Promise(e=>{setTimeout(e,0)})}function Ld(e){return e instanceof Error?e.message:String(e)}async function Rd(e){if(typeof e!=`object`||!e)throw TypeError(`createHeadlessRuntime expects an options object`);if(typeof e.loadModule!=`function`)throw TypeError(`options.loadModule must be a function`);if(e.registry===null||typeof e.registry?.open!=`function`)throw TypeError(`options.registry must open locked device packages`);let t;try{t=n(e.step)}catch(t){let n=bn(`runtime/invalid-time`,Ld(t));throw e.onDiagnostic?.(n),new $(n.code,n.message)}if(t<=0){let t=bn(`runtime/invalid-time`,`options.step must be a positive TimePs value`);throw e.onDiagnostic?.(t),new $(t.code,t.message)}return new Nd(await us({document:e.document,registry:e.registry,loadModule:e.loadModule,hostApiVersion:ta,...e.resolveResource===void 0?{}:{resolveResource:e.resolveResource},...e.programs===void 0?{}:{programs:e.programs},...e.onDiagnostic===void 0?{}:{onDiagnostic:e.onDiagnostic}}),e,t)}let zd=f(`fused-simulation`);f(`fused-display`);let Bd=f(`fused-host-package`),Vd=f(`fused-host-resource`),Hd=f(`fused-model-channel`),Ud=f(`fused-model-sink`);f(`fused-host-audio`);var Wd=class extends Error{code;instanceId;details;constructor(e,t,n={}){super(t),this.name=n.name??`FusedBridgeError`,this.code=e,this.instanceId=n.instanceId,this.details=n.details}};function Gd(e){let t=Jd(e);return Object.assign(Error(JSON.stringify(t)),{name:`FusedSandboxFailure`})}function Kd(e,t){if(e!==`prepare`)return[];let n=t?.instances??[],r=/* @__PURE__ */ new Set;for(let e of n)for(let t of Object.values(e.props))qd(t,r);return[...r]}function qd(e,t){if(e instanceof Uint8Array){e.buffer instanceof ArrayBuffer&&t.add(e.buffer);return}let n=e;if(typeof n==`object`&&n){if(n.kind===`filesystem`)for(let e of n.files)qd(e.data,t);else if(n.kind===`firmware`)for(let e of n.segments)e.bytes instanceof Uint8Array&&e.bytes.buffer instanceof ArrayBuffer&&t.add(e.bytes.buffer)}}function Jd(e){let t=$d(e),n=Zd(e);if(n!==void 0)return{kind:`method`,code:n.code,message:n.message,...n.details===void 0?{}:{details:Qd(n.details)}};let r=Yd(e),i=Xd(e);return{kind:r===`Error`?`failure`:`runtime`,code:r,message:t,...i===void 0?{}:{instanceId:i}}}function Yd(e){if(typeof e!=`object`||!e)return`Error`;let t=e.code;if(typeof t==`string`&&t.length>0)return t;let n=e.name;return typeof n==`string`&&n.length>0?n:`Error`}function Xd(e){if(typeof e!=`object`||!e)return;let t=e.instanceId;return typeof t==`string`?t:void 0}function Zd(e){if(typeof e!=`object`||!e)return;let t=e;if(t.name===`MethodError`&&typeof t.code==`string`&&typeof t.message==`string`)return{code:t.code,message:t.message,...t.details===void 0?{}:{details:t.details}}}function Qd(e){if(e instanceof Uint8Array)return[...e];if(Array.isArray(e))return e.map(e=>Qd(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[n]=Qd(r);return t}return e}function $d(e){return e instanceof Error?e.message:String(e)}function ef(e,t){let n={};for(let[r,i]of Object.entries(t)){if(!Object.hasOwn(e,r))throw rf(r,i.type,`has no resolved value`);let t=e[r];if(t===void 0)throw rf(r,i.type,`resolved to undefined`);switch(i.type){case`string`:case`color`:case`enum`:if(typeof t==`string`){n[r]=t;continue}break;case`integer`:case`number`:if(typeof t==`number`){n[r]=t;continue}break;case`boolean`:if(typeof t==`boolean`){n[r]=t;continue}break;case`image`:case`binary`:if(t===null){n[r]=null;continue}n[r]=tf(r,i.type,t);continue;case`firmware`:if(t===null){n[r]=null;continue}n[r]=nf(r,t);continue;case`program`:if(t===null&&i.nullable===!0){n[r]=null;continue}if(i.loader===`memory`)n[r]=nf(r,t);else{let e=t;if(!e||!Array.isArray(e.paths)||typeof e.read!=`function`)throw rf(r,`program`,`is not a file snapshot`);n[r]=Object.freeze({kind:`filesystem`,files:Object.freeze(e.paths.map(t=>Object.freeze({path:t,data:tf(r,`program`,e.read(t))})))})}continue}if(t===null&&i.nullable===!0)n[r]=null;else throw rf(r,i.type,`resolved to ${af(t)}`)}return Object.freeze(n)}function tf(e,t,n){if(n instanceof Uint8Array)return n.slice();let r=n;if(typeof r==`object`&&r&&typeof r.slice==`function`){let e=r.slice.call(r);if(e instanceof Uint8Array)return e}throw rf(e,t,`is not a byte snapshot`)}function nf(e,t){let n=t?.segments;if(!Array.isArray(n))throw rf(e,`firmware`,`is not a firmware image`);let r=[];for(let t of n){let n=t;if(typeof n.addressSpace!=`string`||typeof n.address!=`number`)throw rf(e,`firmware`,`has a segment without an address space or address`);r.push({addressSpace:n.addressSpace,address:n.address,bytes:tf(e,`firmware`,n.data)})}return Object.freeze({kind:`firmware`,segments:Object.freeze(r)})}function rf(e,t,n){return new Wd(`runtime/presentation-failed`,`Property \"${e}\" (${t}) ${n}; the presentation cannot receive a partial snapshot.`)}function af(e){return e===null?`null`:Array.isArray(e)?`an array`:`a value of type ${typeof e}`}function of(e){let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}function sf(e){return new TextDecoder().decode(e).replace(/^\\uFEFF/,``)}function cf(e){return`${e.id}@${e.version}#${e.integrity}`}function lf(e){let t=e.getProxy(Bd),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>{let r=cf(e),i=n.get(r);return i===void 0&&(i=t.open(e),n.set(r,i)),i};return{open(e){return i(e).then(n=>({lock:n.lock,files:n.files,read:async n=>{let i=`${cf(e)}\\u0000${n}`,a=r.get(i);if(a!==void 0)return a.slice();let o=await t.read(e,n);if(!(o instanceof Uint8Array))throw new Wd(`package/not-found`,`The host returned no bytes for ${e.id}/${n}.`);return r.set(i,o),o.slice()}}))}}}function uf(e,t){return`${e}\\u0000${t}`}function df(e,t,n=c){let r=n(e),i=r.getProxy(Ud),a=/* @__PURE__ */ new Set;return r.register(Hd,{call:t.call,subscribe(e,t){a.add(uf(e,t))},unsubscribe(e,t){a.delete(uf(e,t))},settle:()=>void 0}),{deliver(e){a.has(uf(e.instanceId,e.event))&&i.deliver(e).catch(()=>void 0)},reset(){a.clear()},dispose(){a.clear(),r.dispose()}}}let ff=Object.freeze({status:`idle`,simTime:n(0)});function pf(e,t={}){let n=(t.createEndpoint??c)(e),r=t.importModule??of,a=lf(n),o=hf(n),s=new i,l=new i,u=new i,d=t.ports?.[0],f=d===void 0?void 0:df(d,{call:(e,t,n)=>re(e,t,n)}),p=ff,m,h,g=0,_=!1,v;return n.register(zd,{prepare:te,load:w,step:T,resume:E,pause:D,reset:ne,dispose:ie,call:(e,t,n)=>re(e,t,n),getState:()=>p,onDidChangeState(e){let t=l.event(t=>e(t));return()=>t.dispose()},onDidReportDiagnostic(e){let t=s.event(t=>e(t));return()=>t.dispose()},onDidModelEvent(e){let t=u.event(t=>e(t));return()=>t.dispose()}},{transfer:Kd}),{rpc:n,dispose:ce};function y(e){s.fire(e)}function b(e){(e.status!==p.status||e.simTime!==p.simTime)&&(p=e,l.fire(e))}function x(){if(_)throw Gd(new Wd(`runtime/unavailable-state`,`The fused simulation guest is disposed.`))}function ee(e){if(x(),m===void 0)throw Gd(new Wd(`runtime/unavailable-state`,`${e} requires mounted models; prepare a run session first.`));return m}async function te(e){x();let t=Rt(e.document),n=[],r=[];for(let[e,i]of t.instances.entries())try{let n=await S(e,t,i);n!==void 0&&r.push(n)}catch(e){if(e instanceof Wd&&e.code===`runtime/presentation-failed`){y({code:e.code,message:e.message,instanceId:i.id});continue}n.push({code:`runtime/prepare-failed`,message:`${i.id}: ${$d(e)}`,instanceId:i.id})}for(let e of n)y(e);if(n.length>0)throw Gd(new Wd(`runtime/prepare-failed`,`${n.length} instance(s) cannot join the 2D scene.`));return{instances:r}}async function S(e,t,n){let r=t.dependencies[n.device];if(r===void 0)throw new Wd(`document/unlocked-device`,`Instance \"${n.id}\" uses the unlocked device \"${n.device}\".`,{instanceId:n.id});let i={id:n.device,version:r.version,integrity:r.integrity},o=await aa(a,i),s=o.manifest.view2d;if(s===void 0){y({code:`view2d/unsupported`,message:`${n.device} declares no 2D geometry; \"${n.id}\" stays out of the 2D scene.`,instanceId:n.id});return}let c=Object.keys(o.manifest.pins??{}),l=typeof s.geometry==`string`?_e(sf(await o.read(s.geometry))):s.geometry,u=o.manifest.properties??{};return{instanceId:n.id,device:n.device,lock:i,geometry:Oe(l,c),view:s.entry,props:ef(await C(o,u,n,e),u),methods:Object.keys(o.manifest.model?.methods??{}),events:Object.keys(o.manifest.model?.events??{})}}async function C(e,t,n,r){try{return(await va({instanceId:n.id,package:e,descriptors:t,overrides:n.properties??{},irProperties:/* @__PURE__ */ new Map,pointer:[`instances`,String(r),`properties`],resolveResource:o.resolveResource,programs:o.programs})).props}catch(e){throw new Wd(`runtime/presentation-failed`,`Presentation properties of \"${n.id}\" cannot be resolved: ${gf(e,t)}`,{instanceId:n.id})}}async function w(e){x();let t=e.step;if(!Number.isSafeInteger(t)||t<=0)throw Gd(new Wd(`runtime/invalid-time`,`\\`step\\` must be a positive integer number of picoseconds, received ${String(t)}.`));let n=Rt(e.document),r=++g,i={},s=()=>_||r!==g,c=[],l;try{l=await Rd({document:n,registry:a,loadModule:se,step:t,resolveResource:o.resolveResource,programs:o.programs,onModelEvent:e=>{h===i?O(e):s()||c.push(e)},onDiagnostic:e=>{s()||y(e)}})}catch(e){if(e instanceof xn)for(let t of e.diagnostics)y(t);throw Gd(e)}if(s())return await l.dispose().catch(()=>void 0),p;let u=m;m=void 0,h=void 0,u!==void 0&&await oe(u,!1),h=i,m={runtime:l,subscriptions:[l.onDidChangeState(e=>{h===i&&b({status:e.status,simTime:e.simTime})}),l.onDidReportDiagnostic(e=>{h===i&&y(e)})]};for(let e of c.splice(0))O(e);let d=l.getState();return b({status:d.status,simTime:d.simTime}),p}async function T(){let e=ee(`step`);return await mf(()=>e.runtime.step()),p}async function E(){let e=ee(`resume`);await mf(()=>e.runtime.resume())}function D(){m?.runtime.pause()}async function ne(){let e=ee(`reset`);await mf(()=>e.runtime.reset())}async function re(e,t,n){let r=m;if(_||r===void 0)throw Gd(new Wd(`model/disconnected`,`No model is mounted; prepare a run session first.`,{instanceId:e}));try{let i=r.runtime.getModel(e).methods[t];if(i===void 0)throw new Wd(`model/unknown-method`,`The model of \"${e}\" declares no method \"${t}\".`,{instanceId:e});return await i(n)}catch(e){throw Gd(e)}}async function ie(){x(),await ae(!0)}async function ae(e){let t=m;m=void 0,h=void 0,g+=1,f?.reset(),b(ff),t!==void 0&&await oe(t,e)}async function oe(e,t){for(let t of e.subscriptions.splice(0))t.dispose();try{await e.runtime.dispose()}catch(e){if(y({code:`runtime/model-failed`,message:`Releasing the models failed: ${$d(e)}`}),t)throw Gd(e)}}function O(e){let t={instanceId:e.instanceId,event:e.event,payload:e.payload};f?.deliver(t),u.fire(t)}async function se(e,t){return r(sf(await e.read(t)))}function ce(){return v===void 0&&(_=!0,v=(async()=>{g+=1,f?.dispose();let e=m;m=void 0,h=void 0;let t=[];if(e!==void 0)try{await oe(e,!0)}catch(e){t.push(e)}if(n.dispose(),s.dispose(),l.dispose(),u.dispose(),t.length>0)throw t[0]})()),v}}async function mf(e){try{return await e()}catch(e){throw Gd(e)}}function hf(e){let t=e.getProxy(Vd),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>e.map(e=>({path:e.path,data:e.data.slice()})),a=e=>e.kind===`memory`?{...e,data:e.data.slice()}:{kind:`filesystem`,files:i(e.files)};return{programs:{projects:{resolve:async(e,n)=>{let i=JSON.stringify([n.deviceId,n.property,n.loader,e]),o=r.get(i);return o||(o=await t.resolveProgramProject(e,n),r.set(i,a(o))),a(o)}}},resolveResource:async e=>{let r=`${e.instanceId}\\u0000${e.property}`,i=n.get(r);if(i!==void 0)return i.slice();let a=await t.readResource(e);return n.set(r,a.slice()),a}}}function gf(e,t){return e instanceof R?e.problems.map(e=>{let n=_f(e.pointer,t),r=e.pointer===``?``:` at ${e.pointer}`;return`${e.code}${r}${n===void 0?``:` (${n})`}: ${e.message}`}).join(`; `):$d(e)}function _f(e,t){let n=e.split(`/`),r=n.indexOf(`properties`),i=r<0?void 0:n[r+1];if(i===void 0)return;let a=t[i]?.type;return a===void 0?`property \"${i}\"`:`property \"${i}\", type ${a}`}let vf=!1;self.addEventListener(`message`,e=>{if(vf)return;let t=e.ports[0];t!==void 0&&(vf=!0,pf(t,{ports:e.ports.slice(1)}))})})();", options);
|
|
13
|
-
}
|
|
14
|
-
};
|
|
15
|
-
//#endregion
|
|
16
|
-
//#region src/fused/runtime/workers.ts
|
|
17
|
-
var fusedWorkerFactories = {
|
|
18
|
-
createSimulationWorker(options = {}) {
|
|
19
|
-
return new EntrySandbox({
|
|
20
|
-
name: "fused-simulation",
|
|
21
|
-
...options
|
|
22
|
-
});
|
|
23
|
-
},
|
|
24
|
-
createDisplayWorker(options = {}) {
|
|
25
|
-
return new EntrySandbox$1({
|
|
26
|
-
name: "fused-display",
|
|
27
|
-
...options
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
//#endregion
|
|
32
|
-
export { fusedWorkerFactories };
|
|
33
|
-
|
|
34
|
-
//# sourceMappingURL=workers-BsocIPUc.js.map
|