@mica-js/simulator 2.7.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/device.d.ts +11 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +2390 -1902
- package/dist/index.js.map +1 -1
- package/dist/sandbox.js +1 -1
- package/package.json +2 -2
package/dist/sandbox.js
CHANGED
|
@@ -3,7 +3,7 @@ import { toDisposable } from "@mica-js/core/lifecycle";
|
|
|
3
3
|
import { createRpc } from "@mica-js/core/rpc";
|
|
4
4
|
import { SandboxWorker } from "@mica-js/sandbox";
|
|
5
5
|
//#region \0mica-sandbox-worker-code:/home/runner/work/mica-js/mica-js/packages/simulator/src/guest/simulation-runtime.ts
|
|
6
|
-
var simulation_runtime_default = "(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 ee(){if(b)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function te(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function S(e,t){ee(),a.postMessage(e,t?[...t]: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((i,a)=>{let s=t>0?setTimeout(()=>{C(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{S(e,n)}catch(t){C(e.id)?.reject(o(t))}})}function ne(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function T(e,t,n){if(b)return;let r=o(n);try{S({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),re()}}function E(){if(!b){b=!0,a.removeEventListener(`message`,ie),a.removeEventListener(`close`,E),a.removeEventListener(`messageerror`,re);for(let e of p.keys())C(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())ne(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function re(){if(!b){try{S({kind:`close`})}catch(e){x(e)}E()}}async function D(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{S({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){ne(e.id),T(`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||S({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||S({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&ne(e.id),T(`error`,e.id,t)}}function ie(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,D(t);break;case`unlisten`:ne(t.id);break;case`result`:C(t.id)?.resolve(t.value);break;case`error`:C(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=C(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`:E()}}return a.addEventListener(`message`,ie),a.addEventListener(`close`,E),a.addEventListener(`messageerror`,re),a.start?.(),{register(t,n,i={}){ee();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&&(ne(e),T(`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(ee(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=te();m.set(n,t),w({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!b)try{S({kind:`unlisten`,id:n})}catch(e){x(e)}x(e)});let a=e(()=>{if(m.delete(n)&&(C(n)?.resolve(void 0),!b))try{S({kind:`unlisten`,id:n})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(ee(),w({kind:`call`,id:te(),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:re}}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}function u(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 d(e,t=`value`){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`${t} must be finite`);return e}function f(e,t=`value`){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`${t} must be a safe integer`);return e}function p(e,t=`value`){let n=f(e,t);if(n<0)throw RangeError(`${t} must be nonnegative`);return n}function m(e){if(typeof e!=`string`||e.length===0)throw TypeError(`Expected a nonempty identifier`);return e}function h(e,t,n){let r=p(t,`offset`),i=p(n,`length`);if(r>e.length||i>e.length-r)throw RangeError(`Memory range is out of bounds`);return r}function g(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)&&g(e[n],t[n]))}function _(e){return typeof e!=`object`||!e?e:e instanceof Uint8Array?e.slice():Object.freeze(Array.isArray(e)?e.map(_):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_(t)])))}let v=/* @__PURE__ */ new WeakSet;function y(e){return typeof e==`object`&&!!e&&v.has(e)}function b(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 v.add(r),r}function x(e,t,n,r=!1){if(e.kind===`optional`)return t===null?null:x(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`:{u(t);let r=n.get(e.name);return Object.freeze(Object.fromEntries(r.fields.map(e=>[e.name,x({kind:e.type},t[e.name],n)])))}case`sample`:case`intent`:return t}}function ee(e){return e instanceof Uint8Array?b(e.slice()):_(e)}function te(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(f(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 S(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}function C(e,t){return`${e}\\u0000${t}`}function w(e){return e instanceof Uint8Array||y(e)?e:void 0}function ne(e,t){if(Object.is(e,t))return!0;let n=w(e),r=w(t);if(n!==void 0||r!==void 0){if(n===void 0||r===void 0||n.length!==r.length)return!1;for(let e=0;e<n.length;e+=1)if(n[e]!==r[e])return!1;return!0}if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let i=e,a=t;return i.x===a.x&&i.y===a.y&&i.z===a.z}function T(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.x==`number`&&typeof t.y==`number`}function E(e,t){switch(e){case`boolean`:return typeof t==`boolean`;case`number`:return typeof t==`number`;case`string`:return typeof t==`string`;case`bytes`:case`bytes<rgb565>`:case`bytes<segments>`:return w(t)!==void 0;case`vec2d`:return T(t);case`vec3d`:return T(t)&&typeof t.z==`number`}}function re(e){return e instanceof Uint8Array?new Uint8Array(e):y(e)?e.slice():e}function D(e){return e instanceof Uint8Array?new Uint8Array(e):y(e)?e.slice():typeof e==`object`&&e?{...e}:e}let ie=l(`simulation-runtime`),ae=l(`simulation-runtime`);function oe(e,t){if(e!==`onDidPublish`||!Array.isArray(t))return[];let n=t[0];return se(n?.payload)}function se(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer?[e.buffer]:[]}function O(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 ce(e){return O(e,`time`)}function le(e,t){return O(e,`left`),O(t,`right`),O(e+t,`addition ${e} + ${t}`)}function k(e){return ue(e,/* @__PURE__ */ new Set,[])}function ue(e,t,n){if(typeof e!=`object`||!e)return(typeof e==`function`||typeof e==`symbol`||typeof e==`bigint`)&&j(`IR_SCHEMA`,`Expected ordinary IR data.`,n.slice()),e;t.has(e)&&j(`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&&j(`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)&&j(`IR_SCHEMA`,`IR arrays cannot contain extra properties.`),`value`in Object.getOwnPropertyDescriptor(e,t)||j(`IR_SCHEMA`,`IR arrays cannot contain accessors.`));for(let r=0;r<e.length;r++)Object.hasOwn(e,r)||j(`IR_SCHEMA`,`IR arrays cannot be sparse.`),n.push(r),i.push(ue(Object.getOwnPropertyDescriptor(e,r).value,t,n)),n.pop();r=Object.freeze(i)}else{let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&j(`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))&&j(`IR_SCHEMA`,`IR data cannot contain symbols or accessors.`),n.push(r);let o=ue(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 A=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=k(e)}};function j(e,t,n=[],r=`finalize`,i){throw new A([{code:e,message:t,path:n,phase:r,related:[],...i===void 0?{}:{source:i}}])}let M=Object.freeze({Logic:[`low`,`high`,`unknown`],SampleStatus:[`valid`,`floating`],Overflow:[`drop_new`,`drop_oldest`,`error`]}),de=[`positive`,`negate`,`not`,`bitNot`],fe=[`add`,`subtract`,`multiply`,`divide`,`remainder`,`power`,`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`,`equal`,`notEqual`,`concat`,`bitAnd`,`bitOr`,`bitXor`,`shiftLeft`,`shiftRight`,`shiftRightUnsigned`],pe=[`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`],me=[`load8`,`load16le`,`load16be`,`load32le`,`load32be`],he=[`store8`,`store16le`,`store16be`,`store32le`,`store32be`],ge=[`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`enum`,`record`];function N(e,t){(typeof e!=`object`||!e||Array.isArray(e))&&j(`IR_SCHEMA`,`Expected a data object.`,t)}function P(e,t,n,r,i=!0){for(let n of t)Object.hasOwn(e,n)||j(`IR_SCHEMA`,`Missing field ${n}.`,[...r,n]);for(let a of Object.keys(e))!(i&&a===`source`)&&!t.includes(a)&&!n.includes(a)&&j(`IR_SCHEMA`,`Unexpected field ${a}.`,[...r,a]);Object.hasOwn(e,`source`)&&ye(e.source,[...r,`source`])}function F(e,t){typeof e!=`string`&&j(`IR_SCHEMA`,`Expected a string.`,t)}function _e(e,t){typeof e!=`boolean`&&j(`IR_SCHEMA`,`Expected a boolean.`,t)}function ve(e,t){typeof e!=`number`&&j(`IR_SCHEMA`,`Expected a number.`,t)}function I(e,t){(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)&&j(`IR_SCHEMA`,`Expected a nonnegative safe integer.`,t)}function L(e,t,n){t.includes(e)||j(`IR_SCHEMA`,`Expected one of ${t.join(`, `)}.`,n)}function R(e,t,n){Array.isArray(e)||j(`IR_SCHEMA`,`Expected an array.`,t);for(let r=0;r<e.length;r++)n(e[r],[...t,r])}function ye(e,t){N(e,t);let n=Object.hasOwn(e,`uri`);for(let n of Object.keys(e))[`uri`,`range`,`label`].includes(n)||j(`IR_SCHEMA`,`Invalid source field.`,[...t,n]);if(Object.hasOwn(e,`label`)&&F(e.label,[...t,`label`]),!n){(!Object.hasOwn(e,`label`)||Object.hasOwn(e,`range`))&&j(`IR_SCHEMA`,`Source requires a label or URI and range.`,t);return}F(e.uri,[...t,`uri`]),N(e.range,[...t,`range`]);let r=e.range;for(let e of Object.keys(r))[`start`,`end`].includes(e)||j(`IR_SCHEMA`,`Invalid range field.`,[...t,`range`,e]);for(let e of[`start`,`end`]){let n=r[e];N(n,[...t,`range`,e]);for(let r of Object.keys(n))[`line`,`column`].includes(r)||j(`IR_SCHEMA`,`Invalid position field.`,[...t,`range`,e,r]);for(let r of[`line`,`column`])(!Number.isSafeInteger(n[r])||n[r]<1)&&j(`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)&&j(`IR_SCHEMA`,`Source range is reversed.`,t)}function be(e,t,n=!0){if(N(e,t),e.kind===`optional`&&n)P(e,[`kind`,`inner`],[],t),be(e.inner,[...t,`inner`],!1);else{L(e.kind,ge,[...t,`kind`]);let n=e.kind===`enum`||e.kind===`record`;P(e,n?[`kind`,`name`]:[`kind`],[],t),n&&F(e.name,[...t,`name`])}Object.hasOwn(e,`source`)&&j(`IR_SCHEMA`,`Type descriptors cannot carry source information.`,t)}function xe(e,t,n){N(e,t),Object.hasOwn(e,`source`)&&j(`IR_SCHEMA`,`Resource references cannot carry source information.`,t),L(e.kind,[`pin`,`memory`,`parameter`],[...t,`kind`]),e.kind===`parameter`?(P(e,[`kind`,`resource`,`index`],[],t),L(e.resource,[`pin`,`memory`],[...t,`resource`]),I(e.index,[...t,`index`]),n&&e.resource!==n&&j(`IR_REFERENCE`,`Resource category does not match.`,t)):(P(e,[`kind`,`name`],[],t),F(e.name,[...t,`name`]),n&&e.kind!==n&&j(`IR_REFERENCE`,`Resource category does not match.`,t))}function Se(e,t,n=!1){N(e,t),Object.hasOwn(e,`source`)&&j(`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(L(e.kind,r,[...t,`kind`]),e.kind){case`none`:P(e,[`kind`],[],t);break;case`enum`:P(e,[`kind`,`name`,`member`],[],t),F(e.name,[...t,`name`]),F(e.member,[...t,`member`]);break;case`record`:P(e,[`kind`,`name`,`fields`],[],t),F(e.name,[...t,`name`]),R(e.fields,[...t,`fields`],(e,t)=>{N(e,t),P(e,[`name`,`value`],[],t),F(e.name,[...t,`name`]),[`number`,`boolean`].includes(typeof e.value)||j(`IR_SCHEMA`,`Expected a number or boolean field.`,[...t,`value`])});break;case`bytes`:P(e,[`kind`,`value`],[],t),R(e.value,[...t,`value`],(e,t)=>{(!Number.isInteger(e)||e<0||e>255)&&j(`IR_SCHEMA`,`Expected a byte.`,t)});break;default:P(e,[`kind`,`value`],[],t),e.kind===`number`?(ve(e.value,[...t,`value`]),n&&!Number.isFinite(e.value)&&j(`IR_CONTROL_FLOW`,`Numeric match patterns must be finite.`,t)):e.kind===`bool`?_e(e.value,[...t,`value`]):F(e.value,[...t,`value`])}}function z(e,t,n){N(e,t),P(e,[`operations`],[],t),!n?.has(e)&&R(e.operations,[...t,`operations`],Ce)}function B(e,t,n){N(e,t),P(e,[`type`,`body`],[],t),be(e.type,[...t,`type`]),z(e.body,[...t,`body`],n)}function Ce(e,t,n){N(e,t),F(e.kind,[...t,`kind`]);let r=[],i=[],a=!1,o=e=>{r=e,a=!0};switch(e.kind){case`constant`:o([`constant`]),Se(e.constant,[...t,`constant`]);break;case`read`:o([`resource`,`name`]),L(e.resource,[`property`,`const`,`state`,`derived`],[...t,`resource`]),F(e.name,[...t,`name`]);break;case`parameter`:case`reactionCapture`:o([`index`]),I(e.index,[...t,`index`]);break;case`reactionValue`:o([`binding`]),L(e.binding,[`previous`,`current`],[...t,`binding`]);break;case`unary`:o([`operator`,`value`]),L(e.operator,de,[...t,`operator`]);break;case`binary`:o([`operator`,`left`,`right`]),L(e.operator,fe,[...t,`operator`]);break;case`numeric`:o([`builtin`,`args`]),L(e.builtin,pe,[...t,`builtin`]),R(e.args,[...t,`args`],I);break;case`record`:o([`fields`]),R(e.fields,[...t,`fields`],(e,t)=>{N(e,t),P(e,[`name`,`value`],[],t),F(e.name,[...t,`name`]),I(e.value,[...t,`value`])});break;case`field`:o([`value`,`field`]),F(e.field,[...t,`field`]);break;case`bytes`:o([`elements`]),R(e.elements,[...t,`elements`],I);break;case`length`:case`optional`:case`isNone`:case`nonNull`:o([`value`]);break;case`index`:o([`value`,`index`]),I(e.index,[...t,`index`]);break;case`localRead`:o([`local`]),I(e.local,[...t,`local`]);break;case`local`:r=[`local`,`type`,`initial`],I(e.local,[...t,`local`]),be(e.type,[...t,`type`]);break;case`localWrite`:r=[`local`,`value`],I(e.local,[...t,`local`]);break;case`write`:r=[`resource`,`name`,`value`],L(e.resource,[`state`],[...t,`resource`]),F(e.name,[...t,`name`]);break;case`memoryLength`:o([`memory`]),xe(e.memory,[...t,`memory`],`memory`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:o([`memory`,`offset`]),xe(e.memory,[...t,`memory`],`memory`);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:r=[`memory`,`offset`,`value`],xe(e.memory,[...t,`memory`],`memory`);break;case`copyBytes`:o([`memory`,`offset`,`length`]),xe(e.memory,[...t,`memory`],`memory`);break;case`readSample`:o([`pin`]),xe(e.pin,[...t,`pin`],`pin`);break;case`resistor`:o([`to`,`resistance`]),xe(e.to,[...t,`to`],`pin`);break;case`combineIntents`:o([`values`]),R(e.values,[...t,`values`],I);break;case`refEqual`:o([`left`,`right`]),xe(e.left,[...t,`left`]),xe(e.right,[...t,`right`]);break;case`writeIntent`:r=[`pin`,`value`],xe(e.pin,[...t,`pin`],`pin`);break;case`call`:case`callValue`:r=[`name`,`pure`,`args`],a=e.kind===`callValue`,F(e.name,[...t,`name`]),_e(e.pure,[...t,`pure`]),R(e.args,[...t,`args`],(e,t)=>{N(e,t),e.kind===`value`?(P(e,[`kind`,`value`],[],t),I(e.value,[...t,`value`])):xe(e,t)});break;case`send`:r=[`channel`,`value`],F(e.channel,[...t,`channel`]);break;case`notify`:r=[`notification`],F(e.notification,[...t,`notification`]);break;case`receive`:o([`channel`]),F(e.channel,[...t,`channel`]);break;case`now`:case`random`:o([]);break;case`if`:r=[`condition`,`yes`],i=[`no`],z(e.yes,[...t,`yes`],n),Object.hasOwn(e,`no`)&&z(e.no,[...t,`no`],n);break;case`match`:r=[`value`,`arms`],i=[`otherwise`],R(e.arms,[...t,`arms`],(e,t)=>{N(e,t),P(e,[`pattern`,`body`],[],t),Se(e.pattern,[...t,`pattern`],!0),z(e.body,[...t,`body`],n)}),Object.hasOwn(e,`otherwise`)&&z(e.otherwise,[...t,`otherwise`],n);break;case`while`:r=[`test`,`body`],B(e.test,[...t,`test`],n),z(e.body,[...t,`body`],n);break;case`loop`:r=[`body`],z(e.body,[...t,`body`],n);break;case`and`:case`or`:o([`left`,`right`]),B(e.right,[...t,`right`],n);break;case`select`:o([`condition`,`yes`,`no`]),B(e.yes,[...t,`yes`],n),B(e.no,[...t,`no`],n);break;case`assert`:r=[`condition`],i=[`message`],Object.hasOwn(e,`message`)&&B(e.message,[...t,`message`],n);break;case`wait`:case`elapse`:r=[`duration`];break;case`waitUntil`:r=[`predicate`],F(e.predicate,[...t,`predicate`]);break;case`redirect`:r=[`target`,`delay`];break;case`return`:case`break`:case`continue`:case`stop`:break;case`returnValue`:case`yield`:r=[`value`];break;default:j(`IR_SCHEMA`,`Unknown operation ${e.kind}.`,[...t,`kind`])}P(e,[`kind`,...r,...a?[`result`,`type`]:[]],i,t),a&&(I(e.result,[...t,`result`]),be(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))?I(e[n],[...t,n]):Object.hasOwn(e,n)&&typeof e[n]==`object`&&![`refEqual`,`and`,`or`].includes(e.kind)&&j(`IR_SCHEMA`,`Expected a result identifier.`,[...t,n])}function we(e){N(e,[]),P(e,[`kind`,`name`,`declarations`],[],[]),L(e.kind,[`device`],[`kind`]),F(e.name,[`name`]),R(e.declarations,[`declarations`],(e,t)=>{N(e,t),F(e.kind,[...t,`kind`]);let n=[`kind`],r=[];switch([`start`,`assert`].includes(e.kind)||(n.push(`name`),F(e.name,[...t,`name`])),e.kind){case`enum`:n.push(`members`),R(e.members,[...t,`members`],F);break;case`record`:n.push(`fields`),R(e.fields,[...t,`fields`],(e,t)=>{N(e,t),P(e,[`name`,`type`],[],t),F(e.name,[...t,`name`]),L(e.type,[`number`,`bool`],[...t,`type`])});break;case`property`:n.push(`type`),r=[`default`],Object.hasOwn(e,`default`)&&B(e.default,[...t,`default`]);break;case`const`:case`derived`:n.push(`type`,`value`),B(e.value,[...t,`value`]);break;case`state`:n.push(`type`,`initial`),B(e.initial,[...t,`initial`]);break;case`pin`:r=[`initial`,`low`,`high`];for(let n of r)Object.hasOwn(e,n)&&B(e[n],[...t,n]);Object.hasOwn(e,`low`)!==Object.hasOwn(e,`high`)&&j(`IR_SCHEMA`,`Pin thresholds must be provided together.`,t);break;case`memory`:n.push(`public`,`length`),_e(e.public,[...t,`public`]),B(e.length,[...t,`length`]);break;case`channel`:n.push(`direction`,`type`,`capacity`),r=[`maxLength`,`overflow`],B(e.capacity,[...t,`capacity`]);for(let n of r)Object.hasOwn(e,n)&&B(e[n],[...t,n]);break;case`notification`:n.push(`direction`);break;case`function`:n.push(`pure`,`params`,`body`),r=[`returns`],_e(e.pure,[...t,`pure`]),R(e.params,[...t,`params`],(e,t)=>{N(e,t),P(e,[`name`,`type`],[],t),F(e.name,[...t,`name`]),N(e.type,[...t,`type`]),[`pin`,`memory`].includes(e.type.kind)?P(e.type,[`kind`],[],[...t,`type`]):be(e.type,[...t,`type`])}),Object.hasOwn(e,`returns`)&&be(e.returns,[...t,`returns`]),z(e.body,[...t,`body`]);break;case`start`:case`assert`:n.push(`body`),z(e.body,[...t,`body`]);break;case`on`:n.push(`sourcePath`,`body`),R(e.sourcePath,[...t,`sourcePath`],F),z(e.body,[...t,`body`]);break;case`reaction`:n.push(`sourcePath`,`sourceType`,`previous`,`current`,`captures`,`body`),R(e.sourcePath,[...t,`sourcePath`],F),be(e.sourceType,[...t,`sourceType`]),F(e.previous,[...t,`previous`]),F(e.current,[...t,`current`]),R(e.captures,[...t,`captures`],(e,t)=>{N(e,t),P(e,[`name`,`value`],[],t),F(e.name,[...t,`name`]),B(e.value,[...t,`value`])}),z(e.body,[...t,`body`]);break;default:j(`IR_SCHEMA`,`Unknown declaration ${e.kind}.`,[...t,`kind`])}P(e,n,r,t),Object.hasOwn(e,`type`)&&be(e.type,[...t,`type`]),[`channel`,`notification`].includes(e.kind)&&L(e.direction,[`input`,`output`],[...t,`direction`])})}function Te(e){N(e,[]),P(e,[`kind`,`instructions`],[],[]),L(e.kind,[`block`],[`kind`]),R(e.instructions,[`instructions`],(e,t)=>{N(e,t),P(e,[`pc`,`nextPc`,`body`],[],t);for(let n of[`pc`,`nextPc`])(typeof e[n]!=`number`||!Number.isFinite(e[n]))&&j(`IR_SCHEMA`,`Instruction positions must be finite numbers.`,[...t,n]);z(e.body,[...t,`body`])});let t=e.instructions;t.length||j(`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&&j(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries do not match.`,[`instructions`,e,`pc`])}let V={kind:`number`},H={kind:`bool`},Ee={kind:`string`},De={kind:`bytes`},Oe={kind:`intent`},ke={kind:`sample`},Ae=/* @__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(M),...pe,...me,...he,`resistor`,`copyBytes`,`now`,`random`,`ticks`]);function je(e,t){let n=e,r=t;return n?.kind===r?.kind&&(n?.kind===`optional`?je(n.inner,r?.inner):n?.kind===`enum`||n?.kind===`record`?n.name===r?.name:!0)}function Me(e){return e.kind===`optional`?e.inner:e}function Ne(e){return Me(e).kind!==`intent`}function Pe(e){return{facts:new Map(e.facts),locals:new Map(e.locals)}}function Fe(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}var Ie=class{next=0;byKey=/* @__PURE__ */ new Map;joins=/* @__PURE__ */ new Map;fields=/* @__PURE__ */ new Map;id(e){let t=this.byKey.get(e);return t===void 0&&(t=this.byKey.size,this.byKey.set(e,t)),t}fresh(e){return`${e}:${this.next++}`}join(e,t){let n=`${e}:${t.map(e=>this.id(e)).join(`,`)}`,r=this.joins.get(n);return r===void 0&&(r=this.fresh(`join`),this.joins.set(n,r)),r}field(e,t){let n=this.fields.get(e);n||(n=/* @__PURE__ */ new Map,this.fields.set(e,n));let r=n.get(t);return r===void 0&&(r=this.fresh(`field`),n.set(t,r)),r}};function Le(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 Re(e,t){if(!e.length)return;let n=Pe(e[0]);n.facts=Fe(e.map(e=>e.facts));for(let[r,i]of n.locals){let a=e.map(e=>e.locals.get(r));if(a.some(e=>!e))n.locals.delete(r);else if(a.some(e=>e.value.key!==i.value.key)){let o={type:i.type,key:t.join(r,a.map(e=>e.value.key))},s=a.map((t,n)=>e[n].facts.get(t.value.key));s.every(e=>e===!0)&&n.facts.set(o.key,!0),s.every(e=>e===!1)&&n.facts.set(o.key,!1),n.locals.set(r,{type:i.type,value:o})}}return n}function ze(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;ze(e?r.body:r,t,[...i,n,...e?[`body`]:[]])}}e.kind===`while`&&ze(e.test.body,t,[...i,`test`,`body`]),e.kind===`assert`&&e.message&&ze(e.message.body,t,[...i,`message`,`body`]),(e.kind===`and`||e.kind===`or`)&&ze(e.right.body,t,[...i,`right`,`body`]),e.kind===`match`&&e.arms.forEach((e,n)=>ze(e.body,t,[...i,`arms`,n,`body`]))})}var Be=class{declarations=/* @__PURE__ */ new Map;paths=/* @__PURE__ */ new Map;enums=new Map(Object.entries(M));records=/* @__PURE__ */ new Map;functions=/* @__PURE__ */ new Map};let Ve=/* @__PURE__ */ new WeakMap;function He(e){return Ve.get(e)?.declarations}var Ue=class{device;index;identities=new Ie;effectChecked=/* @__PURE__ */ new Set;receiveOwners=/* @__PURE__ */ new Map;constructor(e){this.device=e;let t=e&&Ve.get(e);if(this.index=t??new Be,!e||t)return;let{declarations:n,paths:r,enums:i,records:a,functions:o}=this.index;this.name(e.name,[`name`]);let s=0;e.declarations.forEach((e,t)=>{let c=[`declarations`,t];e.kind===`start`?++s>1&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`,c):e.kind!==`assert`&&(this.name(e.name,[...c,`name`]),n.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`,c),n.set(e.name,e),r.set(e.name,c),e.kind===`enum`&&(this.uniqueNames(e.members,[...c,`members`]),e.members.length||this.error(`IR_TYPE`,`An enum must have at least one member.`,c),i.set(e.name,e.members)),e.kind===`record`&&(this.uniqueNames(e.fields.map(e=>e.name),[...c,`fields`]),a.set(e.name,e.fields)),e.kind===`function`&&o.set(e.name,e))})}get declarations(){return this.index.declarations}get paths(){return this.index.paths}get enums(){return this.index.enums}get records(){return this.index.records}get functions(){return this.index.functions}error(e,t,n,r){return j(e,t,n,`finalize`,r?.source)}name(e,t){(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||Ae.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=Me(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){je(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:V},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 V;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,visibleResults:[],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=Pe(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=Pe(n),a={breaks:[],continues:[],yielded:[],yieldStates:[]},{results:o,visibleResults:s}=t,c=s.length;for(let n=0;n<e.operations.length;n++){let c=e.operations[n],l=[...r,`operations`,n];i||this.error(`IR_CONTROL_FLOW`,`Operation follows an unconditional path terminator.`,l,c);let u=i,d=(e,t)=>{let n=o.get(e);return n||this.error(`IR_SCOPE`,`Result ${e} is not visible or is used before its definition.`,l,c),t&&this.expect(n.type,t,l,c),n},f=(e,t={})=>{let n=c;this.expect(n.type,e,[...l,`type`],c);let r={type:n.type,key:`v:${n.result}`,...t};return o.set(n.result,r),s.push(n.result),r};`result`in c&&(this.type(c.type,[...l,`type`]),t.resultIds.has(c.result)&&this.error(`IR_SCOPE`,`Duplicate result ${c.result}.`,[...l,`result`],c),t.resultIds.add(c.result));let p=e=>{let t=u.locals.get(e);return t||this.error(`IR_SCOPE`,`Local is not visible or not initialized.`,[...l,`local`],c),t},m=(r,i,a,o={})=>Le(this.region(r,{...t,tail:t.tail&&n===e.operations.length-1,...o},i,[...l,a]),i.locals),h=e=>{a.breaks.push(...e.breaks),a.continues.push(...e.continues),a.yielded.push(...e.yielded),a.yieldStates.push(...e.yieldStates)},g=(e,n,r,i)=>{this.type(e.type,[...l,i,`type`]),this.expect(e.type,n,[...l,i,`type`]);let a=Le(this.region(e.body,{...t,valueRegion:n,loop:0,tail:!1},r,[...l,i,`body`]),r.locals);return a.normal&&this.error(`IR_CONTROL_FLOW`,`A value region has a normal path without yield.`,[...l,i],e),{flow:a,...a.yielded.length?{value:{type:n,key:`region:${`result`in c?c.result:void 0}:${i}`,yes:Fe(a.yielded.map(e=>e.yes??/* @__PURE__ */ new Map)),no:Fe(a.yielded.map(e=>e.no??/* @__PURE__ */ new Map))}}:{}}};switch(c.kind){case`constant`:{this.constant(c.constant,c.type,[...l,`constant`]);let e=f(c.type,{none:c.constant.kind===`none`});c.constant.kind===`none`&&u.facts.set(e.key,!1);break}case`read`:f(this.declaration(c.name,c.resource,l)?.type??c.type);break;case`parameter`:{let e=t.params[c.index];e||this.error(`IR_SCOPE`,`Parameter index is outside the current function.`,l,c),(e.type.kind===`pin`||e.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource parameters cannot be read as values.`,l,c),f(e.type,{key:`parameter:${c.index}`});break}case`reactionValue`:t.reaction||this.error(`IR_SCOPE`,`Reaction bindings are only visible inside their response body.`,l,c),f(t.reaction.sourceType,{key:`reaction:${c.binding}`});break;case`reactionCapture`:t.reaction||this.error(`IR_SCOPE`,`Reaction captures are only visible inside their response body.`,l,c),t.reaction.captures[c.index]||this.error(`IR_SCOPE`,`Reaction capture index is out of range.`,l,c),f(t.reaction.captures[c.index].value.type,{key:`capture:${c.index}`});break;case`unary`:{let e=d(c.value,c.operator===`not`?H:V);f(c.operator===`not`?H:V,c.operator===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{});break}case`binary`:{let e=d(c.left),t=d(c.right);if([`equal`,`notEqual`].includes(c.operator)){this.expect(e.type,t.type,l,c),!Ne(e.type)&&(e.type.kind!==`optional`||!e.none&&!t.none)&&this.error(`IR_TYPE`,`Intent values do not support content equality.`,l,c);let n=e.none?t:t.none?e:void 0,r=c.operator===`equal`;f(H,n?{yes:/* @__PURE__ */ new Map([[n.key,!r]]),no:/* @__PURE__ */ new Map([[n.key,r]])}:{})}else c.operator===`concat`?(d(c.left,Ee),d(c.right,Ee),f(Ee)):(d(c.left,V),d(c.right,V),f([`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(c.operator)?H:V));break}case`numeric`:c.args.length!==([`min`,`max`,`pow`].includes(c.builtin)?2:1)&&this.error(`IR_TYPE`,`Numeric builtin argument count does not match.`,l,c),c.args.forEach(e=>d(e,V)),f(c.builtin.startsWith(`is`)?H:V);break;case`record`:this.recordFields(c.fields,c.type,l,e=>d(e.value).type),f(c.type);break;case`field`:{let e=d(c.value),t=e.type;f(t.kind===`record`&&!this.device?c.type:this.field(t,c.field,l),{key:this.identities.field(e.key,c.field)});break}case`bytes`:c.elements.forEach(e=>d(e,V)),f(De);break;case`length`:{let e=d(c.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`length requires string or bytes.`,l,c),f(V);break}case`index`:{let e=d(c.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`index requires string or bytes.`,l,c),d(c.index,V),f(e.kind===`string`?Ee:V);break}case`optional`:{let e=d(c.value).type;e.kind===`optional`&&this.error(`IR_TYPE`,`Optional types cannot be nested.`,l,c);let t=f({kind:`optional`,inner:e});u.facts.set(t.key,!0);break}case`isNone`:{let e=d(c.value);e.type.kind!==`optional`&&this.error(`IR_TYPE`,`isNone requires an optional value.`,l,c),f(H,{yes:/* @__PURE__ */ new Map([[e.key,!1]]),no:/* @__PURE__ */ new Map([[e.key,!0]])});break}case`nonNull`:{let e=d(c.value);(e.type.kind!==`optional`||u.facts.get(e.key)!==!0)&&this.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`,l,c),f(e.type.inner);break}case`local`:{t.localIds.has(c.local)&&this.error(`IR_SCOPE`,`Duplicate local identifier.`,l,c),t.localIds.add(c.local),this.type(c.type,[...l,`type`]);let e=d(c.initial,c.type);u.locals.set(c.local,{type:c.type,value:e});break}case`localRead`:{let e=p(c.local);f(e.type,{...e.value});break}case`localWrite`:{let e=p(c.local),t=d(c.value,e.type);u.locals.set(c.local,{type:e.type,value:t});break}case`write`:{let e=this.declaration(c.name,`state`,l);d(c.value,e?.type);break}case`memoryLength`:this.ref(c.memory,`memory`,t,l),f(V);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:this.ref(c.memory,`memory`,t,l),d(c.offset,V),f(V);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:this.ref(c.memory,`memory`,t,l),d(c.offset,V),d(c.value,V);break;case`copyBytes`:this.ref(c.memory,`memory`,t,l),d(c.offset,V),d(c.length,V),f(De);break;case`readSample`:this.ref(c.pin,`pin`,t,l),f(ke);break;case`resistor`:this.ref(c.to,`pin`,t,l),d(c.resistance,V),f(Oe);break;case`combineIntents`:c.values.forEach(e=>d(e,Oe)),f(Oe);break;case`refEqual`:this.expect({kind:this.ref(c.left,void 0,t,l)},{kind:this.ref(c.right,void 0,t,l)},l),f(H);break;case`writeIntent`:this.ref(c.pin,`pin`,t,l),d(c.value,Oe);break;case`call`:case`callValue`:{let e=this.declaration(c.name,`function`,l);e&&c.pure&&!e.pure&&this.error(`IR_EFFECT`,`A pure call must target an explicitly pure function.`,l,c),e&&c.args.length!==e.params.length&&this.error(`IR_TYPE`,`Call argument count does not match.`,l,c),c.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.`,l,c),d(n.value,i?.type)):(i&&i.type.kind!==`pin`&&i.type.kind!==`memory`&&this.error(`IR_TYPE`,`Value argument required.`,l,c),this.ref(n,i?.type.kind,t,l))}),c.kind===`callValue`?(e&&!e.returns&&this.error(`IR_TYPE`,`callValue requires a value-returning function.`,l,c),f(e?.returns??c.type)):e?.returns&&this.error(`IR_TYPE`,`call cannot discard the return type of a value-returning function.`,l,c);break}case`send`:{let e=this.declaration(c.channel,`channel`,l);e?.direction===`input`&&this.error(`IR_REFERENCE`,`send requires an output channel.`,l,c),d(c.value,e?.type);break}case`notify`:this.declaration(c.notification,`notification`,l)?.direction===`input`&&this.error(`IR_REFERENCE`,`notify requires an output notification.`,l,c);break;case`receive`:{let e=this.declaration(c.channel,`channel`,l);e?.direction===`output`&&this.error(`IR_REFERENCE`,`receive requires an input channel.`,l,c),f(e?.type??c.type);break}case`now`:case`random`:f(V);break;case`if`:{let e=d(c.condition,H),t=m(c.yes,this.conditioned(u,e,!0),`yes`),n=c.no?m(c.no,this.conditioned(u,e,!1),`no`):{normal:this.conditioned(u,e,!1),breaks:[],continues:[],yielded:[],yieldStates:[]};h(t),h(n),i=Re([t.normal,n.normal].filter(e=>!!e),this.identities);break}case`match`:{let r=d(c.value),a=Me(r.type),o=/* @__PURE__ */ new Set,s=[];for(let i=0;i<c.arms.length;i++){let d=c.arms[i],f=d.pattern;this.constant(f,f.kind===`none`?r.type:a,[...l,`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.`,[...l,`arms`,i]),o.add(p);let m=Pe(u);r.type.kind===`optional`&&m.facts.set(r.key,f.kind!==`none`);let g=Le(this.region(d.body,{...t,tail:t.tail&&n===e.operations.length-1},m,[...l,`arms`,i,`body`]),m.locals);h(g),g.normal&&s.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}`))&&(t.mode!==`jit`||Object.hasOwn(M,a.name)))&&(r.type.kind!==`optional`||o.has(`none:undefined`));if(c.otherwise){let e=Pe(u);r.type.kind===`optional`&&o.has(`none:undefined`)&&e.facts.set(r.key,!0);let t=m(c.otherwise,e,`otherwise`);h(t),t.normal&&s.push(t.normal)}else f||this.error(`IR_CONTROL_FLOW`,`Match requires exhaustive patterns or a default region.`,l,c);i=Re(s,this.identities);break}case`while`:case`loop`:{let e=/* @__PURE__ */ new Set;ze(c.body,t=>{t.kind===`localWrite`&&u.locals.has(t.local)&&e.add(t.local)}),c.kind===`while`&&ze(c.test.body,t=>{t.kind===`localWrite`&&u.locals.has(t.local)&&e.add(t.local)});let n=t=>{let n=Pe(u),r=[u,...t];for(let t of e){let e=u.locals.get(t),i={type:e.type,key:`loop:${l.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),s=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 s)t.localIds.add(e);d=c.kind===`while`?g(c.test,H,r,`test`):void 0;let i=d?Re(d.flow.yieldStates,this.identities)??r:r,a=d?.value?this.conditioned(i,d.value,!0):i;f=m(c.body,a,`body`,{loop:t.loop+1,tail:!1});let l=n([f.normal,...f.continues].filter(e=>!!e));if([...e].every(e=>{let t=l.locals.get(e).value.key;return l.facts.get(t)===r.facts.get(t)}))break;r=l}a.yielded.push(...f.yielded),a.yieldStates.push(...f.yieldStates);let p=[...f.breaks];if(c.kind===`while`&&d?.value){let e=Re(d.flow.yieldStates,this.identities)??r;p.push(this.conditioned(e,d.value,!1))}i=Re(p,this.identities);break}case`and`:case`or`:{let e=d(c.left,H),t=c.kind===`and`,n=g(c.right,H,this.conditioned(u,e,t),`right`),r=n.value,a=(e,t)=>new Map([...e??[],...t??[]]),o=t?a(e.yes,r?.yes):Fe([e.yes??/* @__PURE__ */ new Map,a(e.no,r?.yes)]),s=t?Fe([e.no??/* @__PURE__ */ new Map,a(e.yes,r?.no)]):a(e.no,r?.no);f(H,{yes:o,no:s}),i=Re([this.conditioned(u,e,!t),...n.flow.yieldStates],this.identities);break}case`select`:{let e=d(c.condition,H),t=g(c.yes,c.type,this.conditioned(u,e,!0),`yes`),n=g(c.no,c.type,this.conditioned(u,e,!1),`no`);f(c.type),i=Re([...t.flow.yieldStates,...n.flow.yieldStates],this.identities);break}case`assert`:{let e=d(c.condition,H);c.message&&g(c.message,Ee,this.conditioned(u,e,!1),`message`),i=this.conditioned(u,e,!0);break}case`wait`:(t.valueRegion||t.mode!==`process`)&&this.error(`IR_EFFECT`,`wait is only allowed in a process statement region.`,l,c),d(c.duration,V);break;case`elapse`:(t.valueRegion||t.mode!==`jit`)&&this.error(`IR_EFFECT`,`elapse is only allowed in a JIT statement region.`,l,c),d(c.duration,V);break;case`waitUntil`:t.mode!==`jit`&&this.error(`IR_EFFECT`,`waitUntil requires a JIT instruction.`,l,c),(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.`,l,c);{let e=this.declaration(c.predicate,`function`,l);e&&(!e.pure||e.params.length||!je(e.returns,H))&&this.error(`IR_TYPE`,`waitUntil requires a zero-parameter pure bool function.`,l,c)}i=void 0;break;case`redirect`:[`jit`,`sync`].includes(t.mode)||this.error(`IR_EFFECT`,`redirect is not permitted in this context.`,l,c),d(c.target,V),d(c.delay,V),i=void 0;break;case`stop`:(t.mode!==`jit`||t.valueRegion)&&this.error(`IR_EFFECT`,`stop requires a JIT statement region.`,l,c),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.`,l,c),i=void 0;break;case`returnValue`:(t.valueRegion||!t.returns)&&this.error(`IR_CONTROL_FLOW`,`returnValue is not valid in this body.`,l,c),d(c.value,t.returns),i=void 0;break;case`yield`:t.valueRegion||this.error(`IR_CONTROL_FLOW`,`yield requires a value region.`,l,c);{let e=d(c.value,t.valueRegion);a.yielded.push(e),a.yieldStates.push(u)}i=void 0;break;case`break`:case`continue`:t.loop||this.error(`IR_CONTROL_FLOW`,`${c.kind} requires an enclosing loop in this region.`,l,c),(c.kind===`break`?a.breaks:a.continues).push(u),i=void 0}}for(i&&(a.normal=i);s.length>c;)o.delete(s.pop());return a}effects(e,t,n){ze(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`,...he].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`,...me].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&&t!==`jit`){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=ke,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 Ne(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 ze(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;ze(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=Me(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],V,`creation`,[...i,t]);e.initial&&this.computation(e.initial,Oe,`initial`,[...i,`initial`])}else if(e.kind===`memory`)this.computation(e.length,V,`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,V,`creation`,[...i,`capacity`]),e.maxLength&&this.computation(e.maxLength,V,`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`]),ze(e.body,e=>{if(e.kind===`receive`){let t=`${r}`,n=this.receiveOwners.get(e.channel);if(n&&n!==t){let e=new A([{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)=>{Ne(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 We(e,t){if(!(e instanceof A))throw e;let n=new A(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 Ge=/* @__PURE__ */ new WeakMap,Ke=/* @__PURE__ */ new WeakMap,qe=/* @__PURE__ */ new WeakMap;function Je(e,t){return typeof t==`object`&&t?e.get(t):void 0}function Ye(e,t,n){typeof t==`object`&&t&&e.set(t,n),e.set(n,n)}function Xe(e){let t=Je(Ge,e);if(t!==void 0)return t;let n=k(e);try{we(n);let t=new Ue(n);t.validateDevice();let r=n;return Ve.set(r,t.index),Ye(Ge,e,r),r}catch(e){return We(e,n)}}function Ze(e){let t=k(e);try{return Te(t),t}catch(e){return We(e,t)}}function Qe(e){try{new Ue().validateBlock(e)}catch(t){return We(t,e)}}function $e(e,t){let n=qe.get(e);n||(n=/* @__PURE__ */ new WeakSet,qe.set(e,n)),n.add(t)}function et(e){let t=Je(Ke,e);if(t!==void 0)return t;let n=Ze(e);return Qe(n),Ye(Ke,e,n),n}function tt(e,t){try{let n=Je(Ke,e),r=n??Ze(e),i=Je(Ge,t);if(i===void 0){n===void 0&&(Qe(r),Ye(Ke,e,r));let i=Xe(t);return qe.get(r)?.has(i)||(new Ue(i).validateBlock(r),$e(r,i)),r}if(qe.get(r)?.has(i))return r;try{new Ue(i).validateBlock(r)}catch(t){throw n===void 0&&(Qe(r),Ye(Ke,e,r)),t}return n===void 0&&Ye(Ke,e,r),$e(r,i),r}catch(e){if(e instanceof A){let t=new A(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 nt=/* @__PURE__ */ new WeakMap,rt=/* @__PURE__ */ new WeakMap,it=/* @__PURE__ */ new WeakMap,at=/* @__PURE__ */ new WeakMap,ot=/* @__PURE__ */ new WeakMap,st=e=>{let t=Object.freeze({});return nt.set(t,{type:{kind:e}}),t};function ct(e,t,n){let r={};for(let i of t){let t=Object.freeze({});ot.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 nt.set(i,{type:{kind:`enum`,name:e},members:Object.freeze([...t]),...n?{owner:n}:{}}),i}function lt(e,t,n){let r=Object.freeze({name:e,fields:Object.freeze({...t})});return nt.set(r,{type:{kind:`record`,name:e},fields:r.fields,...n?{owner:n}:{}}),r}let ut={number:st(`number`),bool:st(`bool`),string:st(`string`),bytes:st(`bytes`),intent:st(`intent`),sample:st(`sample`),pin:Object.freeze({kind:`pin`}),memory:Object.freeze({kind:`memory`}),logic:ct(`Logic`,M.Logic),sampleStatus:ct(`SampleStatus`,M.SampleStatus),overflow:ct(`Overflow`,M.Overflow),optional(e){let t=nt.get(e);(!t||t.type.kind===`optional`)&&j(`IR_TYPE`,`optional requires a nonoptional value type.`,[],`construct`);let n=Object.freeze({});return nt.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)&&j(`IR_TYPE`,`Invalid named enum description.`,[],`construct`),ct(e,t)},namedRecord(e,t){(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))&&j(`IR_TYPE`,`Invalid named record description.`,[],`construct`);for(let e of Object.values(t))[`number`,`bool`].includes(nt.get(e)?.type.kind??``)||j(`IR_TYPE`,`Record fields must be number or bool types.`,[],`construct`);return lt(e,t)}};Object.freeze(ut);let U={kind:`number`},W={kind:`bool`},dt={kind:`string`},ft={kind:`bytes`},pt={kind:`intent`},mt={kind:`sample`};function ht(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function gt(e){return typeof e==`object`&&e?rt.get(e):void 0}function _t(e){return typeof e==`object`&&e?ot.get(e):void 0}function vt(e){return typeof e==`object`&&e?at.get(e):void 0}function yt(e,t){let n=Object.freeze({});return e.set(n,t),n}function G(e){return e.alias?G(e.alias):e}function bt(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 xt=/* @__PURE__ */ new WeakMap;var St=class{options;device;jit;closed=!1;active;source;declarations=[];ownNames=/* @__PURE__ */ new Map;names;expectedTypes=/* @__PURE__ */ new Set;pending=[];instructions=[];checkedRegions=/* @__PURE__ */ new WeakSet;constructor(e,t,n=!1){this.options=e,this.device=t,this.jit=n,e.source!==void 0&&(this.source=k(e.source));let r=t&&He(t);if(t&&(!r||!n))for(let e of t.declarations)`name`in e&&this.ownNames.set(e.name,e);if(this.names=(n?r:void 0)??this.ownNames,t&&!n)for(let e of t.declarations)this.declarations.push(e)}error(e,t,n=[]){return this.closed=!0,j(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 A&&e.diagnostics.some(e=>e.phase!==`construct`)?new A(e.diagnostics.map(e=>({...e,phase:`construct`}))):e}}type(e){let t=nt.get(e);if(t||this.error(`IR_TYPE`,`Expected a Builder type descriptor.`),t.owner&&t.owner!==this&&(!this.device||xt.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:k(t)}}body(e,t,n,r,i){let a=new Ct(this,e,{result:0,local:0},{},void 0,n);a.source=r===void 0?this.source:k(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:k(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.ownNames.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&&j(`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)||j(`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(M[n]&&t.kind===`enum`)e.members&&(e.members.length!==M[n].length||e.members.some((e,t)=>e!==M[n][t]))&&j(`IR_TYPE`,`Builtin enum description does not match its members.`);else if(r&&(r.kind!==t.kind&&j(`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]))&&j(`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===nt.get(t)?.type.kind)))&&j(`IR_TYPE`,`Forward record description does not match its declaration.`)}}}},Ct=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:k(this.source)}:{}};Ce(t,[],this.root.checkedRegions),this.operations.push(t)}result(e,t,n={}){let r=this.space.result++;return this.node({...t,result:r,type:e}),yt(rt,{root:this.root,scope:this.scope,space:this.space,type:e,id:r,...n})}handle(e,t){let n=gt(e);return(!n||n.root!==this.root||n.space!==this.space||!ht(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Value is not visible in the current execution body or scope.`),t&&!je(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}localHandle(e){let t=it.get(e);return(!t||t.root!==this.root||t.space!==this.space||!ht(this.scope,t.scope))&&this.root.error(`IR_SCOPE`,`Local is not visible in this execution body or scope.`),t}infer(e){if(gt(e))return this.handle(e).type;let t=_t(e);if(t)return t.owner&&t.owner!==this.root&&(!this.root.device||xt.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 U;if(typeof e==`boolean`)return W;if(typeof e==`string`)return dt;if(Array.isArray(e)||e instanceof Uint8Array)return ft;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=_t(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||xt.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:nt.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(gt(e)){let n=this.handle(e);if(t&&t.kind===`optional`&&je(n.type,t.inner)){let e=this.handle(this.result(t,{kind:`optional`,value:n.id}));return this.facts.set(G(e),!0),e}return t&&!je(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(G(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=vt(e);return(!n||n.root!==this.root||n.space!==this.space||!ht(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 yt(at,{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(G(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}this.root.check();let c={operations:a.operations,...a.source?{source:k(a.source)}:{}};return this.root.checkedRegions.add(c),{body:c,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=bt(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(G(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=bt(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(G(e))===!0)&&this.facts.set(i,!0)}}}}invoke(t,n){if(de.includes(t)){let e=this.operand(n[0],t===`not`?W:U);return this.result(t===`not`?W:U,{kind:`unary`,operator:t,value:e.id},t===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{})}if(fe.includes(t)){let e=[`equal`,`notEqual`].includes(t),r=e?this.root.type(n.shift()):t===`concat`?dt:U,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?W:r,{kind:`binary`,operator:t,left:i.id,right:a.id},o?{yes:/* @__PURE__ */ new Map([[G(o),t!==`equal`]]),no:/* @__PURE__ */ new Map([[G(o),t===`equal`]])}:{})}if(pe.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`)?W:U,{kind:`numeric`,builtin:t,args:n.map(e=>this.operand(e,U).id)})}if(me.includes(t)||he.includes(t)){this.requireRead();let e=this.ref(n[0],`memory`),r=this.operand(n[1],U);if(he.includes(t)){this.requireEffect(),this.node({kind:t,memory:e,offset:r.id,value:this.operand(n[2],U).id});return}return this.result(U,{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=k(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 gt(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),yt(it,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:G(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=nt.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:U},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=G(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(ft,{kind:`bytes`,elements:n.map(e=>this.operand(e,U).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(U,{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`?dt:U,{kind:`index`,value:e.id,index:this.operand(n[1],U).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(G(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(W,{kind:`isNone`,value:e.id},{yes:/* @__PURE__ */ new Map([[G(e),!1]]),no:/* @__PURE__ */ new Map([[G(e),!0]])})}case`nonNull`:{let e=this.handle(n[0]);return(e.type.kind!==`optional`||this.facts.get(G(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(U,{kind:`memoryLength`,memory:this.ref(n[0],`memory`)});case`copyBytes`:return this.requireRead(),this.result(ft,{kind:`copyBytes`,memory:this.ref(n[0],`memory`),offset:this.operand(n[1],U).id,length:this.operand(n[2],U).id});case`readSample`:return this.requireRead(),this.result(mt,{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(pt,{kind:`resistor`,to:this.ref(n[0],`pin`),resistance:this.operand(n[1],U).id});case`combineIntents`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction is not available here.`),this.result(pt,{kind:`combineIntents`,values:n.map(e=>this.operand(e,pt).id)});case`refEqual`:{this.requireRead();let e=vt(n[0]),t=vt(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(W,{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],pt).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(U,{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=vt(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&&!gt(e)){let n=e===null||typeof e==`object`&&!_t(e)&&!Array.isArray(e)&&!(e instanceof Uint8Array),r=n?U: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:k(this.source)}:{}};return Ce(a,[]),this.operations.push(a),this.root.pending.push({node:a,call:i,index:t,value:_t(e)?e:k(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],W),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([[G(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([[G(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,W):void 0,i=this.branch(n[+(t===`while`)],void 0,void 0,!0);this.node({kind:t,...r?{test:{type:W,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],W),r=t===`and`,i=this.branch(n[1],{info:e,truth:r},W),a=gt(i.returned),o=(e,t)=>new Map([...e??[],...t??[]]),s=r?o(e.yes,a?.yes):bt([e.yes??/* @__PURE__ */ new Map,o(e.no,a?.yes)]),c=r?bt([e.no??/* @__PURE__ */ new Map,o(e.yes,a?.no)]):o(e.no,a?.no),l=this.result(W,{kind:t,left:e.id,right:{type:W,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],W),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],W),t=n[1]?this.branch(n[1],{info:e,truth:!1},dt):void 0;this.node({kind:`assert`,condition:e.id,...t?{message:{type:dt,body:t.body}}:{}});for(let[t,n]of e.yes??[])this.facts.set(G(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],U).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],U).id,delay:this.operand(n[1]??0,U).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 yt(rt,n)}};function wt(e={}){let t=new St({name:`JitBlock`,...e.source?{source:e.source}:{}},e.device,!0),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?tt(n,e.device):et(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=k(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 Tt(e,t){return t}function Et(e){return Object.freeze(Object.fromEntries(e))}function Dt(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 Ot=Object.freeze([]);function kt(e){if(e.length===0)return Ot;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 At(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return e===t;if(jt(e)||jt(t)){if(!jt(e)||!jt(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)||!At(n[e],r[e]))return!1;return!0}function jt(e){return Array.isArray(e)||ArrayBuffer.isView(e)||`length`in e&&Symbol.iterator in e}function Mt(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 Nt(e){if(e===null)throw TypeError(`Expected a non-null value`);return e}function Pt(e){if(typeof e!=`boolean`)throw TypeError(`Condition must be a boolean`);return e}function Ft(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 It(e){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`Redirect target must be a finite number`);return e}function Lt(e,t){if(!e)throw TypeError(`Reaction value requires a reaction frame`);return e[t]}function Rt(e,t){if(!e||t>=e.captures.length)throw RangeError(`Reaction capture is not available`);return e.captures[t]}let zt=Symbol(`terminated call`);function*Bt(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 zt;n=e.next(r)}return t=!0,n.value}finally{t||e.return(void 0)}}let Vt=Object.freeze({createEnum:Tt,createRecord:Et,createBytes:Dt,combineIntents:kt,equalValues:At,readIndex:Mt,nonNull:Nt,checkBoolean:Pt,checkDuration:Ft,checkPc:It,reactionValue:Lt,reactionCapture:Rt,delegate:Bt,terminated:zt});function Ht(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 Ut(e){return e.kind===`optional`?Object.freeze({...e,inner:Object.freeze({...e.inner})}):Object.freeze({...e})}function Wt(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 Gt(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 Kt(e){return e.kind===`parameter`?`$${e.index}`:e.name}function qt(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:${Kt(e.memory)}`),e.kind===`readSample`&&t.push(`pin:${Kt(e.pin)}`),e.kind===`writeIntent`&&n.push(`pin:${Kt(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 Jt(e,t){let n=Wt(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 Yt(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 Xt(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 Zt(e,t,n=!0){return new Qt(e,t.optimize!==!1,n).analyze()}var Qt=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`),this.resolveSuspends()}resolveSuspends(){for(let e=this.nodes.length-1;e>=0;e--){let t=this.nodes[e],n=t.effects.maySuspend;for(let e of t.children.values())for(let t of e.nodes)t.suspends&&(n=!0);t.suspends=n}}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(Wt(n)),get effects(){return u??=qt(n)},children:/* @__PURE__ */ new Map,suspends:!1,...l?{source:Ht(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=Jt(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)&&Yt(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}`)),Gt(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}`)),Gt(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:Ut(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:Xt(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:${Kt(t.to)}`),t.kind===`refEqual`)for(let e of[t.left,t.right])g.add(`${e.kind===`parameter`?e.resource:e.kind}:${Kt(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}:${Kt(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 $t(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}`,Ut(e.type)),e.kind===`local`&&c.set(`local:${e.local}`,Ut(e.type)),e.kind===`parameter`&&c.set(`argument:${e.index}`,Ut(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,Ut(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 en={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},tn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),nn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function rn(e,t={}){return new dn(Zt(e,t,!1),t,!1).compileExecutable(e)}function an(e,t={}){return on(rn(e.body,t))}function on(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 sn(e,t){if(!Number.isSafeInteger(t)||t<0)throw TypeError(`IR identifiers must be nonnegative safe integers`);return`${e}${t}`}let K=e=>sn(`v`,e),cn=e=>sn(`l`,e),ln=e=>JSON.stringify(e);function un(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 dn=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??=$t(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,Vt),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`?K(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 Tt(e.name,e.member);case`bytes`:return Object.freeze(Array.from(Dt(e.value)));case`record`:return Et(e.fields.map(e=>[e.name,e.value]));default:return fn(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:un(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`)?`(${K(e)} === ${K(t)})`:`H.equalValues(${K(e)}, ${K(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 ${K(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 ${K(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, ${ln(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}${K(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=en[e.operator];if(!t)throw TypeError(`Unknown binary operator`);i(`(${K(e.left)} ${t} ${K(e.right)})`)}break;case`numeric`:if(!tn.has(e.builtin))throw TypeError(`Unknown numeric builtin`);i(`${nn.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(K).join(`, `)})`);break;case`record`:i(`H.createRecord([${e.fields.map(e=>`[${this.capture(e.name)}, ${K(e.value)}]`).join(`, `)}])`);break;case`field`:i(`${K(e.value)}[${this.capture(e.field)}]`);break;case`bytes`:i(`H.createBytes([${e.elements.map(K).join(`, `)}])`);break;case`length`:i(`${K(e.value)}.length`);break;case`index`:i(`H.readIndex(${K(e.value)}, ${K(e.index)})`);break;case`optional`:i(K(e.value));break;case`isNone`:i(`(${K(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${K(e.value)})`);break;case`localRead`:i(cn(e.local));break;case`local`:this.line(`let ${cn(e.local)} = ${K(e.initial)};`);break;case`localWrite`:this.line(`${cn(e.local)} = ${K(e.value)};`);break;case`write`:{let t=this.boundName(e.name);t?this.line(`${t}.write(${K(e.value)});`):this.line(`host.write(${this.capture(e.name)}, ${K(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}(${K(e.offset)})`:`host.load(${ln(e.kind)}, ${this.ref(e.memory)}, ${K(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}(${K(e.offset)}, ${K(e.value)});`):this.line(`host.store(${ln(e.kind)}, ${this.ref(e.memory)}, ${K(e.offset)}, ${K(e.value)});`);break}case`copyBytes`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.copy(${K(e.offset)}, ${K(e.length)})`:`host.copyBytes(${this.ref(e.memory)}, ${K(e.offset)}, ${K(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(${K(e.resistance)})`:`host.resistor(${this.ref(e.to)}, ${K(e.resistance)})`);break}case`combineIntents`:i(`H.combineIntents([${e.values.map(K).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(${K(e.value)});`):this.line(`host.intent(${this.ref(e.pin)}, ${K(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)}, ${K(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(${K(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`?Tt(a.name,a.member):a.value;this.block(`${i?`else if`:`if`} (H.equalValues(${K(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=K(e.result);this.line(`let ${n} = H.checkBoolean(${K(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=K(e.result);this.line(`let ${n};`),this.block(`if (H.checkBoolean(${K(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(${K(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(${K(e.duration)});`),this.suspension(n);let r=`yield { kind: ${ln(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(${K(e.target)}), delay: H.checkDuration(${K(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 ${K(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} = ${K(e.value)};`),this.line(`break ${r.label};`);break;default:fn(e)}}};function fn(e){throw TypeError(`Unsupported IR operation: ${String(e.kind)}`)}let pn={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,equal:`===`,notEqual:`!==`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},mn={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},hn=/* @__PURE__ */ new Set([`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`,`equal`,`notEqual`]),gn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),_n=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]),vn=/* @__PURE__ */ new Set([`field`,`optional`,`nonNull`,`readSample`,`resistor`,`combineIntents`,`bytes`,`index`,`select`,`match`]),yn=/* @__PURE__ */ new Set([`bytes`,`record`,`sample`,`intent`,`optional`]),bn=/* @__PURE__ */ new Set([`send`,`notify`,`readSample`,`writeIntent`,`resistor`,`random`,`assert`]);function xn(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 Sn(e){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`stored value must be a safe integer`);return e}let Cn=/* @__PURE__ */ new WeakMap;function wn(e){let t=Cn.get(e);return t===void 0&&(t=new DataView(e.buffer,e.byteOffset,e.byteLength),Cn.set(e,t)),t}function Tn(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 En(e,t){return t??wn(e)}function Dn(e,t,n,r){return En(e,t).getUint16(Tn(e,n,2),r)}function On(e,t,n,r){return En(e,t).getUint32(Tn(e,n,4),r)}function kn(e,t,n,r,i){let a=Tn(e,n,2);En(e,t).setUint16(a,Sn(r),i)}function An(e,t,n,r,i){let a=Tn(e,n,4);En(e,t).setUint32(a,Sn(r),i)}let jn=Object.freeze({checkBoolean:Pt,checkDuration:Ft,checkPc:It,combineIntents:kt,createBytes:Dt,equalValues:At,nonNull:Nt,readIndex:Mt,offset:xn,byte:Sn,load16:Dn,load32:On,store16:kn,store32:An}),q=Symbol(`unsupported direct instruction`),Mn=/* @__PURE__ */ new WeakMap;function Nn(e){let t=Mn.get(e);if(t===void 0){try{t=Zt(e,{},!1).constants}catch{t=/* @__PURE__ */ new Map}Mn.set(e,t)}return t}let Pn=/* @__PURE__ */ new WeakMap;function Fn(e){let t=Pn.get(e);return t===void 0&&(t=Object.freeze({operations:e.operations.length,nestedOperations:Qn(e)}),Pn.set(e,t)),t}let In=/* @__PURE__ */ new WeakMap;function Ln(){let e=Object.freeze({});return In.set(e,{entries:/* @__PURE__ */ new Map,constants:[],resistorSlots:/* @__PURE__ */ new Map,functions:/* @__PURE__ */ new Map,shards:[],nextResume:1,nextShard:1,stats:{compiledBlocks:0,reusedBlocks:0,invalidatedBlocks:0,compiledShards:0,reusedShards:0,clears:0},binding:void 0}),e}function Rn(e){let t=In.get(e);if(t===void 0)throw TypeError(`Invalid direct JIT cache`);return t}function zn(e){return{states:[...e.states],memories:[...e.memories],pins:e.pins===void 0?void 0:[...e.pins],pcName:e.pc.name,pcIndex:e.pc.index,host:e.host===!0,functions:e.functions===void 0?void 0:[...e.functions],blockedStates:e.blockedStates===void 0?void 0:[...e.blockedStates].sort(),blockedMemories:e.blockedMemories===void 0?void 0:[...e.blockedMemories].sort()}}function Bn(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 Vn(e,t){return e===t?!0:e===void 0||t===void 0?!1:Bn(e,t)}function Hn(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 Un(e,t){return e.pcName===t.pcName&&e.pcIndex===t.pcIndex&&e.host===t.host&&Vn(e.functions,t.functions)&&Bn(e.states,t.states)&&Bn(e.memories,t.memories)&&Vn(e.pins,t.pins)&&Hn(e.blockedStates,t.blockedStates)&&Hn(e.blockedMemories,t.blockedMemories)}function Wn(e){if(e!==void 0)return{counter:e.counter,cycles:e.cycles,...e.pending===void 0?{}:{pending:{...e.pending}}}}function Gn(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 Kn(e){e.entries.clear(),e.constants.length=0,e.resistorSlots.clear(),e.functions.clear(),e.shards.length=0,e.nextResume=1,e.nextShard=1,e.binding=void 0,e.stats.clears++}let qn=36e3;function Jn(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 Yn(e,t,n){if(!Nr(t.pc.index)||t.states.get(t.pc.name)!==t.pc.index)return;let r=Rn(n??Ln()),i=zn(t);r.binding!==void 0&&!Un(r.binding,i)&&(r.stats.invalidatedBlocks+=r.entries.size,r.entries.clear(),r.constants.length=0,r.resistorSlots.clear(),r.functions.clear(),r.shards.length=0,r.nextResume=1,r.nextShard=1),r.binding=i;let a=e=>`C[${r.constants.push(e)-1}]`,o=(e,t)=>{let n=`${e}\\0${t}`,i=r.resistorSlots.get(n);return i===void 0&&(i=r.resistorSlots.size,r.resistorSlots.set(n,i)),i},s=e=>{let n=r.functions.get(e);if(n===null)throw q;if(n!==void 0)return n;r.functions.set(e,null);let i=t.functions?.get(e);if(i===void 0)throw q;let c=[],l=e=>`C[${c.push(e)-1}]`,u=new Pr(t,l,o,e=>{let t=s(e);return{...t,target:l(t.run)}},i),d=u.compileFunction(c),f={target:a(d),run:d,body:u};return r.functions.set(e,f),f},c=[],l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Set;for(let n of e){if(!Number.isFinite(n.pc)||u.has(n.pc))continue;if(u.add(n.pc),!Number.isFinite(n.nextPc)){r.entries.delete(n.pc)&&r.stats.invalidatedBlocks++;continue}let e=Wn(t.delayLoops?.get(n.pc)),i=r.entries.get(n.pc),d,f=i?.resumeId;if(i!==void 0&&i.body===n.body&&i.nextPc===n.nextPc&&Gn(i.delay,e))d=i.instruction,d!==void 0&&(d.resumeId=f??0),r.stats.reusedBlocks++;else{i!==void 0&&r.stats.invalidatedBlocks++;try{d=new Pr(t,a,o,s).compile(n)}catch(e){if(e!==q)throw e;d=void 0}d?.duration!==void 0&&f===void 0&&(f=r.nextResume++),d!==void 0&&(d.resumeId=f??0),r.entries.set(n.pc,{body:n.body,nextPc:n.nextPc,delay:e,instruction:d,resumeId:f}),r.stats.compiledBlocks++}d!==void 0&&(c.push(d),l.set(d.pcValue,d))}if(!c.length)return;let d=0;for(let e of c)e.slots.length>d&&(d=e.slots.length);let f=Array.from({length:d},(e,t)=>`v${t}`),p=t,m=Nr(p.shardSize)&&p.shardSize>0?p.shardSize:48;if(p.split===!0&&n!==void 0)return Er(r,c,t,m);let h=Nr(p.shardSlotLimit)?p.shardSlotLimit:void 0,g=p.split===!0&&(h===void 0?c.reduce((e,t)=>e+t.size,0)>48e3:c.reduce((e,t)=>e+t.slots.length,0)>h),_=g?lr(c,t,m):cr(c,t,f),v=Function(`C`,`H`,g?`\"use strict\";\\n${_.join(`\n`)}\\nreturn run;`:`\"use strict\"; return (${_.join(`\n`)});`),y=_.filter(e=>e.startsWith(`function stepShard`)).length,b={run:v(Object.freeze([...r.constants]),jn),shards:g?y:1,pcs:Object.freeze(c.map(e=>e.pcValue)),localCount:d,readStates:ir(c,`readStates`),writeStates:ir(c,`writeStates`),readMemories:ir(c,`readMemories`),writeMemories:ir(c,`writeMemories`)};return Object.defineProperty(b,\"emitStats\",{value:Zn(c)}),Object.freeze(b)}let Xn=Object.assign(Yn,{createCache:Ln,clearCache(e){Kn(Rn(e))},cacheStats(e){let t=Rn(e);return Object.freeze({...t.stats,entries:t.entries.size})}});function Zn(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 Qn(e){let t=0;for(let n of e.operations)switch(t++,n.kind){case`if`:t+=Qn(n.yes),n.no&&(t+=Qn(n.no));break;case`match`:for(let e of n.arms)t+=Qn(e.body);n.otherwise&&(t+=Qn(n.otherwise));break;case`select`:t+=Qn(n.yes.body)+Qn(n.no.body);break;case`and`:case`or`:t+=Qn(n.right.body);break;case`while`:t+=Qn(n.test.body)+Qn(n.body);break;case`assert`:n.message&&(t+=Qn(n.message.body))}return t}function $n(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 er(e){return e>=48&&e<=57}function tr(e){return er(e)||e>=65&&e<=90||e>=97&&e<=122||e===95}function nr(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 rr(e){if(!e.startsWith(`select`))return!1;let t=6,n=t;for(;t<e.length&&er(e.charCodeAt(t));)t++;return t>n&&e.startsWith(`: {`,t)}function ir(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 ar=e=>[`const S = F.states, M = F.memories, L = F.locals, SD = F.stateDirty, MD = F.memoryDirty, MV = F.memoryViews ?? [], P = F.pins, R = F.resistors;`,`const BS = F.blockedStates ?? [], BM = F.blockedMemories ?? [];`,...e.length?[`let ${e.join(`,`)};`]:[]],or=`return \"invalidated\";`;function sr(e,t){let n=e.filter(e=>e.isolated).map(e=>`${t} === ${e.pc}`);return n.length?[`if (${n.join(` || `)}) ${or}`]:[]}function cr(e,t,n){let r=sr(e,`S[${t.pc.index}]`),i=[`function run(F, deadline) {`,...ar(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)=>{i.push(`case ${t+1}: {`),e.slots.forEach((e,t)=>i.push(`${e} = L[${t}];`)),i.push(`F.resume = 0;`,...e.suffix,...e.stop?[]:r,Or(e.stop),`}`)}),i.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)=>{i.push(`case ${e.pc}: {`,...e.barrier,...e.guard,`S[${t.pc.index}] = ${e.nextPc};`,Mr(`SD`,t.pc.index),...e.prefix),e.duration!==void 0&&i.push(...Dr(e,n+1)),i.push(...e.suffix,e.isolated?or:Or(e.stop),`}`)}),i.push(`default: return \"fallback\";`,`}`,`}`,`}`),i}function lr(e,t,n){let r=sr(e,`S[${t.pc.index}]`),i=[...e].sort((e,t)=>e.pcValue-t.pcValue),a=[],o=[],s=0;for(let e of i)o.length&&(o.length>=n||s+e.size>qn)&&(a.push(o),o=[],s=0),o.push(e),s+=e.size;o.length&&a.push(o);let c=0,l=a.map(e=>{let t={start:c,entries:e,maxSlots:Math.max(...e.map(e=>e.slots.length)),lastPc:e[e.length-1].pc,lastResume:c+e.length,resumable:e.some(e=>e.duration!==void 0)};return c+=e.length,t}),u=e=>Array.from({length:e},(e,t)=>`v${t}`),d=[];l.forEach((e,n)=>{let r=n?l[n-1].lastPc:void 0;d.push(`function stepShard${n}(F, deadline, pc) {`,...ar(u(e.maxSlots)),`while (true) {`,`switch (pc) {`),e.entries.forEach((n,i)=>{d.push(`case ${n.pc}: {`,...n.barrier,...n.guard,`S[${t.pc.index}] = ${n.nextPc};`,Mr(`SD`,t.pc.index),...n.prefix,...Dr(n,e.start+i+1),...n.suffix,n.isolated?or:jr(n.stop,r,e.lastPc,t.pc.index),`}`)}),d.push(`default: return \"fallback\";`,`}`,`}`,`}`)}),l.forEach((e,t)=>{e.resumable&&(d.push(`function resumeShard${t}(F, resume) {`,...ar(u(e.maxSlots)),`switch (resume) {`),e.entries.forEach((t,n)=>{t.duration!==void 0&&(d.push(`case ${e.start+n+1}: {`),t.slots.forEach((e,t)=>d.push(`${e} = L[${t}];`)),d.push(`F.resume = 0;`,...t.suffix,...t.stop?[]:r,kr(t.stop),`}`))}),d.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`))}),d.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 f=l.map((e,t)=>({shard:e,shardIndex:t})).filter(({shard:e})=>e.resumable);return f.length?Jn(d,`resume`,f.map(({shard:e,shardIndex:t})=>({bound:String(e.lastResume),call:`status = resumeShard${t}(F, resume);`})),`throw new TypeError(\"Unknown direct JIT continuation\");`):d.push(`throw new TypeError(\"Unknown direct JIT continuation\");`),d.push(`} else {`,`if (F.stopAfterInstruction) return \"invalidated\";`,`const pc = S[${t.pc.index}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc);`),Jn(d,`pc`,l.map((e,t)=>({bound:String(e.lastPc),call:`status = stepShard${t}(F, deadline, pc);`})),`return \"fallback\";`),d.push(`}`,`if (status !== \"next\") return status;`,`}`,`}`),d}function ur(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 dr(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 fr(e,t,n){return e.entries.length<n&&e.sourceSize+t.size<=qn}function pr(e,t){if(e.length<=1)return e.length?[e]:[];let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.pcValue,t);let r=`S[${t}] = `,i=/* @__PURE__ */ new Map;for(let t of e){let e=_r(t,n,r);e!==void 0&&i.set(t,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=(e,t)=>e.pcValue>t.pcValue?3:e.nextPcValue===t.pcValue?2:1,c=(e,t,n)=>{let r=s(e,n),i=s(t,n);return r===i?r===2?e.pcValue<t.pcValue:e.pcValue>t.pcValue:r>i};for(let[e,t]of i){let n=a.get(t);(n===void 0||c(e,n,t))&&(n!==void 0&&o.delete(n),a.set(t,e),o.set(e,t))}let l=[],u=/* @__PURE__ */ new Set;for(let t of e){if(u.has(t)||a.has(t))continue;let e=[],n=t;for(;n!==void 0&&!u.has(n);)u.add(n),e.push(n),n=o.get(n);l.push(e)}for(let t of e){if(u.has(t))continue;let e=[],n=t;for(;n!==void 0&&!u.has(n);)u.add(n),e.push(n),n=o.get(n);l.push(e)}return l}function mr(e,t){return e.length<=2?e:pr(e,t).flat()}function hr(e,t,n,r){let i=new Map(t.map(e=>[e.pcValue,e])),a=/* @__PURE__ */ new Map;for(let t=e.shards.length-1;t>=0;t--){let n=e.shards[t],r=[],o=!1;for(let e of n.entries){let t=i.get(e.pcValue);t===void 0?o=!0:(t!==e&&(o=!0),r.push(t))}if(o&&(n.entries=r,n.dirty=!0),!r.length)e.shards.splice(t,1);else{dr(n);for(let e of n.entries)a.set(e.pcValue,n)}}let o=pr([...i.values()].filter(e=>!a.has(e.pcValue)).sort((e,t)=>e.pcValue-t.pcValue),r);for(let t of o){let r=t.reduce((e,t)=>e+t.size,0),i=e.shards[e.shards.length-1];i!==void 0&&i.entries.length>0&&t.length<=n&&r<=qn&&i.sourceSize+r>qn&&(i={id:e.nextShard++,entries:[],sourceSize:0,maxSlots:0,resumable:!1,functions:void 0,signature:void 0,dirty:!0},e.shards.push(i));for(let r of t){let t=e.shards[e.shards.length-1];(t===void 0||!fr(t,r,n))&&(t={id:e.nextShard++,entries:[],sourceSize:0,maxSlots:0,resumable:!1,functions:void 0,signature:void 0,dirty:!0},e.shards.push(t)),t.entries.push(r),t.dirty=!0,dr(t),a.set(r.pcValue,t)}}}function gr(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 _r(e,t,n){let r,i;for(let a of e.prefix){if(!a.startsWith(n)||!a.endsWith(`;`))continue;let o=Number(a.slice(n.length,-1));if(!Number.isSafeInteger(o)||o===e.nextPcValue)continue;let s=t.get(o);s!==void 0&&s!==e&&(o<e.pcValue&&(r=s),i=s)}if(r!==void 0)return r;if(i!==void 0)return i;let a=t.get(e.nextPcValue);return a!==void 0&&a!==e?a:void 0}function vr(e,t,n,r){if(e.stop)return`return \"stopped\";`;let i=n.host===!0&&e.duration!==void 0&&e.suffix.length===0&&!e.isolated?e.dynamicDuration?`if (F.publishPending) return \"invalidated\"; `:``:n.host&&e.duration!==void 0?`if (F.stopAfterInstruction && !F.finishCheckpoint?.(deadline, ${e.suffix.length===0})) return \"invalidated\"; if (F.publishPending) return \"invalidated\"; `:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; `;return r===void 0?`${i}pc = S[${n.pc.index}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc); if (${t}) continue; return pc;`:`${i}pc = S[${n.pc.index}]; if (pc !== ${r.pc}) { if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc); if (${t}) continue; return pc; }`}function yr(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 br(e,t){let n=Array.from({length:e.maxSlots},(e,t)=>`v${t}`),r=gr(e.entries),i=mr(e.entries,t.pc.index),a=[],o=[`function stepShard${e.id}(F, deadline, pc) {`,...ar(n),`while (true) {`,`switch (pc) {`];i.forEach((e,n)=>{let s=i[n+1];o.push(`case ${e.pc}: {`,...e.barrier,...e.guard,`S[${t.pc.index}] = ${e.nextPc};`,Mr(`SD`,t.pc.index),...e.outlinePrefix(a),...Dr(e,e.resumeId,t.host===!0),...e.suffix,e.isolated?or:vr(e,r,t,s),`}`)}),o.push(`default: return pc;`,`}`,`}`,`}`),e.resumable&&(o.push(`function resumeShard${e.id}(F, resume) {`,...ar(n),`switch (resume) {`),e.entries.forEach(e=>{e.duration!==void 0&&(o.push(`case ${e.resumeId}: {`),e.slots.forEach((e,t)=>o.push(`${e} = L[${t}];`)),o.push(`F.resume = 0;`,...e.suffix,yr(e.stop,t.pc.index),`}`))}),o.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`));for(let e of a)o.push(...e);return o}let xr=/* @__PURE__ */ new Map,Sr=0;function Cr(e){let t=e.length<=65536,n=t?xr.get(e):void 0;if(n!==void 0)return xr.delete(e),xr.set(e,n),n;let r=Function(`C`,`H`,e);if(!t)return r;for(;xr.size>=128||Sr+e.length>4194304;){let e=xr.keys().next().value;xr.delete(e),Sr-=e.length}return xr.set(e,r),Sr+=e.length,r}function wr(e,t,n){let r=br(t,n),i=t.resumable?`resumeShard${t.id}`:`undefined`,[a,o]=Cr(`\"use strict\";\\n${r.join(`\n`)}\\nreturn [stepShard${t.id}, ${i}];`)(Object.freeze([...e.constants]),jn);t.functions={step:a,resume:o},t.signature=Object.freeze([...t.entries]),t.dirty=!1,e.stats.compiledShards++}function Tr(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;`,...sr(t,`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 Er(e,t,n,r){if(hr(e,t,r,n.pc.index),!e.shards.length)return;for(let t of e.shards)t.functions!==void 0&&!t.dirty&&ur(t.signature??[],t.entries)?e.stats.reusedShards++:wr(e,t,n);let i=Tr(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:ir(t,`readStates`),writeStates:ir(t,`writeStates`),readMemories:ir(t,`readMemories`),writeMemories:ir(t,`writeMemories`)};return Object.defineProperty(u,\"emitStats\",{value:Zn(t)}),Object.freeze(u)}function Dr(e,t,n=!1){if(e.duration===void 0)return[];let r=e.dynamicDuration?`(Number.isInteger(${e.duration}) && ${e.duration} >= 0 && ${e.duration} <= 7200000000000000 ? ${e.duration} : H.checkDuration(${e.duration}))`:e.duration,i=n&&e.suffix.length===0&&!e.stop&&!e.isolated;return[`F.due = F.time + ${r};`,`if (F.due > 7200000000000000) throw new RangeError(\"Time out of range\");`,`if ((F.publishPending && F.due > F.time) || F.due >= deadline) {`,`F.resume = ${t};`,...n?[`if (F.due < deadline && F.publishCheckpoint?.()) {`,`F.resume = 0;`,...i?[`F.time = F.due;`,`F.stopAfterInstruction = true;`,`if (!F.finishCheckpoint?.(deadline, true)) return \"invalidated\";`]:[`F.stopAfterInstruction = true;`],`} else {`]:[],...e.slots.map((e,t)=>`L[${t}] = ${e};`),n?`if (F.due < deadline || (F.publishPending && F.due > F.time)) return \"invalidated\";`:`if (F.publishPending && F.due > F.time) return \"invalidated\";`,`F.time = deadline;`,`return \"deadline\";`,...n?[`}`]:[],...i?[`} else F.time = F.due;`]:[`}`,`F.time = F.due;`]]}function Or(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; continue;`}function kr(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; return \"next\";`}function Ar(e){return`(typeof ${e} === \"boolean\" ? ${e} : H.checkBoolean(${e}))`}function jr(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 Mr(e,t){return`${e}[${t>>>5}] |= ${1<<(t&31)};`}function Nr(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}var Pr=class{binding;capture;resistorSlot;resolveFunction;fn;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;nextPcValue=0;pc=``;nextPc=``;resumeId=0;duration;dynamicDuration=!1;immediate=!1;stop=!1;get isolated(){return this.backedges!==void 0}backedges;outlineBranches;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;booleanResults=/* @__PURE__ */ new Set;labels=0;constructor(e,t,n,r,i){this.binding=e,this.capture=t,this.resistorSlot=n,this.resolveFunction=r,this.fn=i}compileFunction(e){let t=this.fn,n=e=>e.kind===`number`||e.kind===`bool`;if(t.params.some(({type:e})=>!n(e))||t.returns&&!n(t.returns)||(this.constants=Nn(t.body),this.region(t.body,this.prefix),this.isolated))throw q;this.compact();let r=t.params.map((e,t)=>`a${t}`),i=[...ar(this.slots),...this.prefix];return Function(`C`,`H`,`\"use strict\"; return function(F${r.map(e=>`,${e}`).join(``)}) {\\n${i.join(`\n`)}\\n};`)(Object.freeze([...e]),jn)}compile(e){this.pcValue=e.pc,this.nextPcValue=e.nextPc,this.constants=Nn(e.body);let t=Fn(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&&Nr(n.counter)&&Nr(n.cycles)){let e=n.pending,t=e!==void 0&&Nr(e.state)&&Nr(e.period)&&Nr(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;`,Mr(`SD`,n.counter),...t===void 0?[]:[`S[${t.state}] += rounds * ${n.cycles};`,Mr(`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 q;if(t.kind===`elapse`){if(this.terminated)throw q;this.terminate(this.delay(t.duration)),r=this.suffix}else if(t.kind===`redirect`){if(this.terminated)throw q;let e=this.delay(t.delay);r.push(`S[${this.binding.pc.index}] = H.checkPc(${this.value(t.target)});`,Mr(`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 q;this.terminate({value:`0`,zero:!0,dynamic:!1}),i=!0}else this.operation(t,r)}if(!this.terminated&&!this.stop||this.isolated&&(!this.immediate||this.stop||this.guard.length))throw q;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+=$n(t),rr(t)&&s++;return this.size=a,this.statements=o,this.selects=s,this}emitBarrier(){let e=[];if(this.isolated){let t=this.binding.pc.index;e.push(`if (SD[${t>>>5}] & ${1<<(t&31)>>>0}) ${or}`)}let 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}outlinePrefix(e){if(this.size<=qn||this.slots.length>64||this.isolated||!this.outlineBranches)return this.prefix;let t=[],n=this.slots.join(`,`),r=[`F`,`S`,`M`,`SD`,`MD`,`MV`,`P`,`R`,...this.slots].join(`,`),i=0;for(let{start:a,end:o}of this.outlineBranches.sort((e,t)=>e.start-t.start)){if(a<i)continue;let s=`outlined${e.length}`;t.push(...this.prefix.slice(i,a));let c=`${s}(${r});`;n?(t.push(`const result = ${c}`),this.slots.forEach((e,n)=>t.push(`${e} = result[${n}];`))):t.push(c),e.push([`function ${s}(${r}) {`,...this.prefix.slice(a,o),...n?[`return [${n}];`]:[],`}`]),i=o}return t.push(...this.prefix.slice(i)),t}compact(){let e=this.slots.length;if(e<=1)return;let t=this.prefix.length,n=this.duration===void 0?[]:[this.duration],r=[...this.prefix,...n,...this.suffix],i=r.length,a=new Int32Array(i+1),o=new Int32Array(i).fill(-1),s=new Int32Array(e).fill(-1),c=new Int32Array(e).fill(-1),l=new Int32Array(e).fill(-1),u=new Int32Array(e).fill(-1),d=[];for(let t=0;t<i;t++){a[t]=d.length;let n=r[t],i=0;if(n.charCodeAt(0)===118){let r=1,a=0;for(;r<n.length&&er(n.charCodeAt(r));)a=a*10+(n.charCodeAt(r)-48),r++;if(r>1&&n.charCodeAt(r)===32&&n.charCodeAt(r+1)===61&&n.charCodeAt(r+2)===32){if(a>=e)return;o[t]=a,s[a]<0&&(s[a]=t),c[a]=t,i=r+3}}for(;i<n.length;){if(n.charCodeAt(i)===34){i=nr(n,i);continue}if(n.charCodeAt(i)!==118||i>0&&tr(n.charCodeAt(i-1))){i++;continue}let r=i+1,a=0;for(;r<n.length&&er(n.charCodeAt(r));)a=a*10+(n.charCodeAt(r)-48),r++;if(r===i+1)i++;else if(r<n.length&&tr(n.charCodeAt(r)))i=r;else{if(a>=e)return;d.push(a),l[a]=t,i=r}}}a[i]=d.length;for(let e=0;e<i;e++)for(let t=a[e];t<a[e+1];t++){let n=d[t];if(s[n]<0||s[n]>e)return}for(let t=0;t<e;t++)c[t]>=0&&(u[t]=Math.max(c[t],l[t]));let f=this.backedges&&/* @__PURE__ */ new Map;for(let e of this.backedges??[]){let r=e.lines===this.prefix?0:t+n.length,i=r+e.head,c=r+e.tail,l=[],p=e=>{s[e]<i&&u[e]<c&&(u[e]=c,l.push(e))};for(let e=i;e<c;e++){let t=o[e];t>=0&&p(t);for(let t=a[e];t<a[e+1];t++)p(d[t])}l.length&&f.set(c,l)}let p=new Int32Array(e).fill(-1),m=[],h=0;for(let e=0;e<i;e++){let t=o[e];t>=0&&p[t]<0&&(p[t]=m.length>0?m.pop():h++),t>=0&&u[t]===e&&(u[t]=-1,m.push(p[t]));for(let t=a[e];t<a[e+1];t++){let n=d[t];u[n]===e&&(u[n]=-1,m.push(p[n]))}let n=f?.get(e);if(n)for(let t of n)u[t]===e&&(u[t]=-1,m.push(p[t]))}let g=Array.from({length:h},(e,t)=>`v${t}`),_=t=>{let n=``,r=0,i=0;for(;i<t.length;){if(t.charCodeAt(i)===34){i=nr(t,i);continue}if(t.charCodeAt(i)!==118||i>0&&tr(t.charCodeAt(i-1))){i++;continue}let a=i+1,o=0;for(;a<t.length&&er(t.charCodeAt(a));)o=o*10+(t.charCodeAt(a)-48),a++;if(a===i+1||a<t.length&&tr(t.charCodeAt(a))){i=a;continue}let s=o<e?p[o]:-1;s<0||(n+=t.slice(r,i),n+=g[s],r=a),i=a}return r===0?t:n+t.slice(r)};for(let e=0;e<t;e++)this.prefix[e]=_(this.prefix[e]);for(let e=0;e<this.suffix.length;e++)this.suffix[e]=_(this.suffix[e]);this.duration!==void 0&&(this.duration=_(this.duration)),this.slots=g}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{Ft(t.value)}catch{throw q}return{value:t.text,zero:t.value===0,dynamic:!1}}let n=this.values.get(e);if(n===void 0)throw q;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 q;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:this.booleanResults.has(e)?this.value(e):Ar(this.value(e))}isGuaranteedBoolean(e){if(this.booleanResults.has(e))return!0;let t=this.folded.get(e);return t!==void 0&&typeof t.value==`boolean`}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(!Nr(n)||t&&this.binding.blockedStates?.has(e))throw q;return(t?this.writeStates:this.readStates).add(e),t&&this.writtenStates.add(n),n}memory(e){if(e.memory.kind!==`memory`)throw q;let t=e.memory.name,n=this.binding.memories.get(t),r=e.kind.startsWith(`store`);if(!Nr(n)||r&&this.binding.blockedMemories?.has(t))throw q;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:(e.constant.kind===`bool`&&this.booleanResults.add(e.result),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=mn[e.operator],i=n(e.value);return!r||i===void 0?!1:(e.operator===`not`&&this.booleanResults.add(e.result),t.set(e.result,`(${r}${i})`),!0)}case`binary`:{let r=pn[e.operator],i=n(e.left),a=n(e.right);return!r||i===void 0||a===void 0?!1:(hn.has(e.operator)&&this.booleanResults.add(e.result),t.set(e.result,`(${i} ${r} ${a})`),!0)}case`numeric`:{if(!gn.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)}_n.has(e.builtin)&&this.booleanResults.add(e.result);let i=_n.has(e.builtin)?`Number`:`Math`;return t.set(e.result,`${i}.${e.builtin}(${r.join(`,`)})`),!0}case`nonNull`:{let r=n(e.value);return r!==void 0&&(t.set(e.result,`H.nonNull(${r})`),!0)}default:return!1}}requireHost(){if(this.binding.host!==!0)throw q}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 q;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 q;t.push(`${n.slot} = ${this.value(r.value)}; break ${n.label};`)}else this.operation(r,t,n)}operation(e,t,n){let r;if(bn.has(e.kind)&&this.requireHost(),`result`in e){let t=e.type.kind;if(t!==`number`&&t!==`bool`&&!(vn.has(e.kind)||e.kind===`constant`&&(t===`string`||t===`enum`||t===`bytes`)))throw q;if(this.foldResult(e))return;r=this.slot(),this.values.set(e.result,r),yn.has(t)&&this.references.add(e.result)}let i=e=>{t.push(`${r} = ${e};`)};switch(e.kind){case`parameter`:if(!this.fn?.params[e.index])throw q;i(`a${e.index}`);break;case`return`:case`returnValue`:if(!this.fn)throw q;t.push(e.kind===`returnValue`?`return ${this.value(e.value)};`:`return;`);break;case`call`:case`callValue`:{let n=this.resolveFunction?.(e.name);if(!n)throw q;let r=e.args.map(e=>{if(e.kind!==`value`)throw q;return this.value(e.value)});for(let e of n.body.readStates)this.state(e,!1);for(let e of n.body.writeStates)this.state(e,!0);for(let e of n.body.readMemories)this.memory({kind:`load8`,memory:{kind:`memory`,name:e}});for(let e of n.body.writeMemories)this.memory({kind:`store8`,memory:{kind:`memory`,name:e}});let a=`${n.target}(F${r.map(e=>`, ${e}`).join(``)})`;e.kind===`callValue`?i(a):t.push(`${a};`);break}case`constant`:{if(e.constant.kind!==`bytes`)throw q;let t;try{t=Object.freeze(Array.from(Dt(e.constant.value)))}catch{throw q}i(`H.createBytes(${this.capture(t)})`);break}case`read`:if(e.resource!==`state`)throw q;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)};`,Mr(`SD`,n));break}case`unary`:{let t=mn[e.operator];if(!t)throw q;i(`(${t}${this.value(e.value)})`),e.operator===`not`&&this.booleanResults.add(e.result);break}case`binary`:{let t=pn[e.operator];if(!t)throw q;let n=this.value(e.left),r=this.value(e.right);if(hn.has(e.operator)&&this.booleanResults.add(e.result),(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(!gn.has(e.builtin))throw q;_n.has(e.builtin)&&this.booleanResults.add(e.result),i(`${_n.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 q;let t=this.binding.pins?.get(e.pin.name);if(Nr(t)){i(`P[${t}].sample`);break}i(`F.host.sample(${this.capture(e.pin.name)})`);break}case`writeIntent`:{if(e.pin.kind!==`pin`)throw q;let n=this.binding.pins?.get(e.pin.name);if(Nr(n)){t.push(`F.writePinIntent(${n}, ${this.value(e.value)});`);break}t.push(`F.host.intent(${this.capture(e.pin.name)}, ${this.value(e.value)});`);break}case`resistor`:{if(e.to.kind!==`pin`)throw q;let t=this.binding.pins?.get(e.to.name),n=this.folded.get(e.resistance);if(Nr(t)&&this.resistorSlot!==void 0&&n!==void 0&&typeof n.value==`number`&&Number.isFinite(n.value)&&n.value>=.001&&n.value<=1e9){let t=this.resistorSlot(e.to.name,n.value);i(`(R[${t}] ?? (R[${t}] = F.host.resistor(${this.capture(e.to.name)}, ${n.text})))`);break}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`:if(this.binding.pins!==void 0&&/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e.field)){i(`${this.value(e.value)}.${e.field}`);break}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 q;this.booleanResults.add(e.result),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`:this.booleanResults.add(e.result),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 q;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 q;i(t);break}case`localWrite`:{let n=this.locals.get(e.local);if(!n)throw q;t.push(`${n} = ${this.value(e.value)};`);break}case`load8`:{let t=`M[${this.memory(e)}]`,n=this.folded.get(e.offset);if(n!==void 0&&typeof n.value==`number`&&Number.isSafeInteger(n.value)&&n.value>=0){i(`(${n.text} < ${t}.length ? ${t}[${n.text}] : H.offset(${t},${n.text}))`);break}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)});`,Mr(`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});`,Mr(`MD`,n));break}case`and`:case`or`:{if(e.right.body.operations.at(-1)?.kind!==`yield`)throw q;this.booleanResults.add(e.result);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} = ${Ar(r)};`,`}`);break}case`match`:{let r=this.value(e.value);if(!e.arms.length&&!e.otherwise||!e.otherwise&&n)throw q;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)}) {`);let r=t.length;if(this.region(e.yes,t,n),e.no){let i=t.length-r;t.push(`} else {`);let a=t.length;this.region(e.no,t,n);let o=t.length-a;!n&&t===this.prefix&&i>0&&o>=512&&o>=i*8&&(this.outlineBranches??=[]).push({start:a,end:t.length})}t.push(`}`);break}case`while`:{if(n||e.test.body.operations.at(-1)?.kind!==`yield`)throw q;let r=t.length,i=this.slot(),a=`loopTest${this.labels++}`;t.push(`while (true) {`,`${a}: {`),this.region(e.test.body,t,{slot:i,label:a}),t.push(`}`,`if (!${Ar(i)}) break;`),this.region(e.body,t),(this.backedges??=[]).push({lines:t,head:r,tail:t.length}),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),o=()=>{if(e.type.kind!==`bool`)return;let t=e.yes.body.operations.at(-1),n=e.no.body.operations.at(-1);t?.kind===`yield`&&n?.kind===`yield`&&this.isGuaranteedBoolean(t.value)&&this.isGuaranteedBoolean(n.value)&&this.booleanResults.add(e.result)};if(i!==void 0&&a!==void 0){t.push(`${r} = ${n} ? ${i} : ${a};`),o();break}let s=`select${this.labels++}`;t.push(`${s}: {`,`if (${n}) {`),this.region(e.yes.body,t,{slot:r,label:s}),t.push(`} else {`),this.region(e.no.body,t,{slot:r,label:s}),t.push(`}`,`}`),o();break}default:throw q}}};let Fr=Object.freeze([]),Ir=/* @__PURE__ */ new Set([`wait`,`elapse`,`receive`,`waitUntil`,`redirect`,`stop`]);var Lr=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())}},Rr=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}]`}},zr=class extends dn{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 Br;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 ${K(e.result)} = ${r};`):this.line(`${r};`)}else super.emitOperation(e,t,n,r)}},Br=class extends Error{};function Vr(e,t){try{return Zt(e,t,!1)}catch{return}}function Hr(e,t,n){let r=Vr(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(Ir.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=Vr(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 Ur(e,t={}){try{let n=Hr(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 Lr,a=new Rr(n.length),o=t.bindResources!==!1,s=i.capture(Fr),c=[];for(let e=0;e<n.length;e++){let l=n[e],u=new zr(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(),Vt),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=>Gr(e,t))};return(n,r)=>u(e,n??Fr,r,t)}})}catch{return}}let Wr=Object.freeze([]);function Gr(e,t){return t.length?typeof e.bind==`function`?e.bind(t):Object.freeze(t.map(([t,n])=>Kr(e,t,n))):Wr}function Kr(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 qr=Symbol(`unsupported resumable body`),Jr=/^(\\s*)(?:const|let) (v\\d+|l\\d+)( = |;)/;function Yr(e,t={}){if(ii(e))try{return new Xr(Zt(e,t,!1),t,!1).compileMachine(e)}catch{return}}var Xr=class extends dn{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()))});`]:[],`let pc = F.pc;`,`for (;;) {`,`switch (pc) {`];for(let e of this.blocks){a.push(`case ${e.id}: {`);for(let t of e.code)a.push(t);a.push(...Qr(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,Vt),slotCount:this.slots.size,blocks:this.blocks.length,start:0})}locals(){let e=/* @__PURE__ */ new Set;for(let t of this.analysis.nodes){let n=t.operation;`result`in n&&e.add(K(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];ti(i,this.analysis)?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 Zr(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(${K(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`?Tt(c.name,c.member):c.value,u=this.open();u.term={kind:`branch`,test:`H.equalValues(${K(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 qr;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(${K(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 qr}}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?K(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){this.blocks[e].term={kind:`jump`,to:t}}save(e){let t=this.analysis.byOperation.get(e),n=`result`in e?K(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 qr;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 qr;return e.startsWith(`value:`)?K(n):cn(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 Zr(e){let t=[];for(let n of e){let e=Jr.exec(n);e?e[3]!==`;`&&t.push(`${e[1]}${e[2]}${e[3]}${n.slice(e[0].length)}`):t.push(n)}return t}function Qr(e){let t=e.term;if(!t)throw qr;switch(t.kind){case`jump`:return[`pc = ${t.to};`,`break;`];case`branch`:return[`if (${t.test}) pc = ${t.yes};`,`else pc = ${t.no};`,`break;`];case`suspend`:return[`return true;`];case`done`:return[`F.pc = 0;`,`return false;`];default:throw qr}}let $r=/* @__PURE__ */ new Set([`if`,`match`,`while`,`loop`,`break`,`continue`,`return`,`returnValue`,`wait`,`receive`]),ei=/* @__PURE__ */ new Set([`elapse`,`call`,`callValue`,`waitUntil`,`redirect`,`stop`,`yield`]);function ti(e,t){switch(e.kind){case`if`:case`match`:case`while`:case`loop`:return ni(e,t,!1);default:return!$r.has(e.kind)&&!ei.has(e.kind)}}function ni(e,t,n){if(!$r.has(e.kind))return!ei.has(e.kind);switch(e.kind){case`if`:case`match`:case`while`:case`loop`:if(t.byOperation.get(e).suspends)return!1;switch(e.kind){case`if`:return ri(e.yes,t,!0)&&(e.no===void 0||ri(e.no,t,!0));case`match`:return e.arms.every(e=>ri(e.body,t,!0))&&(e.otherwise===void 0||ri(e.otherwise,t,!0));case`while`:return ri(e.test.body,t,!0)&&ri(e.body,t,n);default:return ri(e.body,t,n)}case`break`:case`continue`:return!n;default:return!1}}function ri(e,t,n){return e.operations.every(e=>ni(e,t,n))}function ii(e){for(let t of e.operations)switch(t.kind){case`if`:if(!ii(t.yes)||t.no&&!ii(t.no))return!1;break;case`match`:for(let e of t.arms)if(!ii(e.body))return!1;if(t.otherwise&&!ii(t.otherwise))return!1;break;case`while`:if(!ai(t.test.body)||!ii(t.body))return!1;break;case`loop`:if(!ii(t.body))return!1;break;case`and`:case`or`:if(!ai(t.right.body))return!1;break;case`select`:if(!ai(t.yes.body)||!ai(t.no.body))return!1;break;case`assert`:if(t.message&&!ai(t.message.body))return!1}return!0}function ai(e){for(let t of e.operations)if(t.kind!==`yield`&&($r.has(t.kind)||ei.has(t.kind)||!ii({operations:[t]})))return!1;return!0}var oi=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 si(e,t={}){if(!Number.isFinite(e)||e<.001||e>1e9)throw new oi(`INVALID_ELECTRICAL_PARAMETER`,`Resistance must be finite and in [0.001, 1000000000] ohms.`,t)}let ci=65536;function li(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 ui(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>ci)break}return t}function di(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 fi(e,t,n){let r;for(let i=0;i<e.blocks.length;i++){let a=e.blocks[i],o=di(a,t,n);o!==a&&(r??=e.blocks.slice(),r[i]=o)}return r===void 0?e:{...e,blocks:r}}function pi(e){return{component:e,key:e.nodes.join(`,`)}}function mi(e,t){let n=new _i(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=[];for(let t of r.values()){let n=!0;for(let r of t.nodes)if(e[r].reference!==void 0){n=!1;break}n&&i++;for(let n of vi(t,e)){let e=a.length;a.push(pi(n));for(let t of n.edges)(o[t.pin]??=[])[t.index]=e}}return{blocks:a,edgeBlocks:o,components:r.size,floatingComponents:i}}let hi=e=>e===0?0:e;function gi(e){return{instanceId:e.instance,resource:e.name}}var _i=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 vi(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 _i(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 yi(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 bi(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 xi(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 Si(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=yi(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 Ci(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]=yi(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]=yi(s),Number.isFinite(o[t])||n(`Non-finite backward substitution.`)}}return o}function wi(e,t){e=0+e;let n=e+t;return n+(Math.abs(e)>=Math.abs(t)?e-n+t:t-n+e)}function Ti(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 };`)(wi,r)}function Ei(e,t){let n=[...e],r=new Map(n.map((e,t)=>[e,t])),i=new _i(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 oi(`INVALID_ELECTRICAL_PARAMETER`,`Pin thresholds must both be omitted or finite with low < high.`,gi(e));let o=(e,t)=>{let n=r.get(e);if(n===void 0)throw new oi(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,t===void 0?gi(e):{network:t});return n},s=(e,t)=>{let n=r.get(e);if(n===void 0)throw new oi(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,gi(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 oi(`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=hi(e.voltage);if(t.reference!==void 0&&t.reference!==n)throw new oi(`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=li(e,[]);v[e]=t,y+=t,b^=t}let x=(e,t)=>{let n=li(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]:li(e,n);if(r[e]!==i)return}return n}},te=(e,t)=>{if(!(t.cost>ci))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},()=>[]),ne=Object.freeze([]),T=new Int32Array(l.length),E=[],re=[],D=[],ie=Array(n.length),ae=[],oe=[],se=new Int32Array(n.length),O=0,ce=!1,le=(e,t)=>{for(let n of e)t.indexOf(n)===-1&&(T[n.from]=T[n.from]-1,T[n.to]=T[n.to]-1);for(let n of t)e.indexOf(n)===-1&&(T[n.from]=T[n.from]+1,T[n.to]=T[n.to]+1)},k={solves:0,components:0,floatingComponents:0,factorizations:0,factorizationReuses:0,cacheHits:0,leafPlans:0,leafPropagations:0,topologyPrepares:0},ue=Object.freeze([]),A=[],j=[],M=0,de=Array(n.length),fe=new Int32Array(n.length),pe=1,me=[],he=[],ge=[],N=[],P=[],F=[],_e=/* @__PURE__ */ new Map,ve=()=>(++O===2147483647&&(se.fill(0),O=1),O),I=(e,t)=>{let n=_e.get(e);n===void 0&&(_e.size>=256&&_e.clear(),n={},_e.set(e,n));let r=n[t];return r===void 0&&(r=Object.freeze({voltage:hi(e),level:t,status:`valid`}),n[t]=r),r},L=(e,t)=>e.low===void 0?`unknown`:t<=e.low?`low`:t>=e.high?`high`:`unknown`,R=(e,t,r,i,a)=>{let o=f[e],s=u[o],c=l[i].reference,d=[],p=[],m=[];for(let e=0;e<s.length;e++){let t=s[e],r=n[t];d.push(t),p.push(r),m.push(I(c,L(r,c)))}return{intent:t,targetPin:r.to,resistance:r.resistance,target:i,edges:a,edgeHash:li(e,a),node:o,voltage:c,slots:Object.freeze(d),pins:Object.freeze(p),samples:Object.freeze(m)}},ye=(e,t,n,r,i)=>{let a=R(e,t,n,r,i),o=de[e];if(o===void 0)de[e]=[a],k.leafPlans++;else{for(let e of o)if(e.targetPin===n.to&&e.resistance===n.resistance){e.intent=t;return}o.length<2?o.push(a):o[o.length-1]=a,k.leafPlans++}},be=()=>{for(let e=0;e<F.length;e++){let t=F[e];ye(t.slot,t.intent,t.branch,t.target,t.edges)}F.length=0},xe=(e,t)=>{if(h===void 0)return;let n=de[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(T[i]!==1||l[i].reference!==void 0)return;let a=n[0];if(a.intent===t)return l[a.target].reference===void 0?void 0:a;if(n.length>1){let e=n[1];if(e.intent===t)return l[e.target].reference===void 0?void 0:e}if(t.length!==1)return;let o=t[0];for(let e=0;e<n.length;e++){let r=n[e];if(r.targetPin===o.to&&r.resistance===o.resistance)return l[r.target].reference===void 0?void 0:(r.intent=t,r)}},Se=e=>{j[M++]=e},z=()=>{for(let e=1;e<M;e++){let t=j[e],n=e;for(;n>0&&j[n-1]>t;)j[n]=j[n-1],n--;j[n]=t}},B=e=>{for(let t=0;t<M;t++)e(j[t])},Ce=()=>{if(M===0)return ue;z();let e=Array(M);for(let t=0;t<M;t++)e[t]=j[t];return e},we=(e,t,n,r,i,a)=>{let o=w[e][0].to;if(o!==t&&(T[o]=T[o]-1,T[t]=T[t]+1),S[f[e]]=n,C[e]=r,w[e]=i,a!==void 0){let t=v[e];a!==t&&(v[e]=a,y+=a-t,b^=t^a)}else x(e,i)},Te=()=>{ce=!0,k.solves++,k.leafPropagations++},V=(e,t,n)=>{let{node:r,target:i,voltage:a}=n;if(M=0,S[r]!==a){let e=n.pins,t=n.samples,r=n.slots;for(let n=0;n<e.length;n++){let i=e[n],a=t[n];i.sample!==a&&(i.sample=a,j[M++]=r[n])}}we(e,i,a,t,n.edges,n.edgeHash),Te()},H=e=>{M=0;for(let t=0;t<e;t++){let e=f[me[t]],r=P[t];if(r!==void 0){if(S[e]===r.voltage)continue;let t=r.slots,n=r.pins,i=r.samples;for(let e=0;e<t.length;e++){let r=n[e],a=i[e];r.sample!==a&&(r.sample=a,Se(t[e]))}continue}let i=l[N[t]].reference;if(S[e]===i)continue;let a=u[e];for(let e=0;e<a.length;e++){let t=a[e],r=n[t],o=r.low===void 0?`unknown`:i<=r.low?`low`:i>=r.high?`high`:`unknown`,s=r.sample;(s.voltage!==i||s.level!==o||s.status!==`valid`)&&(r.sample=I(i,o),Se(t))}}for(let t=0;t<e;t++){let e=me[t],n=N[t];we(e,n,l[n].reference,he[t],ge[t],P[t]?.edgeHash)}Te()};function Ee(e){let t=de[e];if(t!==void 0){let r=n[e].intent;if(r!==C[e]){if(fe[e]===pe){let n=t[0],i=n.intent===r?n:t[1];if(i?.intent===r){V(e,r,i);return}}let n=xe(e,r);if(n!==void 0){fe[e]=pe,V(e,r,n);return}}}A[0]=e,A.length=1,Me(A)}function De(e,t){if(h!==void 0){let r=ve(),i=0,a=!0;for(let o=0;o<t;o++){let t=e[o];if(se[t]===r)continue;se[t]=r;let s=n[t].intent;if(s===C[t])continue;let c;if(fe[t]===pe){let e=de[t],n=e[0],r=n.intent===s?n:e[1];r?.intent===s&&(c=r)}if(c===void 0){if(c=xe(t,s),c===void 0){a=!1;break}fe[t]=pe}me[i]=t,he[i]=s,ge[i]=c.edges,N[i]=c.target,P[i]=c,i++}if(a){if(i===0){je(e,t),Me(A);return}H(i);return}}je(e,t),Me(A)}function Oe(e,t){Ee(e),t!==void 0&&M!==0&&B(t)}function ke(e,t,n){De(e,t),n!==void 0&&M!==0&&B(n)}return{get stats(){return Object.freeze({...k})},solve(e){if(Me(Ae(e)),M===0)return ne;z();let t=[];for(let e=0;e<M;e++)t.push(n[j[e]]);return Object.freeze(t)},solveSlot(e){return Ee(e),Ce()},solveSlotInto:Oe,solveSlotBatchInto:ke,solveSlots(e){if(typeof e==`number`)return Ee(e),Ce();if(e===void 0)return Me(void 0),Ce();if(A.length=0,Array.isArray(e)||ArrayBuffer.isView(e)&&Symbol.iterator in e){let t=e;for(let e=0;e<t.length;e++)A.push(t[e])}else for(let t of e)A.push(t);return De(A,A.length),Ce()}};function Ae(e){if(e!==void 0){A.length=0;for(let t of e)A.push(o(t));return A}}function je(e,t){A.length=t;for(let n=0;n<t;n++)A[n]=e[n]}function Me(e){++pe===2147483647&&(fe.fill(0),pe=1);let t=h===void 0;if(F.length=0,M=0,h!==void 0&&!ce&&e!==void 0&&e.length===0){k.solves++,k.cacheHits+=h.blocks.length;return}E.length=0,re.length=0,D.length=0,oe.length=0;let r=ve(),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(se[a]===r)continue;se[a]=r;let o=n[a].intent;if(o===C[a])continue;let s=xe(a,o);if(s===void 0){t=-1;break}me[t]=a,he[t]=o,ge[t]=s.edges,N[t]=s.target,P[t]=s,t++}if(t>0){H(t);return}r=ve()}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(se[u]===r)continue;se[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)||si(e.resistance,gi(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&&T[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]&&F.push({slot:u,intent:p,branch:p[0],target:g[0].to,edges:g}),E.push(u),re.push(p),D.push(g)}if(a&&i){for(let e=0;e<E.length;e++)me[e]=E[e],he[e]=re[e],ge[e]=D[e],N[e]=D[e][0].to,P[e]=void 0;be(),H(E.length);return}ce&&(i=!0);let d=E.length;if(h!==void 0&&!i&&oe.length===0){for(let e=0;e<d;e++){let t=E[e];C[t]=re[e],w[t]=D[e]}k.solves++,k.cacheHits+=h.blocks.length,be();return}let _=h,ne,O,ue=0,A=/* @__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=E[e];ie[t]=D[e],ae.push(t)}if(i){let e=y,t=b;for(let n=0;n<d;n++){let r=E[n],i=li(r,D[n]),a=v[r];i!==a&&(e+=i-a,t^=a^i)}if(ne=`${e}:${t}`,O=ee(ne,ie),O!==void 0)_=fi(O.topology,w,ie);else{let e=w.slice();for(let t=0;t<d;t++)e[E[t]]=D[t];_=mi(l,e),ue++}}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)A.set(t,di(_.blocks[t],w,ie))}let de,_e=/* @__PURE__ */ new Map,I=0,L=0,R=i?0:_.blocks.length-A.size;for(let e of i?_.blocks:A.values()){let{component:t,key:n}=e,r=p.get(n);if(r!==void 0&&xi(r,t,l)){R++,(de??=/* @__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 oi(`ELECTRICAL_SOLVE_FAILED`,e,{...gi(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=Ti(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=>yi(e)),_=Float64Array.from(r,e=>yi(e))}r?.factorization!==void 0&&bi(r.factorization.matrix,h)&&bi(r.factorization.anchors,g)?(c=r.factorization,L++):(c=Si(h,g,s),I++);let v=Ci(c,_,s);e.forEach((e,t)=>{let n=hi(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};(de??=/* @__PURE__ */ new Map).set(n,d);for(let[e,t]of i)S[e]!==t&&_e.set(e,t)}let ye=/* @__PURE__ */ new Map;M=0;for(let[e,t]of _e){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[M++]=i),(l||k.solves===0)&&ye.set(a,Object.freeze({voltage:t===null?null:hi(t),level:o,status:s}))}}for(let e=1;e<M;e++){let t=j[e],n=e;for(;n>0&&j[n-1]>t;)j[n]=j[n-1],n--;j[n]=t}for(let[e,t]of ye)e.sample=t;for(let[e,t]of _e)S[e]=t;for(let e=0;e<d;e++){let t=E[e],n=D[e];le(w[t],n),C[t]=re[e],w[t]=n,x(t,n)}if(i)p=de??/* @__PURE__ */ new Map;else{if(de!==void 0)for(let[e,t]of de)p.set(e,t);for(let[e,t]of A)_.blocks[e]=t}if(h=_,ce=!1,i){let e=O!==void 0&&_===O.topology?O:{id:O?.id??g++,cost:O?.cost??ui(_),topology:_,hashes:O?.hashes??v.slice()};te(ne,e)}k.solves++,k.components=_.components,k.floatingComponents=_.floatingComponents,k.factorizations+=I,k.factorizationReuses+=L,k.cacheHits+=R,k.topologyPrepares+=ue,be()}}var Di=class{times=[];orders=[];values=[];size=0;sequence=0;get time(){return this.size===0?1/0:this.times[0]}push(e,t){let n=this.size++;this.times[n]=e,this.orders[n]=this.sequence++,this.values[n]=t,this.siftUp(n)}pop(){let e=this.values[0],t=--this.size;return t>=0&&(this.times[0]=this.times[t],this.orders[0]=this.orders[t],this.values[0]=this.values[t],this.times[t]=0,this.orders[t]=0,this.values[t]=void 0,this.siftDown()),e}clear(){this.size=0}before(e,t){let n=this.times,r=n[e],i=n[t];return r<i||r===i&&this.orders[e]<this.orders[t]}swap(e,t){let n=this.times,r=this.orders,i=this.values,a=n[e],o=r[e],s=i[e];n[e]=n[t],r[e]=r[t],i[e]=i[t],n[t]=a,r[t]=o,i[t]=s}siftUp(e){for(;e>0;){let t=e-1>>>1;if(!this.before(e,t))break;this.swap(e,t),e=t}}siftDown(){let e=this.size,t=0;for(;;){let n=t*2+1;if(n>=e)break;let r=n+1,i=r<e&&this.before(r,n)?r:n;if(!this.before(i,t))break;this.swap(t,i),t=i}}},Oi=class{entries=[];words=[];activeWords=[];activeCount=0;get size(){return this.activeCount}register(e){return this.entries.push(e)-1}add(e){let t=e>>>5,n=this.words[t]??0;n===0&&(this.activeWords[this.activeCount++]=t),this.words[t]=n|1<<(e&31)}drain(e){let t=this.activeWords,n=this.activeCount;if(n!==0){if(n>1)for(let e=1;e<n;e++){let n=t[e],r=e;for(;r>0&&t[r-1]>n;)t[r]=t[r-1],r--;t[r]=n}for(let r=0;r<n;r++){let n=t[r],i=this.words[n];this.words[n]=0;let a=n*32;for(;i!==0;)e(this.entries[a+31-Math.clz32(i&-i)]),i&=i-1}if(this.activeCount===n)this.activeCount=0;else{for(let e=n;e<this.activeCount;e++)t[e-n]=t[e];this.activeCount-=n}}}clear(){this.entries.length=0,this.words.length=0,this.activeWords.length=0,this.activeCount=0}},ki=class{values=[];head=0;tail=0;get length(){return this.tail-this.head}push(e){this.values[this.tail++]=e}shift(){let e=this.values[this.head];return this.values[this.head++]=void 0,this.head===this.tail&&(this.head=0,this.tail=0),e}clear(){this.values.length=0,this.head=0,this.tail=0}drain(){let e=this.values.slice(this.head,this.tail);return this.clear(),e}};let Ai={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},ji={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},Mi=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),Ni=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function Pi(e,t,n){let r=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,i=h(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 Fi(e,t,n){let r=h(e.bytes,t,n);return e.bytes.slice(r,r+Number(n))}function Ii(e){throw Error(e===void 0?`Assertion failed`:String(e))}function Li(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let Ri=Object.freeze({checkBoolean:Pt,createBytes:Dt,createEnum:Tt,createRecord:Et,equalValues:At,nonNull:Nt,readIndex:Mt,load:Pi,copyBytes:Fi,assertFalse:Ii,sameBytes:Li});var zi=class extends Error{};function J(e){throw new zi(e)}var Bi=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)&&J(`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)&&J(`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)||J(`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`&&J(`resource argument`),this.value(e.value)}memoryRef(e,t){e.kind===`parameter`&&J(`parameterised memory ${t}`);let n=this.target.memoryPlan(e.name);return this.slot(n.slot),n}pinRef(e,t){e.kind===`parameter`&&J(`parameterised pin ${t}`);let n=this.target.pins.get(e.name),r=this.target.sampleResources.get(e.name);return(!n||!r)&&J(`unknown pin ${e.name}`),this.slot(r),n}operation(e,t){let n=t=>{`result`in e||J(`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(Dt(t.value))))})`):t.kind===`enum`?n(this.ref(Tt(t.name,t.member))):t.kind===`record`?n(this.ref(Et(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))&&J(`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`&&J(`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)&&J(`value parameter outside a call`),n(t[e.index]);break}case`unary`:{let t=Ai[e.operator];t||J(`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=ji[e.operator];t||J(`unsupported binary ${e.operator}`),n(`(${this.value(e.left)} ${t} ${this.value(e.right)})`)}break;case`numeric`:Mi.has(e.builtin)||J(`unsupported builtin ${e.builtin}`),n(`${Ni.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||J(`impure call`);let t=this.target.declarations.get(e.name);(t?.kind!==`function`||!t.pure)&&J(`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`?Tt(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||J(`yield outside a value region`),this.line(`${t.slot} = ${this.value(e.value)};`),this.line(`break ${t.label};`);break;default:{let t=e.kind;J(`unsupported operation ${String(t)}`)}}}};function Vi(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 Hi(e,t,n){let r=t;for(let t=1;t<n.length;t++)r=Vi(e,r,n[t]);return{type:r}}function Ui(e){return e?e.kind===`optional`?Ui(e.inner):[`number`,`bool`,`string`,`enum`].includes(e.kind):!1}function Wi(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=>Wi(e,Vi(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=>Wi(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=Wi(e,t.inner,n,r);return i===void 0?void 0:`(${n} === ${r} || (${n} === null ? ${r} === null : (${r} !== null && ${i})))`}default:return}}function Gi(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}=Hi(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 Bi(e),o=a.build(r,n),s=Function(`B`,`H`,`\"use strict\"; return (${o});`)(a.bindingTable(),Ri),c=`function (a, b) { return ${Wi(e.declarations,i,`a`,`b`)??`H.same(a, b)`}; }`,l=Function(`H`,`\"use strict\"; return (${c});`)({...Ri,same:g});return{ok:!0,plan:{key:t,path:[...n],source:o,comparison:c,slots:a.slotsUsed(),evaluate:s,equals:l,needsSnapshot:!Ui(i)}}}catch(e){return{ok:!1,reason:e instanceof zi?e.message:`unexpected code generation failure: ${e instanceof Error?e.message:String(e)}`}}}let Ki=/* @__PURE__ */ new WeakMap,qi=/* @__PURE__ */ new WeakMap,Ji=/* @__PURE__ */ new WeakMap,Yi=/* @__PURE__ */ new WeakMap,Xi=72e14;function Zi(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 Qi(e){let t=Ki.get(e);return t||(t=rn(e),Ki.set(e,t)),t}function $i(e,t){let n=e.entry.model,r=Yi.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,Yi.set(n,r));let i=r.get(t);if(i!==void 0)return i??void 0;let a=Ur(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 ea(e){let t=qi.get(e);return t===void 0&&(t=Yr(e,{bindResources:!0})??null,qi.set(e,t)),t??void 0}function ta(e){return{pc:e.start,slots:Array(e.slotCount),kind:0,duration:0,channel:``,value:void 0}}function na(e,t){let n=Ji.get(e);return n||(n=an(e),Ji.set(e,n)),n(t)}var ra=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 ia(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var aa=class extends TypeError{code=`ASYNC_HOOK_RESULT`;constructor(){super(`Device hooks must return synchronously`)}},oa=class extends RangeError{code=`INVALID_ELECTRICAL_PARAMETER`};function sa(e){if(typeof e!=`number`||!Number.isFinite(e))throw new oa(`Electrical parameters must be finite numbers`);return e}function ca(e){if(ia(e))throw Promise.resolve(e).catch(()=>{}),new aa}function la(e){if(!(e instanceof A))return{};let t=e.diagnostics[0];return t?{...t.path?{path:Object.freeze([...t.path])}:{},...t.source?{source:_(t.source)}:{}}:{}}function ua(e,t,n){return new ra(Object.freeze({code:e,message:t instanceof Error?t.message:String(t),phase:n,time:null,cause:t,...la(t),related:Object.freeze([])}))}let da=Object.freeze([]),fa=/* @__PURE__ */ new WeakMap;function pa(e,t){if(t.length===0)return e;let n=fa.get(e),r=n?.get(t);if(r!==void 0)return r;let i=Xe({...e,declarations:e.declarations.concat(t)});for(let t of i.declarations.slice(e.declarations.length))if(t.kind!==`function`)throw TypeError(`Expected JIT function declaration`);return n===void 0&&(n=/* @__PURE__ */ new WeakMap,fa.set(e,n)),n.set(t,i),i}function ma(e,t){for(let n of t.keys())if(!e.has(n))return!1;return!0}function ha(e,t){return Object.freeze({get props(){return t.assertReadAllowed(e),Object.freeze(Object.fromEntries([...e.props].map(([e,t])=>[e,ee(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 ga=class extends Map{names=[];bankValues=[];dirty=/* @__PURE__ */ new Int32Array;pending=!1;bindDirectBank(e,t){this.names=e,this.bankValues=t,this.dirty=new Int32Array(Math.ceil(e.length/32))}markDirectDirty(e,t){this.dirty[e]|=t,this.pending=!0}flush(){if(!this.pending)return;this.pending=!1;let{names:e,bankValues:t,dirty:n}=this;for(let r=0;r<n.length;r++){let i=n[r];if(i===0)continue;n[r]=0;let a=r<<5;for(;i!==0;){let n=a+31-Math.clz32(i&-i);super.set(e[n],t[n]),i&=i-1}}}get(e){return this.pending&&this.flush(),super.get(e)}set(e,t){return this.pending&&this.flush(),super.set(e,t)}entries(){return this.pending&&this.flush(),super.entries()}values(){return this.pending&&this.flush(),super.values()}forEach(e,t){this.pending&&this.flush(),super.forEach(e,t)}[Symbol.iterator](){return this.pending&&this.flush(),super[Symbol.iterator]()}},_a=class{board;entry;id;declarations=/* @__PURE__ */ new Map;props=/* @__PURE__ */ new Map;constants=/* @__PURE__ */ new Map;states=new ga;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;derivedName;derivedEntry;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;intentEntries=/* @__PURE__ */ new Map;stateSlots=/* @__PURE__ */ new Map;resourceHandles=/* @__PURE__ */ new Map;memoryPlans=/* @__PURE__ */ new Map;codeVersions=/* @__PURE__ */ new Map;codeMemories=/* @__PURE__ */ new Set;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,waiters:void 0});u(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=te(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:(e,t)=>{this.writeIntent(e,t)},resistor:(e,t)=>{let n=sa(t);if(n<.001||n>1e9)throw new oa(`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=h(r.bytes,n,i),o=this.dependencies();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=h(i.bytes,n,a),s=f(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,o,a)},copyBytes:(e,t,n)=>{this.track(this.memoryResources,String(e));let r=this.memory(e),i=h(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:()=>S(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=ha(this,e)}track(e,t){this.trackSlot(e.get(t))}dependencies(){let e=this.dependencyStack;return e.length===0?void 0:e[e.length-1]}trackSlot(e){let t=this.dependencies();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}setDerived(e,t){(this.derivedName!==e||this.derivedEntry!==t)&&(this.derived.set(e,t),this.derivedName=e,this.derivedEntry=t)}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.dependencies();if(e)for(let[t,r]of n)e.set(t,r)}}evaluateSource(e,t){this.dependencyStack.push(t);try{return _(this.source(e))}finally{this.dependencyStack.pop();let e=this.dependencies();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:_(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||!ma(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=t===this.derivedName?this.derivedEntry:this.derived.get(t),n=this.board.resourceEpoch;if(e===void 0||e.epoch!==n&&!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();let i=this.evaluate(()=>na(n.value,this.host),r);e={value:i.value,dependencies:i.dependencies,epoch:this.board.resourceEpoch},this.setDerived(t,e)}else e.epoch!==n&&(e.epoch=n);let r=this.dependencies();if(r)for(let[t,n]of e.dependencies)r.set(t,n);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=x(e.type,this.rawProps[t],this.declarations,!0);else if(e.default)r=x(e.type,na(e.default,this.host),this.declarations,!0);else throw TypeError(`Missing property ${t}`)}else r=na(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 Qi(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}writeIntent(e,t){let n=typeof e==`string`?e:String(e),r=this.board,i=this.intentEntries.get(n);if(i===void 0){let e=this.pin(n);i={pin:e,slot:r.electricalSlot(e)},this.intentEntries.set(n,i)}return i.pin.intent!==t&&(i.pin.intent=t,r.markElectricalDirty(i.slot),!0)}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.dependencies();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`}),t=Object.freeze(e),n=e.map(e=>this.states.get(e));this.states.bindDirectBank(t,n),this.directBank={stateNames:t,stateSlots:Object.freeze(e.map(e=>this.stateResources.get(e))),states:new Map(e.map((e,t)=>[e,t])),stateValues:n}}return this.directBank}commitDirectStates(e){let{stateSlots:t}=this.directBank,n=this.states,r=this.board,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===0)continue;e[a]=0,i=!0,n.markDirectDirty(a,o);let s=a<<5;for(;o!==0;){let e=t[s+31-Math.clz32(o&-o)];e.subscribers.size===0?(e.version++,r.noteResourceVersion(e)):r.invalidate(e),o&=o-1}}return i}writeState(e,t,n){let r=_(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}codeVersion(e){return this.codeVersions.get(e)??0}intersectsCodeRegion(e,t,n){return t===void 0||n===void 0||t<e.size&&t+n>0}hasCodeRegion(e,t,n){for(let r of this.jits)if(r.active){for(let i of r.codeRegions)if(i.memory===e&&this.intersectsCodeRegion(i,t,n))return!0}return!1}addMetadataChange(e,t){let n=e.pending,r=t.offset+t.length,i=t.offset;for(let e=0;e<n.length;){let a=n[e],o=a.offset+a.length;t.offset<=o&&a.offset<=r?(i=Math.min(i,a.offset),r=Math.max(r,o),n.splice(e,1)):e++}n.push({memory:t.memory,offset:i,length:r-i})}markMetadataChanged(e,t,n,r){if(e.metadata)for(let i of e.metadata.regions.values()){let a=i.region;if(a.memory!==t||i.appliedVersion===-1||(t===e.options.code&&(i.dirty=!0),!this.intersectsCodeRegion(a,n,r)))continue;i.dirty=!0;let o=n===void 0?0:Math.max(0,n),s=n===void 0?a.size:Math.min(a.size,n+(r??0));s>o&&this.addMetadataChange(i,{memory:t,offset:o,length:s-o})}}memoryChanged(e,t,n){this.memoryChangedSlot(e,this.memoryPlan(e).slot,t,n)}memoryChangedPlan(e,t,n){this.memoryChangedSlot(e.name,e.slot,t,n)}memoryChangedSlot(e,t,n,r){if(this.board.invalidate(t),this.codeMemories.has(e)){this.hasCodeRegion(e,n,r)&&this.codeVersions.set(e,this.codeVersion(e)+1);for(let t of this.jits){let i=!1;for(let a of t.codeRegions)if(a.memory===e&&this.intersectsCodeRegion(a,n,r)){i=!0;break}if(i){if(this.markMetadataChanged(t,e,n,r),t.options.code===e)t.cache.clear(),t.cacheMemories.clear(),t.revision++,t.directPrograms.clear(),t.directProgramRevision=-1,t.directSkip=void 0,t.directMisses.clear(),t.direct?.frame.resume?t.direct.frame.stopAfterInstruction=!0:t.direct=void 0;else if(t.cacheMemories.has(e)){for(let[n,r]of t.cache)r.codeRegion?.memory===e&&t.cache.delete(n);t.cacheMemories.delete(e)}}}}}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=this.pins.get(t),n=e===void 0?-1:this.board.electricalSlot(e),r=e===void 0?void 0:this.sampleResources.get(t),i,a,o=()=>(e===void 0&&(e=this.pin(t),n=this.board.electricalSlot(e),r=this.sampleResources.get(t)),e);return Object.freeze({sample:()=>{let e=o(),t=this.dependencies();return t&&t.set(r,r.version),e.sample},intent:e=>{let t=o();t.intent!==e&&(t.intent=e,this.board.markElectricalDirty(n))},resistor:e=>{if(a!==void 0&&e===i)return a;let n=sa(e);if(n<.001||n>1e9)throw new oa(`Resistance outside [0.001, 1e9]`);let r=this.resistorIntent(t,n);return i=e,a=r,r}})}if(e===`state`){let e=this.states.has(t)?this.stateResources.get(t):void 0,n=e===void 0?-1:this.directBank?.states.get(t)??-2,r=()=>e??=this.stateSlot(t),i=this.states;return Object.freeze({read:()=>{let e=r(),a=this.dependencies();return a&&a.set(e,e.version),n===-2&&(n=this.directBank?.states.get(t)??-1),n<0?i.get(t):this.directBank.stateValues[n]},write:e=>{let n=r();this.writeState(t,e,n)}})}let n=this.memories.has(t)?this.memoryPlan(t):void 0,r=()=>n??=this.memoryPlan(t),i=(e,t,n)=>{let i=r(),a=h(i.bytes,n,e),o=this.dependencies();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=h(o.bytes,i,e),c=f(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,s,e)};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=h(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,_(na(e.initial,this.host)));break;case`memory`:{let t=p(na(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=sa(na(e.low,this.host)),r=sa(na(e.high,this.host));if(n>=r)throw new oa(`Pin thresholds must satisfy low < high`);Object.assign(t,{low:n,high:r})}e.initial&&(t.intent=na(e.initial,this.host));break}case`channel`:{let t=p(na(e.capacity,this.host),`capacity`);if(t===0)throw RangeError(`Capacity must be positive`);let n;if(e.maxLength&&(n=p(na(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(na(e.overflow,this.host)):`drop_new`,incoming:new ki,pending:new ki,outgoing:new ki});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:ea(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:$i(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]=da);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:ee(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`&&!Qi(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]=b(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=x(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})}captureCodeRegions(e){let t=this.memories.get(e.code),n=Object.freeze({memory:e.code,base:0,size:t.length}),r=[];if(Object.hasOwn(e,`codeRegions`)){if(!Array.isArray(e.codeRegions))throw TypeError(`codeRegions must be an array`);for(let t of e.codeRegions){u(t,[`memory`,`base`,`size`]);let e=m(t.memory),i=p(t.base,`code region base`),a=p(t.size,`code region size`);if(a===0)throw RangeError(`Code region size must be positive`);let o=this.memories.get(e)?.length;if(o===void 0)throw this.board.error(`INVALID_BINDING`,`Unknown code region memory`,this);if(a>o)throw this.board.error(`INVALID_BINDING`,`Code region exceeds memory`,this);if(i>2**53-1-a)throw this.board.error(`INVALID_BINDING`,`Code region range is not a safe integer`,this);let s=Object.freeze({memory:e,base:i,size:a});for(let e of[n,...r])if(s.base<e.base+e.size&&e.base<s.base+s.size)throw this.board.error(`INVALID_BINDING`,`Code regions overlap`,this);r.push(s)}}return{all:Object.freeze([n,...r]),additional:Object.freeze(r)}}capturePolling(e,t){let n=/* @__PURE__ */ new Map;if(!Array.isArray(e))throw TypeError(`polling must be an array`);for(let r of e){u(r,[`pc`,`predicate`,`consume`,`wait`]);let e=d(r.pc,`polling pc`);if(t!==void 0&&(e<t.base||e>=t.base+t.size))throw this.board.error(`INVALID_BINDING`,`Polling pc is outside its code region`,this);let i=m(r.predicate),a=this.declarations.get(i);if(n.has(e)||a?.kind!==`function`||!a.pure||a.params.length||a.returns?.kind!==`bool`)throw this.board.error(`INVALID_BINDING`,`Invalid polling declaration`,this);let o;if(Object.hasOwn(r,`consume`)){o=m(r.consume);let e=this.declarations.get(o);if(e?.kind!==`function`||e.params.length!==0||e.returns!==void 0)throw this.board.error(`INVALID_BINDING`,`Invalid polling consume function`,this)}let s;if(Object.hasOwn(r,`wait`)){u(r.wait,[`delay`,`advance`]);let e=m(r.wait.delay),t=m(r.wait.advance),n=this.declarations.get(e),i=this.declarations.get(t);if(n?.kind!==`function`||!n.pure||n.params.length!==0||n.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);s=Object.freeze({delay:e,advance:t})}n.set(e,Object.freeze({predicate:i,...o===void 0?{}:{consume:o},...s===void 0?{}:{wait:s}}))}return n}captureMetadataDelays(e,t){if(!(e instanceof Map))throw TypeError(`codeMetadata delays must be a Map`);let n=/* @__PURE__ */ new Map;for(let[r,i]of e){let e=d(r,`delay pc`);if(e<t.base||e>=t.base+t.size)throw this.board.error(`INVALID_BINDING`,`Delay pc is outside its code region`,this);u(i,[`counter`,`cycles`,`pending`]);let a=m(i.counter),o=f(i.cycles,`delay cycles`);if(o<=0)throw RangeError(`Delay cycles must be positive`);let s;Object.hasOwn(i,`pending`)&&(u(i.pending,[`state`,`period`,`active`]),s=Object.freeze({state:m(i.pending.state),period:m(i.pending.period),active:m(i.pending.active)})),n.set(e,Object.freeze({counter:a,cycles:o,...s?{pending:s}:{}}))}return n}captureCodeMetadata(e,t){if(u(t,[`polling`,`delays`]),!Object.hasOwn(t,`polling`)||!Object.hasOwn(t,`delays`))throw TypeError(`codeMetadata must contain polling and delays`);return{polling:this.capturePolling(t.polling,e),delays:this.captureMetadataDelays(t.delays,e)}}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(u(e,[`entry`,`code`,`codeRegions`,`codeMetadata`,`pc`,`functions`,`beforeInstruction`,`polling`,`delays`,`translate`]),m(e.entry),m(e.code),m(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);let t=this.captureCodeRegions(e);if(Object.hasOwn(e,`codeMetadata`)){if(typeof e.codeMetadata!=`function`)throw this.board.error(`INVALID_BINDING`,`Invalid codeMetadata provider`,this);if(Object.hasOwn(e,`polling`)||Object.hasOwn(e,`delays`))throw this.board.error(`INVALID_BINDING`,`codeMetadata is mutually exclusive with static polling/delays`,this)}if(e.beforeInstruction!==void 0){u(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 n=Object.hasOwn(e,`polling`)?this.capturePolling(e.polling):/* @__PURE__ */ new Map;if(Object.hasOwn(e,`delays`)&&!(e.delays instanceof Map))throw TypeError(`delays must be a Map`);let r=Object.hasOwn(e,`codeMetadata`)?{regions:new Map(t.all.map(e=>[e,{region:e,appliedVersion:-1,dirty:!1,pending:[],polling:/* @__PURE__ */ new Map,delays:/* @__PURE__ */ new Map}])),polling:/* @__PURE__ */ new Map,delays:/* @__PURE__ */ new Map}:void 0,i=this.entry.model,a=e.functions;if(Object.hasOwn(e,`functions`)&&typeof a!=`function`)throw TypeError(`functions must be a JIT function builder callback`);let o=i,s,c=this.host;if(a){let e=a(i);if(ca(e),!Array.isArray(e))throw TypeError(`Expected JIT function declarations`);o=pa(i,e);let t=/* @__PURE__ */ new Map;for(let e of o.declarations.slice(i.declarations.length))e.kind===`function`&&t.set(e.name,e);s=t,c={...this.host,call:(e,n)=>{let r=t.get(e);return r?Qi(r.body)(c,n):this.invoke(e,n)}}}let l={instance:this,model:o,host:c,...s===void 0?{}:{functions:s},options:Object.freeze({...e,...e.codeRegions===void 0?{}:{codeRegions:t.additional},...e.beforeInstruction?{beforeInstruction:Object.freeze({...e.beforeInstruction})}:{}}),codeRegions:t.all,cache:/* @__PURE__ */ new Map,cacheMemories:/* @__PURE__ */ new Set,metadata:r,polling:n,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:/* @__PURE__ */ new Map,pollReads:void 0,currentPc:void 0,automaticPolling:!1,pollingWait:!1,pollingPeriod:0,pollingOrigin:0,pollingToken:0,dependencyDirty:!0,waiterSlots:void 0,active:!0,stopped:!1,queued:!1,execution:void 0};this.jits.push(l),this.board.jits.push(l);for(let e of l.codeRegions)this.codeMemories.add(e.memory);let d={dispose:()=>{l.active&&(l.active=!1,l.execution=void 0,delete l.predicate,l.pollingToken++,this.board.unparkWaiter(l),l.cache.clear(),l.cacheMemories.clear(),l.directPrograms.clear(),l.direct=void 0,l.directMisses.clear(),l.pollReads=void 0)}};return this.resources.push(d),d}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.codeRegions.some(t=>t.memory===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=h(r,n,t.length);t.length&&(r.set(t.slice(),i),this.memoryChanged(e,i,t.length))}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 va=/* @__PURE__ */ new WeakMap;function ya(e,t){va.set(e,t)}function ba(e){let t=va.get(e);if(t===void 0)throw TypeError(`Topic bridge was not created by a board`);return t}function xa(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}function Sa(e,t){let n=e.host.call(t,[]).next();if(!n.done)throw TypeError(`Unexpected suspension in synchronous function`);return n.value}function Ca(e){return e<16?1:Math.max(64,e)}let wa=/* @__PURE__ */ new WeakMap;function Ta(e){let t=wa.get(e);return t===void 0&&(t={stateMask:/* @__PURE__ */ new Int32Array,memoryMask:/* @__PURE__ */ new Int32Array},wa.set(e,t)),t}function Ea(e){let t=e;return t.directStats??={directCompiles:0,directShards:0,directCalls:0,directFallbacks:0,directDeadlines:0,directStopped:0}}function Da(e,t){for(let n of e.codeRegions)if(t>=n.base&&t<n.base+n.size)return n}function Oa(e,t){let n=t.codeRegion;return n===void 0||n.memory===e.options.code}function ka(e){return e.metadata?.polling??e.polling}function Aa(e){return e.metadata?.delays??e.delays}function ja(e){return e.codeRegions.filter(t=>t.memory===e.options.code)}function Ma(e,t,n){let r=t.metadata,i=t.options.codeMetadata;if(r===void 0||i===void 0)return;let a=[],o=/* @__PURE__ */ new Set;for(let e of n){let n=r.regions.get(e);if(n===void 0||o.has(n))continue;o.add(n);let i=t.instance.codeVersion(e.memory);if(n.appliedVersion===i&&n.pending.length===0&&!n.dirty)continue;let s=n.appliedVersion===-1?[Object.freeze({memory:e.memory,offset:0,length:e.size})]:n.pending.map(e=>Object.freeze({...e}));a.push({state:n,changes:s,version:i})}if(a.length===0)return;let s=e.phase;e.phase=`translate`;let c=[];try{for(let n of a){let{region:r}=n.state,a=t.instance.memory(r.memory),o=r.size>=a.length?a:a.subarray(0,r.size),s=!0;try{let a=b(o,()=>{if(!s)throw e.error(`OBJECT_DISPOSED`,`Metadata view expired`,t.instance)}),l=Object.freeze({memory:r.memory,base:r.base,size:r.size,codeVersion:n.version,code:a}),u=i(Object.freeze({region:l,changes:Object.freeze(n.changes.slice())}));ca(u);let d=t.instance.captureCodeMetadata(r,u);c.push({state:n.state,version:n.version,polling:d.polling,delays:d.delays})}finally{s=!1}}let n=!1;for(let e of c){e.state.appliedVersion=e.version,e.state.dirty=!1,e.state.pending.length=0,e.state.polling.clear();for(let[t,n]of e.polling)e.state.polling.set(t,n);e.state.delays.clear();for(let[t,n]of e.delays)e.state.delays.set(t,n);e.state.region.memory===t.options.code&&(n=!0)}r.polling.clear(),r.delays.clear();for(let e of r.regions.values()){for(let[t,n]of e.polling)r.polling.set(t,n);for(let[t,n]of e.delays)r.delays.set(t,n)}n&&(t.directPrograms.clear(),t.directProgramRevision=-1,t.directSkip=void 0,t.direct?.frame.resume||(t.direct=void 0,t.directRevision=-1))}catch(n){throw e.wrap(n,`JIT_FAILED`,`translate`,t.instance)}finally{e.phase=s}}function Na(e,t,n){if(t.metadata===void 0)return;let r=Da(t,n)??t.codeRegions[0],i=[r];e.execution===`throughput`&&e.jits.length===1&&r.memory===t.options.code&&i.push(...ja(t)),Ma(e,t,i)}function Pa(e){let t=Ta(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 Fa(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&&(Pa(e),e.directSkip=void 0)}}function Ia(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(),t.writeIntent(e,i)&&(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 La(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)),s=[...t.pins.keys()],c=new Map(s.map((e,t)=>[e,t])),l=s.map(e=>t.pin(e)),u=Int32Array.from(l,e=>t.board.electricalSlot(e));return e.directLayout={...n,memoryNames:Object.freeze(r),memories:i,memoryBanks:Object.freeze(a),memoryViews:Object.freeze(o),pinNames:Object.freeze(s),pins:c,pinObjects:Object.freeze(l),pinElectricalSlots:u},e.directLayout}function Ra(e,t,n,r){e.time=r.time,r.publishPending=!1;let i=t.commitDirectStates(r.stateDirty);for(let e=0;e<r.memoryDirty.length;e++){let a=r.memoryDirty[e];if(a!==0)for(r.memoryDirty[e]=0;a!==0;){let r=e*32+31-Math.clz32(a&-a);t.memoryChanged(n.memoryNames[r]),a&=a-1,i=!0}}return i}function za(e,t,n,r,i){let a=t.instance,{pinObjects:o,pinNames:s,pinElectricalSlots:c}=n,l={states:n.stateValues,memories:[...n.memoryBanks],memoryViews:n.memoryViews,pins:o,resistors:[],locals:Array(r.localCount),stateDirty:new Int32Array(Math.ceil(n.stateNames.length/32)),memoryDirty:new Int32Array(Math.ceil(n.memoryNames.length/32)),time:e.time,due:e.time,resume:0,stopAfterInstruction:!1,boundarySettled:!1};if(l.writePinIntent=(t,n)=>{if(Object.hasOwn(a,`writeIntent`))e.time=l.time,a.writeIntent(s[t],n)&&(l.publishPending=!0);else{let e=o[t];if(e.intent===n)return;e.intent=n,a.board.markElectricalDirty(c[t]),l.publishPending=!0}},l.host=Ia(e,a,l),t.metadata===void 0&&(l.publishCheckpoint=()=>(Ra(e,a,n,l),e.boundary(),t.directProgramRevision===-1||!e.canContinueDirect(t,l.due)?(l.boundarySettled=!0,!1):(e.current=a,!0)),t.options.beforeInstruction===void 0)){let r=n.states.get(t.options.pc);l.finishCheckpoint=(i,o)=>{o?e.time=l.time:Ra(e,a,n,l),e.boundary();let s=t.direct,c=l.states[r];return t.directProgramRevision===-1||s?.frame!==l||!s.pcs.has(c)||t.directSkip===c||t.directRevision!==t.revision&&t.revision-t.directRevision>=Ca(s.pcs.size)||l.time>=i||e.events.time<i||!o&&!e.canContinueDirect(t,l.time)?(l.boundarySettled=!0,!1):(t.directObserverRevision!==a.observerRevision&&Fa(t),l.stopAfterInstruction=!1,e.current=a,!0)}}return l.blockedStates=i.stateMask,l.blockedMemories=i.memoryMask,l}function Ba(e,t,n){let r=t.instance,i=!!t.direct?.frame.resume;if(!i){let i=d(r.states.get(t.options.pc),`pc`),a=Da(t,i);if(e.execution!==`throughput`||e.jits.length!==1||a!==void 0&&a.memory!==t.options.code||ka(t).has(i)||t.cache.get(i)?.polling||(Fa(t,n),t.directSkip===i))return!1;if(t.directRevision!==t.revision){let n=t.direct?.pcs.size??0,r=t.revision-t.directRevision,a=Ca(n),o=t.direct?.pcs.has(i)===!0,s=o?0:t.directMisses.get(i)??0;if(t.direct===void 0||r>=a||s>=4){t.directProgramRevision!==t.revision&&(t.directProgramRevision===-1&&t.directCache!==void 0&&Xn.clearCache(t.directCache),t.directPrograms.clear(),t.directProgramRevision=t.revision);let n=La(t),r=[...t.cache.values()].filter(e=>!e.polling&&!ka(t).has(e.pc)&&Oa(t,e)),i=/* @__PURE__ */ new Map;for(let[e,r]of Aa(t)){let t=n.states.get(r.counter);if(t===void 0)continue;let a=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)};i.set(e,a!==void 0&&a.state!==void 0&&a.period!==void 0&&a.active!==void 0?{counter:t,cycles:r.cycles,pending:a}:{counter:t,cycles:r.cycles})}let a=JSON.stringify([...i].sort(([e],[t])=>e-t)),o=t.directPrograms.get(a);if(o)t.direct=o,t.directRevision=t.revision;else{let{states:o,memories:s,pins:c}=n,l=t.directCache??=Xn.createCache(),u=Xn(r,{states:o,memories:s,pins:c,pc:{name:t.options.pc,index:o.get(t.options.pc)},host:!0,...t.functions===void 0?{}:{functions:t.functions},split:!0,shardSize:32,delayLoops:i},l);t.directRevision=t.revision,t.directMisses.clear();let d=Ea(t);d.directShards=u?.shards??0,u&&d.directCompiles++;let f=Ta(t);f.stateIndex=o,f.memoryIndex=s;let p=Math.ceil(n.stateNames.length/32),m=Math.ceil(n.memoryNames.length/32);f.stateMask.length!==p&&(f.stateMask=new Int32Array(p)),f.memoryMask.length!==m&&(f.memoryMask=new Int32Array(m)),Pa(t),t.direct=u?{program:u,pcs:new Set(u.pcs),frame:za(e,t,n,u,f)}:void 0,t.direct?t.directPrograms.set(a,t.direct):t.directPrograms.delete(a)}}else if(!o){let e=Ea(t);return e.directCalls++,e.directFallbacks++,t.cache.has(i)&&t.directMisses.set(i,s+1),!1}}if(!t.direct)return!1}let a=t.direct,o=a.frame,s=t.directLayout;for(;;){i&&(o.stopAfterInstruction=!0),o.time=e.time;let n=e.time,c,l,u=Ea(t);u.directCalls++;try{c=a.program.run(o,Math.min(e.executionEnd,e.events.time))}finally{l=Ra(e,r,s,o)}if(o.boundarySettled?o.boundarySettled=!1:(c!==`fallback`||l||e.time!==n)&&e.boundary(),c===`fallback`){let i=d(r.states.get(t.options.pc),`pc`);if(ka(t).has(i)||t.cache.get(i)?.polling||(u.directFallbacks++,t.directSkip=i),!l&&e.time===n&&e.time<e.executionEnd)return!1}else if(c===`stopped`)return u.directStopped++,t.stopped=!0,!0;else c===`invalidated`?(o.stopAfterInstruction=!1,t.directProgramRevision===-1&&o.resume===0&&(t.direct=void 0,t.directRevision=-1)):u.directDeadlines++;if(o.resume){let n=Math.max(o.due,e.time);if(t.metadata===void 0&&e.canContinueDirect(t,n)){e.time=n,e.current=r,i=!0;continue}if(n>e.time)return e.events.push(n,()=>e.queueJit(t)),!0}return e.queueJit(t),!0}}function Va(e,t,n){let r=new Map(t),i=e.instance,a=i.stateResources.get(e.options.pc);r.set(a,a.version);let o=(n===void 0?void 0:Da(e,n))?.memory??e.options.code,s=i.memoryResources.get(o);return r.set(s,s.version),r}function Ha(e,t,n,r,i){t.dependencies=n,t.pollingWait=!0,t.pollingPeriod=0,e.parkWaiter(t);let a=++t.pollingToken;if(e.boundary(),r===0||i===void 0)return;let o=Zi(e.time+r);e.events.push(o,()=>{if(a!==t.pollingToken||!t.active||t.stopped||!e.waitingJits.has(t))return;let n=t.dependencies;delete t.dependencies,e.unparkWaiter(t),t.pollingToken++,e.current=t.instance,t.instance.dependenciesCurrent(n)&&(t.instance.syncCall(i,[r]),e.boundary()),e.queueJit(t)})}function Ua(e,t,n){if(n.kind===`elapse`){let r=Zi(n.duration);if(r===0)return!1;let i=Zi(e.time+r);return e.events.push(i,()=>e.queueJit(t)),e.boundary(),!0}if(n.kind===`waitUntil`){let r=t.instance.evaluate(()=>Sa(t,n.predicate));return r.value!==!0&&(t.predicate=n.predicate,t.pollingWait=!1,t.dependencies=r.dependencies,e.parkWaiter(t),e.boundary(),!0)}if(n.kind===`stop`)return t.stopped=!0,t.execution=void 0,e.boundary(),!0;if(n.kind===`redirect`){d(n.pc,`redirect target`);let r=Zi(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?Va(t,i,t.currentPc):void 0;return t.automaticPolling=!1,t.pollReads=void 0,e.boundary(),r===0?e.queueJit(t):e.events.push(Zi(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.parkWaiter(t)):e.queueJit(t))}),!0}throw TypeError(`Invalid JIT suspension`)}function Wa(e,t){if(t.queued=!1,t.active&&!t.stopped){if(e.current=t.instance,t.metadata!==void 0&&Na(e,t,d(t.instance.states.get(t.options.pc),`pc`)),t.direct?.frame.resume)Ba(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||ka(t).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,Ua(e,t,r.value))return;throw TypeError(`Invalid hook suspension`)}}n=s?.dependencies,r=c}let a=d(t.instance.states.get(t.options.pc),`pc`);if(e.execution===`throughput`){let i=ka(t).get(a);if(i){let r=t.instance.evaluate(()=>t.instance.syncCall(i.predicate));if(r.value!==!0){let o=new Map([...n??[],...r.dependencies]),s=0,c=i.wait;c&&(s=Zi(t.instance.evaluate(()=>t.instance.syncCall(c.delay),o).value)),Ha(e,t,Va(t,o,a),s,c?.advance);return}i.consume&&t.instance.syncCall(i.consume)}if(!r&&e.jits.length===1&&Ba(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=Da(t,a),i=n?.memory??t.options.code,s=t.instance.memory(i),c=b(n===void 0||n.size>=s.length?s:s.subarray(0,n.size),()=>{if(!r)throw e.error(`OBJECT_DISPOSED`,`Translation view expired`,t.instance)}),l=t.options.translate(Object.freeze({pc:a,code:c,codeBase:n?.base??0,codeVersion:t.instance.codeVersion(i)}),wt({device:t.model}));ca(l);let u=tt(l,t.model);if(u.instructions[0]?.pc!==a)throw TypeError(`Translated first pc does not match`);let d=u.instructions.map(e=>{let n=Da(t,e.pc);return{pc:e.pc,nextPc:e.nextPc,body:e.body,polling:xa(e.body,e.pc,t.options.pc),execute:Qi(e.body),codeRegion:n}});d.some(e=>t.direct?.pcs.has(e.pc))&&(t.direct=void 0,t.directPrograms.clear());for(let e=d.length-1;e>=0;e--){let n=d[e];t.cache.set(n.pc,n),t.cacheMemories.add(n.codeRegion?.memory??t.options.code)}d.some(e=>e.codeRegion===void 0||e.codeRegion.memory===t.options.code)&&t.revision++,t.directSkip=void 0,o=d[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.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(Ua(e,t,n.value))return}}}}let Ga=Symbol.for(`mica-js.simulator/observations`),Ka=Symbol.for(`mica-js.simulator/processes`),qa=Object.freeze({}),Ja=/* @__PURE__ */ new WeakMap;function Ya(e){try{if(!Array.isArray(e))throw TypeError(`Expected device entries`);let t=/* @__PURE__ */ new Set,n=e.map(e=>{u(e,[`id`,`model`,`create`]);let n=m(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=Xe(e.model)}catch(e){throw ua(e instanceof A&&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 Ja.set(r,n),r}catch(e){throw e instanceof ra?e:ua(`INVALID_CONFIGURATION`,e,`library`)}}var Xa=class{time=0;status=`ready`;phase=`assembly`;current;pendingElectricalSlot=-2;dirtyElectricalSlots=/* @__PURE__ */ new Int32Array;dirtyElectricalStamps=/* @__PURE__ */ new Int32Array;dirtyElectricalLength=0;dirtyElectricalEpoch=1;observations=new Oi;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 t;diagnostics=new t;listeners=/* @__PURE__ */ new Set;hostListeners=0;models=new ki;events=new Di;readyJits=new ki;versionEpoch=0;waitingJits=/* @__PURE__ */ new Set;waiterEpoch=0;waitingScanEpoch=0;pollingWaiterCount=0;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{u(t,[`instances`,`nets`]),u(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`)?f(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`)?f(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){u(e,[`id`,`type`,`props`,`randomState`]);let t=m(e.id),n=m(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 _a(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,p=/* @__PURE__ */ new Set;for(let e of t.nets){u(e,[`id`,`pins`,`voltage`]);let t=m(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`)&&d(e.voltage,`voltage`);for(let t of e.pins){u(t,[`instance`,`pin`]);let e=m(t.instance),n=m(t.pin);if(c.get(e)?.declarations.get(n)?.kind!==`pin`)throw TypeError(`Unknown pin endpoint`);let r=`${e}\\0${n}`;if(p.has(r))throw TypeError(`Duplicate connected endpoint`);p.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 h=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}:{}})),g=[];for(let e of this.instances)for(let t of e.pins.values()){let n=e.sampleResources.get(t.name);g.push(t),this.sampleSlots.set(t,n),this.electricalSlots.set(t,this.sampleSlotsBySlot.length),this.sampleSlotsBySlot.push(n)}this.network=Ei(g,h),this.dirtyElectricalSlots=new Int32Array(g.length),this.dirtyElectricalStamps=new Int32Array(g.length),this.phase=`initialize`;for(let e of this.instances){this.current=e;let t;try{if(t=e.entry.create(e.context),ca(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,Ga,{value:()=>this.observationReport(),enumerable:!1}),Object.defineProperty(this,Ka,{value:()=>this.processReport(),enumerable:!1})}catch(e){let t=e instanceof ra?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=[],n=[];for(let r of this.instances)for(let i of r.processes){let a=`${r.id}/${i.declaration.kind===`on`?i.declaration.name:`start`}`;(i.resumable?e:t).push(a),n.push(Object.freeze({key:a,blocks:i.resumable?.blocks??0}))}return Object.freeze({resumable:Object.freeze(e),generic:Object.freeze(t),programs:Object.freeze(n),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 oi?r:void 0;return new ra(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},...la(r),...r===void 0?{}:{cause:r},related:Object.freeze([])}))}wrap(e,t,n,r){if(e instanceof ra&&![`DEVICE_CALLBACK_FAILED`,`JIT_FAILED`,`CLEANUP_FAILED`].includes(t))return e;let i=e instanceof oi||e instanceof oa||e instanceof aa?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&&ca(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 ya(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++,this.versionEpoch++,this.flagWaiters(e),e.subscribers.size!==0)for(let t of e.subscribers)this.observations.add(t.order)}noteResourceVersion(e){this.versionEpoch++,this.flagWaiters(e)}flagWaiters(e){let t=e.waiters;if(t!==void 0&&t.size!==0){for(let e of t)e.dependencyDirty=!0;this.waiterEpoch++}}watchWaiter(e){let t=e.dependencies;if(e.waiterSlots===t)return;let n=e.waiterSlots;if(n!==void 0)for(let t of n.keys())t.waiters?.delete(e);if(t!==void 0)for(let n of t.keys())(n.waiters??=/* @__PURE__ */ new Set).add(e);e.waiterSlots=t,e.dependencyDirty=!0}parkWaiter(e){this.waitingJits.has(e)||(this.waitingJits.add(e),e.pollingWait&&this.pollingWaiterCount++),this.watchWaiter(e),e.dependencyDirty=!0,this.waiterEpoch++}unparkWaiter(e){this.waitingJits.delete(e)&&e.pollingWait&&(e.pollingWait=!1,this.pollingWaiterCount--);let t=e.waiterSlots;if(t!==void 0){for(let n of t.keys())n.waiters?.delete(e);e.waiterSlots=void 0}}get resourceEpoch(){return this.versionEpoch}electricalSlot(e){return this.electricalSlots.get(e)}markElectricalDirty(e){let t=this.pendingElectricalSlot;if(t===e)return;let n=this.dirtyElectricalStamps;if(e>=n.length)throw RangeError(`Electrical slot is outside the board`);let r=this.dirtyElectricalEpoch;if(n[e]!==r){if(n[e]=r,t>=0){let i=this.dirtyElectricalSlots;i[0]=t,i[1]=e,n[t]=r,this.dirtyElectricalLength=2,this.pendingElectricalSlot=-2}else t===-1?this.pendingElectricalSlot=e:this.dirtyElectricalSlots[this.dirtyElectricalLength++]=e}}get dirtyElectricalCount(){return this.pendingElectricalSlot>=0?1:this.dirtyElectricalLength}publish(){let e=this.pendingElectricalSlot;e!==-1&&(e>=0?this.network.solveSlotInto(e,this.publishSlot):this.network.solveSlotBatchInto(this.dirtyElectricalSlots,this.dirtyElectricalLength,this.publishSlot),e===-2&&(this.dirtyElectricalLength=0),++this.dirtyElectricalEpoch===2147483647&&(this.dirtyElectricalStamps.fill(0),this.dirtyElectricalEpoch=1),this.pendingElectricalSlot=-1)}publishSlot=e=>{this.invalidate(this.sampleSlotsBySlot[e])};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=Gi(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,epoch:-1},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(qa):(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?_(n):n,this.commitChain(e,n)}commitChain(e,t){let n=e.plan.path;if(n.length!==1)return;let r=e.plan.slots,i=e.dependencies;for(let e=0;e<r.length;e++){let t=r[e];i.set(t,t.version)}let a=e.entry;a.value!==t&&(a.value=t),a.dependencies=i,a.epoch=this.versionEpoch,e.instance.setDerived(n[0],a)}collectChain(e){let t=e.plan.evaluate(),n=e.plan.needsSnapshot?_(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.pendingElectricalSlot!==-1&&this.publish(),!this.observations.size)return;let e=this.reactionBatch;e.length&&=0;let t=this.changeObservations;t.length&&=0,this.changePrevious.length&&(this.changePrevious.length=0),this.changeCurrent.length&&(this.changeCurrent.length=0),this.observations.drain(this.consumeObservation);let n=t.length;if(n){for(let e=0;e<n;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}}consumeObservation=e=>{if(`plan`in e){this.collectChain(e);return}let t=e.readSource();if(g(e.previous,t))return;let n=e.previous;e.previous=t,this.changeObservations.length?this.recordChange(e,n,t):this.applyChange(e,n,t)};runBoundaryReactions(e){try{for(let t of e)if(t.declaration.captures.length){let e=t.frame;e.captures=t.declaration.captures.map(e=>_(na(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=$i(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??=Qi(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??=Qi(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=Zi(r.duration),a=Zi(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){let r=e.instance;this.current=r,e.state=`running`;let i=e.frame??=ta(t),a=r.host,o=n;for(;;){if(i.value=o,!t.run(a,void 0,void 0,i)){this.boundary(),e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}if(i.kind===2){let t=r.channels.get(i.channel);if(t.incoming.length){o=t.incoming.shift().value;continue}e.state=`waiting`,t.receiver=e,this.boundary();return}let n=i.duration,s=Zi(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(s,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=Zi(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&&(this.waiterEpoch!==this.waitingScanEpoch||this.pollingWaiterCount!==0)){this.waitingScanEpoch=this.waiterEpoch;for(let n=0;n<this.jits.length;n++){let r=this.jits[n];if(r.active&&!r.stopped&&this.waitingJits.has(r)&&(this.watchWaiter(r),r.dependencyDirty||r.pollingWait)){if(r.instance.dependenciesCurrent(r.dependencies)){if(r.dependencyDirty=!1,r.pollingWait&&r.pollingPeriod>0){let n=Xi-(Xi-r.pollingOrigin)%r.pollingPeriod;n<72e14&&n<t&&(n===this.time?(r.pollingToken++,delete r.dependencies,this.unparkWaiter(r),this.queueJit(r)):e=Math.min(e,n))}}else if(r.dependencyDirty=!1,r.pollingWait){r.pollingToken++,delete r.dependencies,this.unparkWaiter(r);let e=r.pollingPeriod>0?(this.time-r.pollingOrigin)%r.pollingPeriod:0;e?this.events.push(Zi(this.time+(r.pollingPeriod-e)),()=>this.queueJit(r)):this.queueJit(r)}else if(r.predicate){let e=r.instance.evaluate(()=>Sa(r,r.predicate));r.dependencies=e.dependencies,e.value===!0?(delete r.predicate,delete r.dependencies,this.unparkWaiter(r),this.queueJit(r)):(this.watchWaiter(r),this.waiterEpoch++)}}}}if(this.time<t&&this.readyJits.length){if(Wa(this,this.readyJits.shift()),this.isFaulted)throw this.primary;continue}if(e<this.events.time&&e<=t){this.time=e;continue}let n=this.events.time;if(n<=t)for(this.time=n;this.events.time===this.time;)this.events.pop()();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{ca(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 ra(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{ca(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 Za(e,t,n){let r=Ja.get(e);if(!r)throw ua(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Unknown device library`),`assembly`);if(arguments.length>=3&&n===void 0)throw ua(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Explicit undefined options`),`assembly`);return new Xa(r,t,n??{})}var Y=class extends Error{name=`SimulationRuntimeError`;code;deviceId;constructor(e,t,n={}){super(t,n.cause===void 0?void 0:{cause:n.cause}),this.code=e,this.deviceId=n.deviceId}};function Qa(e){return e instanceof Error&&e.message.length>0?e.message:String(e)}let $a=[`level`,`message`];function eo(e){return $a.includes(e)?e:void 0}let to={boolean:`level`,number:`level`,vec2d:`level`,vec3d:`level`,string:`message`,bytes:`message`,\"bytes<rgb565>\":`message`,\"bytes<segments>\":`message`};function no(e){return to[e]}function ro(e,t){return eo(e)??no(t)}let io=[`file`,`inline`,`store`];function ao(e){return typeof e==`string`&&io.includes(e)}function oo(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.src==`string`&&ao(t.mode)}function so(e){if(e.startsWith(`/`))return`must be relative to the project root, not absolute`;if(/^[A-Za-z]:/.test(e))return`must not carry a drive letter`;if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return`must not be a URL`;if(e.includes(`\\\\`))return`must use POSIX separators`;let t=e.split(`/`).find(e=>e===`..`||e.startsWith(`~`));if(t!==void 0)return`must stay inside the project root (segment \"${t}\")`}function co(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)?void 0:`must be base64 text`}function lo(e,t){return e===`inline`?co(t):e===`file`?so(t):void 0}var uo=class extends Error{diagnostics;constructor(e){super(fo(e)),this.name=`SchematicError`,this.diagnostics=e}get code(){return this.diagnostics[0]?.code}};function fo(e){let t=e.filter(e=>e.severity===`error`),[n,...r]=t.length>0?t:e;if(n===void 0)return`Schematic validation failed.`;let i=n.pointer===void 0||n.pointer===``?``:` at ${n.pointer}`,a=r.length===0?``:` (and ${r.length} more)`;return`${n.code}${i}: ${n.message}${a}`}function po(e){if(e.some(e=>e.severity===`error`))throw new uo(e)}function mo(e,t){if(typeof e!=`string`)return{ok:!0,value:e};try{return{ok:!0,value:JSON.parse(e)}}catch(e){let n=e instanceof Error?e.message:String(e);return t.push({severity:`error`,code:`json/invalid`,message:`Invalid JSON: ${n}`}),{ok:!1,value:void 0}}}let ho=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function go(e){return ho.test(e)}let _o={\"builtin:label\":`label`,\"builtin:power\":`power`,\"builtin:ground\":`ground`},vo=/^@[A-Za-z0-9][A-Za-z0-9._+-]*$/,yo=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,bo=/^(?:[A-Za-z0-9][A-Za-z0-9._+-]*|-[A-Za-z0-9-]*)$/;function xo(e){let t=e.indexOf(`:`);if(t<=0||t===e.length-1||e.indexOf(`:`,t+1)!==-1)return;let n=e.slice(0,t),r=e.slice(t+1);if(So(n)&&bo.test(r))return{raw:e,packageId:n,deviceId:r}}function So(e){if(e.startsWith(`@`)){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;return n!==void 0&&r!==void 0&&vo.test(n)&&yo.test(r)}return yo.test(e)}function Co(e){return e===`builtin:text`}function wo(e){return _o[e]}function To(e){switch(wo(e)){case`label`:return`net-label`;case`power`:return`power`;case`ground`:return`ground`;default:return Co(e)?`text`:`component`}}function Eo(e){return e===`component`}function Do(e){return e===`net-label`||e===`power`||e===`ground`}function Oo(e){return Eo(To(e.device))?e.designator??e.id:void 0}function ko(e){switch(To(e.device)){case`power`:return e.net??`VCC`;case`ground`:return e.net??`GND`;case`net-label`:return e.net;default:return}}function Ao(e){return e.length===0?``:`/${e.map(e=>e.replace(/~/g,`~0`).replace(/\\//g,`~1`)).join(`/`)}`}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jo(e){return e.some(e=>e.severity===`error`)}function Z(e,t,n,r,i){let a={severity:`error`,code:t,message:n,pointer:Ao(r)};e.push(i===void 0?a:{...a,entity:i})}function Mo(e,t,n,r){for(let i of Object.keys(e))t.includes(i)||Z(r,`schema/unknown-field`,`Unknown field \"${i}\".`,[...n,i])}function No(e,t,n,r,i={}){let a=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(typeof o!=`string`)Z(r,`schema/invalid-type`,`Field \"${t}\" must be a string.`,a);else if(i.nonEmpty===!0&&o.length===0)Z(r,`schema/invalid-value`,`Field \"${t}\" must not be empty.`,a);else return o}function Po(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(typeof a!=`number`)Z(r,`schema/invalid-type`,`Field \"${t}\" must be a number.`,i);else if(!Number.isFinite(a))Z(r,`schema/invalid-value`,`Field \"${t}\" must be a finite number.`,i);else return a}function Fo(e,t,n,r){let i=Po(e,t,n,r);if(i!==void 0){if(!Number.isInteger(i))Z(r,`schema/invalid-value`,`Field \"${t}\" must be an integer.`,[...n,t]);else return i}}function Io(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!Array.isArray(a))Z(r,`schema/invalid-type`,`Field \"${t}\" must be an array.`,i);else return a}function Lo(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!X(a))Z(r,`schema/invalid-type`,`Field \"${t}\" must be an object.`,i);else return a}function Ro(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Point must be an object.`,t);return}Mo(e,[`x`,`y`],t,n);let r=Po(e,`x`,t,n),i=Po(e,`y`,t,n);if(r!==void 0&&i!==void 0)return{x:r,y:i}}function zo(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Resource reference must be an object.`,t);return}Mo(e,[`src`,`mode`],t,n);let r=No(e,`src`,t,n,{nonEmpty:!0}),i;if(Object.prototype.hasOwnProperty.call(e,`mode`)?ao(e.mode)?i=e.mode:Z(n,`schema/invalid-value`,`Field \"mode\" must be \"file\", \"inline\" or \"store\".`,[...t,`mode`]):Z(n,`schema/missing-field`,`Missing required field \"mode\".`,[...t,`mode`]),r===void 0||i===void 0)return;let a=lo(i,r);if(a!==void 0)Z(n,`schema/invalid-value`,`Field \"src\" ${a}.`,[...t,`src`]);else return{src:r,mode:i}}function Bo(e,t,n){if(!X(e)){Z(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)){if(a.length===0){Z(n,`schema/invalid-value`,`Property keys must not be empty.`,t),i=!0;continue}let e=[...t,a];if(typeof o==`string`||typeof o==`boolean`)r[a]=o;else if(o===null)r[a]=null;else if(typeof o==`number`){if(!Number.isFinite(o)){Z(n,`schema/invalid-value`,`Property \"${a}\" must be a finite number.`,e),i=!0;continue}r[a]=o}else if(typeof o==`object`&&!Array.isArray(o)){let t=zo(o,e,n);if(t===void 0){i=!0;continue}r[a]=t}else Z(n,`schema/invalid-value`,`Property \"${a}\" must be a string, finite number, boolean, resource reference or null.`,e),i=!0}return i?void 0:r}function Vo(e,t,n){let r=/* @__PURE__ */ new Set;for(let i of e)r.has(i.id)?Z(n,`id/duplicate`,`Duplicate ${t} id \"${i.id}\".`,i.path,{kind:t,id:i.id}):r.add(i.id)}function Ho(e){let t=[],n=mo(e,t);if(!n.ok)throw new uo(t);let r=Uo(n.value,t);if(r===void 0||jo(t))throw new uo(t);return r}function Uo(e,t){if(!X(e)){Z(t,`json/not-object`,`Schematic must be a JSON object.`,[]);return}Mo(e,[`version`,`sheet`],[],t);let n=Wo(e,t),r=Go(Lo(e,`sheet`,[],t),t);if(n!==void 0&&r!==void 0)return{version:n,sheet:r}}function Wo(e,t){let n=Fo(e,`version`,[],t);if(n!==void 0){if(n!==1)Z(t,`schema/unsupported-version`,`Unsupported version ${n}; expected 1.`,[`version`]);else return 1}}function Go(e,t){if(e===void 0)return;Mo(e,[`symbols`,`wires`,`junctions`],[`sheet`],t);let n=Io(e,`symbols`,[`sheet`],t)??[],r=Io(e,`wires`,[`sheet`],t)??[],i=Io(e,`junctions`,[`sheet`],t)??[],a=[],o=[];n.forEach((e,n)=>{let r=[`sheet`,`symbols`,String(n)],i=qo(e,r,t);i!==void 0&&(a.push(i),o.push({id:i.id,path:[...r,`id`]}))});let s=[],c=[];r.forEach((e,n)=>{let r=[`sheet`,`wires`,String(n)],i=Yo(e,r,t);i!==void 0&&(s.push(i),c.push({id:i.id,path:[...r,`id`]}))});let l=new Set(s.map(e=>e.id)),u=[],d=[];return i.forEach((e,n)=>{let r=[`sheet`,`junctions`,String(n)],i=Xo(e,r,t);if(i===void 0)return;let a=/* @__PURE__ */ new Set;i.wires.forEach((e,n)=>{let o=[...r,`wires`,String(n)];a.has(e)?Z(t,`junction/duplicate-wire`,`Junction \"${i.id}\" references wire \"${e}\" more than once.`,o,{kind:`junction`,id:i.id}):a.add(e),l.has(e)||Z(t,`junction/unknown-wire`,`Junction \"${i.id}\" references unknown wire \"${e}\".`,o,{kind:`junction`,id:i.id})}),u.push(i),d.push({id:i.id,path:[...r,`id`]})}),Vo(o,`symbol`,t),Ko(a,t),Vo(c,`wire`,t),Vo(d,`junction`,t),{symbols:a,wires:s,junctions:u}}function Ko(e,t){let n=/* @__PURE__ */ new Set;e.forEach((e,r)=>{let i=Oo(e);i!==void 0&&(n.has(i)?Z(t,`symbol/designator-duplicate`,`Reference designator ${JSON.stringify(i)} is used more than once.`,[`sheet`,`symbols`,String(r),`designator`],{kind:`symbol`,id:e.id}):n.add(i))})}function qo(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Symbol must be an object.`,t);return}Mo(e,[`id`,`device`,`x`,`y`,`rotation`,`properties`,`designator`,`net`,`reference`],t,n);let r=Zo(e,t,n),i=No(e,`device`,t,n,{nonEmpty:!0}),a=Po(e,`x`,t,n),o=Po(e,`y`,t,n),s=Po(e,`rotation`,t,n),c=e.properties===void 0?void 0:Bo(e.properties,[...t,`properties`],n),l=e.reference===void 0?void 0:Ro(e.reference,[...t,`reference`],n),u=Jo(e,`designator`,i,t,n,Eo),d=Jo(e,`net`,i,t,n,Do);if(i!==void 0){let r=To(i);Do(r)&&d===void 0&&e.net===void 0&&Z(n,`symbol/missing-net`,`Symbols of role \"${r}\" must name the net they attach to.`,[...t,`net`]),!Eo(r)&&e.reference!==void 0&&Z(n,`symbol/unsupported-field`,`Symbols of role \"${r}\" carry no reference designator.`,[...t,`reference`])}if(!(r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||e.reference!==void 0&&l===void 0))return{id:r,device:i,x:a,y:o,rotation:s,...c===void 0?{}:{properties:c},...u===void 0?{}:{designator:u},...d===void 0?{}:{net:d},...l===void 0?{}:{reference:l}}}function Jo(e,t,n,r,i,a){if(e[t]===void 0||n===void 0)return;let o=To(n);if(!a(o))Z(i,`symbol/unsupported-field`,`Symbols of role \"${o}\" must not declare \"${t}\".`,[...r,t]);else return No(e,t,r,i,{nonEmpty:!0})}function Yo(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Wire must be an object.`,t);return}Mo(e,[`id`,`points`],t,n);let r=Zo(e,t,n),i=Io(e,`points`,t,n),a=[];if(i!==void 0&&(i.length<2&&Z(n,`wire/invalid-points`,`Wire must contain at least two points.`,[...t,`points`]),i.forEach((e,r)=>{let i=Ro(e,[...t,`points`,String(r)],n);i!==void 0&&a.push(i)})),r!==void 0&&i!==void 0){for(let e=1;e<a.length;e+=1){let r=a[e-1],i=a[e];if(r!==void 0&&i!==void 0&&r.x!==i.x&&r.y!==i.y){Z(n,`wire/not-orthogonal`,`Wire segments must be horizontal or vertical.`,[...t,`points`,String(e)]);return}}return{id:r,points:a}}}function Xo(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Junction must be an object.`,t);return}Mo(e,[`id`,`x`,`y`,`wires`],t,n);let r=Zo(e,t,n),i=Po(e,`x`,t,n),a=Po(e,`y`,t,n),o=Io(e,`wires`,t,n),s=[];if(o!==void 0&&(o.length<2&&Z(n,`schema/invalid-value`,`Junction must reference at least two wires.`,[...t,`wires`]),o.forEach((e,r)=>{let i=[...t,`wires`,String(r)];typeof e==`string`?e.length===0?Z(n,`schema/invalid-value`,`Junction wire reference must not be empty.`,i):s.push(e):Z(n,`schema/invalid-type`,`Junction wire reference must be a string.`,i)})),r!==void 0&&i!==void 0&&a!==void 0&&o!==void 0)return{id:r,x:i,y:a,wires:s}}function Zo(e,t,n){let r=No(e,`id`,t,n,{nonEmpty:!0});if(r!==void 0){if(!go(r))Z(n,`schema/invalid-value`,`Field \"id\" must be a UUID v4.`,[...t,`id`]);else return r}}function Qo(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function $o(e,t,n=0){return Qo(e,t)<=n}function es(e,t,n,r=0){let i=n.x-t.x,a=n.y-t.y,o=Math.hypot(i,a);if(o===0)return $o(e,t,r);let s=(e.x-t.x)*a-(e.y-t.y)*i;if(Math.abs(s)/o>r)return!1;let c=((e.x-t.x)*i+(e.y-t.y)*a)/(o*o),l=r/o;return c<-l||c>1+l?!1:ts(e,t,n)<=r}function ts(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=r*r+i*i;if(a===0)return Qo(e,t);let o=((e.x-t.x)*r+(e.y-t.y)*i)/a,s=o<0?0:o>1?1:o;return Qo(e,{x:t.x+s*r,y:t.y+s*i})}function ns(e,t,n=0){if(e.length===1){let[r]=e;return r!==void 0&&$o(r,t,n)}for(let r=1;r<e.length;r+=1){let i=e[r-1],a=e[r];if(i!==void 0&&a!==void 0&&es(t,i,a,n))return!0}return!1}function rs(e){let[t,...n]=e;if(t===void 0)return;let r=t.x,i=t.y,a=t.x,o=t.y;for(let e of n)r=Math.min(r,e.x),i=Math.min(i,e.y),a=Math.max(a,e.x),o=Math.max(o,e.y);return{x:r,y:i,width:a-r,height:o-i}}function is(e,t){if(e===void 0)return t;if(t===void 0)return e;let n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),i=Math.max(e.x+e.width,t.x+t.width),a=Math.max(e.y+e.height,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}function as(e,t){let n=t*Math.PI/180,r=Math.cos(n),i=Math.sin(n);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}}function os(e,t){let n=as(t,e.rotation);return{x:e.x+n.x,y:e.y+n.y}}function ss(e,t,n){if(t!==void 0)return rs([{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x,y:t.y+t.height},{x:t.x+t.width,y:t.y+t.height}].map(t=>os(e,t)));let r=Object.values(n).map(t=>os(e,t));return r.length>0?rs(r):{x:e.x,y:e.y,width:0,height:0}}function cs(e,t={}){let n=[],r=t.tolerance??0,{devices:i}=t,{symbols:a,wires:o,junctions:s}=e.sheet,c=[],l;for(let e of a){l=is(l,{x:e.x,y:e.y,width:0,height:0});let t=wo(e.device);if(t!==void 0){let n=ko(e);n!==void 0&&c.push({kind:t,symbolId:e.id,point:{x:e.x,y:e.y},name:n});continue}let r=xo(e.device);if(r===void 0){i!==void 0&&n.push({severity:`error`,code:`device/invalid-reference`,message:`Symbol \"${e.id}\" has an invalid device reference ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});continue}if(i===void 0)continue;let a=i.getDeviceSymbol(r);if(i.getDeviceName(r)===void 0)n.push({severity:`error`,code:`device/unresolved`,message:`Symbol \"${e.id}\" references unresolved device ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});else if(a!==void 0){l=is(l,ss(e,a.bounds,a.pins));for(let[t,n]of Object.entries(a.pins)){let r=os(e,n);c.push({kind:`pin`,symbolId:e.id,pinId:t,point:r}),l=is(l,{x:r.x,y:r.y,width:0,height:0})}}}for(let e of o)l=is(l,rs(e.points));let u=/* @__PURE__ */ new Map;o.forEach((e,t)=>u.set(e.id,t));let d=o.length,f=Array(d+c.length);for(let e=0;e<f.length;e+=1)f[e]=e;let p=e=>{let t=e;for(;f[t]!==t;){let e=f[t];f[t]=f[e],t=e}return t},m=(e,t)=>{let n=p(e),r=p(t);n!==r&&(f[r]=n)};for(let e of s){let[t,...n]=e.wires.map(e=>u.get(e)).filter(e=>e!==void 0);if(t!==void 0)for(let e of n)m(t,e)}let h=/* @__PURE__ */ new Map;c.forEach((e,t)=>{o.forEach((n,i)=>{if(!ns(n.points,e.point,r))return;m(i,d+t);let a=h.get(i);a===void 0?h.set(i,[t]):a.push(t)})});let g=/* @__PURE__ */ new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n={wires:[],connections:[]};return g.set(e,n),n};o.forEach((e,t)=>{_(p(t)).wires.push(t)}),c.forEach((e,t)=>{_(p(d+t)).connections.push(t)});let v=/* @__PURE__ */ new Map,y=[];for(let e of ls(g,c,n)){let t=e.wires.length>0||e.connections.length>=2;if(e.connections.length===0||!t)continue;let n=e.name,r=e.connections.map(e=>c[e]).map(e=>{if(e!==void 0)return e.kind===`pin`?{kind:`pin`,symbolId:e.symbolId,pinId:e.pinId}:{kind:e.kind,symbolId:e.symbolId}}).filter(e=>e!==void 0).sort(ds),i={name:n,wireIds:e.wires.map(e=>o[e]?.id).filter(e=>e!==void 0).sort(),members:r};y.push(i);for(let t of e.connections)v.set(t,i)}let b=[];c.forEach((e,t)=>{if(e.kind!==`pin`)return;let n=v.get(t);b.push({symbolId:e.symbolId,pinId:e.pinId,position:e.point,open:n===void 0,netName:n?.name??null})}),b.sort((e,t)=>e.symbolId.localeCompare(t.symbolId)||e.pinId.localeCompare(t.pinId));let x=[];return o.forEach((e,t)=>{let n=[{end:`start`,point:e.points[0]},{end:`end`,point:e.points[e.points.length-1]}];for(let{end:i,point:a}of n){if(a===void 0)continue;let n=(h.get(t)??[]).some(e=>{let t=c[e];return t!==void 0&&$o(t.point,a,r)}),o=s.some(t=>t.wires.includes(e.id)&&$o({x:t.x,y:t.y},a,r));!n&&!o&&x.push({wireId:e.id,end:i,point:a})}}),x.sort((e,t)=>e.wireId.localeCompare(t.wireId)||e.end.localeCompare(t.end)),po(n),{nets:y.sort((e,t)=>fs(e.name,t.name)||ds(e.members[0],t.members[0])),pins:b,danglingWireEnds:x,bounds:l}}function ls(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let a of e.values()){let e=a.connections.map(e=>t[e]).filter(e=>e!==void 0&&e.kind!==`pin`).map(e=>e.name).sort();e.length>1&&n.push({severity:`error`,code:`net/naming-conflict`,message:`Net has conflicting names: ${e.map(e=>JSON.stringify(e)).join(`, `)}.`});let o=e.length===1?e[0]:null;if(o===null||a.wires.length===0&&a.connections.length<2){i.push({wires:a.wires,connections:a.connections,name:o});continue}let s=r.get(o);if(s===void 0){let e={wires:[...a.wires],connections:[...a.connections]};r.set(o,e),i.push({...e,name:o})}else s.wires.push(...a.wires),s.connections.push(...a.connections)}return i}let us=[`label`,`power`,`ground`,`pin`];function ds(e,t){if(e===void 0||t===void 0)return e===void 0?t===void 0?0:1:-1;if(e.kind!==t.kind)return us.indexOf(e.kind)-us.indexOf(t.kind);let n=e.symbolId.localeCompare(t.symbolId);if(n!==0)return n;let r=e.kind===`pin`?e.pinId:``,i=t.kind===`pin`?t.pinId:``;return r.localeCompare(i)}function fs(e,t){return e===null||t===null?e===null?t===null?0:1:-1:e.localeCompare(t)}function ps(e,t={}){let n=t.pinPitch??10,r=t.stubLength??10,i=t.minWidth??60,a=t.minHeight??40,o=t.horizontalPadding??10,s=t.verticalPadding??10,c=t.characterWidth??5.5,l=t.labelCharacterWidth??4.5,u=t.nameGap??12,d=t.labelInset??10,f={left:[],right:[],top:[],bottom:[]};for(let[t,n]of Object.entries(e.pins))f[n.side??`left`].push(t);let p=Math.max(f.left.length,f.right.length),m=Math.max(f.top.length,f.bottom.length),h=Math.max(a,s*2+Math.max(p-1,0)*n+n,2*(1*c+n/2+d+hs(f,l))),g=Math.max(i,o*2+Math.max(m-1,0)*n+n),_=(ms(f.left)+ms(f.right))*l+e.name.length*c+o*2+u*2,v=Math.ceil(Math.max(g,_)/n)*n,y=Math.ceil(h/n)*n,b={x:-v/2,y:-y/2,width:v,height:y},x=Object.create(null),ee=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`left`?b.x-r:b.x+b.width+r;x[e]={x:s,y:o,side:t}})};ee(f.left,`left`),ee(f.right,`right`);let te=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`top`?b.y-r:b.y+b.height+r;x[e]={x:o,y:s,side:t}})};return te(f.top,`top`),te(f.bottom,`bottom`),{name:e.name,pins:x,bounds:b}}function ms(e){return e.reduce((e,t)=>Math.max(e,t.length),0)}function hs(e,t){return Math.max(ms(e.top),ms(e.bottom))*t/2}let Q=(e,t,n)=>{t.push({severity:`error`,code:`device/invalid-description`,pointer:e,message:n})},gs=(e,t,n)=>{typeof e!=`string`&&Q(t,n,`Expected a string.`)},_s=(e,t,n)=>{(typeof e!=`string`||e.length===0)&&Q(t,n,`Expected a nonempty string.`)},vs=(e,t,n)=>{(typeof e!=`number`||!Number.isFinite(e))&&Q(t,n,`Expected a finite number.`)},ys=(e,t,n)=>{vs(e,t,n),typeof e==`number`&&e<=0&&Q(t,n,`Expected a positive number.`)},bs=(e,t,n)=>{typeof e!=`boolean`&&Q(t,n,`Expected a boolean.`)},xs=(...e)=>(t,n,r)=>{e.includes(t)||Q(n,r,`Expected one of ${e.join(`, `)}.`)},Ss=e=>e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`),$=(e,t=[])=>(n,r,i)=>{if(!X(n))Q(r,i,`Expected an object.`);else{for(let e of t)Object.hasOwn(n,e)||Q(`${r}/${Ss(e)}`,i,`Required field is missing.`);for(let[t,a]of Object.entries(n)){let n=Object.hasOwn(e,t)?e[t]:void 0;n===void 0?Q(`${r}/${Ss(t)}`,i,`Unknown field.`):n(a,`${r}/${Ss(t)}`,i)}}},Cs=e=>(t,n,r)=>{if(!X(t))Q(n,r,`Expected a map.`);else for(let[i,a]of Object.entries(t))e(a,`${n}/${Ss(i)}`,r)},ws=(e,t,n)=>{!Array.isArray(e)||e.length!==2?Q(t,n,`Expected two coordinates.`):e.forEach((e,r)=>vs(e,`${t}/${r}`,n))},Ts=(e,t,n)=>{Array.isArray(e)?(e.forEach((e,r)=>_s(e,`${t}/${r}`,n)),new Set(e).size!==e.length&&Q(t,n,`Values must be unique.`)):Q(t,n,`Expected an array.`)},Es=xs(`left`,`center`,`right`),Ds=$({visible:bs,position:ws,align:Es},[`visible`]),Os=(e,t,n)=>{let r={kind:xs(`number`,`text`,`textarea`,`checkbox`,`file`,`select`)};X(e)&&e.kind===`number`&&Object.assign(r,{min:vs,max:vs,step:ys}),X(e)&&e.kind===`file`&&(r.extensions=(e,t,n)=>{Ts(e,t,n),Array.isArray(e)&&e.forEach((e,r)=>{typeof e==`string`&&!/^\\.[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*$/.test(e)&&Q(`${t}/${r}`,n,`Expected a dotted filename extension.`)})},r.maxSize=(e,t,n)=>{ys(e,t,n),typeof e==`number`&&!Number.isInteger(e)&&Q(t,n,`Expected an integer byte count.`)}),X(e)&&e.kind===`select`&&(r.labels=Cs(gs)),$(r,[`kind`])(e,t,n)},ks=(e,t,n)=>{$({type:xs(`number`,`boolean`,`string`,`enum`,`bytes`),required:bs,nullable:bs,default:()=>{},enumName:_s,values:Ts,title:gs,description:gs,unit:gs,group:gs,order:(e,t,n)=>{(typeof e!=`number`||!Number.isInteger(e)||e<0)&&Q(t,n,`Expected a nonnegative integer.`)},editor:Os},[`type`,`required`])(e,t,n),X(e)&&(e.required===!0&&Object.hasOwn(e,`default`)&&Q(`${t}/default`,n,`Required properties cannot declare defaults.`),e.type===`enum`?((!Object.hasOwn(e,`enumName`)||!Object.hasOwn(e,`values`))&&Q(t,n,`Enum properties require enumName and values.`),Array.isArray(e.values)&&e.values.length===0&&Q(`${t}/values`,n,`Enum values cannot be empty.`)):(Object.hasOwn(e,`enumName`)||Object.hasOwn(e,`values`))&&Q(t,n,`Only enum properties declare enumName and values.`))},As=(e,t,n)=>{let r={type:xs(`line`,`polyline`,`rect`,`circle`,`arc`,`text`),fill:xs(`none`,`foreground`,`background`),strokeWidth:ys},i={line:{fields:{from:ws,to:ws},required:[`from`,`to`]},polyline:{fields:{points:(e,t,n)=>{!Array.isArray(e)||e.length<2?Q(t,n,`Expected at least two points.`):e.forEach((e,r)=>ws(e,`${t}/${r}`,n))},closed:bs},required:[`points`]},rect:{fields:{x:vs,y:vs,width:ys,height:ys},required:[`x`,`y`,`width`,`height`]},circle:{fields:{center:ws,radius:ys},required:[`center`,`radius`]},arc:{fields:{center:ws,radius:ys,startAngle:vs,sweepAngle:(e,t,n)=>{vs(e,t,n),typeof e==`number`&&(e===0||e<-360||e>360)&&Q(t,n,`Sweep must be nonzero and within [-360, 360].`)}},required:[`center`,`radius`,`startAngle`,`sweepAngle`]},text:{fields:{position:ws,text:gs,align:Es,fontSize:ys},required:[`position`,`text`]}},a=X(e)&&typeof e.type==`string`&&Object.hasOwn(i,e.type)?i[e.type]:void 0;$({...r,...a?.fields},[`type`,...a?.required??[]])(e,t,n)},js=(e,t,n)=>{Array.isArray(e)?e.forEach((e,r)=>As(e,`${t}/${r}`,n)):Q(t,n,`Expected graphics array.`)},Ms=$({designator:$({position:ws,align:Es},[`position`])}),Ns=$({kind:xs(`device`),id:(e,t,n)=>{(typeof e!=`string`||!/^[A-Za-z0-9-]+$/.test(e))&&Q(t,n,`Invalid device id.`)},version:_s,displayName:_s,description:_s,license:_s,tags:Ts,templates:Ts,recommends:$({widgets:Ts}),designatorPrefix:(e,t,n)=>{(typeof e!=`string`||!/^\\S+$/.test(e))&&Q(t,n,`Expected a nonempty prefix without whitespace.`)},properties:Cs(ks),pins:Cs($({label:gs,description:gs,group:gs})),ports:Cs($({direction:xs(`input`,`output`),type:xs(`boolean`,`number`,`string`,`vec2d`,`vec3d`,`bytes`,`bytes<rgb565>`,`bytes<segments>`),title:gs,description:gs,delivery:xs(`level`,`message`)},[`direction`,`type`])),symbol:$({bounds:$({x:vs,y:vs,width:ys,height:ys},[`x`,`y`,`width`,`height`]),graphics:js,pins:Cs($({position:ws,direction:xs(`left`,`right`,`up`,`down`),label:Ds},[`position`,`direction`])),annotations:Ms},[`bounds`,`graphics`,`pins`])},[`kind`,`id`,`version`,`displayName`]);function Ps(e){let t=[],n=mo(e,t);if(n.ok&&Ns(n.value,``,t),t.length>0)throw new uo(t);return n.value}function Fs(e){let t=e.symbol,n=t===void 0?ps({name:e.displayName,pins:Object.fromEntries(Object.keys(e.pins??{}).map(e=>[e,{}]))}):void 0,r=Object.create(null);for(let[i,a]of Object.entries(t?.pins??n.pins)){let n=e.pins?.[i]?.label;if(t!==void 0){let e=t.pins[i];r[i]={x:e.position[0],y:e.position[1],side:e.direction===`up`?`top`:e.direction===`down`?`bottom`:e.direction,...e.label===void 0?{}:{label:e.label},...n===void 0?{}:{displayName:n}}}else r[i]={...a,...n===void 0?{}:{displayName:n}}}return t===void 0?{...n,pins:r}:{name:e.displayName,bounds:t.bounds,graphics:t.graphics,pins:r,...t.annotations===void 0?{}:{annotations:t.annotations}}}async function Is(e,t,n){if(!Vs(e)||!Array.isArray(e.devices))throw new Y(`invalid-input`,`Expected schematic and devices`);let r=Ho(e.schematic),i=zs(e.assets),a=Rs(e.voltageReferences),o=/* @__PURE__ */ new Map;for(let t of e.devices){if(!Vs(t)||typeof t.id!=`string`||xo(t.id)===void 0||o.has(t.id)||typeof t.code!=`string`||t.code.trim().length===0)throw new Y(`invalid-input`,`Expected unique device ids and self-contained ESM code`);let e;try{e=structuredClone(Ps(t.definition))}catch(e){throw new Y(`invalid-device`,`Invalid metadata for \"${t.id}\": ${Qa(e)}`,{cause:e})}if(e.id!==xo(t.id).deviceId)throw new Y(`invalid-device`,`Metadata id does not match \"${t.id}\"`,{deviceId:t.id});o.set(t.id,{definition:e,code:t.code})}let s=/* @__PURE__ */ new Map,c=r.sheet.symbols.filter(e=>To(e.device)===`component`);for(let e of c){if(s.has(e.device))continue;let r=o.get(e.device);if(r===void 0)throw new Y(`unresolved-device`,`Missing prepared device \"${e.device}\"`,{deviceId:e.device});n();try{let i=await t(r.code,e.device);if(n(),!Vs(i)||!Object.hasOwn(i,`model`)||!Object.hasOwn(i,`create`)||typeof i.create!=`function`)throw TypeError(`SDK device modules must export named model and synchronous create`);let a=Xe(i.model),o=a.declarations.filter(e=>e.kind===`pin`).map(e=>e.name),c=r.definition.pins;if(c!==void 0&&!Bs(Object.keys(c),o))throw TypeError(`Metadata pins do not match model pins`);let l={...r.definition,pins:c??Object.fromEntries(o.map(e=>[e,{}]))},u=Fs(l);if(!Bs(Object.keys(u.pins),o))throw TypeError(`Symbol pins do not match model pins`);s.set(e.device,{id:e.device,definition:l,model:a,create:i.create,topics:new Map(Object.entries(l.ports??{}).map(([e,t])=>[e,{port:e,...t,delivery:ro(t.delivery,t.type)}]))})}catch(t){throw n(),new Y(`invalid-device`,`Device \"${e.device}\" failed to load: ${Qa(t)}`,{deviceId:e.device,cause:t})}}let l=cs(r,{devices:{getDeviceName:e=>s.get(e.raw)?.definition.displayName,getDeviceSymbol:e=>{let t=s.get(e.raw);return t===void 0?void 0:Fs(t.definition)}}}),u=r.sheet.symbols.length===0&&r.sheet.wires.length===0&&r.sheet.junctions.length===0;for(let e of a.keys())if(!u&&!l.nets.some(t=>t.name===e))throw new Y(`invalid-input`,`Voltage reference names missing schematic net \"${e}\"`);return{instances:c.map(e=>({symbol:e.id,device:s.get(e.device)})),...e.execution===void 0?{}:{execution:e.execution},description:{instances:c.map(e=>({id:e.id,type:e.id,props:Ls(e,s.get(e.device),i.get(e.id))})),nets:l.nets.map((e,t)=>{let n=e.name===null?void 0:a.get(e.name),r=e.members.some(e=>e.kind===`ground`);if(r&&n!==void 0&&n!==0)throw new Y(`invalid-input`,`Conflicting voltage references on ground net \"${e.name}\": 0 and ${n}`);let i=r?0:n;return{id:`net:${t}`,pins:e.members.flatMap(e=>e.kind===`pin`?[{instance:e.symbolId,pin:e.pinId}]:[]),...i===void 0?{}:{voltage:i}}})}}}function Ls(e,t,n){let r=Object.create(null);for(let[e,n]of Object.entries(t.definition.properties??{}))Object.hasOwn(n,`default`)&&(r[e]=n.default);Object.assign(r,e.properties);let i=Object.create(null);for(let[a,o]of Object.entries(r))if(oo(o)){let r=lo(o.mode,o.src);if(r!==void 0)throw new Y(`invalid-input`,r,{deviceId:t.id});let s=n?.get(o.src);if(s===void 0)throw new Y(`unresolved-asset`,`Symbol \"${e.id}\" is missing resource \"${o.src}\"`,{deviceId:t.id});i[a]=new Uint8Array(s)}else if(o instanceof Uint8Array)i[a]=new Uint8Array(o);else if(o===null||typeof o==`number`||typeof o==`boolean`||typeof o==`string`)i[a]=o;else throw new Y(`invalid-input`,`Unsupported property \"${e.id}.${a}\"`,{deviceId:t.id});return i}function Rs(e){if(e===void 0)return/* @__PURE__ */ new Map;if(!Vs(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new Y(`invalid-input`,`Expected a plain voltageReferences map`);let t=/* @__PURE__ */ new Map;for(let n of Reflect.ownKeys(e)){let r=typeof n==`string`?e[n]:void 0;if(typeof n!=`string`||n.trim().length===0||typeof r!=`number`||!Number.isFinite(r))throw new Y(`invalid-input`,`Expected voltageReferences with nonempty net names and finite numeric voltages`);t.set(n,r)}return t}function zs(e){let t=/* @__PURE__ */ new Map;if(e===void 0)return t;if(!Vs(e))throw new Y(`invalid-input`,`Expected assets keyed by symbol id`);for(let[n,r]of Object.entries(e)){if(!Vs(r))throw new Y(`invalid-input`,`Expected asset entries keyed by src`);let e=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(r)){if(!t||!(n instanceof Uint8Array))throw new Y(`invalid-input`,`Resource bytes must be Uint8Array`);e.set(t,new Uint8Array(n))}t.set(n,e)}return t}function Bs(e,t){return e.length===t.length&&e.every(e=>t.includes(e))}function Vs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hs(e={}){let n=new t,r=new t,i=[],a=/* @__PURE__ */ new Map,o,s=ce(0),c=!1,l=0,u=()=>{if(c)throw new Y(`disposed`,`Simulation runtime has been disposed`)},d=e=>{if(n.hasListeners)for(let t of e.outputs.splice(0)){if(t.delivery===`level`){let e=C(t.symbol,t.port);if(a.has(e)&&ne(a.get(e),t.payload))continue;n.hasListeners&&a.set(e,D(t.payload))}n.fire({target:{symbol:t.symbol,port:t.port},payload:t.payload,simTime:s})}else e.outputs.length=0;for(let t of e.diagnostics.splice(0))r.fire(t.runtimeCode===void 0?{...t,simTime:s}:t)},f=e=>{if(e!==void 0)try{e.board.dispose()}catch(e){r.fire({code:`board/diagnostic`,symbol:``,message:Qa(e),simTime:s,phase:`dispose`})}finally{for(let t of e.subscriptions)t.dispose()}},p=e=>{let t=o;o=e,i.length=0,a.clear(),s=ce(0),f(t)};return{async load(t){u();let r=++l,i=await Is(t,e.importer??Ks,u);u(),r===l&&p(Us(i,()=>n.hasListeners))},async reset(){u(),++l,o===void 0?(i.length=0,a.clear(),s=ce(0)):p(Us(o.prepared,()=>n.hasListeners))},async tick(e){if(u(),!Number.isSafeInteger(e)||e<=0)throw TypeError(`tick expects a positive integer dt in picoseconds`);let t=le(s,e),n=o;if(n===void 0)return s=t,{simTime:s,executed:0};try{for(let e of i.splice(0))n.board.topics.publish(Gs(e.symbol,e.port),e.payload);n.board.runUntil(t)}finally{s=ce(n.board.time),d(n)}return{simTime:s,executed:1}},async deliver(e){if(u(),typeof e!=`object`||!e||e.target===null||typeof e.target!=`object`||typeof e.target.symbol!=`string`||typeof e.target.port!=`string`)throw new Y(`invalid-input`,`Expected a message with string symbol and port`);if(o===void 0)throw new Y(`not-loaded`,`No simulation loaded`);let{symbol:t,port:n}=e.target,r=o.inputs.get(C(t,n));if(r===void 0||!E(r.type,e.payload))throw new Y(`invalid-input`,`Unknown input or invalid payload for ${t}.${n}`);if(r.delivery===`level`){let e=i.findIndex(e=>e.symbol===t&&e.port===n);e!==-1&&i.splice(e,1)}i.push({symbol:t,port:n,payload:D(e.payload)})},onDidPublish:n.event,onDidDiagnostic:r.event,async dispose(){c||(c=!0,++l,i.length=0,a.clear(),f(o),o=void 0,n.dispose(),r.dispose())}}}function Us(e,t){let n=[],r=[],i=/* @__PURE__ */ new Map,a=Za(Ya(e.instances.map(e=>{for(let t of e.device.topics.values())t.direction===`input`&&i.set(C(e.symbol,t.port),t);return{id:e.symbol,model:e.device.model,create:i=>e.device.create({...i,topics:Ws(i.topics,e,n,r,t)})}})),{...e.description,instances:e.description.instances.map(e=>({...e,props:Object.fromEntries(Object.entries(e.props??{}).map(([e,t])=>[e,t instanceof Uint8Array?new Uint8Array(t):t]))}))},e.execution===void 0?{}:{execution:e.execution}),o=(e,t)=>{r.push({code:t?e.phase===`topic`?`device/input-failed`:e.phase===`sync`?`device/output-failed`:`board/error`:`board/diagnostic`,symbol:e.instanceId??``,message:e.message,simTime:ce(e.time??a.time),runtimeCode:e.code,phase:e.phase})};return{prepared:e,board:a,inputs:i,outputs:n,diagnostics:r,subscriptions:[a.onDidError(e=>o(e,!0)),a.onDidDiagnostic(e=>o(e,!1))]}}function Ws(e,t,n,r,i){let a=`${encodeURIComponent(t.symbol)}/`,o=ba(e),s=0,c=()=>s===0&&o.hostListeners()===0&&!i();return{onDidReceive:((n,r,i)=>{let o=e.onDidReceive(e=>{if(!e.topic.startsWith(a))return;let i=e.topic.slice(a.length);if(t.device.topics.get(i)?.direction===`input`)return n.call(r,{topic:i,payload:D(e.payload)})},void 0,void 0);s++;let c=!0,l={dispose:()=>{c&&(c=!1,s--,o.dispose())}};return i?.push(l),l}),publish(i,a){let s=t.device.topics.get(i);if(s?.direction!==`output`||!E(s.type,a)){r.push({code:`device/output-failed`,symbol:t.symbol,port:i,message:`Unknown output or invalid payload for ${t.symbol}.${i}`,simTime:ce(0)});return}if(c()){o.assertPublishAllowed();return}let l=D(a);e.publish(Gs(t.symbol,i),l),n.push({symbol:t.symbol,port:i,payload:l,delivery:s.delivery})}}}function Gs(e,t){return`${encodeURIComponent(e)}/${t}`}function Ks(e){if(typeof URL>`u`||typeof URL.createObjectURL!=`function`||typeof Blob>`u`)return Promise.reject(/* @__PURE__ */ Error(`Inject a module importer outside a browser worker`));let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}function qs(e,t,n){let r=Xs(t),i=e.register(ie,r,{transfer:oe}),a=n===void 0?void 0:n.register(ae,{deliver:r.deliver,onDidPublish:r.onDidPublish,async flushPublishes(){}},{transfer:oe}),o=!1;return{dispose(){if(!o){o=!0;try{a?.dispose()}finally{i.dispose()}}}}}function Js(e,t={}){let n=a(e),r=Hs(Ys(t)),i=t.ports??[],o=i[0],s=o===void 0?void 0:a(o),c=qs(n,r,s),l=!1;return{rpc:n,ports:i,runtime:r,async dispose(){if(!l){l=!0;try{c.dispose(),await r.dispose()}finally{s?.dispose(),n.dispose(),e.close();for(let e of i)e.close()}}}}}function Ys(e){return{...e.importer===void 0?{}:{importer:e.importer}}}function Xs(e){return{load:t=>e.load(t),reset:()=>e.reset(),tick:t=>e.tick(t),deliver:t=>e.deliver(t),onDidPublish:t=>{let n=e.onDidPublish(e=>t(Zs(e)));return()=>n.dispose()},onDidDiagnostic(t){let n=e.onDidDiagnostic(t);return()=>n.dispose()},dispose:()=>e.dispose()}}function Zs(e){let t=re(e.payload);return t===e.payload?e:{...e,payload:t}}globalThis.addEventListener(`message`,function e(t){let[n,...r]=t.ports;n!==void 0&&(globalThis.removeEventListener(`message`,e),Js(n,{ports:r}))})})();";
|
|
6
|
+
var simulation_runtime_default = "(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 ee(){if(b)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function te(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function S(e,t){ee(),a.postMessage(e,t?[...t]: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((i,a)=>{let s=t>0?setTimeout(()=>{C(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{S(e,n)}catch(t){C(e.id)?.reject(o(t))}})}function ne(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function T(e,t,n){if(b)return;let r=o(n);try{S({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),re()}}function E(){if(!b){b=!0,a.removeEventListener(`message`,ie),a.removeEventListener(`close`,E),a.removeEventListener(`messageerror`,re);for(let e of p.keys())C(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())ne(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function re(){if(!b){try{S({kind:`close`})}catch(e){x(e)}E()}}async function D(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{S({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){ne(e.id),T(`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||S({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||S({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&ne(e.id),T(`error`,e.id,t)}}function ie(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,D(t);break;case`unlisten`:ne(t.id);break;case`result`:C(t.id)?.resolve(t.value);break;case`error`:C(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=C(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`:E()}}return a.addEventListener(`message`,ie),a.addEventListener(`close`,E),a.addEventListener(`messageerror`,re),a.start?.(),{register(t,n,i={}){ee();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&&(ne(e),T(`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(ee(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=te();m.set(n,t),w({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!b)try{S({kind:`unlisten`,id:n})}catch(e){x(e)}x(e)});let a=e(()=>{if(m.delete(n)&&(C(n)?.resolve(void 0),!b))try{S({kind:`unlisten`,id:n})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(ee(),w({kind:`call`,id:te(),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:re}}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}function u(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 d(e,t=`value`){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`${t} must be finite`);return e}function f(e,t=`value`){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`${t} must be a safe integer`);return e}function p(e,t=`value`){let n=f(e,t);if(n<0)throw RangeError(`${t} must be nonnegative`);return n}function m(e){if(typeof e!=`string`||e.length===0)throw TypeError(`Expected a nonempty identifier`);return e}function h(e,t,n){let r=p(t,`offset`),i=p(n,`length`);if(r>e.length||i>e.length-r)throw RangeError(`Memory range is out of bounds`);return r}function g(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)&&g(e[n],t[n]))}function _(e){return typeof e!=`object`||!e?e:e instanceof Uint8Array?e.slice():Object.freeze(Array.isArray(e)?e.map(_):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_(t)])))}let v=/* @__PURE__ */ new WeakSet;function y(e){return typeof e==`object`&&!!e&&v.has(e)}function b(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 v.add(r),r}function x(e,t,n,r=!1){if(e.kind===`optional`)return t===null?null:x(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`:{u(t);let r=n.get(e.name);return Object.freeze(Object.fromEntries(r.fields.map(e=>[e.name,x({kind:e.type},t[e.name],n)])))}case`sample`:case`intent`:return t}}function ee(e){return e instanceof Uint8Array?b(e.slice()):_(e)}function te(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(f(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 S(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}function C(e,t){return`${e}\\u0000${t}`}function w(e){return e instanceof Uint8Array||y(e)?e:void 0}function ne(e,t){if(Object.is(e,t))return!0;let n=w(e),r=w(t);if(n!==void 0||r!==void 0){if(n===void 0||r===void 0||n.length!==r.length)return!1;for(let e=0;e<n.length;e+=1)if(n[e]!==r[e])return!1;return!0}if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let i=e,a=t;return i.x===a.x&&i.y===a.y&&i.z===a.z}function T(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.x==`number`&&typeof t.y==`number`}function E(e,t){switch(e){case`boolean`:return typeof t==`boolean`;case`number`:return typeof t==`number`;case`string`:return typeof t==`string`;case`bytes`:case`bytes<rgb565>`:case`bytes<segments>`:return w(t)!==void 0;case`vec2d`:return T(t);case`vec3d`:return T(t)&&typeof t.z==`number`}}function re(e){return e instanceof Uint8Array?new Uint8Array(e):y(e)?e.slice():e}function D(e){return e instanceof Uint8Array?new Uint8Array(e):y(e)?e.slice():typeof e==`object`&&e?{...e}:e}let ie=l(`simulation-runtime`),ae=l(`simulation-runtime`);function oe(e,t){if(e!==`onDidPublish`||!Array.isArray(t))return[];let n=t[0];return se(n?.payload)}function se(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer?[e.buffer]:[]}function O(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 ce(e){return O(e,`time`)}function le(e,t){return O(e,`left`),O(t,`right`),O(e+t,`addition ${e} + ${t}`)}function k(e){return ue(e,/* @__PURE__ */ new Set,[])}function ue(e,t,n){if(typeof e!=`object`||!e)return(typeof e==`function`||typeof e==`symbol`||typeof e==`bigint`)&&j(`IR_SCHEMA`,`Expected ordinary IR data.`,n.slice()),e;t.has(e)&&j(`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&&j(`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)&&j(`IR_SCHEMA`,`IR arrays cannot contain extra properties.`),`value`in Object.getOwnPropertyDescriptor(e,t)||j(`IR_SCHEMA`,`IR arrays cannot contain accessors.`));for(let r=0;r<e.length;r++)Object.hasOwn(e,r)||j(`IR_SCHEMA`,`IR arrays cannot be sparse.`),n.push(r),i.push(ue(Object.getOwnPropertyDescriptor(e,r).value,t,n)),n.pop();r=Object.freeze(i)}else{let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&j(`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))&&j(`IR_SCHEMA`,`IR data cannot contain symbols or accessors.`),n.push(r);let o=ue(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 A=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=k(e)}};function j(e,t,n=[],r=`finalize`,i){throw new A([{code:e,message:t,path:n,phase:r,related:[],...i===void 0?{}:{source:i}}])}let M=Object.freeze({Logic:[`low`,`high`,`unknown`],SampleStatus:[`valid`,`floating`],Overflow:[`drop_new`,`drop_oldest`,`error`]}),de=[`positive`,`negate`,`not`,`bitNot`],fe=[`add`,`subtract`,`multiply`,`divide`,`remainder`,`power`,`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`,`equal`,`notEqual`,`concat`,`bitAnd`,`bitOr`,`bitXor`,`shiftLeft`,`shiftRight`,`shiftRightUnsigned`],pe=[`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`],me=[`load8`,`load16le`,`load16be`,`load32le`,`load32be`],he=[`store8`,`store16le`,`store16be`,`store32le`,`store32be`],ge=[`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`enum`,`record`];function N(e,t){(typeof e!=`object`||!e||Array.isArray(e))&&j(`IR_SCHEMA`,`Expected a data object.`,t)}function P(e,t,n,r,i=!0){for(let n of t)Object.hasOwn(e,n)||j(`IR_SCHEMA`,`Missing field ${n}.`,[...r,n]);for(let a of Object.keys(e))!(i&&a===`source`)&&!t.includes(a)&&!n.includes(a)&&j(`IR_SCHEMA`,`Unexpected field ${a}.`,[...r,a]);Object.hasOwn(e,`source`)&&ye(e.source,[...r,`source`])}function F(e,t){typeof e!=`string`&&j(`IR_SCHEMA`,`Expected a string.`,t)}function _e(e,t){typeof e!=`boolean`&&j(`IR_SCHEMA`,`Expected a boolean.`,t)}function ve(e,t){typeof e!=`number`&&j(`IR_SCHEMA`,`Expected a number.`,t)}function I(e,t){(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)&&j(`IR_SCHEMA`,`Expected a nonnegative safe integer.`,t)}function L(e,t,n){t.includes(e)||j(`IR_SCHEMA`,`Expected one of ${t.join(`, `)}.`,n)}function R(e,t,n){Array.isArray(e)||j(`IR_SCHEMA`,`Expected an array.`,t);for(let r=0;r<e.length;r++)n(e[r],[...t,r])}function ye(e,t){N(e,t);let n=Object.hasOwn(e,`uri`);for(let n of Object.keys(e))[`uri`,`range`,`label`].includes(n)||j(`IR_SCHEMA`,`Invalid source field.`,[...t,n]);if(Object.hasOwn(e,`label`)&&F(e.label,[...t,`label`]),!n){(!Object.hasOwn(e,`label`)||Object.hasOwn(e,`range`))&&j(`IR_SCHEMA`,`Source requires a label or URI and range.`,t);return}F(e.uri,[...t,`uri`]),N(e.range,[...t,`range`]);let r=e.range;for(let e of Object.keys(r))[`start`,`end`].includes(e)||j(`IR_SCHEMA`,`Invalid range field.`,[...t,`range`,e]);for(let e of[`start`,`end`]){let n=r[e];N(n,[...t,`range`,e]);for(let r of Object.keys(n))[`line`,`column`].includes(r)||j(`IR_SCHEMA`,`Invalid position field.`,[...t,`range`,e,r]);for(let r of[`line`,`column`])(!Number.isSafeInteger(n[r])||n[r]<1)&&j(`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)&&j(`IR_SCHEMA`,`Source range is reversed.`,t)}function be(e,t,n=!0){if(N(e,t),e.kind===`optional`&&n)P(e,[`kind`,`inner`],[],t),be(e.inner,[...t,`inner`],!1);else{L(e.kind,ge,[...t,`kind`]);let n=e.kind===`enum`||e.kind===`record`;P(e,n?[`kind`,`name`]:[`kind`],[],t),n&&F(e.name,[...t,`name`])}Object.hasOwn(e,`source`)&&j(`IR_SCHEMA`,`Type descriptors cannot carry source information.`,t)}function xe(e,t,n){N(e,t),Object.hasOwn(e,`source`)&&j(`IR_SCHEMA`,`Resource references cannot carry source information.`,t),L(e.kind,[`pin`,`memory`,`parameter`],[...t,`kind`]),e.kind===`parameter`?(P(e,[`kind`,`resource`,`index`],[],t),L(e.resource,[`pin`,`memory`],[...t,`resource`]),I(e.index,[...t,`index`]),n&&e.resource!==n&&j(`IR_REFERENCE`,`Resource category does not match.`,t)):(P(e,[`kind`,`name`],[],t),F(e.name,[...t,`name`]),n&&e.kind!==n&&j(`IR_REFERENCE`,`Resource category does not match.`,t))}function Se(e,t,n=!1){N(e,t),Object.hasOwn(e,`source`)&&j(`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(L(e.kind,r,[...t,`kind`]),e.kind){case`none`:P(e,[`kind`],[],t);break;case`enum`:P(e,[`kind`,`name`,`member`],[],t),F(e.name,[...t,`name`]),F(e.member,[...t,`member`]);break;case`record`:P(e,[`kind`,`name`,`fields`],[],t),F(e.name,[...t,`name`]),R(e.fields,[...t,`fields`],(e,t)=>{N(e,t),P(e,[`name`,`value`],[],t),F(e.name,[...t,`name`]),[`number`,`boolean`].includes(typeof e.value)||j(`IR_SCHEMA`,`Expected a number or boolean field.`,[...t,`value`])});break;case`bytes`:P(e,[`kind`,`value`],[],t),R(e.value,[...t,`value`],(e,t)=>{(!Number.isInteger(e)||e<0||e>255)&&j(`IR_SCHEMA`,`Expected a byte.`,t)});break;default:P(e,[`kind`,`value`],[],t),e.kind===`number`?(ve(e.value,[...t,`value`]),n&&!Number.isFinite(e.value)&&j(`IR_CONTROL_FLOW`,`Numeric match patterns must be finite.`,t)):e.kind===`bool`?_e(e.value,[...t,`value`]):F(e.value,[...t,`value`])}}function z(e,t,n){N(e,t),P(e,[`operations`],[],t),!n?.has(e)&&R(e.operations,[...t,`operations`],Ce)}function B(e,t,n){N(e,t),P(e,[`type`,`body`],[],t),be(e.type,[...t,`type`]),z(e.body,[...t,`body`],n)}function Ce(e,t,n){N(e,t),F(e.kind,[...t,`kind`]);let r=[],i=[],a=!1,o=e=>{r=e,a=!0};switch(e.kind){case`constant`:o([`constant`]),Se(e.constant,[...t,`constant`]);break;case`read`:o([`resource`,`name`]),L(e.resource,[`property`,`const`,`state`,`derived`],[...t,`resource`]),F(e.name,[...t,`name`]);break;case`parameter`:case`reactionCapture`:o([`index`]),I(e.index,[...t,`index`]);break;case`reactionValue`:o([`binding`]),L(e.binding,[`previous`,`current`],[...t,`binding`]);break;case`unary`:o([`operator`,`value`]),L(e.operator,de,[...t,`operator`]);break;case`binary`:o([`operator`,`left`,`right`]),L(e.operator,fe,[...t,`operator`]);break;case`numeric`:o([`builtin`,`args`]),L(e.builtin,pe,[...t,`builtin`]),R(e.args,[...t,`args`],I);break;case`record`:o([`fields`]),R(e.fields,[...t,`fields`],(e,t)=>{N(e,t),P(e,[`name`,`value`],[],t),F(e.name,[...t,`name`]),I(e.value,[...t,`value`])});break;case`field`:o([`value`,`field`]),F(e.field,[...t,`field`]);break;case`bytes`:o([`elements`]),R(e.elements,[...t,`elements`],I);break;case`length`:case`optional`:case`isNone`:case`nonNull`:o([`value`]);break;case`index`:o([`value`,`index`]),I(e.index,[...t,`index`]);break;case`localRead`:o([`local`]),I(e.local,[...t,`local`]);break;case`local`:r=[`local`,`type`,`initial`],I(e.local,[...t,`local`]),be(e.type,[...t,`type`]);break;case`localWrite`:r=[`local`,`value`],I(e.local,[...t,`local`]);break;case`write`:r=[`resource`,`name`,`value`],L(e.resource,[`state`],[...t,`resource`]),F(e.name,[...t,`name`]);break;case`memoryLength`:o([`memory`]),xe(e.memory,[...t,`memory`],`memory`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:o([`memory`,`offset`]),xe(e.memory,[...t,`memory`],`memory`);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:r=[`memory`,`offset`,`value`],xe(e.memory,[...t,`memory`],`memory`);break;case`copyBytes`:o([`memory`,`offset`,`length`]),xe(e.memory,[...t,`memory`],`memory`);break;case`readSample`:o([`pin`]),xe(e.pin,[...t,`pin`],`pin`);break;case`resistor`:o([`to`,`resistance`]),xe(e.to,[...t,`to`],`pin`);break;case`combineIntents`:o([`values`]),R(e.values,[...t,`values`],I);break;case`refEqual`:o([`left`,`right`]),xe(e.left,[...t,`left`]),xe(e.right,[...t,`right`]);break;case`writeIntent`:r=[`pin`,`value`],xe(e.pin,[...t,`pin`],`pin`);break;case`call`:case`callValue`:r=[`name`,`pure`,`args`],a=e.kind===`callValue`,F(e.name,[...t,`name`]),_e(e.pure,[...t,`pure`]),R(e.args,[...t,`args`],(e,t)=>{N(e,t),e.kind===`value`?(P(e,[`kind`,`value`],[],t),I(e.value,[...t,`value`])):xe(e,t)});break;case`send`:r=[`channel`,`value`],F(e.channel,[...t,`channel`]);break;case`notify`:r=[`notification`],F(e.notification,[...t,`notification`]);break;case`receive`:o([`channel`]),F(e.channel,[...t,`channel`]);break;case`now`:case`random`:o([]);break;case`if`:r=[`condition`,`yes`],i=[`no`],z(e.yes,[...t,`yes`],n),Object.hasOwn(e,`no`)&&z(e.no,[...t,`no`],n);break;case`match`:r=[`value`,`arms`],i=[`otherwise`],R(e.arms,[...t,`arms`],(e,t)=>{N(e,t),P(e,[`pattern`,`body`],[],t),Se(e.pattern,[...t,`pattern`],!0),z(e.body,[...t,`body`],n)}),Object.hasOwn(e,`otherwise`)&&z(e.otherwise,[...t,`otherwise`],n);break;case`while`:r=[`test`,`body`],B(e.test,[...t,`test`],n),z(e.body,[...t,`body`],n);break;case`loop`:r=[`body`],z(e.body,[...t,`body`],n);break;case`and`:case`or`:o([`left`,`right`]),B(e.right,[...t,`right`],n);break;case`select`:o([`condition`,`yes`,`no`]),B(e.yes,[...t,`yes`],n),B(e.no,[...t,`no`],n);break;case`assert`:r=[`condition`],i=[`message`],Object.hasOwn(e,`message`)&&B(e.message,[...t,`message`],n);break;case`wait`:case`elapse`:r=[`duration`];break;case`waitUntil`:r=[`predicate`],F(e.predicate,[...t,`predicate`]);break;case`redirect`:r=[`target`,`delay`];break;case`return`:case`break`:case`continue`:case`stop`:break;case`returnValue`:case`yield`:r=[`value`];break;default:j(`IR_SCHEMA`,`Unknown operation ${e.kind}.`,[...t,`kind`])}P(e,[`kind`,...r,...a?[`result`,`type`]:[]],i,t),a&&(I(e.result,[...t,`result`]),be(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))?I(e[n],[...t,n]):Object.hasOwn(e,n)&&typeof e[n]==`object`&&![`refEqual`,`and`,`or`].includes(e.kind)&&j(`IR_SCHEMA`,`Expected a result identifier.`,[...t,n])}function we(e){N(e,[]),P(e,[`kind`,`name`,`declarations`],[],[]),L(e.kind,[`device`],[`kind`]),F(e.name,[`name`]),R(e.declarations,[`declarations`],(e,t)=>{N(e,t),F(e.kind,[...t,`kind`]);let n=[`kind`],r=[];switch([`start`,`assert`].includes(e.kind)||(n.push(`name`),F(e.name,[...t,`name`])),e.kind){case`enum`:n.push(`members`),R(e.members,[...t,`members`],F);break;case`record`:n.push(`fields`),R(e.fields,[...t,`fields`],(e,t)=>{N(e,t),P(e,[`name`,`type`],[],t),F(e.name,[...t,`name`]),L(e.type,[`number`,`bool`],[...t,`type`])});break;case`property`:n.push(`type`),r=[`default`],Object.hasOwn(e,`default`)&&B(e.default,[...t,`default`]);break;case`const`:case`derived`:n.push(`type`,`value`),B(e.value,[...t,`value`]);break;case`state`:n.push(`type`,`initial`),B(e.initial,[...t,`initial`]);break;case`pin`:r=[`initial`,`low`,`high`];for(let n of r)Object.hasOwn(e,n)&&B(e[n],[...t,n]);Object.hasOwn(e,`low`)!==Object.hasOwn(e,`high`)&&j(`IR_SCHEMA`,`Pin thresholds must be provided together.`,t);break;case`memory`:n.push(`public`,`length`),_e(e.public,[...t,`public`]),B(e.length,[...t,`length`]);break;case`channel`:n.push(`direction`,`type`,`capacity`),r=[`maxLength`,`overflow`],B(e.capacity,[...t,`capacity`]);for(let n of r)Object.hasOwn(e,n)&&B(e[n],[...t,n]);break;case`notification`:n.push(`direction`);break;case`function`:n.push(`pure`,`params`,`body`),r=[`returns`],_e(e.pure,[...t,`pure`]),R(e.params,[...t,`params`],(e,t)=>{N(e,t),P(e,[`name`,`type`],[],t),F(e.name,[...t,`name`]),N(e.type,[...t,`type`]),[`pin`,`memory`].includes(e.type.kind)?P(e.type,[`kind`],[],[...t,`type`]):be(e.type,[...t,`type`])}),Object.hasOwn(e,`returns`)&&be(e.returns,[...t,`returns`]),z(e.body,[...t,`body`]);break;case`start`:case`assert`:n.push(`body`),z(e.body,[...t,`body`]);break;case`on`:n.push(`sourcePath`,`body`),R(e.sourcePath,[...t,`sourcePath`],F),z(e.body,[...t,`body`]);break;case`reaction`:n.push(`sourcePath`,`sourceType`,`previous`,`current`,`captures`,`body`),R(e.sourcePath,[...t,`sourcePath`],F),be(e.sourceType,[...t,`sourceType`]),F(e.previous,[...t,`previous`]),F(e.current,[...t,`current`]),R(e.captures,[...t,`captures`],(e,t)=>{N(e,t),P(e,[`name`,`value`],[],t),F(e.name,[...t,`name`]),B(e.value,[...t,`value`])}),z(e.body,[...t,`body`]);break;default:j(`IR_SCHEMA`,`Unknown declaration ${e.kind}.`,[...t,`kind`])}P(e,n,r,t),Object.hasOwn(e,`type`)&&be(e.type,[...t,`type`]),[`channel`,`notification`].includes(e.kind)&&L(e.direction,[`input`,`output`],[...t,`direction`])})}function Te(e){N(e,[]),P(e,[`kind`,`instructions`],[],[]),L(e.kind,[`block`],[`kind`]),R(e.instructions,[`instructions`],(e,t)=>{N(e,t),P(e,[`pc`,`nextPc`,`body`],[],t);for(let n of[`pc`,`nextPc`])(typeof e[n]!=`number`||!Number.isFinite(e[n]))&&j(`IR_SCHEMA`,`Instruction positions must be finite numbers.`,[...t,n]);z(e.body,[...t,`body`])});let t=e.instructions;t.length||j(`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&&j(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries do not match.`,[`instructions`,e,`pc`])}let V={kind:`number`},H={kind:`bool`},Ee={kind:`string`},De={kind:`bytes`},Oe={kind:`intent`},ke={kind:`sample`},Ae=/* @__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(M),...pe,...me,...he,`resistor`,`copyBytes`,`now`,`random`,`ticks`]);function je(e,t){let n=e,r=t;return n?.kind===r?.kind&&(n?.kind===`optional`?je(n.inner,r?.inner):n?.kind===`enum`||n?.kind===`record`?n.name===r?.name:!0)}function Me(e){return e.kind===`optional`?e.inner:e}function Ne(e){return Me(e).kind!==`intent`}function Pe(e){return{facts:new Map(e.facts),locals:new Map(e.locals)}}function Fe(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}var Ie=class{next=0;byKey=/* @__PURE__ */ new Map;joins=/* @__PURE__ */ new Map;fields=/* @__PURE__ */ new Map;id(e){let t=this.byKey.get(e);return t===void 0&&(t=this.byKey.size,this.byKey.set(e,t)),t}fresh(e){return`${e}:${this.next++}`}join(e,t){let n=`${e}:${t.map(e=>this.id(e)).join(`,`)}`,r=this.joins.get(n);return r===void 0&&(r=this.fresh(`join`),this.joins.set(n,r)),r}field(e,t){let n=this.fields.get(e);n||(n=/* @__PURE__ */ new Map,this.fields.set(e,n));let r=n.get(t);return r===void 0&&(r=this.fresh(`field`),n.set(t,r)),r}};function Le(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 Re(e,t){if(!e.length)return;let n=Pe(e[0]);n.facts=Fe(e.map(e=>e.facts));for(let[r,i]of n.locals){let a=e.map(e=>e.locals.get(r));if(a.some(e=>!e))n.locals.delete(r);else if(a.some(e=>e.value.key!==i.value.key)){let o={type:i.type,key:t.join(r,a.map(e=>e.value.key))},s=a.map((t,n)=>e[n].facts.get(t.value.key));s.every(e=>e===!0)&&n.facts.set(o.key,!0),s.every(e=>e===!1)&&n.facts.set(o.key,!1),n.locals.set(r,{type:i.type,value:o})}}return n}function ze(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;ze(e?r.body:r,t,[...i,n,...e?[`body`]:[]])}}e.kind===`while`&&ze(e.test.body,t,[...i,`test`,`body`]),e.kind===`assert`&&e.message&&ze(e.message.body,t,[...i,`message`,`body`]),(e.kind===`and`||e.kind===`or`)&&ze(e.right.body,t,[...i,`right`,`body`]),e.kind===`match`&&e.arms.forEach((e,n)=>ze(e.body,t,[...i,`arms`,n,`body`]))})}var Be=class{declarations=/* @__PURE__ */ new Map;paths=/* @__PURE__ */ new Map;enums=new Map(Object.entries(M));records=/* @__PURE__ */ new Map;functions=/* @__PURE__ */ new Map};let Ve=/* @__PURE__ */ new WeakMap;function He(e){return Ve.get(e)?.declarations}var Ue=class{device;index;identities=new Ie;effectChecked=/* @__PURE__ */ new Set;receiveOwners=/* @__PURE__ */ new Map;constructor(e){this.device=e;let t=e&&Ve.get(e);if(this.index=t??new Be,!e||t)return;let{declarations:n,paths:r,enums:i,records:a,functions:o}=this.index;this.name(e.name,[`name`]);let s=0;e.declarations.forEach((e,t)=>{let c=[`declarations`,t];e.kind===`start`?++s>1&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`,c):e.kind!==`assert`&&(this.name(e.name,[...c,`name`]),n.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`,c),n.set(e.name,e),r.set(e.name,c),e.kind===`enum`&&(this.uniqueNames(e.members,[...c,`members`]),e.members.length||this.error(`IR_TYPE`,`An enum must have at least one member.`,c),i.set(e.name,e.members)),e.kind===`record`&&(this.uniqueNames(e.fields.map(e=>e.name),[...c,`fields`]),a.set(e.name,e.fields)),e.kind===`function`&&o.set(e.name,e))})}get declarations(){return this.index.declarations}get paths(){return this.index.paths}get enums(){return this.index.enums}get records(){return this.index.records}get functions(){return this.index.functions}error(e,t,n,r){return j(e,t,n,`finalize`,r?.source)}name(e,t){(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||Ae.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=Me(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){je(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:V},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 V;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,visibleResults:[],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=Pe(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=Pe(n),a={breaks:[],continues:[],yielded:[],yieldStates:[]},{results:o,visibleResults:s}=t,c=s.length;for(let n=0;n<e.operations.length;n++){let c=e.operations[n],l=[...r,`operations`,n];i||this.error(`IR_CONTROL_FLOW`,`Operation follows an unconditional path terminator.`,l,c);let u=i,d=(e,t)=>{let n=o.get(e);return n||this.error(`IR_SCOPE`,`Result ${e} is not visible or is used before its definition.`,l,c),t&&this.expect(n.type,t,l,c),n},f=(e,t={})=>{let n=c;this.expect(n.type,e,[...l,`type`],c);let r={type:n.type,key:`v:${n.result}`,...t};return o.set(n.result,r),s.push(n.result),r};`result`in c&&(this.type(c.type,[...l,`type`]),t.resultIds.has(c.result)&&this.error(`IR_SCOPE`,`Duplicate result ${c.result}.`,[...l,`result`],c),t.resultIds.add(c.result));let p=e=>{let t=u.locals.get(e);return t||this.error(`IR_SCOPE`,`Local is not visible or not initialized.`,[...l,`local`],c),t},m=(r,i,a,o={})=>Le(this.region(r,{...t,tail:t.tail&&n===e.operations.length-1,...o},i,[...l,a]),i.locals),h=e=>{a.breaks.push(...e.breaks),a.continues.push(...e.continues),a.yielded.push(...e.yielded),a.yieldStates.push(...e.yieldStates)},g=(e,n,r,i)=>{this.type(e.type,[...l,i,`type`]),this.expect(e.type,n,[...l,i,`type`]);let a=Le(this.region(e.body,{...t,valueRegion:n,loop:0,tail:!1},r,[...l,i,`body`]),r.locals);return a.normal&&this.error(`IR_CONTROL_FLOW`,`A value region has a normal path without yield.`,[...l,i],e),{flow:a,...a.yielded.length?{value:{type:n,key:`region:${`result`in c?c.result:void 0}:${i}`,yes:Fe(a.yielded.map(e=>e.yes??/* @__PURE__ */ new Map)),no:Fe(a.yielded.map(e=>e.no??/* @__PURE__ */ new Map))}}:{}}};switch(c.kind){case`constant`:{this.constant(c.constant,c.type,[...l,`constant`]);let e=f(c.type,{none:c.constant.kind===`none`});c.constant.kind===`none`&&u.facts.set(e.key,!1);break}case`read`:f(this.declaration(c.name,c.resource,l)?.type??c.type);break;case`parameter`:{let e=t.params[c.index];e||this.error(`IR_SCOPE`,`Parameter index is outside the current function.`,l,c),(e.type.kind===`pin`||e.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource parameters cannot be read as values.`,l,c),f(e.type,{key:`parameter:${c.index}`});break}case`reactionValue`:t.reaction||this.error(`IR_SCOPE`,`Reaction bindings are only visible inside their response body.`,l,c),f(t.reaction.sourceType,{key:`reaction:${c.binding}`});break;case`reactionCapture`:t.reaction||this.error(`IR_SCOPE`,`Reaction captures are only visible inside their response body.`,l,c),t.reaction.captures[c.index]||this.error(`IR_SCOPE`,`Reaction capture index is out of range.`,l,c),f(t.reaction.captures[c.index].value.type,{key:`capture:${c.index}`});break;case`unary`:{let e=d(c.value,c.operator===`not`?H:V);f(c.operator===`not`?H:V,c.operator===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{});break}case`binary`:{let e=d(c.left),t=d(c.right);if([`equal`,`notEqual`].includes(c.operator)){this.expect(e.type,t.type,l,c),!Ne(e.type)&&(e.type.kind!==`optional`||!e.none&&!t.none)&&this.error(`IR_TYPE`,`Intent values do not support content equality.`,l,c);let n=e.none?t:t.none?e:void 0,r=c.operator===`equal`;f(H,n?{yes:/* @__PURE__ */ new Map([[n.key,!r]]),no:/* @__PURE__ */ new Map([[n.key,r]])}:{})}else c.operator===`concat`?(d(c.left,Ee),d(c.right,Ee),f(Ee)):(d(c.left,V),d(c.right,V),f([`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(c.operator)?H:V));break}case`numeric`:c.args.length!==([`min`,`max`,`pow`].includes(c.builtin)?2:1)&&this.error(`IR_TYPE`,`Numeric builtin argument count does not match.`,l,c),c.args.forEach(e=>d(e,V)),f(c.builtin.startsWith(`is`)?H:V);break;case`record`:this.recordFields(c.fields,c.type,l,e=>d(e.value).type),f(c.type);break;case`field`:{let e=d(c.value),t=e.type;f(t.kind===`record`&&!this.device?c.type:this.field(t,c.field,l),{key:this.identities.field(e.key,c.field)});break}case`bytes`:c.elements.forEach(e=>d(e,V)),f(De);break;case`length`:{let e=d(c.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`length requires string or bytes.`,l,c),f(V);break}case`index`:{let e=d(c.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`index requires string or bytes.`,l,c),d(c.index,V),f(e.kind===`string`?Ee:V);break}case`optional`:{let e=d(c.value).type;e.kind===`optional`&&this.error(`IR_TYPE`,`Optional types cannot be nested.`,l,c);let t=f({kind:`optional`,inner:e});u.facts.set(t.key,!0);break}case`isNone`:{let e=d(c.value);e.type.kind!==`optional`&&this.error(`IR_TYPE`,`isNone requires an optional value.`,l,c),f(H,{yes:/* @__PURE__ */ new Map([[e.key,!1]]),no:/* @__PURE__ */ new Map([[e.key,!0]])});break}case`nonNull`:{let e=d(c.value);(e.type.kind!==`optional`||u.facts.get(e.key)!==!0)&&this.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`,l,c),f(e.type.inner);break}case`local`:{t.localIds.has(c.local)&&this.error(`IR_SCOPE`,`Duplicate local identifier.`,l,c),t.localIds.add(c.local),this.type(c.type,[...l,`type`]);let e=d(c.initial,c.type);u.locals.set(c.local,{type:c.type,value:e});break}case`localRead`:{let e=p(c.local);f(e.type,{...e.value});break}case`localWrite`:{let e=p(c.local),t=d(c.value,e.type);u.locals.set(c.local,{type:e.type,value:t});break}case`write`:{let e=this.declaration(c.name,`state`,l);d(c.value,e?.type);break}case`memoryLength`:this.ref(c.memory,`memory`,t,l),f(V);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:this.ref(c.memory,`memory`,t,l),d(c.offset,V),f(V);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:this.ref(c.memory,`memory`,t,l),d(c.offset,V),d(c.value,V);break;case`copyBytes`:this.ref(c.memory,`memory`,t,l),d(c.offset,V),d(c.length,V),f(De);break;case`readSample`:this.ref(c.pin,`pin`,t,l),f(ke);break;case`resistor`:this.ref(c.to,`pin`,t,l),d(c.resistance,V),f(Oe);break;case`combineIntents`:c.values.forEach(e=>d(e,Oe)),f(Oe);break;case`refEqual`:this.expect({kind:this.ref(c.left,void 0,t,l)},{kind:this.ref(c.right,void 0,t,l)},l),f(H);break;case`writeIntent`:this.ref(c.pin,`pin`,t,l),d(c.value,Oe);break;case`call`:case`callValue`:{let e=this.declaration(c.name,`function`,l);e&&c.pure&&!e.pure&&this.error(`IR_EFFECT`,`A pure call must target an explicitly pure function.`,l,c),e&&c.args.length!==e.params.length&&this.error(`IR_TYPE`,`Call argument count does not match.`,l,c),c.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.`,l,c),d(n.value,i?.type)):(i&&i.type.kind!==`pin`&&i.type.kind!==`memory`&&this.error(`IR_TYPE`,`Value argument required.`,l,c),this.ref(n,i?.type.kind,t,l))}),c.kind===`callValue`?(e&&!e.returns&&this.error(`IR_TYPE`,`callValue requires a value-returning function.`,l,c),f(e?.returns??c.type)):e?.returns&&this.error(`IR_TYPE`,`call cannot discard the return type of a value-returning function.`,l,c);break}case`send`:{let e=this.declaration(c.channel,`channel`,l);e?.direction===`input`&&this.error(`IR_REFERENCE`,`send requires an output channel.`,l,c),d(c.value,e?.type);break}case`notify`:this.declaration(c.notification,`notification`,l)?.direction===`input`&&this.error(`IR_REFERENCE`,`notify requires an output notification.`,l,c);break;case`receive`:{let e=this.declaration(c.channel,`channel`,l);e?.direction===`output`&&this.error(`IR_REFERENCE`,`receive requires an input channel.`,l,c),f(e?.type??c.type);break}case`now`:case`random`:f(V);break;case`if`:{let e=d(c.condition,H),t=m(c.yes,this.conditioned(u,e,!0),`yes`),n=c.no?m(c.no,this.conditioned(u,e,!1),`no`):{normal:this.conditioned(u,e,!1),breaks:[],continues:[],yielded:[],yieldStates:[]};h(t),h(n),i=Re([t.normal,n.normal].filter(e=>!!e),this.identities);break}case`match`:{let r=d(c.value),a=Me(r.type),o=/* @__PURE__ */ new Set,s=[];for(let i=0;i<c.arms.length;i++){let d=c.arms[i],f=d.pattern;this.constant(f,f.kind===`none`?r.type:a,[...l,`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.`,[...l,`arms`,i]),o.add(p);let m=Pe(u);r.type.kind===`optional`&&m.facts.set(r.key,f.kind!==`none`);let g=Le(this.region(d.body,{...t,tail:t.tail&&n===e.operations.length-1},m,[...l,`arms`,i,`body`]),m.locals);h(g),g.normal&&s.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}`))&&(t.mode!==`jit`||Object.hasOwn(M,a.name)))&&(r.type.kind!==`optional`||o.has(`none:undefined`));if(c.otherwise){let e=Pe(u);r.type.kind===`optional`&&o.has(`none:undefined`)&&e.facts.set(r.key,!0);let t=m(c.otherwise,e,`otherwise`);h(t),t.normal&&s.push(t.normal)}else f||this.error(`IR_CONTROL_FLOW`,`Match requires exhaustive patterns or a default region.`,l,c);i=Re(s,this.identities);break}case`while`:case`loop`:{let e=/* @__PURE__ */ new Set;ze(c.body,t=>{t.kind===`localWrite`&&u.locals.has(t.local)&&e.add(t.local)}),c.kind===`while`&&ze(c.test.body,t=>{t.kind===`localWrite`&&u.locals.has(t.local)&&e.add(t.local)});let n=t=>{let n=Pe(u),r=[u,...t];for(let t of e){let e=u.locals.get(t),i={type:e.type,key:`loop:${l.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),s=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 s)t.localIds.add(e);d=c.kind===`while`?g(c.test,H,r,`test`):void 0;let i=d?Re(d.flow.yieldStates,this.identities)??r:r,a=d?.value?this.conditioned(i,d.value,!0):i;f=m(c.body,a,`body`,{loop:t.loop+1,tail:!1});let l=n([f.normal,...f.continues].filter(e=>!!e));if([...e].every(e=>{let t=l.locals.get(e).value.key;return l.facts.get(t)===r.facts.get(t)}))break;r=l}a.yielded.push(...f.yielded),a.yieldStates.push(...f.yieldStates);let p=[...f.breaks];if(c.kind===`while`&&d?.value){let e=Re(d.flow.yieldStates,this.identities)??r;p.push(this.conditioned(e,d.value,!1))}i=Re(p,this.identities);break}case`and`:case`or`:{let e=d(c.left,H),t=c.kind===`and`,n=g(c.right,H,this.conditioned(u,e,t),`right`),r=n.value,a=(e,t)=>new Map([...e??[],...t??[]]),o=t?a(e.yes,r?.yes):Fe([e.yes??/* @__PURE__ */ new Map,a(e.no,r?.yes)]),s=t?Fe([e.no??/* @__PURE__ */ new Map,a(e.yes,r?.no)]):a(e.no,r?.no);f(H,{yes:o,no:s}),i=Re([this.conditioned(u,e,!t),...n.flow.yieldStates],this.identities);break}case`select`:{let e=d(c.condition,H),t=g(c.yes,c.type,this.conditioned(u,e,!0),`yes`),n=g(c.no,c.type,this.conditioned(u,e,!1),`no`);f(c.type),i=Re([...t.flow.yieldStates,...n.flow.yieldStates],this.identities);break}case`assert`:{let e=d(c.condition,H);c.message&&g(c.message,Ee,this.conditioned(u,e,!1),`message`),i=this.conditioned(u,e,!0);break}case`wait`:(t.valueRegion||t.mode!==`process`)&&this.error(`IR_EFFECT`,`wait is only allowed in a process statement region.`,l,c),d(c.duration,V);break;case`elapse`:(t.valueRegion||t.mode!==`jit`)&&this.error(`IR_EFFECT`,`elapse is only allowed in a JIT statement region.`,l,c),d(c.duration,V);break;case`waitUntil`:t.mode!==`jit`&&this.error(`IR_EFFECT`,`waitUntil requires a JIT instruction.`,l,c),(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.`,l,c);{let e=this.declaration(c.predicate,`function`,l);e&&(!e.pure||e.params.length||!je(e.returns,H))&&this.error(`IR_TYPE`,`waitUntil requires a zero-parameter pure bool function.`,l,c)}i=void 0;break;case`redirect`:[`jit`,`sync`].includes(t.mode)||this.error(`IR_EFFECT`,`redirect is not permitted in this context.`,l,c),d(c.target,V),d(c.delay,V),i=void 0;break;case`stop`:(t.mode!==`jit`||t.valueRegion)&&this.error(`IR_EFFECT`,`stop requires a JIT statement region.`,l,c),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.`,l,c),i=void 0;break;case`returnValue`:(t.valueRegion||!t.returns)&&this.error(`IR_CONTROL_FLOW`,`returnValue is not valid in this body.`,l,c),d(c.value,t.returns),i=void 0;break;case`yield`:t.valueRegion||this.error(`IR_CONTROL_FLOW`,`yield requires a value region.`,l,c);{let e=d(c.value,t.valueRegion);a.yielded.push(e),a.yieldStates.push(u)}i=void 0;break;case`break`:case`continue`:t.loop||this.error(`IR_CONTROL_FLOW`,`${c.kind} requires an enclosing loop in this region.`,l,c),(c.kind===`break`?a.breaks:a.continues).push(u),i=void 0}}for(i&&(a.normal=i);s.length>c;)o.delete(s.pop());return a}effects(e,t,n){ze(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`,...he].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`,...me].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&&t!==`jit`){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=ke,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 Ne(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 ze(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;ze(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=Me(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],V,`creation`,[...i,t]);e.initial&&this.computation(e.initial,Oe,`initial`,[...i,`initial`])}else if(e.kind===`memory`)this.computation(e.length,V,`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,V,`creation`,[...i,`capacity`]),e.maxLength&&this.computation(e.maxLength,V,`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`]),ze(e.body,e=>{if(e.kind===`receive`){let t=`${r}`,n=this.receiveOwners.get(e.channel);if(n&&n!==t){let e=new A([{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)=>{Ne(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 We(e,t){if(!(e instanceof A))throw e;let n=new A(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 Ge=/* @__PURE__ */ new WeakMap,Ke=/* @__PURE__ */ new WeakMap,qe=/* @__PURE__ */ new WeakMap;function Je(e,t){return typeof t==`object`&&t?e.get(t):void 0}function Ye(e,t,n){typeof t==`object`&&t&&e.set(t,n),e.set(n,n)}function Xe(e){let t=Je(Ge,e);if(t!==void 0)return t;let n=k(e);try{we(n);let t=new Ue(n);t.validateDevice();let r=n;return Ve.set(r,t.index),Ye(Ge,e,r),r}catch(e){return We(e,n)}}function Ze(e){let t=k(e);try{return Te(t),t}catch(e){return We(e,t)}}function Qe(e){try{new Ue().validateBlock(e)}catch(t){return We(t,e)}}function $e(e,t){let n=qe.get(e);n||(n=/* @__PURE__ */ new WeakSet,qe.set(e,n)),n.add(t)}function et(e){let t=Je(Ke,e);if(t!==void 0)return t;let n=Ze(e);return Qe(n),Ye(Ke,e,n),n}function tt(e,t){try{let n=Je(Ke,e),r=n??Ze(e),i=Je(Ge,t);if(i===void 0){n===void 0&&(Qe(r),Ye(Ke,e,r));let i=Xe(t);return qe.get(r)?.has(i)||(new Ue(i).validateBlock(r),$e(r,i)),r}if(qe.get(r)?.has(i))return r;try{new Ue(i).validateBlock(r)}catch(t){throw n===void 0&&(Qe(r),Ye(Ke,e,r)),t}return n===void 0&&Ye(Ke,e,r),$e(r,i),r}catch(e){if(e instanceof A){let t=new A(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 nt=/* @__PURE__ */ new WeakMap,rt=/* @__PURE__ */ new WeakMap,it=/* @__PURE__ */ new WeakMap,at=/* @__PURE__ */ new WeakMap,ot=/* @__PURE__ */ new WeakMap,st=e=>{let t=Object.freeze({});return nt.set(t,{type:{kind:e}}),t};function ct(e,t,n){let r={};for(let i of t){let t=Object.freeze({});ot.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 nt.set(i,{type:{kind:`enum`,name:e},members:Object.freeze([...t]),...n?{owner:n}:{}}),i}function lt(e,t,n){let r=Object.freeze({name:e,fields:Object.freeze({...t})});return nt.set(r,{type:{kind:`record`,name:e},fields:r.fields,...n?{owner:n}:{}}),r}let ut={number:st(`number`),bool:st(`bool`),string:st(`string`),bytes:st(`bytes`),intent:st(`intent`),sample:st(`sample`),pin:Object.freeze({kind:`pin`}),memory:Object.freeze({kind:`memory`}),logic:ct(`Logic`,M.Logic),sampleStatus:ct(`SampleStatus`,M.SampleStatus),overflow:ct(`Overflow`,M.Overflow),optional(e){let t=nt.get(e);(!t||t.type.kind===`optional`)&&j(`IR_TYPE`,`optional requires a nonoptional value type.`,[],`construct`);let n=Object.freeze({});return nt.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)&&j(`IR_TYPE`,`Invalid named enum description.`,[],`construct`),ct(e,t)},namedRecord(e,t){(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))&&j(`IR_TYPE`,`Invalid named record description.`,[],`construct`);for(let e of Object.values(t))[`number`,`bool`].includes(nt.get(e)?.type.kind??``)||j(`IR_TYPE`,`Record fields must be number or bool types.`,[],`construct`);return lt(e,t)}};Object.freeze(ut);let U={kind:`number`},W={kind:`bool`},dt={kind:`string`},ft={kind:`bytes`},pt={kind:`intent`},mt={kind:`sample`};function ht(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function gt(e){return typeof e==`object`&&e?rt.get(e):void 0}function _t(e){return typeof e==`object`&&e?ot.get(e):void 0}function vt(e){return typeof e==`object`&&e?at.get(e):void 0}function yt(e,t){let n=Object.freeze({});return e.set(n,t),n}function G(e){return e.alias?G(e.alias):e}function bt(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 xt=/* @__PURE__ */ new WeakMap;var St=class{options;device;jit;closed=!1;active;source;declarations=[];ownNames=/* @__PURE__ */ new Map;names;expectedTypes=/* @__PURE__ */ new Set;pending=[];instructions=[];checkedRegions=/* @__PURE__ */ new WeakSet;constructor(e,t,n=!1){this.options=e,this.device=t,this.jit=n,e.source!==void 0&&(this.source=k(e.source));let r=t&&He(t);if(t&&(!r||!n))for(let e of t.declarations)`name`in e&&this.ownNames.set(e.name,e);if(this.names=(n?r:void 0)??this.ownNames,t&&!n)for(let e of t.declarations)this.declarations.push(e)}error(e,t,n=[]){return this.closed=!0,j(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 A&&e.diagnostics.some(e=>e.phase!==`construct`)?new A(e.diagnostics.map(e=>({...e,phase:`construct`}))):e}}type(e){let t=nt.get(e);if(t||this.error(`IR_TYPE`,`Expected a Builder type descriptor.`),t.owner&&t.owner!==this&&(!this.device||xt.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:k(t)}}body(e,t,n,r,i){let a=new Ct(this,e,{result:0,local:0},{},void 0,n);a.source=r===void 0?this.source:k(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:k(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.ownNames.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&&j(`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)||j(`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(M[n]&&t.kind===`enum`)e.members&&(e.members.length!==M[n].length||e.members.some((e,t)=>e!==M[n][t]))&&j(`IR_TYPE`,`Builtin enum description does not match its members.`);else if(r&&(r.kind!==t.kind&&j(`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]))&&j(`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===nt.get(t)?.type.kind)))&&j(`IR_TYPE`,`Forward record description does not match its declaration.`)}}}},Ct=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:k(this.source)}:{}};Ce(t,[],this.root.checkedRegions),this.operations.push(t)}result(e,t,n={}){let r=this.space.result++;return this.node({...t,result:r,type:e}),yt(rt,{root:this.root,scope:this.scope,space:this.space,type:e,id:r,...n})}handle(e,t){let n=gt(e);return(!n||n.root!==this.root||n.space!==this.space||!ht(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Value is not visible in the current execution body or scope.`),t&&!je(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}localHandle(e){let t=it.get(e);return(!t||t.root!==this.root||t.space!==this.space||!ht(this.scope,t.scope))&&this.root.error(`IR_SCOPE`,`Local is not visible in this execution body or scope.`),t}infer(e){if(gt(e))return this.handle(e).type;let t=_t(e);if(t)return t.owner&&t.owner!==this.root&&(!this.root.device||xt.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 U;if(typeof e==`boolean`)return W;if(typeof e==`string`)return dt;if(Array.isArray(e)||e instanceof Uint8Array)return ft;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=_t(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||xt.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:nt.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(gt(e)){let n=this.handle(e);if(t&&t.kind===`optional`&&je(n.type,t.inner)){let e=this.handle(this.result(t,{kind:`optional`,value:n.id}));return this.facts.set(G(e),!0),e}return t&&!je(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(G(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=vt(e);return(!n||n.root!==this.root||n.space!==this.space||!ht(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 yt(at,{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(G(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}this.root.check();let c={operations:a.operations,...a.source?{source:k(a.source)}:{}};return this.root.checkedRegions.add(c),{body:c,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=bt(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(G(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=bt(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(G(e))===!0)&&this.facts.set(i,!0)}}}}invoke(t,n){if(de.includes(t)){let e=this.operand(n[0],t===`not`?W:U);return this.result(t===`not`?W:U,{kind:`unary`,operator:t,value:e.id},t===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{})}if(fe.includes(t)){let e=[`equal`,`notEqual`].includes(t),r=e?this.root.type(n.shift()):t===`concat`?dt:U,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?W:r,{kind:`binary`,operator:t,left:i.id,right:a.id},o?{yes:/* @__PURE__ */ new Map([[G(o),t!==`equal`]]),no:/* @__PURE__ */ new Map([[G(o),t===`equal`]])}:{})}if(pe.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`)?W:U,{kind:`numeric`,builtin:t,args:n.map(e=>this.operand(e,U).id)})}if(me.includes(t)||he.includes(t)){this.requireRead();let e=this.ref(n[0],`memory`),r=this.operand(n[1],U);if(he.includes(t)){this.requireEffect(),this.node({kind:t,memory:e,offset:r.id,value:this.operand(n[2],U).id});return}return this.result(U,{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=k(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 gt(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),yt(it,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:G(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=nt.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:U},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=G(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(ft,{kind:`bytes`,elements:n.map(e=>this.operand(e,U).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(U,{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`?dt:U,{kind:`index`,value:e.id,index:this.operand(n[1],U).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(G(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(W,{kind:`isNone`,value:e.id},{yes:/* @__PURE__ */ new Map([[G(e),!1]]),no:/* @__PURE__ */ new Map([[G(e),!0]])})}case`nonNull`:{let e=this.handle(n[0]);return(e.type.kind!==`optional`||this.facts.get(G(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(U,{kind:`memoryLength`,memory:this.ref(n[0],`memory`)});case`copyBytes`:return this.requireRead(),this.result(ft,{kind:`copyBytes`,memory:this.ref(n[0],`memory`),offset:this.operand(n[1],U).id,length:this.operand(n[2],U).id});case`readSample`:return this.requireRead(),this.result(mt,{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(pt,{kind:`resistor`,to:this.ref(n[0],`pin`),resistance:this.operand(n[1],U).id});case`combineIntents`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction is not available here.`),this.result(pt,{kind:`combineIntents`,values:n.map(e=>this.operand(e,pt).id)});case`refEqual`:{this.requireRead();let e=vt(n[0]),t=vt(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(W,{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],pt).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(U,{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=vt(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&&!gt(e)){let n=e===null||typeof e==`object`&&!_t(e)&&!Array.isArray(e)&&!(e instanceof Uint8Array),r=n?U: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:k(this.source)}:{}};return Ce(a,[]),this.operations.push(a),this.root.pending.push({node:a,call:i,index:t,value:_t(e)?e:k(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],W),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([[G(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([[G(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,W):void 0,i=this.branch(n[+(t===`while`)],void 0,void 0,!0);this.node({kind:t,...r?{test:{type:W,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],W),r=t===`and`,i=this.branch(n[1],{info:e,truth:r},W),a=gt(i.returned),o=(e,t)=>new Map([...e??[],...t??[]]),s=r?o(e.yes,a?.yes):bt([e.yes??/* @__PURE__ */ new Map,o(e.no,a?.yes)]),c=r?bt([e.no??/* @__PURE__ */ new Map,o(e.yes,a?.no)]):o(e.no,a?.no),l=this.result(W,{kind:t,left:e.id,right:{type:W,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],W),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],W),t=n[1]?this.branch(n[1],{info:e,truth:!1},dt):void 0;this.node({kind:`assert`,condition:e.id,...t?{message:{type:dt,body:t.body}}:{}});for(let[t,n]of e.yes??[])this.facts.set(G(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],U).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],U).id,delay:this.operand(n[1]??0,U).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 yt(rt,n)}};function wt(e={}){let t=new St({name:`JitBlock`,...e.source?{source:e.source}:{}},e.device,!0),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?tt(n,e.device):et(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=k(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 Tt(e,t){return t}function Et(e){return Object.freeze(Object.fromEntries(e))}function Dt(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 Ot=Object.freeze([]);function kt(e){if(e.length===0)return Ot;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 At(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return e===t;if(jt(e)||jt(t)){if(!jt(e)||!jt(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)||!At(n[e],r[e]))return!1;return!0}function jt(e){return Array.isArray(e)||ArrayBuffer.isView(e)||`length`in e&&Symbol.iterator in e}function Mt(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 Nt(e){if(e===null)throw TypeError(`Expected a non-null value`);return e}function Pt(e){if(typeof e!=`boolean`)throw TypeError(`Condition must be a boolean`);return e}function Ft(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 It(e){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`Redirect target must be a finite number`);return e}function Lt(e,t){if(!e)throw TypeError(`Reaction value requires a reaction frame`);return e[t]}function Rt(e,t){if(!e||t>=e.captures.length)throw RangeError(`Reaction capture is not available`);return e.captures[t]}let zt=Symbol(`terminated call`);function*Bt(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 zt;n=e.next(r)}return t=!0,n.value}finally{t||e.return(void 0)}}let Vt=Object.freeze({createEnum:Tt,createRecord:Et,createBytes:Dt,combineIntents:kt,equalValues:At,readIndex:Mt,nonNull:Nt,checkBoolean:Pt,checkDuration:Ft,checkPc:It,reactionValue:Lt,reactionCapture:Rt,delegate:Bt,terminated:zt});function Ht(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 Ut(e){return e.kind===`optional`?Object.freeze({...e,inner:Object.freeze({...e.inner})}):Object.freeze({...e})}function Wt(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 Gt(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 Kt(e){return e.kind===`parameter`?`$${e.index}`:e.name}function qt(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:${Kt(e.memory)}`),e.kind===`readSample`&&t.push(`pin:${Kt(e.pin)}`),e.kind===`writeIntent`&&n.push(`pin:${Kt(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 Jt(e,t){let n=Wt(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 Yt(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 Xt(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 Zt(e,t,n=!0){return new Qt(e,t.optimize!==!1,n).analyze()}var Qt=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`),this.resolveSuspends()}resolveSuspends(){for(let e=this.nodes.length-1;e>=0;e--){let t=this.nodes[e],n=t.effects.maySuspend;for(let e of t.children.values())for(let t of e.nodes)t.suspends&&(n=!0);t.suspends=n}}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(Wt(n)),get effects(){return u??=qt(n)},children:/* @__PURE__ */ new Map,suspends:!1,...l?{source:Ht(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=Jt(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)&&Yt(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}`)),Gt(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}`)),Gt(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:Ut(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:Xt(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:${Kt(t.to)}`),t.kind===`refEqual`)for(let e of[t.left,t.right])g.add(`${e.kind===`parameter`?e.resource:e.kind}:${Kt(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}:${Kt(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 $t(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}`,Ut(e.type)),e.kind===`local`&&c.set(`local:${e.local}`,Ut(e.type)),e.kind===`parameter`&&c.set(`argument:${e.index}`,Ut(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,Ut(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 en={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},tn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),nn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function rn(e,t={}){return new dn(Zt(e,t,!1),t,!1).compileExecutable(e)}function an(e,t={}){return on(rn(e.body,t))}function on(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 sn(e,t){if(!Number.isSafeInteger(t)||t<0)throw TypeError(`IR identifiers must be nonnegative safe integers`);return`${e}${t}`}let K=e=>sn(`v`,e),cn=e=>sn(`l`,e),ln=e=>JSON.stringify(e);function un(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 dn=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??=$t(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,Vt),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`?K(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 Tt(e.name,e.member);case`bytes`:return Object.freeze(Array.from(Dt(e.value)));case`record`:return Et(e.fields.map(e=>[e.name,e.value]));default:return fn(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:un(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`)?`(${K(e)} === ${K(t)})`:`H.equalValues(${K(e)}, ${K(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 ${K(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 ${K(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, ${ln(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}${K(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=en[e.operator];if(!t)throw TypeError(`Unknown binary operator`);i(`(${K(e.left)} ${t} ${K(e.right)})`)}break;case`numeric`:if(!tn.has(e.builtin))throw TypeError(`Unknown numeric builtin`);i(`${nn.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(K).join(`, `)})`);break;case`record`:i(`H.createRecord([${e.fields.map(e=>`[${this.capture(e.name)}, ${K(e.value)}]`).join(`, `)}])`);break;case`field`:i(`${K(e.value)}[${this.capture(e.field)}]`);break;case`bytes`:i(`H.createBytes([${e.elements.map(K).join(`, `)}])`);break;case`length`:i(`${K(e.value)}.length`);break;case`index`:i(`H.readIndex(${K(e.value)}, ${K(e.index)})`);break;case`optional`:i(K(e.value));break;case`isNone`:i(`(${K(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${K(e.value)})`);break;case`localRead`:i(cn(e.local));break;case`local`:this.line(`let ${cn(e.local)} = ${K(e.initial)};`);break;case`localWrite`:this.line(`${cn(e.local)} = ${K(e.value)};`);break;case`write`:{let t=this.boundName(e.name);t?this.line(`${t}.write(${K(e.value)});`):this.line(`host.write(${this.capture(e.name)}, ${K(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}(${K(e.offset)})`:`host.load(${ln(e.kind)}, ${this.ref(e.memory)}, ${K(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}(${K(e.offset)}, ${K(e.value)});`):this.line(`host.store(${ln(e.kind)}, ${this.ref(e.memory)}, ${K(e.offset)}, ${K(e.value)});`);break}case`copyBytes`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.copy(${K(e.offset)}, ${K(e.length)})`:`host.copyBytes(${this.ref(e.memory)}, ${K(e.offset)}, ${K(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(${K(e.resistance)})`:`host.resistor(${this.ref(e.to)}, ${K(e.resistance)})`);break}case`combineIntents`:i(`H.combineIntents([${e.values.map(K).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(${K(e.value)});`):this.line(`host.intent(${this.ref(e.pin)}, ${K(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)}, ${K(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(${K(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`?Tt(a.name,a.member):a.value;this.block(`${i?`else if`:`if`} (H.equalValues(${K(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=K(e.result);this.line(`let ${n} = H.checkBoolean(${K(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=K(e.result);this.line(`let ${n};`),this.block(`if (H.checkBoolean(${K(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(${K(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(${K(e.duration)});`),this.suspension(n);let r=`yield { kind: ${ln(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(${K(e.target)}), delay: H.checkDuration(${K(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 ${K(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} = ${K(e.value)};`),this.line(`break ${r.label};`);break;default:fn(e)}}};function fn(e){throw TypeError(`Unsupported IR operation: ${String(e.kind)}`)}let pn={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,equal:`===`,notEqual:`!==`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},mn={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},hn=/* @__PURE__ */ new Set([`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`,`equal`,`notEqual`]),gn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),_n=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]),vn=/* @__PURE__ */ new Set([`field`,`optional`,`nonNull`,`readSample`,`resistor`,`combineIntents`,`bytes`,`index`,`select`,`match`]),yn=/* @__PURE__ */ new Set([`bytes`,`record`,`sample`,`intent`,`optional`]),bn=/* @__PURE__ */ new Set([`send`,`notify`,`readSample`,`writeIntent`,`resistor`,`random`,`assert`]);function xn(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 Sn(e){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`stored value must be a safe integer`);return e}let Cn=/* @__PURE__ */ new WeakMap;function wn(e){let t=Cn.get(e);return t===void 0&&(t=new DataView(e.buffer,e.byteOffset,e.byteLength),Cn.set(e,t)),t}function Tn(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 En(e,t){return t??wn(e)}function Dn(e,t,n,r){return En(e,t).getUint16(Tn(e,n,2),r)}function On(e,t,n,r){return En(e,t).getUint32(Tn(e,n,4),r)}function kn(e,t,n,r,i){let a=Tn(e,n,2);En(e,t).setUint16(a,Sn(r),i)}function An(e,t,n,r,i){let a=Tn(e,n,4);En(e,t).setUint32(a,Sn(r),i)}let jn=Object.freeze({checkBoolean:Pt,checkDuration:Ft,checkPc:It,combineIntents:kt,createBytes:Dt,equalValues:At,nonNull:Nt,readIndex:Mt,offset:xn,byte:Sn,load16:Dn,load32:On,store16:kn,store32:An}),q=Symbol(`unsupported direct instruction`),Mn=/* @__PURE__ */ new WeakMap;function Nn(e){let t=Mn.get(e);if(t===void 0){try{t=Zt(e,{},!1).constants}catch{t=/* @__PURE__ */ new Map}Mn.set(e,t)}return t}let Pn=/* @__PURE__ */ new WeakMap;function Fn(e){let t=Pn.get(e);return t===void 0&&(t=Object.freeze({operations:e.operations.length,nestedOperations:or(e)}),Pn.set(e,t)),t}function In(e){return e!==void 0&&typeof e!=`function`}function Ln(e,t){return e===t?!0:e===void 0||typeof e==`function`||typeof t==`function`?!1:e.step===t.step&&e.nextPc===t.nextPc}let Rn=/* @__PURE__ */ new WeakMap,zn=/* @__PURE__ */ new WeakMap;function Bn(){let e=Object.freeze({});return Rn.set(e,{entries:/* @__PURE__ */ new Map,constants:[],resistorSlots:/* @__PURE__ */ new Map,functions:/* @__PURE__ */ new Map,shards:[],nextResume:1,nextShard:1,helperBytes:0,stats:{compiledBlocks:0,reusedBlocks:0,invalidatedBlocks:0,compiledShards:0,reusedShards:0,clears:0},binding:void 0}),e}function Vn(e){let t=Rn.get(e);if(t===void 0)throw TypeError(`Invalid direct JIT cache`);return t}function Hn(e){return{states:[...e.states],memories:[...e.memories],pins:e.pins===void 0?void 0:[...e.pins],pcName:e.pc.name,pcIndex:e.pc.index,host:e.host===!0,functions:e.functions===void 0?void 0:[...e.functions],blockedStates:e.blockedStates===void 0?void 0:[...e.blockedStates].sort(),blockedMemories:e.blockedMemories===void 0?void 0:[...e.blockedMemories].sort(),entryBlockedStates:e.entryBlockedStates===void 0?void 0:[...e.entryBlockedStates].sort(),entryBlockedMemories:e.entryBlockedMemories===void 0?void 0:[...e.entryBlockedMemories].sort()}}function Un(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 Wn(e,t){return e===t?!0:e===void 0||t===void 0?!1:Un(e,t)}function Gn(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 Kn(e,t){return e.pcName===t.pcName&&e.pcIndex===t.pcIndex&&e.host===t.host&&Wn(e.functions,t.functions)&&Un(e.states,t.states)&&Un(e.memories,t.memories)&&Wn(e.pins,t.pins)&&Gn(e.blockedStates,t.blockedStates)&&Gn(e.blockedMemories,t.blockedMemories)&&Gn(e.entryBlockedStates,t.entryBlockedStates)&&Gn(e.entryBlockedMemories,t.entryBlockedMemories)}function qn(e){if(e!==void 0)return{counter:e.counter,cycles:e.cycles,...e.pending===void 0?{}:{pending:{...e.pending}}}}function Jn(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 Yn(e,t){return Xn(e,t,/* @__PURE__ */ new WeakMap)}function Xn(e,t,n){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let r=Array.isArray(e);if(r!==Array.isArray(t)||r&&e.length!==t.length)return!1;let i=n.get(e);if(i?.has(t))return!0;if(i===void 0&&(i=/* @__PURE__ */ new WeakSet,n.set(e,i)),i.add(t),r){let r=e,i=t;for(let e=0;e<r.length;e++)if(!Xn(r[e],i[e],n))return!1;return!0}let a=e,o=t,s=/* @__PURE__ */ new Set([...Object.keys(a),...Object.keys(o)]);for(let e of s)if((a[e]!==void 0||o[e]!==void 0)&&!Xn(a[e],o[e],n))return!1;return!0}function Zn(e){return JSON.stringify([e.storage,e.codeVersion,e.offset,e.byteLength])}function Qn(e){if(e===void 0)return{share:void 0,invalid:!1};if(typeof e!=`object`||!e)return{share:void 0,invalid:!0};let{storage:t,codeVersion:n,offset:r,byteLength:i}=e;return typeof t!=`string`||t.length===0||!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(i)||i<=0||!Number.isSafeInteger(r+i)?{share:void 0,invalid:!0}:{share:{storage:t,codeVersion:n,offset:r,byteLength:i},invalid:!1}}function $n(e,t){return e===t||e!==void 0&&t!==void 0&&e.storage===t.storage&&e.codeVersion===t.codeVersion&&e.offset===t.offset&&e.byteLength===t.byteLength}function er(e){e.entries.clear(),e.constants.length=0,e.resistorSlots.clear(),e.functions.clear(),e.shards.length=0,e.nextResume=1,e.nextShard=1,e.binding=void 0,e.stats.clears++}let tr=36e3;function nr(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 rr(e,t,n){if(!J(t.pc.index)||t.states.get(t.pc.name)!==t.pc.index)return;let r=n??Bn();zn.get(r)?.dispose();let i=Vn(r),a=Hn(t);i.binding!==void 0&&!Kn(i.binding,a)&&(i.stats.invalidatedBlocks+=i.entries.size,i.entries.clear(),i.constants.length=0,i.resistorSlots.clear(),i.functions.clear(),i.shards.length=0,i.nextResume=1,i.nextShard=1),i.binding=a;let o=e=>`C[${i.constants.push(e)-1}]`,s=(e,t)=>{let n=`${e}\\0${t}`,r=i.resistorSlots.get(n);return r===void 0&&(r=i.resistorSlots.size,i.resistorSlots.set(n,r)),r},c=e=>{let n=i.functions.get(e);if(n===null)throw q;if(n!==void 0)return n;i.functions.set(e,null);let r=t.functions?.get(e);if(r===void 0)throw q;let a=[],l=e=>`C[${a.push(e)-1}]`,u=new Gr(t,l,s,e=>{let t=c(e);return{...t,target:l(t.run)}},r),d=u.compileFunction(a);i.helperBytes+=u.functionSourceSize;let f={target:o(d),run:d,body:u};return i.functions.set(e,f),f},l=[],u=/* @__PURE__ */ new Map,d=/* @__PURE__ */ new Set;for(let n of e){if(!Number.isFinite(n.pc)||d.has(n.pc))continue;if(d.add(n.pc),!Number.isFinite(n.nextPc)){i.entries.delete(n.pc)&&i.stats.invalidatedBlocks++;continue}let e=qn(t.delayLoops?.get(n.pc)),r=i.entries.get(n.pc),a,f=r?.resumeId;if(r!==void 0&&r.body===n.body&&r.nextPc===n.nextPc&&Jn(r.delay,e))a=r.instruction,a!==void 0&&(a.resumeId=f??0),(r.share!==void 0||r.shareInvalid)&&i.entries.set(n.pc,{...r,share:void 0,shareInvalid:!1}),i.stats.reusedBlocks++;else{r!==void 0&&i.stats.invalidatedBlocks++;try{a=new Gr(t,o,s,c).compile(n)}catch(e){if(e!==q)throw e;a=void 0}a?.duration!==void 0&&f===void 0&&(f=i.nextResume++),a!==void 0&&(a.resumeId=f??0),i.entries.set(n.pc,{body:n.body,nextPc:n.nextPc,delay:e,instruction:a,resumeId:f,share:void 0,shareInvalid:!1}),i.stats.compiledBlocks++}a!==void 0&&(l.push(a),u.set(a.pcValue,a))}if(!l.length)return;let f=0;for(let e of l)e.slots.length>f&&(f=e.slots.length);let p=Array.from({length:f},(e,t)=>`v${t}`),m=t,h=J(m.shardSize)&&m.shardSize>0?m.shardSize:48;if(m.split===!0&&n!==void 0)return Fr(i,l,t,h);let g=J(m.shardSlotLimit)?m.shardSlotLimit:void 0,_=m.split===!0&&(g===void 0?l.reduce((e,t)=>e+t.size,0)>48e3:l.reduce((e,t)=>e+t.slots.length,0)>g),v=_?_r(l,t,h):gr(l,t,p),y=Function(`C`,`H`,_?`\"use strict\";\\n${v.join(`\n`)}\\nreturn run;`:`\"use strict\"; return (${v.join(`\n`)});`),b=v.filter(e=>e.startsWith(`function stepShard`)).length,x={run:y(Object.freeze([...i.constants]),jn),shards:_?b:1,pcs:Object.freeze(l.map(e=>e.pcValue)),localCount:f,readStates:fr(l,`readStates`),writeStates:fr(l,`writeStates`),readMemories:fr(l,`readMemories`),writeMemories:fr(l,`writeMemories`)};return Object.defineProperty(x,\"emitStats\",{value:ar(l)}),Object.freeze(x)}let ir=Object.assign(rr,{createCache:Bn,createSession(e,t){return Yr(e,t)},clearCache(e){zn.get(e)?.dispose(),er(Vn(e))},cacheStats(e){let t=Vn(e);return Object.freeze({...t.stats,entries:t.entries.size})}});function ar(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 or(e){let t=0;for(let n of e.operations)switch(t++,n.kind){case`if`:t+=or(n.yes),n.no&&(t+=or(n.no));break;case`match`:for(let e of n.arms)t+=or(e.body);n.otherwise&&(t+=or(n.otherwise));break;case`select`:t+=or(n.yes.body)+or(n.no.body);break;case`and`:case`or`:t+=or(n.right.body);break;case`while`:t+=or(n.test.body)+or(n.body);break;case`assert`:n.message&&(t+=or(n.message.body))}return t}function sr(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 cr(e){return e>=48&&e<=57}function lr(e){return cr(e)||e>=65&&e<=90||e>=97&&e<=122||e===95}function ur(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 dr(e){if(!e.startsWith(`select`))return!1;let t=6,n=t;for(;t<e.length&&cr(e.charCodeAt(t));)t++;return t>n&&e.startsWith(`: {`,t)}function fr(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 pr=e=>[`const S = F.states, M = F.memories, L = F.locals, SD = F.stateDirty, MD = F.memoryDirty, MV = F.memoryViews ?? [], P = F.pins, R = F.resistors;`,`const BS = F.blockedStates ?? [], BM = F.blockedMemories ?? [];`,...e.length?[`let ${e.join(`,`)};`]:[]],mr=`return \"invalidated\";`;function hr(e,t){let n=e.filter(e=>e.isolated).map(e=>`${t} === ${e.pc}`);return n.length?[`if (${n.join(` || `)}) ${mr}`]:[]}function gr(e,t,n){let r=hr(e,`S[${t.pc.index}]`),i=[`function run(F, deadline) {`,...pr(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)=>{i.push(`case ${t+1}: {`),e.slots.forEach((e,t)=>i.push(`${e} = L[${t}];`)),i.push(`F.resume = 0;`,...e.suffix,...e.stop?[]:r,e.isolated?mr:Lr(e.stop),`}`)}),i.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)=>{i.push(`case ${e.pc}: {`,...e.barrier,...e.guard,`S[${t.pc.index}] = ${e.nextPc};`,Vr(`SD`,t.pc.index),...e.prefix),e.duration!==void 0&&i.push(...Ir(e,n+1)),i.push(...e.suffix,e.isolated?mr:Lr(e.stop),`}`)}),i.push(`default: return \"fallback\";`,`}`,`}`,`}`),i}function _r(e,t,n){let r=hr(e,`S[${t.pc.index}]`),i=[...e].sort((e,t)=>e.pcValue-t.pcValue),a=[],o=[],s=0;for(let e of i)o.length&&(o.length>=n||s+e.size>tr)&&(a.push(o),o=[],s=0),o.push(e),s+=e.size;o.length&&a.push(o);let c=0,l=a.map(e=>{let t={start:c,entries:e,maxSlots:Math.max(...e.map(e=>e.slots.length)),lastPc:e[e.length-1].pc,lastResume:c+e.length,resumable:e.some(e=>e.duration!==void 0)};return c+=e.length,t}),u=e=>Array.from({length:e},(e,t)=>`v${t}`),d=[];l.forEach((e,n)=>{let r=n?l[n-1].lastPc:void 0;d.push(`function stepShard${n}(F, deadline, pc) {`,...pr(u(e.maxSlots)),`while (true) {`,`switch (pc) {`),e.entries.forEach((n,i)=>{d.push(`case ${n.pc}: {`,...n.barrier,...n.guard,`S[${t.pc.index}] = ${n.nextPc};`,Vr(`SD`,t.pc.index),...n.prefix,...Ir(n,e.start+i+1),...n.suffix,n.isolated?mr:Br(n.stop,r,e.lastPc,t.pc.index),`}`)}),d.push(`default: return \"fallback\";`,`}`,`}`,`}`)}),l.forEach((e,t)=>{e.resumable&&(d.push(`function resumeShard${t}(F, resume) {`,...pr(u(e.maxSlots)),`switch (resume) {`),e.entries.forEach((t,n)=>{t.duration!==void 0&&(d.push(`case ${e.start+n+1}: {`),t.slots.forEach((e,t)=>d.push(`${e} = L[${t}];`)),d.push(`F.resume = 0;`,...t.suffix,...t.stop?[]:r,t.isolated?mr:Rr(t.stop),`}`))}),d.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`))}),d.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 f=l.map((e,t)=>({shard:e,shardIndex:t})).filter(({shard:e})=>e.resumable);return f.length?nr(d,`resume`,f.map(({shard:e,shardIndex:t})=>({bound:String(e.lastResume),call:`status = resumeShard${t}(F, resume);`})),`throw new TypeError(\"Unknown direct JIT continuation\");`):d.push(`throw new TypeError(\"Unknown direct JIT continuation\");`),d.push(`} else {`,`if (F.stopAfterInstruction) return \"invalidated\";`,`const pc = S[${t.pc.index}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc);`),nr(d,`pc`,l.map((e,t)=>({bound:String(e.lastPc),call:`status = stepShard${t}(F, deadline, pc);`})),`return \"fallback\";`),d.push(`}`,`if (status !== \"next\") return status;`,`}`,`}`),d}function vr(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 yr(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 br(e,t,n){return e.entries.length<n&&e.sourceSize+t.size<=tr}function xr(e,t){if(e.length<=1)return e.length?[e]:[];let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.pcValue,t);let r=`S[${t}] = `,i=/* @__PURE__ */ new Map;for(let t of e){let e=Tr(t,n,r);e!==void 0&&i.set(t,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=(e,t)=>e.pcValue>t.pcValue?3:e.nextPcValue===t.pcValue?2:1,c=(e,t,n)=>{let r=s(e,n),i=s(t,n);return r===i?r===2?e.pcValue<t.pcValue:e.pcValue>t.pcValue:r>i};for(let[e,t]of i){let n=a.get(t);(n===void 0||c(e,n,t))&&(n!==void 0&&o.delete(n),a.set(t,e),o.set(e,t))}let l=[],u=/* @__PURE__ */ new Set;for(let t of e){if(u.has(t)||a.has(t))continue;let e=[],n=t;for(;n!==void 0&&!u.has(n);)u.add(n),e.push(n),n=o.get(n);l.push(e)}for(let t of e){if(u.has(t))continue;let e=[],n=t;for(;n!==void 0&&!u.has(n);)u.add(n),e.push(n),n=o.get(n);l.push(e)}return l}function Sr(e,t){return e.length<=2?e:xr(e,t).flat()}function Cr(e,t,n,r){let i=new Map(t.map(e=>[e.pcValue,e])),a=/* @__PURE__ */ new Map;for(let t=e.shards.length-1;t>=0;t--){let n=e.shards[t],r=[],o=!1;for(let e of n.entries){let t=i.get(e.pcValue);t===void 0?o=!0:(t!==e&&(o=!0),r.push(t))}if(o&&(n.entries=r,n.dirty=!0),!r.length)e.shards.splice(t,1);else{yr(n);for(let e of n.entries)a.set(e.pcValue,n)}}let o=xr([...i.values()].filter(e=>!a.has(e.pcValue)).sort((e,t)=>e.pcValue-t.pcValue),r);for(let t of o){let r=t.reduce((e,t)=>e+t.size,0),i=e.shards[e.shards.length-1];i!==void 0&&i.entries.length>0&&t.length<=n&&r<=tr&&i.sourceSize+r>tr&&(i={id:e.nextShard++,entries:[],sourceSize:0,maxSlots:0,resumable:!1,functions:void 0,signature:void 0,dirty:!0},e.shards.push(i));for(let r of t){let t=e.shards[e.shards.length-1];(t===void 0||!br(t,r,n))&&(t={id:e.nextShard++,entries:[],sourceSize:0,maxSlots:0,resumable:!1,functions:void 0,signature:void 0,dirty:!0},e.shards.push(t)),t.entries.push(r),t.dirty=!0,yr(t),a.set(r.pcValue,t)}}}function wr(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 Tr(e,t,n){let r,i;for(let a of e.prefix){if(!a.startsWith(n)||!a.endsWith(`;`))continue;let o=Number(a.slice(n.length,-1));if(!Number.isSafeInteger(o)||o===e.nextPcValue)continue;let s=t.get(o);s!==void 0&&s!==e&&(o<e.pcValue&&(r=s),i=s)}if(r!==void 0)return r;if(i!==void 0)return i;let a=t.get(e.nextPcValue);return a!==void 0&&a!==e?a:void 0}function Er(e,t,n,r){if(e.stop)return`return \"stopped\";`;let i=n.host===!0&&e.duration!==void 0&&e.suffix.length===0&&!e.isolated,a;a=e.duration===void 0?n.host===!0?`if (F.stopAfterInstruction) return \"invalidated\"; if (F.publishPending && F.finishCheckpoint?.(deadline, false) !== true) return \"invalidated\"; `:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; `:i?e.dynamicDuration?`if (F.publishPending) return \"invalidated\"; `:``:n.host?`if (F.stopAfterInstruction && !F.finishCheckpoint?.(deadline, ${e.suffix.length===0})) return \"invalidated\"; if (F.publishPending) return \"invalidated\"; `:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; `;let o=`if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc);`;if(t===void 0)return`${a}const pc = S[${n.pc.index}]; ${o} return pc;`;let s=`pc = S[${n.pc.index}]; ${o}`;return r===void 0?`${a}${s} if (${t}) continue; return pc;`:`${a}pc = S[${n.pc.index}]; if (pc !== ${r.pc}) { ${o} if (${t}) continue; return pc; }`}function Dr(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 Or(e,t){let n=Array.from({length:e.maxSlots},(e,t)=>`v${t}`),r=wr(e.entries),i=Sr(e.entries,t.pc.index),a=[],o=[`function stepShard${e.id}(F, deadline, pc) {`,...pr(n),`while (true) {`,`switch (pc) {`];i.forEach((e,n)=>{let s=i[n+1];o.push(`case ${e.pc}: {`,...e.barrier,...e.guard,`S[${t.pc.index}] = ${e.nextPc};`,Vr(`SD`,t.pc.index),...e.outlinePrefix(a),...Ir(e,e.resumeId,t.host===!0),...e.suffix,e.isolated?mr:Er(e,r,t,s),`}`)}),o.push(`default: return pc;`,`}`,`}`,`}`),e.resumable&&(o.push(`function resumeShard${e.id}(F, resume) {`,...pr(n),`switch (resume) {`),e.entries.forEach(e=>{e.duration!==void 0&&(o.push(`case ${e.resumeId}: {`),e.slots.forEach((e,t)=>o.push(`${e} = L[${t}];`)),o.push(`F.resume = 0;`,...e.suffix,e.isolated?mr:Dr(e.stop,t.pc.index),`}`))}),o.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`));for(let e of a)o.push(...e);return o}function kr(e,t,n){let r=e.instruction,i=Array.from({length:r.slots.length},(e,t)=>`v${t}`),a=[],o=[`function stepShared${e.id}(F, deadline, nextPc) {`,...pr(i),...r.barrier,...r.guard,`S[${n}] = nextPc;`,Vr(`SD`,n),...r.outlinePrefix(a),...Ir(r,e.resumeId,t.host===!0),...r.suffix,r.isolated?mr:Er(r,void 0,t),`}`];r.duration!==void 0&&o.push(`function resumeShared${e.id}(F, resume) {`,...pr(i),...r.slots.map((e,t)=>`${e} = L[${t}];`),`F.resume = 0;`,...r.suffix,r.isolated?mr:Dr(r.stop,n),`}`);for(let e of a)o.push(...e);return o}let Ar=/* @__PURE__ */ new Map,jr=0;function Mr(e){let t=e.length<=65536,n=t?Ar.get(e):void 0;if(n!==void 0)return Ar.delete(e),Ar.set(e,n),n;let r=Function(`C`,`H`,e);if(!t)return r;for(;Ar.size>=128||jr+e.length>4194304;){let e=Ar.keys().next().value;Ar.delete(e),jr-=e.length}return Ar.set(e,r),jr+=e.length,r}function Nr(e,t,n){let r=Or(t,n),i=t.resumable?`resumeShard${t.id}`:`undefined`,a=`\"use strict\";\\n${r.join(`\n`)}\\nreturn [stepShard${t.id}, ${i}];`,[o,s]=Mr(a)(Object.freeze([...e.constants]),jn);return t.functions={step:o,resume:s},t.signature=Object.freeze([...t.entries]),t.dirty=!1,e.stats.compiledShards++,a.length}function Pr(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;`,...hr(t,`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 Fr(e,t,n,r){if(Cr(e,t,r,n.pc.index),!e.shards.length)return;for(let t of e.shards)t.functions!==void 0&&!t.dirty&&vr(t.signature??[],t.entries)?e.stats.reusedShards++:Nr(e,t,n);let i=Pr(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:fr(t,`readStates`),writeStates:fr(t,`writeStates`),readMemories:fr(t,`readMemories`),writeMemories:fr(t,`writeMemories`)};return Object.defineProperty(u,\"emitStats\",{value:ar(t)}),Object.freeze(u)}function Ir(e,t,n=!1){if(e.duration===void 0)return[];let r=e.dynamicDuration?`(Number.isInteger(${e.duration}) && ${e.duration} >= 0 && ${e.duration} <= 7200000000000000 ? ${e.duration} : H.checkDuration(${e.duration}))`:e.duration,i=n&&e.suffix.length===0&&!e.stop&&!e.isolated;return[`F.due = F.time + ${r};`,`if (F.due > 7200000000000000) throw new RangeError(\"Time out of range\");`,`if ((F.publishPending && F.due > F.time) || F.due >= deadline) {`,`F.resume = ${t};`,...n?[`if (F.due < deadline && F.publishCheckpoint?.()) {`,`F.resume = 0;`,...i?[`F.time = F.due;`,`F.stopAfterInstruction = true;`,`if (!F.finishCheckpoint?.(deadline, true)) return \"invalidated\";`]:[`F.stopAfterInstruction = true;`],`} else {`]:[],...e.slots.map((e,t)=>`L[${t}] = ${e};`),n?`if (F.due < deadline || (F.publishPending && F.due > F.time)) return \"invalidated\";`:`if (F.publishPending && F.due > F.time) return \"invalidated\";`,`F.time = deadline;`,`return \"deadline\";`,...n?[`}`]:[],...i?[`} else F.time = F.due;`]:[`}`,`F.time = F.due;`]]}function Lr(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; continue;`}function Rr(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction || F.publishPending) return \"invalidated\"; return \"next\";`}function zr(e){return`(typeof ${e} === \"boolean\" ? ${e} : H.checkBoolean(${e}))`}function Br(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 Vr(e,t){return`${e}[${t>>>5}] |= ${1<<(t&31)};`}function J(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Hr(e){return e.operations.some(Wr)}function Ur(e){return e.operations.some(e=>e.kind===`redirect`||Wr(e))}function Wr(e){switch(e.kind){case`redirect`:return!1;case`if`:return Ur(e.yes)||e.no!==void 0&&Ur(e.no);case`match`:return e.arms.some(e=>Ur(e.body))||e.otherwise!==void 0&&Ur(e.otherwise);case`while`:return Ur(e.test.body)||Ur(e.body);case`loop`:return Ur(e.body);case`and`:case`or`:return Ur(e.right.body);case`select`:return Ur(e.yes.body)||Ur(e.no.body);case`assert`:return e.message!==void 0&&Ur(e.message.body);default:return!1}}var Gr=class{binding;capture;resistorSlot;resolveFunction;fn;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;functionSourceSize=0;foldedOperations=0;nestedOperations=0;guard=[];barrier=[];prefix=[];suffix=[];pcValue=0;nextPcValue=0;pc=``;nextPc=``;resumeId=0;duration;dynamicDuration=!1;immediate=!1;stop=!1;get isolated(){return this.backedges!==void 0}backedges;outlineBranches;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;booleanResults=/* @__PURE__ */ new Set;exitLabel;exitDuration;labels=0;constructor(e,t,n,r,i){this.binding=e,this.capture=t,this.resistorSlot=n,this.resolveFunction=r,this.fn=i}compileFunction(e){let t=this.fn,n=e=>e.kind===`number`||e.kind===`bool`;if(t.params.some(({type:e})=>!n(e))||t.returns&&!n(t.returns)||(this.constants=Nn(t.body),this.region(t.body,this.prefix),this.isolated))throw q;this.compact();let r=t.params.map((e,t)=>`a${t}`),i=[...pr(this.slots),...this.prefix],a=`\"use strict\"; return function(F${r.map(e=>`,${e}`).join(``)}) {\\n${i.join(`\n`)}\\n};`;return this.functionSourceSize=a.length,Function(`C`,`H`,a)(Object.freeze([...e]),jn)}compile(e){this.pcValue=e.pc,this.nextPcValue=e.nextPc,this.constants=Nn(e.body);let t=Fn(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&&J(n.counter)&&J(n.cycles)){let e=n.pending,t=e!==void 0&&J(e.state)&&J(e.period)&&J(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;`,Vr(`SD`,n.counter),...t===void 0?[]:[`S[${t.state}] += rounds * ${n.cycles};`,Vr(`SD`,t.state)],`}`,`if (F.time >= deadline) { F.time = deadline; return \"deadline\"; }`,`}`)}let r=this.prefix,i=!1;if(Hr(e.body))this.compileConditional(e.body.operations);else for(let t of e.body.operations){if(i)throw q;if(t.kind===`elapse`){if(this.terminated)throw q;this.terminate(this.delay(t.duration)),r=this.suffix}else if(t.kind===`redirect`){if(this.terminated)throw q;let e=this.delay(t.delay);r.push(`S[${this.binding.pc.index}] = H.checkPc(${this.value(t.target)});`,Vr(`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 q;this.terminate({value:`0`,zero:!0,dynamic:!1}),i=!0}else this.operation(t,r)}if(!this.terminated&&!this.stop||this.isolated&&this.exitLabel===void 0&&(!this.immediate||this.stop||this.guard.length))throw q;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+=sr(t),dr(t)&&s++;return this.size=a,this.statements=o,this.selects=s,this}compileConditional(e){if(e[e.length-1]?.kind!==`elapse`||this.guard.length)throw q;let t=`exit${this.labels++}`,n=this.slot();this.exitDuration=n,this.exitLabel=t,this.prefix.push(`${t}: {`);for(let t=0;t<e.length;t++){let r=e[t];if(r.kind===`elapse`){if(t!==e.length-1)throw q;this.prefix.push(`${n} = ${this.delay(r.duration).value};`)}else if(r.kind===`redirect`||r.kind===`stop`||r.kind===`yield`)throw q;else this.operation(r,this.prefix)}this.prefix.push(`}`),this.duration=n,this.dynamicDuration=!0}emitBarrier(){let e=[];if(this.isolated){let t=this.binding.pc.index;e.push(`if (SD[${t>>>5}] & ${1<<(t&31)>>>0}) ${mr}`)}let t=(t,n,r,i)=>{if(!r?.size||!n.size)return;let a=/* @__PURE__ */ new Set;for(let e of r){let t=i.get(e);J(t)&&n.has(t)&&a.add(t)}if(!a.size)return;let o=/* @__PURE__ */ new Map;for(let e of a)o.set(e>>>5,(o.get(e>>>5)??0)|1<<(e&31));for(let[n,r]of[...o].sort(([e],[t])=>e-t))e.push(`if (${t}[${n}] & ${r>>>0}) return \"fallback\";`)};return t(`BS`,this.writtenStates,this.binding.entryBlockedStates,this.binding.states),t(`BM`,this.writtenMemories,this.binding.entryBlockedMemories,this.binding.memories),e}get terminated(){return this.duration!==void 0||this.immediate}outlinePrefix(e){if(this.exitLabel!==void 0||this.size<=tr||this.slots.length>64||this.isolated||!this.outlineBranches)return this.prefix;let t=[],n=this.slots.join(`,`),r=[`F`,`S`,`M`,`SD`,`MD`,`MV`,`P`,`R`,`BS`,`BM`,...this.slots].join(`,`),i=0;for(let{start:a,end:o}of this.outlineBranches.sort((e,t)=>e.start-t.start)){if(a<i)continue;let s=`outlined${e.length}`;t.push(...this.prefix.slice(i,a));let c=`${s}(${r});`;n?(t.push(`const result = ${c}`),this.slots.forEach((e,n)=>t.push(`${e} = result[${n}];`))):t.push(c),e.push([`function ${s}(${r}) {`,...this.prefix.slice(a,o),...n?[`return [${n}];`]:[],`}`]),i=o}return t.push(...this.prefix.slice(i)),t}compact(){let e=this.slots.length;if(e<=1)return;let t=this.prefix.length,n=this.duration===void 0?[]:[this.duration],r=[...this.prefix,...n,...this.suffix],i=r.length,a=new Int32Array(i+1),o=new Int32Array(i).fill(-1),s=new Int32Array(e).fill(-1),c=new Int32Array(e).fill(-1),l=new Int32Array(e).fill(-1),u=new Int32Array(e).fill(-1),d=[];for(let t=0;t<i;t++){a[t]=d.length;let n=r[t],i=0;if(n.charCodeAt(0)===118){let r=1,a=0;for(;r<n.length&&cr(n.charCodeAt(r));)a=a*10+(n.charCodeAt(r)-48),r++;if(r>1&&n.charCodeAt(r)===32&&n.charCodeAt(r+1)===61&&n.charCodeAt(r+2)===32){if(a>=e)return;o[t]=a,s[a]<0&&(s[a]=t),c[a]=t,i=r+3}}for(;i<n.length;){if(n.charCodeAt(i)===34){i=ur(n,i);continue}if(n.charCodeAt(i)!==118||i>0&&lr(n.charCodeAt(i-1))){i++;continue}let r=i+1,a=0;for(;r<n.length&&cr(n.charCodeAt(r));)a=a*10+(n.charCodeAt(r)-48),r++;if(r===i+1)i++;else if(r<n.length&&lr(n.charCodeAt(r)))i=r;else{if(a>=e)return;d.push(a),l[a]=t,i=r}}}a[i]=d.length;for(let e=0;e<i;e++)for(let t=a[e];t<a[e+1];t++){let n=d[t];if(s[n]<0||s[n]>e)return}for(let t=0;t<e;t++)c[t]>=0&&(u[t]=Math.max(c[t],l[t]));let f=this.backedges&&/* @__PURE__ */ new Map;for(let e of this.backedges??[]){let r=e.lines===this.prefix?0:t+n.length,i=r+e.head,c=r+e.tail,l=[],p=e=>{s[e]<i&&u[e]<c&&(u[e]=c,l.push(e))};for(let e=i;e<c;e++){let t=o[e];t>=0&&p(t);for(let t=a[e];t<a[e+1];t++)p(d[t])}l.length&&f.set(c,l)}let p=new Int32Array(e).fill(-1),m=[],h=0;for(let e=0;e<i;e++){let t=o[e];t>=0&&p[t]<0&&(p[t]=m.length>0?m.pop():h++),t>=0&&u[t]===e&&(u[t]=-1,m.push(p[t]));for(let t=a[e];t<a[e+1];t++){let n=d[t];u[n]===e&&(u[n]=-1,m.push(p[n]))}let n=f?.get(e);if(n)for(let t of n)u[t]===e&&(u[t]=-1,m.push(p[t]))}let g=Array.from({length:h},(e,t)=>`v${t}`),_=t=>{let n=``,r=0,i=0;for(;i<t.length;){if(t.charCodeAt(i)===34){i=ur(t,i);continue}if(t.charCodeAt(i)!==118||i>0&&lr(t.charCodeAt(i-1))){i++;continue}let a=i+1,o=0;for(;a<t.length&&cr(t.charCodeAt(a));)o=o*10+(t.charCodeAt(a)-48),a++;if(a===i+1||a<t.length&&lr(t.charCodeAt(a))){i=a;continue}let s=o<e?p[o]:-1;s<0||(n+=t.slice(r,i),n+=g[s],r=a),i=a}return r===0?t:n+t.slice(r)};for(let e=0;e<t;e++)this.prefix[e]=_(this.prefix[e]);for(let e=0;e<this.suffix.length;e++)this.suffix[e]=_(this.suffix[e]);this.duration!==void 0&&(this.duration=_(this.duration)),this.slots=g}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{Ft(t.value)}catch{throw q}return{value:t.text,zero:t.value===0,dynamic:!1}}let n=this.values.get(e);if(n===void 0)throw q;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 q;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:this.booleanResults.has(e)?this.value(e):zr(this.value(e))}isGuaranteedBoolean(e){if(this.booleanResults.has(e))return!0;let t=this.folded.get(e);return t!==void 0&&typeof t.value==`boolean`}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(!J(n)||t&&this.binding.entryBlockedStates?.has(e))throw q;return(t?this.writeStates:this.readStates).add(e),t&&this.writtenStates.add(n),n}memory(e){if(e.memory.kind!==`memory`)throw q;let t=e.memory.name,n=this.binding.memories.get(t),r=e.kind.startsWith(`store`);if(!J(n)||r&&this.binding.entryBlockedMemories?.has(t))throw q;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:(e.constant.kind===`bool`&&this.booleanResults.add(e.result),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=mn[e.operator],i=n(e.value);return!r||i===void 0?!1:(e.operator===`not`&&this.booleanResults.add(e.result),t.set(e.result,`(${r}${i})`),!0)}case`binary`:{let r=pn[e.operator],i=n(e.left),a=n(e.right);return!r||i===void 0||a===void 0?!1:(hn.has(e.operator)&&this.booleanResults.add(e.result),t.set(e.result,`(${i} ${r} ${a})`),!0)}case`numeric`:{if(!gn.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)}_n.has(e.builtin)&&this.booleanResults.add(e.result);let i=_n.has(e.builtin)?`Number`:`Math`;return t.set(e.result,`${i}.${e.builtin}(${r.join(`,`)})`),!0}case`nonNull`:{let r=n(e.value);return r!==void 0&&(t.set(e.result,`H.nonNull(${r})`),!0)}default:return!1}}requireHost(){if(this.binding.host!==!0)throw q}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 q;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){let r=!1;for(let i of e.operations){if(r)throw q;if(i.kind===`yield`){if(!n)throw q;t.push(`${n.slot} = ${this.value(i.value)}; break ${n.label};`)}else if(i.kind===`redirect`){if(n!==void 0||this.exitLabel===void 0||this.exitDuration===void 0)throw q;let e=this.delay(i.delay);t.push(`S[${this.binding.pc.index}] = H.checkPc(${this.value(i.target)});`,Vr(`SD`,this.binding.pc.index),`${this.exitDuration} = ${e.value};`,`break ${this.exitLabel};`),r=!0}else this.operation(i,t,n)}}operation(e,t,n){let r;if(bn.has(e.kind)&&this.requireHost(),`result`in e){let t=e.type.kind;if(t!==`number`&&t!==`bool`&&!(vn.has(e.kind)||e.kind===`constant`&&(t===`string`||t===`enum`||t===`bytes`)))throw q;if(this.foldResult(e))return;r=this.slot(),this.values.set(e.result,r),yn.has(t)&&this.references.add(e.result)}let i=e=>{t.push(`${r} = ${e};`)};switch(e.kind){case`parameter`:if(!this.fn?.params[e.index])throw q;i(`a${e.index}`);break;case`return`:case`returnValue`:if(!this.fn)throw q;t.push(e.kind===`returnValue`?`return ${this.value(e.value)};`:`return;`);break;case`call`:case`callValue`:{let n=this.resolveFunction?.(e.name);if(!n)throw q;let r=e.args.map(e=>{if(e.kind!==`value`)throw q;return this.value(e.value)});for(let e of n.body.readStates)this.state(e,!1);for(let e of n.body.writeStates)this.state(e,!0);for(let e of n.body.readMemories)this.memory({kind:`load8`,memory:{kind:`memory`,name:e}});for(let e of n.body.writeMemories)this.memory({kind:`store8`,memory:{kind:`memory`,name:e}});let a=`${n.target}(F${r.map(e=>`, ${e}`).join(``)})`;e.kind===`callValue`?i(a):t.push(`${a};`);break}case`constant`:{if(e.constant.kind!==`bytes`)throw q;let t;try{t=Object.freeze(Array.from(Dt(e.constant.value)))}catch{throw q}i(`H.createBytes(${this.capture(t)})`);break}case`read`:if(e.resource!==`state`)throw q;i(`S[${this.state(e.name,!1)}]`);break;case`write`:{let n=this.state(e.name,!0),r=n>>>5,i=1<<(n&31)>>>0;t.push(`S[${n}] = ${this.value(e.value)};`,Vr(`SD`,n),`if (BS[${r}] & ${i}) F.publishPending = true;`);break}case`unary`:{let t=mn[e.operator];if(!t)throw q;i(`(${t}${this.value(e.value)})`),e.operator===`not`&&this.booleanResults.add(e.result);break}case`binary`:{let t=pn[e.operator];if(!t)throw q;let n=this.value(e.left),r=this.value(e.right);if(hn.has(e.operator)&&this.booleanResults.add(e.result),(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(!gn.has(e.builtin))throw q;_n.has(e.builtin)&&this.booleanResults.add(e.result),i(`${_n.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 q;let t=this.binding.pins?.get(e.pin.name);if(J(t)){i(`P[${t}].sample`);break}i(`F.host.sample(${this.capture(e.pin.name)})`);break}case`writeIntent`:{if(e.pin.kind!==`pin`)throw q;let n=this.binding.pins?.get(e.pin.name);if(J(n)){t.push(`F.writePinIntent(${n}, ${this.value(e.value)});`);break}t.push(`F.host.intent(${this.capture(e.pin.name)}, ${this.value(e.value)});`);break}case`resistor`:{if(e.to.kind!==`pin`)throw q;let t=this.binding.pins?.get(e.to.name),n=this.folded.get(e.resistance);if(J(t)&&this.resistorSlot!==void 0&&n!==void 0&&typeof n.value==`number`&&Number.isFinite(n.value)&&n.value>=.001&&n.value<=1e9){let t=this.resistorSlot(e.to.name,n.value);i(`(R[${t}] ?? (R[${t}] = F.host.resistor(${this.capture(e.to.name)}, ${n.text})))`);break}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`:if(this.binding.pins!==void 0&&/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e.field)){i(`${this.value(e.value)}.${e.field}`);break}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 q;this.booleanResults.add(e.result),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`:this.booleanResults.add(e.result),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 q;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 q;i(t);break}case`localWrite`:{let n=this.locals.get(e.local);if(!n)throw q;t.push(`${n} = ${this.value(e.value)};`);break}case`load8`:{let t=`M[${this.memory(e)}]`,n=this.folded.get(e.offset);if(n!==void 0&&typeof n.value==`number`&&Number.isSafeInteger(n.value)&&n.value>=0){i(`(${n.text} < ${t}.length ? ${t}[${n.text}] : H.offset(${t},${n.text}))`);break}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)});`,Vr(`MD`,n),`if (BM[${n>>>5}] & ${1<<(n&31)>>>0}) F.publishPending = true;`);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});`,Vr(`MD`,n),`if (BM[${n>>>5}] & ${1<<(n&31)>>>0}) F.publishPending = true;`);break}case`and`:case`or`:{if(e.right.body.operations.at(-1)?.kind!==`yield`)throw q;this.booleanResults.add(e.result);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} = ${zr(r)};`,`}`);break}case`match`:{let r=this.value(e.value);if(!e.arms.length&&!e.otherwise||!e.otherwise&&n)throw q;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)}) {`);let r=t.length;if(this.region(e.yes,t,n),e.no){let i=t.length-r;t.push(`} else {`);let a=t.length;this.region(e.no,t,n);let o=t.length-a;!n&&t===this.prefix&&i>0&&o>=512&&o>=i*8&&(this.outlineBranches??=[]).push({start:a,end:t.length})}t.push(`}`);break}case`while`:{if(n||e.test.body.operations.at(-1)?.kind!==`yield`)throw q;let r=t.length,i=this.slot(),a=`loopTest${this.labels++}`;t.push(`while (true) {`,`${a}: {`),this.region(e.test.body,t,{slot:i,label:a}),t.push(`}`,`if (!${zr(i)}) break;`),this.region(e.body,t),(this.backedges??=[]).push({lines:t,head:r,tail:t.length}),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),o=()=>{if(e.type.kind!==`bool`)return;let t=e.yes.body.operations.at(-1),n=e.no.body.operations.at(-1);t?.kind===`yield`&&n?.kind===`yield`&&this.isGuaranteedBoolean(t.value)&&this.isGuaranteedBoolean(n.value)&&this.booleanResults.add(e.result)};if(i!==void 0&&a!==void 0){t.push(`${r} = ${n} ? ${i} : ${a};`),o();break}let s=`select${this.labels++}`;t.push(`${s}: {`,`if (${n}) {`),this.region(e.yes.body,t,{slot:r,label:s}),t.push(`} else {`),this.region(e.no.body,t,{slot:r,label:s}),t.push(`}`,`}`),o();break}default:throw q}}};function Kr(e,t){let n={...e};return delete n.delayLoops,t===void 0?n:{...n,delayLoops:t}}function qr(e){let t=e.shardSize;return J(t)&&t>0?t:48}var Jr=class{cache;state;binding;fingerprint;routes=/* @__PURE__ */ new Map;resumes=/* @__PURE__ */ new Map;rejected=/* @__PURE__ */ new Set;isolated=/* @__PURE__ */ new Set;owners=/* @__PURE__ */ new Map;sharedVariants=[];variantsByKey=/* @__PURE__ */ new Map;sharedRoutes=/* @__PURE__ */ new Map;shareStates=/* @__PURE__ */ new Map;candidateKeys=/* @__PURE__ */ new Map;candidatesByKey=/* @__PURE__ */ new Map;shareRejected={missing:0,invalid:0,single:0,ir:0,delay:0,isolated:0,context:0};nextSharedVariant=1;counters={batches:0,routeInstalls:0,routeRemovals:0,compiledShards:0,reusedShards:0,compiledBlocks:0,reusedBlocks:0,invalidatedBlocks:0,bodyBytes:0,shardBytes:0,dispatcherBytes:0,helperBytes:0,sharedBodies:0,sharedBytes:0,shareReusedBodies:0,shareReusedRoutes:0};delays;compileBinding;localSlots=0;sessionPcs=Object.freeze([]);emitStatsValue=ar([]);closed=!1;runFunction;constructor(e,t,n,r){this.cache=e,this.state=t,this.binding=n,this.fingerprint=r,this.delays=n.delayLoops,this.compileBinding=Kr(n,this.delays),this.runFunction=this.createDispatcher();let i=this.state.helperBytes,a=this.reconcileDelays(this.delays);a.size&&(this.applyEntryChanges(a),this.counters.helperBytes+=this.state.helperBytes-i),this.rebuildAll(),this.refreshEmitStats()}get sessionFingerprint(){return this.fingerprint}get isDisposed(){return this.closed}get localCount(){return this.localSlots}get shardCount(){return this.closed?0:this.state.shards.length}get routeCount(){return this.routes.size}get pcs(){return this.sessionPcs===void 0&&(this.sessionPcs=Object.freeze([...this.routes.keys()].sort((e,t)=>e-t))),this.sessionPcs}get emitStats(){return this.emitStatsValue}has(e){return!this.closed&&this.routes.has(e)}run(e,t){return this.closed?`untranslated`:this.runFunction(e,t)}add(e){this.assertActive();let t=this.state.helperBytes,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=!1;for(let t of e){if(!Number.isFinite(t.pc)||n.has(t.pc))continue;n.add(t.pc);let e=this.state.entries.get(t.pc);if(e!==void 0&&(e.share!==void 0||e.shareInvalid)&&(i=!0),!Number.isFinite(t.nextPc)){r.set(t.pc,{pc:t.pc,remove:!0,record:void 0,changed:!0,metadataOnly:!1});continue}let a=qn(this.delays?.get(t.pc)),o=Qn(t.share);if((t.share!==void 0||o.invalid)&&(i=!0),e!==void 0&&e.body===t.body&&e.nextPc===t.nextPc&&Jn(e.delay,a)){let n=e.instruction;n!==void 0&&(n.resumeId=e.resumeId??0),$n(e.share,o.share)&&e.shareInvalid===o.invalid?r.set(t.pc,{pc:t.pc,remove:!1,record:e,changed:!1,metadataOnly:!1}):e.share===void 0?(i=!0,r.set(t.pc,{pc:t.pc,remove:!1,record:{...e,share:o.share,shareInvalid:o.invalid},changed:!1,metadataOnly:!0})):r.set(t.pc,{pc:t.pc,remove:!1,record:this.compileRecord(t,a,o),changed:!0,metadataOnly:!1})}else r.set(t.pc,{pc:t.pc,remove:!1,record:this.compileRecord(t,a,o),changed:!0,metadataOnly:!1})}r.size&&(this.commitChanges(r,i),this.counters.helperBytes+=this.state.helperBytes-t),this.counters.batches++}remove(e){this.assertActive();let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map;for(let r of e)Number.isFinite(r)&&!t.has(r)&&(t.add(r),this.state.entries.has(r)&&n.set(r,{pc:r,remove:!0,record:void 0,changed:!0,metadataOnly:!1}));n.size&&this.commitChanges(n,!1)}updateDelays(e){this.assertActive();let t=e??this.binding.delayLoops;this.delays=t,this.compileBinding=Kr(this.binding,t);let n=this.state.helperBytes,r=this.reconcileDelays(t);r.size&&(this.commitChanges(r,!1),this.counters.helperBytes+=this.state.helperBytes-n)}clear(){this.assertActive(),this.counters.routeRemovals+=this.routes.size,this.routes.clear(),this.resumes.clear(),this.rejected.clear(),this.isolated.clear(),this.owners.clear(),this.sharedVariants.length=0,this.variantsByKey.clear(),this.sharedRoutes.clear(),this.shareStates.clear(),this.candidateKeys.clear(),this.candidatesByKey.clear(),this.nextSharedVariant=1,this.state.entries.clear(),this.state.constants.length=0,this.state.resistorSlots.clear(),this.state.functions.clear(),this.state.shards.length=0,this.state.nextShard=1,this.state.stats.clears++,this.refreshPcs(),this.refreshEmitStats()}stats(){let e=0;for(let t of this.candidatesByKey.values())e+=t.size;let t=0;for(let e of this.sharedVariants)e.functions!==void 0&&e.entries.size>0&&t++;return Object.freeze({batches:this.counters.batches,routeInstalls:this.counters.routeInstalls,routeRemovals:this.counters.routeRemovals,compiledShards:this.counters.compiledShards,reusedShards:this.counters.reusedShards,compiledBlocks:this.counters.compiledBlocks,reusedBlocks:this.counters.reusedBlocks,invalidatedBlocks:this.counters.invalidatedBlocks,routes:this.routes.size,shards:this.closed?0:this.state.shards.length,bodyBytes:this.counters.bodyBytes,shardBytes:this.counters.shardBytes,dispatcherBytes:this.counters.dispatcherBytes,helperBytes:this.counters.helperBytes,shareCandidates:this.closed?0:e,shareGroups:t,sharedRoutes:this.sharedRoutes.size,shareReusedBodies:this.counters.shareReusedBodies,shareReusedRoutes:this.counters.shareReusedRoutes,shareRejected:Object.freeze({...this.shareRejected}),sharedBodies:this.counters.sharedBodies,sharedBytes:this.counters.sharedBytes})}dispose(){this.closed||(this.closed=!0,this.routes.clear(),this.resumes.clear(),this.rejected.clear(),this.isolated.clear(),this.owners.clear(),this.sharedVariants.length=0,this.variantsByKey.clear(),this.sharedRoutes.clear(),this.shareStates.clear(),this.candidateKeys.clear(),this.candidatesByKey.clear(),this.refreshPcs(),zn.get(this.cache)===this&&zn.delete(this.cache))}assertActive(){if(this.closed)throw TypeError(`Direct JIT session has been disposed`)}createDispatcher(){let e=[`\"use strict\";`,`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 = RESUME.get(resume);`,`if (resumed === undefined) throw new TypeError(\"Unknown direct JIT continuation\");`,`const next = resumed(F, resume);`,`if (typeof next !== \"number\") return next;`,`if (ISOLATED.has(next)) return \"invalidated\";`,`pc = next;`,`} else {`,`if (F.stopAfterInstruction) return \"invalidated\";`,`pc = S[${this.binding.pc.index}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc);`,`}`,`while (true) {`,`const route = ROUTES.get(pc);`,`if (route === undefined) return REJECTED.has(pc) ? \"fallback\" : \"untranslated\";`,`const next = typeof route === \"function\" ? route(F, deadline, pc) : route.step(F, deadline, route.nextPc);`,`if (typeof next !== \"number\") return next;`,`pc = next;`,`}`,`}`,`return run;`].join(`\n`);return this.counters.dispatcherBytes=e.length,Function(`ROUTES`,`RESUME`,`REJECTED`,`ISOLATED`,`H`,e)(this.routes,this.resumes,this.rejected,this.isolated,jn)}reconcileDelays(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.state.entries){let i=qn(e?.get(n));if(Jn(r.delay,i))continue;let a=this.compileRecord({pc:n,nextPc:r.nextPc,body:r.body},i,{share:r.share,invalid:r.shareInvalid});t.set(n,{pc:n,remove:!1,record:a,changed:!0,metadataOnly:!1})}return t}compileRecord(e,t,n){let r=this.compileInstruction(e),i;return r?.duration!==void 0&&(i=this.state.nextResume++),r!==void 0&&(r.resumeId=i??0),{body:e.body,nextPc:e.nextPc,delay:t,instruction:r,resumeId:i,share:n.share,shareInvalid:n.invalid}}compileInstruction(e){let t=e=>`C[${this.state.constants.push(e)-1}]`,n=(e,t)=>{let n=`${e}\\0${t}`,r=this.state.resistorSlots.get(n);return r===void 0&&(r=this.state.resistorSlots.size,this.state.resistorSlots.set(n,r)),r},r=e=>this.resolveFunction(e,n);try{return new Gr(this.compileBinding,t,n,r).compile(e)}catch(e){if(e!==q)throw e;return}}resolveFunction(e,t){let n=this.state.functions.get(e);if(n===null)throw q;if(n!==void 0)return n;this.state.functions.set(e,null);let r=this.binding.functions?.get(e);if(r===void 0)throw q;let i=[],a=e=>`C[${i.push(e)-1}]`,o=new Gr(this.compileBinding,a,t,e=>{let n=this.resolveFunction(e,t);return{...n,target:a(n.run)}},r),s=o.compileFunction(i);this.state.helperBytes+=o.functionSourceSize;let c={target:(e=>`C[${this.state.constants.push(e)-1}]`)(s),run:s,body:o};return this.state.functions.set(e,c),c}applyEntryChanges(e){for(let t of e.values()){if(t.remove){this.state.entries.delete(t.pc)&&(this.state.stats.invalidatedBlocks++,this.counters.invalidatedBlocks++),this.indexShareCandidate(t.pc);continue}let e=t.record;t.changed?(this.state.entries.has(t.pc)&&(this.state.stats.invalidatedBlocks++,this.counters.invalidatedBlocks++),this.state.entries.set(t.pc,e),this.state.stats.compiledBlocks++,this.counters.compiledBlocks++,e.instruction!==void 0&&(this.counters.bodyBytes+=e.instruction.size),this.indexShareCandidate(t.pc)):(this.state.stats.reusedBlocks++,this.counters.reusedBlocks++,t.metadataOnly&&(this.state.entries.set(t.pc,e),this.indexShareCandidate(t.pc)))}}indexShareCandidate(e){let t=this.state.entries.get(e),n=t?.share===void 0?void 0:Zn(t.share),r=this.candidateKeys.get(e);if(r!==n){if(r!==void 0){let t=this.candidatesByKey.get(r);t!==void 0&&(t.delete(e),t.size||this.candidatesByKey.delete(r)),this.candidateKeys.delete(e)}if(n!==void 0){let t=this.candidatesByKey.get(n);t===void 0&&(t=/* @__PURE__ */ new Set,this.candidatesByKey.set(n,t)),t.add(e),this.candidateKeys.set(e,n)}}}rebuildCandidateIndex(){this.candidateKeys.clear(),this.candidatesByKey.clear();for(let e of this.state.entries.keys())this.indexShareCandidate(e)}commitChanges(e,t){let n=/* @__PURE__ */ new Set;for(let t of e.keys()){let e=this.candidateKeys.get(t);e!==void 0&&n.add(e)}this.applyEntryChanges(e);for(let t of e.keys()){let e=this.candidateKeys.get(t);e!==void 0&&n.add(e)}if(!(t||n.size>0||this.shareStates.size>0||this.sharedRoutes.size>0)){this.applyShardChanges(e),this.refreshEmitStats();return}let r=new Set(e.keys());for(let e of n){let t=this.candidatesByKey.get(e);if(t!==void 0)for(let e of t)r.add(e)}let i=/* @__PURE__ */ new Map;for(let e of r)i.set(e,this.routes.get(e));this.reconcileSharedLayout(n,new Set(e.keys())),this.applyIncrementalSharedLayout(e,r,i),this.refreshEmitStats()}reconcileSharedLayout(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set;for(let t of e){let e=this.candidatesByKey.get(t),o=[];if(e!==void 0)for(let i of e){let e=this.state.entries.get(i);if(e===void 0||e.share===void 0||Zn(e.share)!==t)continue;r.add(i);let a=e.instruction;a===void 0?n.set(i,{variant:void 0,shared:!1,category:`context`}):a.isolated?n.set(i,{variant:void 0,shared:!1,category:`isolated`}):o.push({pc:i,nextPc:e.nextPc,record:e,instruction:a,share:e.share})}let s=this.variantsByKey.get(t);if(s!==void 0)for(let e of s){if(e.functions!==void 0)for(let t of e.entries.keys())a.add(t);e.entries=/* @__PURE__ */ new Map}o.sort((e,t)=>e.pc-t.pc);let c=[];for(let e of o){let t;for(let n of c){let r=n[0];if(Jn(r.record.delay,e.record.delay)&&Yn(r.record.body,e.record.body)){t=n;break}}t===void 0?c.push([e]):t.push(e)}for(let e of c){let r=e[0],a=s?.find(e=>Jn(e.delay,r.record.delay)&&Yn(e.body,r.record.body))??void 0;a===void 0&&(s===void 0&&(s=[],this.variantsByKey.set(t,s)),a={id:this.nextSharedVariant++,key:t,share:r.share,delay:r.record.delay,body:r.record.body,instruction:r.instruction,functions:void 0,resumeId:0,sourceSize:0,entries:/* @__PURE__ */ new Map,attributed:/* @__PURE__ */ new Set},this.sharedVariants.push(a),s.push(a));for(let t of e)a.entries.set(t.pc,t.nextPc);a.functions===void 0&&a.entries.size>=2&&(this.compileSharedVariant(a),i.add(a));for(let t of e){if(a.functions!==void 0){n.set(t.pc,{variant:a,shared:!0,category:`shared`});continue}if(o.length===1){n.set(t.pc,{variant:a,shared:!1,category:`single`});continue}let i=c.some(t=>t!==e&&Jn(t[0].record.delay,r.record.delay));n.set(t.pc,{variant:a,shared:!1,category:i?`ir`:`delay`})}}}for(let e of a)this.sharedRoutes.delete(e);for(let t of e){let e=this.variantsByKey.get(t);if(e!==void 0)for(let t of e){let e=t.functions;if(e!==void 0&&t.entries.size){t.resumeId!==0&&e.resume!==void 0&&this.resumes.set(t.resumeId,e.resume);for(let[n,r]of t.entries)this.sharedRoutes.set(n,{step:e.step,nextPc:r,variant:t})}}}for(let t of e){let e=this.variantsByKey.get(t);if(e!==void 0)for(let t of e){if(t.functions===void 0){t.attributed.clear();continue}let e=0;for(let n of t.entries.keys())t.attributed.has(n)||e++;i.has(t)&&(e=Math.max(0,e-1)),this.counters.shareReusedBodies+=e;for(let e of[...t.attributed])t.entries.has(e)||t.attributed.delete(e);for(let e of t.entries.keys())t.attributed.add(e)}}let o=new Set(t);for(let e of r)o.add(e);for(let e of o){let t=this.state.entries.get(e),r;if(t!==void 0){if(t.share!==void 0){if(t.instruction===void 0)r=`context`;else if(t.instruction.isolated)r=`isolated`;else{let t=n.get(e);r=t===void 0?this.sharedRoutes.has(e)?`shared`:`single`:t.shared?`shared`:t.category}}else t.shareInvalid?r=`invalid`:this.shareStates.has(e)&&(r=`missing`)}let i=this.shareStates.get(e);r===void 0?this.shareStates.delete(e):(r!==`shared`&&i!==r&&this.shareRejected[r]++,this.shareStates.set(e,r))}}applyIncrementalSharedLayout(e,t,n){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=e=>{let t=this.state.entries.get(e);t===void 0?r.set(e,{pc:e,remove:!0,record:void 0,changed:!0,metadataOnly:!1}):r.set(e,{pc:e,remove:!1,record:t,changed:!0,metadataOnly:!1})};for(let t of e.keys()){let e=this.sharedRoutes.get(t),r=n.get(t);e===void 0?a(t):In(r)||i.add(t)}for(let r of t){if(e.has(r))continue;let t=this.sharedRoutes.get(r),o=n.get(r);t===void 0?In(o)&&a(r):In(o)||i.add(r)}i.size&&this.detachFromShards(i),(r.size||i.size)&&this.applyShardChanges(r);for(let e of t){let t=this.sharedRoutes.get(e),n=this.routes.get(e);if(t!==void 0){if(Ln(n,t))continue;this.routes.set(e,t),this.counters.routeInstalls++,this.counters.shareReusedRoutes++}else In(n)&&(this.routes.delete(e),this.counters.routeRemovals++)}for(let e of t){let t=this.state.entries.get(e)?.instruction;t!==void 0&&t.slots.length>this.localSlots&&(this.localSlots=t.slots.length)}this.refreshPcs()}detachFromShards(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.owners.get(n);if(this.owners.delete(n),e===void 0)continue;let r=e.entries.findIndex(e=>e.pcValue===n);r<0||(e.entries.splice(r,1),e.dirty=!0,t.add(e))}for(let e of t)yr(e);for(let e=this.state.shards.length-1;e>=0;e--)this.state.shards[e].entries.length||this.state.shards.splice(e,1)}compileSharedVariant(e){let t=e.instruction;t.duration!==void 0&&(e.resumeId=this.state.nextResume++);let n=kr(e,this.compileBinding,this.binding.pc.index),r=t.duration===void 0?`undefined`:`resumeShared${e.id}`,i=`\"use strict\";\\n${n.join(`\n`)}\\nreturn [stepShared${e.id}, ${r}];`,[a,o]=Mr(i)(Object.freeze([...this.state.constants]),jn);e.functions={step:a,resume:o},e.sourceSize=i.length,this.counters.sharedBodies++,this.counters.sharedBytes+=i.length}reconcileResidentLayout(){let e=[];for(let[t,n]of this.state.entries){let r=n.instruction;r!==void 0&&!this.sharedRoutes.has(t)&&e.push(r)}Cr(this.state,e,this.shardSize,this.binding.pc.index);try{this.compileShards()}catch(e){for(let e of this.state.shards)e.dirty=!0;throw e}let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;this.owners.clear();for(let e of this.state.shards){let r=e.functions;if(r!==void 0)for(let i of e.entries)this.owners.set(i.pcValue,e),t.set(i.pcValue,r.step),i.isolated&&n.add(i.pcValue),i.resumeId!==0&&r.resume!==void 0&&this.resumes.set(i.resumeId,r.resume)}for(let[e,n]of this.sharedRoutes){t.set(e,n);let r=n.variant.functions;n.variant.resumeId!==0&&r.resume!==void 0&&this.resumes.set(n.variant.resumeId,r.resume)}for(let[e,t]of this.state.entries)t.instruction===void 0&&r.add(e);for(let e of[...this.routes.keys()])t.has(e)||(this.routes.delete(e),this.counters.routeRemovals++);for(let[e,n]of t)Ln(this.routes.get(e),n)||(this.routes.set(e,n),this.counters.routeInstalls++,In(n)&&this.counters.shareReusedRoutes++);this.isolated.clear();for(let e of n)this.isolated.add(e);this.rejected.clear();for(let e of r)this.rejected.add(e);for(let e of this.state.entries.values()){let t=e.instruction;t!==void 0&&t.slots.length>this.localSlots&&(this.localSlots=t.slots.length)}this.refreshPcs()}applyShardChanges(e){let t=[],n=/* @__PURE__ */ new Set;for(let r of e.values()){let e=r.remove?void 0:r.record.instruction,i=this.owners.get(r.pc);if(i!==void 0){let t=i.entries.findIndex(e=>e.pcValue===r.pc);if(t>=0){e===void 0?(i.entries.splice(t,1),i.dirty=!0,n.add(i)):i.entries[t]!==e&&(i.entries[t]=e,i.dirty=!0,n.add(i));continue}this.owners.delete(r.pc)}e!==void 0&&t.push(e)}for(let e of n)yr(e);for(let e=this.state.shards.length-1;e>=0;e--)this.state.shards[e].entries.length||this.state.shards.splice(e,1);this.appendPending(t);let r;try{r=this.compileShards()}catch(e){for(let e of this.state.shards)e.dirty=!0;throw e}for(let e of r)this.installShard(e);for(let t of e.values()){let e=t.remove?void 0:t.record.instruction;e===void 0?(this.removeRoute(t.pc),t.remove?this.rejected.delete(t.pc):this.rejected.add(t.pc),this.owners.delete(t.pc)):(this.rejected.delete(t.pc),e.slots.length>this.localSlots&&(this.localSlots=e.slots.length))}this.refreshPcs()}appendPending(e){if(!e.length)return;e.sort((e,t)=>e.pcValue-t.pcValue);let t=xr(e,this.binding.pc.index);for(let e of t){let t=e.reduce((e,t)=>e+t.size,0),n=this.state.shards[this.state.shards.length-1];n!==void 0&&n.entries.length>0&&e.length<=this.shardSize&&t<=tr&&n.sourceSize+t>tr&&this.newShard();for(let t of e){let e=this.state.shards[this.state.shards.length-1];(e===void 0||!br(e,t,this.shardSize))&&(e=this.newShard()),e.entries.push(t),e.dirty=!0,yr(e),this.owners.set(t.pcValue,e)}}}newShard(){let e={id:this.state.nextShard++,entries:[],sourceSize:0,maxSlots:0,resumable:!1,functions:void 0,signature:void 0,dirty:!0};return this.state.shards.push(e),e}compileShards(){let e=/* @__PURE__ */ new Set;for(let t of this.state.shards)t.functions!==void 0&&!t.dirty&&vr(t.signature??[],t.entries)?(this.state.stats.reusedShards++,this.counters.reusedShards++):(this.counters.shardBytes+=Nr(this.state,t,this.compileBinding),this.counters.compiledShards++,e.add(t));return e}installShard(e){let t=e.functions;if(t!==void 0)for(let n of e.entries)this.owners.set(n.pcValue,e),this.routes.get(n.pcValue)!==t.step&&(this.routes.set(n.pcValue,t.step),this.counters.routeInstalls++),n.resumeId!==0&&t.resume!==void 0&&this.resumes.set(n.resumeId,t.resume),n.isolated?this.isolated.add(n.pcValue):this.isolated.delete(n.pcValue),this.rejected.delete(n.pcValue)}removeRoute(e){this.routes.delete(e)&&this.counters.routeRemovals++,this.isolated.delete(e)}rebuildAll(){this.rebuildCandidateIndex();let e=this.candidatesByKey.size>0||this.shareStates.size>0||this.sharedRoutes.size>0;for(let t of this.state.entries.values())if(t.shareInvalid){e=!0;break}if(e){this.reconcileSharedLayout(new Set(this.candidatesByKey.keys()),new Set(this.state.entries.keys())),this.reconcileResidentLayout();return}let t=[];for(let e of this.state.entries.values())e.instruction!==void 0&&t.push(e.instruction);Cr(this.state,t,this.shardSize,this.binding.pc.index),this.compileShards(),this.routes.clear(),this.resumes.clear(),this.rejected.clear(),this.isolated.clear(),this.owners.clear();for(let e of this.state.shards)this.installShard(e);for(let[e,t]of this.state.entries)t.instruction===void 0&&this.rejected.add(e);this.localSlots=0;for(let e of this.state.entries.values())e.instruction!==void 0&&e.instruction.slots.length>this.localSlots&&(this.localSlots=e.instruction.slots.length);this.refreshPcs()}refreshPcs(){this.sessionPcs=void 0}refreshEmitStats(){let e=[];for(let t of this.state.entries.values())t.instruction!==void 0&&e.push(t.instruction);this.emitStatsValue=ar(e)}get shardSize(){return qr(this.binding)}};function Yr(e,t){if(!J(e.pc.index)||e.states.get(e.pc.name)!==e.pc.index)throw TypeError(`Invalid direct JIT binding`);let n=t??Bn(),r=Vn(n),i=Hn(e),a=zn.get(n);if(a!==void 0){if(!a.isDisposed&&Kn(a.sessionFingerprint,i))return a;a.dispose()}r.binding!==void 0&&!Kn(r.binding,i)&&(r.stats.invalidatedBlocks+=r.entries.size,r.entries.clear(),r.constants.length=0,r.resistorSlots.clear(),r.functions.clear(),r.shards.length=0,r.nextResume=1,r.nextShard=1),r.binding=i;let o=new Jr(n,r,e,i);return zn.set(n,o),o}let Xr=Object.freeze([]),Zr=/* @__PURE__ */ new Set([`wait`,`elapse`,`receive`,`waitUntil`,`redirect`,`stop`]);var Qr=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())}},$r=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}]`}},ei=class extends dn{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 ti;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 ${K(e.result)} = ${r};`):this.line(`${r};`)}else super.emitOperation(e,t,n,r)}},ti=class extends Error{};function ni(e,t){try{return Zt(e,t,!1)}catch{return}}function ri(e,t,n){let r=ni(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(Zr.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=ni(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 ii(e,t={}){try{let n=ri(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 Qr,a=new $r(n.length),o=t.bindResources!==!1,s=i.capture(Xr),c=[];for(let e=0;e<n.length;e++){let l=n[e],u=new ei(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(),Vt),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=>oi(e,t))};return(n,r)=>u(e,n??Xr,r,t)}})}catch{return}}let ai=Object.freeze([]);function oi(e,t){return t.length?typeof e.bind==`function`?e.bind(t):Object.freeze(t.map(([t,n])=>si(e,t,n))):ai}function si(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 ci=Symbol(`unsupported resumable body`),li=/^(\\s*)(?:const|let) (v\\d+|l\\d+)( = |;)/;function ui(e,t={}){if(yi(e))try{return new di(Zt(e,t,!1),t,!1).compileMachine(e)}catch{return}}var di=class extends dn{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()))});`]:[],`let pc = F.pc;`,`for (;;) {`,`switch (pc) {`];for(let e of this.blocks){a.push(`case ${e.id}: {`);for(let t of e.code)a.push(t);a.push(...pi(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,Vt),slotCount:this.slots.size,blocks:this.blocks.length,start:0})}locals(){let e=/* @__PURE__ */ new Set;for(let t of this.analysis.nodes){let n=t.operation;`result`in n&&e.add(K(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];gi(i,this.analysis)?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 fi(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(${K(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`?Tt(c.name,c.member):c.value,u=this.open();u.term={kind:`branch`,test:`H.equalValues(${K(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 ci;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(${K(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 ci}}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?K(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){this.blocks[e].term={kind:`jump`,to:t}}save(e){let t=this.analysis.byOperation.get(e),n=`result`in e?K(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 ci;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 ci;return e.startsWith(`value:`)?K(n):cn(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 fi(e){let t=[];for(let n of e){let e=li.exec(n);e?e[3]!==`;`&&t.push(`${e[1]}${e[2]}${e[3]}${n.slice(e[0].length)}`):t.push(n)}return t}function pi(e){let t=e.term;if(!t)throw ci;switch(t.kind){case`jump`:return[`pc = ${t.to};`,`break;`];case`branch`:return[`if (${t.test}) pc = ${t.yes};`,`else pc = ${t.no};`,`break;`];case`suspend`:return[`return true;`];case`done`:return[`F.pc = 0;`,`return false;`];default:throw ci}}let mi=/* @__PURE__ */ new Set([`if`,`match`,`while`,`loop`,`break`,`continue`,`return`,`returnValue`,`wait`,`receive`]),hi=/* @__PURE__ */ new Set([`elapse`,`call`,`callValue`,`waitUntil`,`redirect`,`stop`,`yield`]);function gi(e,t){switch(e.kind){case`if`:case`match`:case`while`:case`loop`:return _i(e,t,!1);default:return!mi.has(e.kind)&&!hi.has(e.kind)}}function _i(e,t,n){if(!mi.has(e.kind))return!hi.has(e.kind);switch(e.kind){case`if`:case`match`:case`while`:case`loop`:if(t.byOperation.get(e).suspends)return!1;switch(e.kind){case`if`:return vi(e.yes,t,!0)&&(e.no===void 0||vi(e.no,t,!0));case`match`:return e.arms.every(e=>vi(e.body,t,!0))&&(e.otherwise===void 0||vi(e.otherwise,t,!0));case`while`:return vi(e.test.body,t,!0)&&vi(e.body,t,n);default:return vi(e.body,t,n)}case`break`:case`continue`:return!n;default:return!1}}function vi(e,t,n){return e.operations.every(e=>_i(e,t,n))}function yi(e){for(let t of e.operations)switch(t.kind){case`if`:if(!yi(t.yes)||t.no&&!yi(t.no))return!1;break;case`match`:for(let e of t.arms)if(!yi(e.body))return!1;if(t.otherwise&&!yi(t.otherwise))return!1;break;case`while`:if(!bi(t.test.body)||!yi(t.body))return!1;break;case`loop`:if(!yi(t.body))return!1;break;case`and`:case`or`:if(!bi(t.right.body))return!1;break;case`select`:if(!bi(t.yes.body)||!bi(t.no.body))return!1;break;case`assert`:if(t.message&&!bi(t.message.body))return!1}return!0}function bi(e){for(let t of e.operations)if(t.kind!==`yield`&&(mi.has(t.kind)||hi.has(t.kind)||!yi({operations:[t]})))return!1;return!0}var xi=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 Si(e,t={}){if(!Number.isFinite(e)||e<.001||e>1e9)throw new xi(`INVALID_ELECTRICAL_PARAMETER`,`Resistance must be finite and in [0.001, 1000000000] ohms.`,t)}let Ci=65536;function wi(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 Ti(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>Ci)break}return t}function Ei(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 Di(e,t,n){let r;for(let i=0;i<e.blocks.length;i++){let a=e.blocks[i],o=Ei(a,t,n);o!==a&&(r??=e.blocks.slice(),r[i]=o)}return r===void 0?e:{...e,blocks:r}}function Oi(e){return{component:e,key:e.nodes.join(`,`)}}function ki(e,t){let n=new Mi(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=[];for(let t of r.values()){let n=!0;for(let r of t.nodes)if(e[r].reference!==void 0){n=!1;break}n&&i++;for(let n of Ni(t,e)){let e=a.length;a.push(Oi(n));for(let t of n.edges)(o[t.pin]??=[])[t.index]=e}}return{blocks:a,edgeBlocks:o,components:r.size,floatingComponents:i}}let Ai=e=>e===0?0:e;function ji(e){return{instanceId:e.instance,resource:e.name}}var Mi=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 Ni(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 Mi(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 Pi(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 Fi(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 Ii(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 Li(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=Pi(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 Ri(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]=Pi(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]=Pi(s),Number.isFinite(o[t])||n(`Non-finite backward substitution.`)}}return o}function zi(e,t){e=0+e;let n=e+t;return n+(Math.abs(e)>=Math.abs(t)?e-n+t:t-n+e)}function Bi(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 };`)(zi,r)}function Vi(e,t){let n=[...e],r=new Map(n.map((e,t)=>[e,t])),i=new Mi(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 xi(`INVALID_ELECTRICAL_PARAMETER`,`Pin thresholds must both be omitted or finite with low < high.`,ji(e));let o=(e,t)=>{let n=r.get(e);if(n===void 0)throw new xi(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,t===void 0?ji(e):{network:t});return n},s=(e,t)=>{let n=r.get(e);if(n===void 0)throw new xi(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,ji(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 xi(`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=Ai(e.voltage);if(t.reference!==void 0&&t.reference!==n)throw new xi(`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=wi(e,[]);v[e]=t,y+=t,b^=t}let x=(e,t)=>{let n=wi(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]:wi(e,n);if(r[e]!==i)return}return n}},te=(e,t)=>{if(!(t.cost>Ci))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},()=>[]),ne=Object.freeze([]),T=new Int32Array(l.length),E=[],re=[],D=[],ie=Array(n.length),ae=[],oe=[],se=new Int32Array(n.length),O=0,ce=!1,le=(e,t)=>{for(let n of e)t.indexOf(n)===-1&&(T[n.from]=T[n.from]-1,T[n.to]=T[n.to]-1);for(let n of t)e.indexOf(n)===-1&&(T[n.from]=T[n.from]+1,T[n.to]=T[n.to]+1)},k={solves:0,components:0,floatingComponents:0,factorizations:0,factorizationReuses:0,cacheHits:0,leafPlans:0,leafPropagations:0,topologyPrepares:0},ue=Object.freeze([]),A=[],j=[],M=0,de=Array(n.length),fe=new Int32Array(n.length),pe=1,me=[],he=[],ge=[],N=[],P=[],F=[],_e=/* @__PURE__ */ new Map,ve=()=>(++O===2147483647&&(se.fill(0),O=1),O),I=(e,t)=>{let n=_e.get(e);n===void 0&&(_e.size>=256&&_e.clear(),n={},_e.set(e,n));let r=n[t];return r===void 0&&(r=Object.freeze({voltage:Ai(e),level:t,status:`valid`}),n[t]=r),r},L=(e,t)=>e.low===void 0?`unknown`:t<=e.low?`low`:t>=e.high?`high`:`unknown`,R=(e,t,r,i,a)=>{let o=f[e],s=u[o],c=l[i].reference,d=[],p=[],m=[];for(let e=0;e<s.length;e++){let t=s[e],r=n[t];d.push(t),p.push(r),m.push(I(c,L(r,c)))}return{intent:t,targetPin:r.to,resistance:r.resistance,target:i,edges:a,edgeHash:wi(e,a),node:o,voltage:c,slots:Object.freeze(d),pins:Object.freeze(p),samples:Object.freeze(m)}},ye=(e,t,n,r,i)=>{let a=R(e,t,n,r,i),o=de[e];if(o===void 0)de[e]=[a],k.leafPlans++;else{for(let e of o)if(e.targetPin===n.to&&e.resistance===n.resistance){e.intent=t;return}o.length<2?o.push(a):o[o.length-1]=a,k.leafPlans++}},be=()=>{for(let e=0;e<F.length;e++){let t=F[e];ye(t.slot,t.intent,t.branch,t.target,t.edges)}F.length=0},xe=(e,t)=>{if(h===void 0)return;let n=de[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(T[i]!==1||l[i].reference!==void 0)return;let a=n[0];if(a.intent===t)return l[a.target].reference===void 0?void 0:a;if(n.length>1){let e=n[1];if(e.intent===t)return l[e.target].reference===void 0?void 0:e}if(t.length!==1)return;let o=t[0];for(let e=0;e<n.length;e++){let r=n[e];if(r.targetPin===o.to&&r.resistance===o.resistance)return l[r.target].reference===void 0?void 0:(r.intent=t,r)}},Se=e=>{j[M++]=e},z=()=>{for(let e=1;e<M;e++){let t=j[e],n=e;for(;n>0&&j[n-1]>t;)j[n]=j[n-1],n--;j[n]=t}},B=e=>{for(let t=0;t<M;t++)e(j[t])},Ce=()=>{if(M===0)return ue;z();let e=Array(M);for(let t=0;t<M;t++)e[t]=j[t];return e},we=(e,t,n,r,i,a)=>{let o=w[e][0].to;if(o!==t&&(T[o]=T[o]-1,T[t]=T[t]+1),S[f[e]]=n,C[e]=r,w[e]=i,a!==void 0){let t=v[e];a!==t&&(v[e]=a,y+=a-t,b^=t^a)}else x(e,i)},Te=()=>{ce=!0,k.solves++,k.leafPropagations++},V=(e,t,n)=>{let{node:r,target:i,voltage:a}=n;if(M=0,S[r]!==a){let e=n.pins,t=n.samples,r=n.slots;for(let n=0;n<e.length;n++){let i=e[n],a=t[n];i.sample!==a&&(i.sample=a,j[M++]=r[n])}}we(e,i,a,t,n.edges,n.edgeHash),Te()},H=e=>{M=0;for(let t=0;t<e;t++){let e=f[me[t]],r=P[t];if(r!==void 0){if(S[e]===r.voltage)continue;let t=r.slots,n=r.pins,i=r.samples;for(let e=0;e<t.length;e++){let r=n[e],a=i[e];r.sample!==a&&(r.sample=a,Se(t[e]))}continue}let i=l[N[t]].reference;if(S[e]===i)continue;let a=u[e];for(let e=0;e<a.length;e++){let t=a[e],r=n[t],o=r.low===void 0?`unknown`:i<=r.low?`low`:i>=r.high?`high`:`unknown`,s=r.sample;(s.voltage!==i||s.level!==o||s.status!==`valid`)&&(r.sample=I(i,o),Se(t))}}for(let t=0;t<e;t++){let e=me[t],n=N[t];we(e,n,l[n].reference,he[t],ge[t],P[t]?.edgeHash)}Te()};function Ee(e){let t=de[e];if(t!==void 0){let r=n[e].intent;if(r!==C[e]){if(fe[e]===pe){let n=t[0],i=n.intent===r?n:t[1];if(i?.intent===r){V(e,r,i);return}}let n=xe(e,r);if(n!==void 0){fe[e]=pe,V(e,r,n);return}}}A[0]=e,A.length=1,Me(A)}function De(e,t){if(h!==void 0){let r=ve(),i=0,a=!0;for(let o=0;o<t;o++){let t=e[o];if(se[t]===r)continue;se[t]=r;let s=n[t].intent;if(s===C[t])continue;let c;if(fe[t]===pe){let e=de[t],n=e[0],r=n.intent===s?n:e[1];r?.intent===s&&(c=r)}if(c===void 0){if(c=xe(t,s),c===void 0){a=!1;break}fe[t]=pe}me[i]=t,he[i]=s,ge[i]=c.edges,N[i]=c.target,P[i]=c,i++}if(a){if(i===0){je(e,t),Me(A);return}H(i);return}}je(e,t),Me(A)}function Oe(e,t){Ee(e),t!==void 0&&M!==0&&B(t)}function ke(e,t,n){De(e,t),n!==void 0&&M!==0&&B(n)}return{get stats(){return Object.freeze({...k})},solve(e){if(Me(Ae(e)),M===0)return ne;z();let t=[];for(let e=0;e<M;e++)t.push(n[j[e]]);return Object.freeze(t)},solveSlot(e){return Ee(e),Ce()},solveSlotInto:Oe,solveSlotBatchInto:ke,solveSlots(e){if(typeof e==`number`)return Ee(e),Ce();if(e===void 0)return Me(void 0),Ce();if(A.length=0,Array.isArray(e)||ArrayBuffer.isView(e)&&Symbol.iterator in e){let t=e;for(let e=0;e<t.length;e++)A.push(t[e])}else for(let t of e)A.push(t);return De(A,A.length),Ce()}};function Ae(e){if(e!==void 0){A.length=0;for(let t of e)A.push(o(t));return A}}function je(e,t){A.length=t;for(let n=0;n<t;n++)A[n]=e[n]}function Me(e){++pe===2147483647&&(fe.fill(0),pe=1);let t=h===void 0;if(F.length=0,M=0,h!==void 0&&!ce&&e!==void 0&&e.length===0){k.solves++,k.cacheHits+=h.blocks.length;return}E.length=0,re.length=0,D.length=0,oe.length=0;let r=ve(),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(se[a]===r)continue;se[a]=r;let o=n[a].intent;if(o===C[a])continue;let s=xe(a,o);if(s===void 0){t=-1;break}me[t]=a,he[t]=o,ge[t]=s.edges,N[t]=s.target,P[t]=s,t++}if(t>0){H(t);return}r=ve()}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(se[u]===r)continue;se[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)||Si(e.resistance,ji(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&&T[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]&&F.push({slot:u,intent:p,branch:p[0],target:g[0].to,edges:g}),E.push(u),re.push(p),D.push(g)}if(a&&i){for(let e=0;e<E.length;e++)me[e]=E[e],he[e]=re[e],ge[e]=D[e],N[e]=D[e][0].to,P[e]=void 0;be(),H(E.length);return}ce&&(i=!0);let d=E.length;if(h!==void 0&&!i&&oe.length===0){for(let e=0;e<d;e++){let t=E[e];C[t]=re[e],w[t]=D[e]}k.solves++,k.cacheHits+=h.blocks.length,be();return}let _=h,ne,O,ue=0,A=/* @__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=E[e];ie[t]=D[e],ae.push(t)}if(i){let e=y,t=b;for(let n=0;n<d;n++){let r=E[n],i=wi(r,D[n]),a=v[r];i!==a&&(e+=i-a,t^=a^i)}if(ne=`${e}:${t}`,O=ee(ne,ie),O!==void 0)_=Di(O.topology,w,ie);else{let e=w.slice();for(let t=0;t<d;t++)e[E[t]]=D[t];_=ki(l,e),ue++}}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)A.set(t,Ei(_.blocks[t],w,ie))}let de,_e=/* @__PURE__ */ new Map,I=0,L=0,R=i?0:_.blocks.length-A.size;for(let e of i?_.blocks:A.values()){let{component:t,key:n}=e,r=p.get(n);if(r!==void 0&&Ii(r,t,l)){R++,(de??=/* @__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 xi(`ELECTRICAL_SOLVE_FAILED`,e,{...ji(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=Bi(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=>Pi(e)),_=Float64Array.from(r,e=>Pi(e))}r?.factorization!==void 0&&Fi(r.factorization.matrix,h)&&Fi(r.factorization.anchors,g)?(c=r.factorization,L++):(c=Li(h,g,s),I++);let v=Ri(c,_,s);e.forEach((e,t)=>{let n=Ai(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};(de??=/* @__PURE__ */ new Map).set(n,d);for(let[e,t]of i)S[e]!==t&&_e.set(e,t)}let ye=/* @__PURE__ */ new Map;M=0;for(let[e,t]of _e){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[M++]=i),(l||k.solves===0)&&ye.set(a,Object.freeze({voltage:t===null?null:Ai(t),level:o,status:s}))}}for(let e=1;e<M;e++){let t=j[e],n=e;for(;n>0&&j[n-1]>t;)j[n]=j[n-1],n--;j[n]=t}for(let[e,t]of ye)e.sample=t;for(let[e,t]of _e)S[e]=t;for(let e=0;e<d;e++){let t=E[e],n=D[e];le(w[t],n),C[t]=re[e],w[t]=n,x(t,n)}if(i)p=de??/* @__PURE__ */ new Map;else{if(de!==void 0)for(let[e,t]of de)p.set(e,t);for(let[e,t]of A)_.blocks[e]=t}if(h=_,ce=!1,i){let e=O!==void 0&&_===O.topology?O:{id:O?.id??g++,cost:O?.cost??Ti(_),topology:_,hashes:O?.hashes??v.slice()};te(ne,e)}k.solves++,k.components=_.components,k.floatingComponents=_.floatingComponents,k.factorizations+=I,k.factorizationReuses+=L,k.cacheHits+=R,k.topologyPrepares+=ue,be()}}var Hi=class{times=[];orders=[];values=[];size=0;sequence=0;get time(){return this.size===0?1/0:this.times[0]}push(e,t){let n=this.size++;this.times[n]=e,this.orders[n]=this.sequence++,this.values[n]=t,this.siftUp(n)}pop(){let e=this.values[0],t=--this.size;return t>=0&&(this.times[0]=this.times[t],this.orders[0]=this.orders[t],this.values[0]=this.values[t],this.times[t]=0,this.orders[t]=0,this.values[t]=void 0,this.siftDown()),e}clear(){this.size=0}before(e,t){let n=this.times,r=n[e],i=n[t];return r<i||r===i&&this.orders[e]<this.orders[t]}swap(e,t){let n=this.times,r=this.orders,i=this.values,a=n[e],o=r[e],s=i[e];n[e]=n[t],r[e]=r[t],i[e]=i[t],n[t]=a,r[t]=o,i[t]=s}siftUp(e){for(;e>0;){let t=e-1>>>1;if(!this.before(e,t))break;this.swap(e,t),e=t}}siftDown(){let e=this.size,t=0;for(;;){let n=t*2+1;if(n>=e)break;let r=n+1,i=r<e&&this.before(r,n)?r:n;if(!this.before(i,t))break;this.swap(t,i),t=i}}},Ui=class{entries=[];words=[];activeWords=[];activeCount=0;get size(){return this.activeCount}register(e){return this.entries.push(e)-1}add(e){let t=e>>>5,n=this.words[t]??0;n===0&&(this.activeWords[this.activeCount++]=t),this.words[t]=n|1<<(e&31)}drain(e){let t=this.activeWords,n=this.activeCount;if(n!==0){if(n>1)for(let e=1;e<n;e++){let n=t[e],r=e;for(;r>0&&t[r-1]>n;)t[r]=t[r-1],r--;t[r]=n}for(let r=0;r<n;r++){let n=t[r],i=this.words[n];this.words[n]=0;let a=n*32;for(;i!==0;)e(this.entries[a+31-Math.clz32(i&-i)]),i&=i-1}if(this.activeCount===n)this.activeCount=0;else{for(let e=n;e<this.activeCount;e++)t[e-n]=t[e];this.activeCount-=n}}}clear(){this.entries.length=0,this.words.length=0,this.activeWords.length=0,this.activeCount=0}},Wi=class{values=[];head=0;tail=0;get length(){return this.tail-this.head}push(e){this.values[this.tail++]=e}shift(){let e=this.values[this.head];return this.values[this.head++]=void 0,this.head===this.tail&&(this.head=0,this.tail=0),e}clear(){this.values.length=0,this.head=0,this.tail=0}drain(){let e=this.values.slice(this.head,this.tail);return this.clear(),e}};let Gi={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},Ki={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},qi=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),Ji=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function Yi(e,t,n){let r=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,i=h(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 Xi(e,t,n){let r=h(e.bytes,t,n);return e.bytes.slice(r,r+Number(n))}function Zi(e){throw Error(e===void 0?`Assertion failed`:String(e))}function Qi(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let $i=Object.freeze({checkBoolean:Pt,createBytes:Dt,createEnum:Tt,createRecord:Et,equalValues:At,nonNull:Nt,readIndex:Mt,load:Yi,copyBytes:Xi,assertFalse:Zi,sameBytes:Qi});var ea=class extends Error{};function Y(e){throw new ea(e)}var ta=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)&&Y(`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)&&Y(`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)||Y(`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`&&Y(`resource argument`),this.value(e.value)}memoryRef(e,t){e.kind===`parameter`&&Y(`parameterised memory ${t}`);let n=this.target.memoryPlan(e.name);return this.slot(n.slot),n}pinRef(e,t){e.kind===`parameter`&&Y(`parameterised pin ${t}`);let n=this.target.pins.get(e.name),r=this.target.sampleResources.get(e.name);return(!n||!r)&&Y(`unknown pin ${e.name}`),this.slot(r),n}operation(e,t){let n=t=>{`result`in e||Y(`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(Dt(t.value))))})`):t.kind===`enum`?n(this.ref(Tt(t.name,t.member))):t.kind===`record`?n(this.ref(Et(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))&&Y(`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`&&Y(`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)&&Y(`value parameter outside a call`),n(t[e.index]);break}case`unary`:{let t=Gi[e.operator];t||Y(`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=Ki[e.operator];t||Y(`unsupported binary ${e.operator}`),n(`(${this.value(e.left)} ${t} ${this.value(e.right)})`)}break;case`numeric`:qi.has(e.builtin)||Y(`unsupported builtin ${e.builtin}`),n(`${Ji.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||Y(`impure call`);let t=this.target.declarations.get(e.name);(t?.kind!==`function`||!t.pure)&&Y(`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`?Tt(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||Y(`yield outside a value region`),this.line(`${t.slot} = ${this.value(e.value)};`),this.line(`break ${t.label};`);break;default:{let t=e.kind;Y(`unsupported operation ${String(t)}`)}}}};function na(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 ra(e,t,n){let r=t;for(let t=1;t<n.length;t++)r=na(e,r,n[t]);return{type:r}}function ia(e){return e?e.kind===`optional`?ia(e.inner):[`number`,`bool`,`string`,`enum`].includes(e.kind):!1}function aa(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=>aa(e,na(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=>aa(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=aa(e,t.inner,n,r);return i===void 0?void 0:`(${n} === ${r} || (${n} === null ? ${r} === null : (${r} !== null && ${i})))`}default:return}}function oa(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}=ra(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 ta(e),o=a.build(r,n),s=Function(`B`,`H`,`\"use strict\"; return (${o});`)(a.bindingTable(),$i),c=`function (a, b) { return ${aa(e.declarations,i,`a`,`b`)??`H.same(a, b)`}; }`,l=Function(`H`,`\"use strict\"; return (${c});`)({...$i,same:g});return{ok:!0,plan:{key:t,path:[...n],source:o,comparison:c,slots:a.slotsUsed(),evaluate:s,equals:l,needsSnapshot:!ia(i)}}}catch(e){return{ok:!1,reason:e instanceof ea?e.message:`unexpected code generation failure: ${e instanceof Error?e.message:String(e)}`}}}let sa=/* @__PURE__ */ new WeakMap,ca=/* @__PURE__ */ new WeakMap,la=/* @__PURE__ */ new WeakMap,ua=/* @__PURE__ */ new WeakMap,da=72e14;function fa(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 pa(e){let t=sa.get(e);return t||(t=rn(e),sa.set(e,t)),t}function ma(e,t){let n=e.entry.model,r=ua.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,ua.set(n,r));let i=r.get(t);if(i!==void 0)return i??void 0;let a=ii(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 ha(e){let t=ca.get(e);return t===void 0&&(t=ui(e,{bindResources:!0})??null,ca.set(e,t)),t??void 0}function ga(e){return{pc:e.start,slots:Array(e.slotCount),kind:0,duration:0,channel:``,value:void 0}}function _a(e,t){let n=la.get(e);return n||(n=an(e),la.set(e,n)),n(t)}var va=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 ya(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var ba=class extends TypeError{code=`ASYNC_HOOK_RESULT`;constructor(){super(`Device hooks must return synchronously`)}},xa=class extends RangeError{code=`INVALID_ELECTRICAL_PARAMETER`};function Sa(e){if(typeof e!=`number`||!Number.isFinite(e))throw new xa(`Electrical parameters must be finite numbers`);return e}function Ca(e){if(ya(e))throw Promise.resolve(e).catch(()=>{}),new ba}function wa(e){if(!(e instanceof A))return{};let t=e.diagnostics[0];return t?{...t.path?{path:Object.freeze([...t.path])}:{},...t.source?{source:_(t.source)}:{}}:{}}function Ta(e,t,n){return new va(Object.freeze({code:e,message:t instanceof Error?t.message:String(t),phase:n,time:null,cause:t,...wa(t),related:Object.freeze([])}))}function Ea(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}function Da(e,t){let n=e.host.call(t,[]).next();if(!n.done)throw TypeError(`Unexpected suspension in synchronous function`);return n.value}let Oa=/* @__PURE__ */ new WeakMap;function ka(e){let t=Oa.get(e);return t===void 0&&(t={publications:0,finishes:0,emptySuffixes:0,boundaryCalls:0,continues:0,exits:0},Oa.set(e,t)),t}function Aa(e){return Oa.get(e)}let ja=/* @__PURE__ */ new WeakMap;function Ma(e){let t=ja.get(e);return t===void 0&&(t={stateMask:/* @__PURE__ */ new Int32Array,memoryMask:/* @__PURE__ */ new Int32Array},ja.set(e,t)),t}function Na(e){let t=e;return t.directStats??={directCompiles:0,directShards:0,directCalls:0,directFallbacks:0,directDeadlines:0,directStopped:0,directSessions:0,directShardCompiles:0,directRouteInstalls:0,directRouteRemovals:0,directRoutes:0,directDispatchMisses:0,directGenericInstructions:0,directBodyBytes:0,directShardBytes:0,directDispatcherBytes:0,directHelperBytes:0,directShareCallbacks:0,directShareCandidates:0,directShareGroups:0,directSharedRoutes:0,directSharedBodies:0,directSharedBytes:0,directShareReusedBodies:0,directShareReusedRoutes:0,directShareRejected:{missing:0,invalid:0,single:0,ir:0,delay:0,isolated:0,context:0},directShareMarkRejected:{unknownPc:0,duplicate:0,invalidPc:0,invalidLength:0,outsideRegion:0,crossView:0,service:0,notAdmitted:0}}}function Pa(e){return e.directStats}let Fa=/* @__PURE__ */ new WeakMap;function Ia(e,t){let n=t.stats(),r=Na(e),i=Fa.get(e),a=i?.session===t?i.stats:void 0;r.directShardCompiles+=n.compiledShards-(a?.compiledShards??0),r.directRouteInstalls+=n.routeInstalls-(a?.routeInstalls??0),r.directRouteRemovals+=n.routeRemovals-(a?.routeRemovals??0),r.directBodyBytes+=n.bodyBytes-(a?.bodyBytes??0),r.directShardBytes+=n.shardBytes-(a?.shardBytes??0),r.directDispatcherBytes+=n.dispatcherBytes-(a?.dispatcherBytes??0),r.directHelperBytes+=n.helperBytes-(a?.helperBytes??0),r.directShareGroups=n.shareGroups,r.directSharedRoutes=n.sharedRoutes,r.directSharedBodies+=n.sharedBodies-(a?.sharedBodies??0),r.directSharedBytes+=n.sharedBytes-(a?.sharedBytes??0),r.directShareReusedBodies+=n.shareReusedBodies-(a?.shareReusedBodies??0),r.directShareReusedRoutes+=n.shareReusedRoutes-(a?.shareReusedRoutes??0),r.directShareRejected.missing+=n.shareRejected.missing-(a?.shareRejected.missing??0),r.directShareRejected.invalid+=n.shareRejected.invalid-(a?.shareRejected.invalid??0),r.directShareRejected.single+=n.shareRejected.single-(a?.shareRejected.single??0),r.directShareRejected.ir+=n.shareRejected.ir-(a?.shareRejected.ir??0),r.directShareRejected.delay+=n.shareRejected.delay-(a?.shareRejected.delay??0),r.directShareRejected.isolated+=n.shareRejected.isolated-(a?.shareRejected.isolated??0),r.directShareRejected.context+=n.shareRejected.context-(a?.shareRejected.context??0),r.directShards=n.shards,r.directRoutes=n.routes,Fa.set(e,{session:t,stats:n})}function La(e){let t=e.direct;t!==void 0&&(Ia(e,t.session),e.direct=void 0,t.session.dispose(),Fa.delete(e),e.directMemories.clear());let n=Pa(e);n!==void 0&&(n.directShards=0,n.directRoutes=0,n.directShareGroups=0,n.directSharedRoutes=0)}function Ra(e,t){let n=e.direct;return n===void 0?(e.directStale=!1,!1):(e.directStale=!0,t||n.frame.resume!==0?(n.frame.stopAfterInstruction=!0,!0):(La(e),e.directStale=!1,!0))}function za(e,t=!1){t&&(e.directCacheInvalid=!0),e.directSkip=void 0,Ra(e,!1)}function Ba(e){La(e),e.directStale=!1,e.directSkip=void 0,e.directMemories.clear()}function Va(e,t){for(let n of e.codeRegions)if(t>=n.base&&t<n.base+n.size)return n}function Ha(e,t){let n=t.codeRegion;return n===void 0||n.memory===e.options.code}function Ua(e,t){return!t.polling&&!Ka(e).has(t.pc)&&Ha(e,t)}function Wa(e,t){return{pc:t.pc,nextPc:t.nextPc,body:t.body,...e.options.shareDirectBodies===!0&&t.share!==void 0?{share:t.share}:{}}}function Ga(e,t,n,r,i){if(i.length===0)return;let a=/* @__PURE__ */ new Map;for(let e=0;e<r.length;e++){let t=r[e].pc;a.has(t)||a.set(t,e)}let o=Na(e),s=o.directShareMarkRejected,c=/* @__PURE__ */ new Set;for(let{pc:l,byteLength:u}of i){if(!Number.isSafeInteger(l)||l<0){s.invalidPc++;continue}if(!Number.isSafeInteger(u)||u<=0){s.invalidLength++;continue}if(c.has(l)){s.duplicate++;continue}c.add(l);let i=a.get(l);if(i===void 0){s.unknownPc++;continue}let d=r[i],f=d.codeRegion;if(f===void 0){s.service++;continue}if(t===void 0||f!==t){s.crossView++;continue}let p=l-f.base;p<0||!Number.isSafeInteger(p+u)||p+u>f.size||p+u>n?s.outsideRegion++:Ua(e,d)?(r[i]={...d,share:Object.freeze({storage:f.memory,codeVersion:d.codeVersion,offset:p,byteLength:u})},o.directShareCandidates++):s.notAdmitted++}}function Ka(e){return e.metadata?.polling??e.polling}function qa(e){return e.metadata?.delays??e.delays}function Ja(e){return e.codeRegions.filter(t=>t.memory===e.options.code)}function Ya(e,t,n){let r=t.metadata,i=t.options.codeMetadata;if(r===void 0||i===void 0)return;let a=[],o=/* @__PURE__ */ new Set;for(let e of n){let n=r.regions.get(e);if(n===void 0||o.has(n))continue;o.add(n);let i=t.instance.codeVersion(e.memory);if(n.appliedVersion===i&&n.pending.length===0&&!n.dirty)continue;let s=n.appliedVersion===-1?[Object.freeze({memory:e.memory,offset:0,length:e.size})]:n.pending.map(e=>Object.freeze({...e}));a.push({state:n,changes:s,version:i})}if(a.length===0)return;let s=e.phase;e.phase=`translate`;let c=[];try{for(let n of a){let{region:r}=n.state,a=t.instance.memory(r.memory),o=r.size>=a.length?a:a.subarray(0,r.size),s=!0;try{let a=b(o,()=>{if(!s)throw e.error(`OBJECT_DISPOSED`,`Metadata view expired`,t.instance)}),l=Object.freeze({memory:r.memory,base:r.base,size:r.size,codeVersion:n.version,code:a}),u=i(Object.freeze({region:l,changes:Object.freeze(n.changes.slice())}));Ca(u);let d=t.instance.captureCodeMetadata(r,u);c.push({state:n.state,version:n.version,polling:d.polling,delays:d.delays})}finally{s=!1}}let n=!1;for(let e of c){e.state.appliedVersion=e.version,e.state.dirty=!1,e.state.pending.length=0,e.state.polling.clear();for(let[t,n]of e.polling)e.state.polling.set(t,n);e.state.delays.clear();for(let[t,n]of e.delays)e.state.delays.set(t,n);e.state.region.memory===t.options.code&&(n=!0)}r.polling.clear(),r.delays.clear();for(let e of r.regions.values()){for(let[t,n]of e.polling)r.polling.set(t,n);for(let[t,n]of e.delays)r.delays.set(t,n)}n?za(t,!0):t.direct!==void 0&&!t.directStale&&so(t)}catch(n){throw e.wrap(n,`JIT_FAILED`,`translate`,t.instance)}finally{e.phase=s}}function Xa(e,t,n){if(t.metadata===void 0)return;let r=Va(t,n)??t.codeRegions[0],i=[r];e.execution===`throughput`&&e.jits.length===1&&r.memory===t.options.code&&i.push(...Ja(t)),Ya(e,t,i)}function Za(e){let t=Ma(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 Qa(e,t,n){t!==void 0&&t.boundaryCalls++,e.boundary(n)}function $a(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set([e.options.code]),r=e.instance;for(let[n,i]of r.stateResources)e.directHookReads.has(i)&&t.add(n);for(let[t,i]of r.memoryResources)e.directHookReads.has(i)&&n.add(t);return{states:t,memories:n}}function eo(e,t,n=!1){let r=!1,i=!1,a=e.instance,o=e.directHookReads.size;if(t)for(let n of t.keys()){if(e.directHookReads.has(n))continue;e.directHookReads.add(n);let t=!1;for(let e of a.stateResources.values())if(e===n){t=!0;break}if(!t){for(let e of a.memoryResources.values())if(e===n){t=!0;break}}t&&(i=!0)}if(e.directObserverRevision===a.observerRevision&&o===e.directHookReads.size&&!i)return!1;e.directObserverRevision=a.observerRevision;for(let[t,n]of a.stateResources){let i=n.subscribers.size>0;e.directStateGuards.has(t)!==i&&(i?e.directStateGuards.add(t):e.directStateGuards.delete(t),r=!0)}for(let[t,n]of a.memoryResources){let i=n.subscribers.size>0;e.directMemoryGuards.has(t)!==i&&(i?e.directMemoryGuards.add(t):e.directMemoryGuards.delete(t),r=!0)}let s=!1;return i&&e.direct!==void 0&&(s=Ra(e,n)),r&&Za(e),(r||i)&&(e.directSkip=void 0),s}function to(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(),t.writeIntent(e,i)&&(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 no(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)),s=[...t.pins.keys()],c=new Map(s.map((e,t)=>[e,t])),l=s.map(e=>t.pin(e)),u=Int32Array.from(l,e=>t.board.electricalSlot(e));return e.directLayout={...n,memoryNames:Object.freeze(r),memories:i,memoryBanks:Object.freeze(a),memoryViews:Object.freeze(o),pinNames:Object.freeze(s),pins:c,pinObjects:Object.freeze(l),pinElectricalSlots:u},e.directLayout}function ro(e,t,n,r){e.time=r.time,r.publishPending=!1;let i=t.commitDirectStates(r.stateDirty);for(let e=0;e<r.memoryDirty.length;e++){let a=r.memoryDirty[e];if(a!==0)for(r.memoryDirty[e]=0;a!==0;){let r=e*32+31-Math.clz32(a&-a);t.memoryChanged(n.memoryNames[r]),a&=a-1,i=!0}}return i}function io(e,t){let n=/* @__PURE__ */ new Map;for(let[r,i]of qa(e)){let e=t.states.get(i.counter);if(e===void 0)continue;let a=i.pending===void 0?void 0:{state:t.states.get(i.pending.state),period:t.states.get(i.pending.period),active:t.states.get(i.pending.active)};n.set(r,a!==void 0&&a.state!==void 0&&a.period!==void 0&&a.active!==void 0?{counter:e,cycles:i.cycles,pending:a}:{counter:e,cycles:i.cycles})}return n}function ao(e,t){let{states:n,memories:r,pins:i}=t,a=$a(e);return{states:n,memories:r,pins:i,pc:{name:e.options.pc,index:n.get(e.options.pc)},host:!0,...e.functions===void 0?{}:{functions:e.functions},split:!0,shardSize:32,delayLoops:io(e,t),entryBlockedStates:a.states,entryBlockedMemories:a.memories,blockedStates:e.directStateGuards,blockedMemories:e.directMemoryGuards}}function oo(e){e.frame.resume===0&&e.frame.locals.length<e.session.localCount&&(e.frame.locals.length=e.session.localCount)}function so(e){let t=e.direct;t===void 0||e.directStale||(t.session.updateDelays(io(e,e.directLayout)),oo(t),Ia(e,t.session))}function co(e,t){let n=e.direct;if(n===void 0||e.directStale||n.frame.resume!==0)return;let r=[];for(let n of t)Ua(e,n)&&r.push(n);if(n.session.updateDelays(io(e,e.directLayout)),r.length){n.session.add(r.map(t=>Wa(e,t)));for(let t of r)e.directMemories.add(t.codeRegion?.memory??e.options.code);oo(n)}Ia(e,n.session)}function lo(e,t,n){let r=e.direct;r===void 0||e.directStale||(r.frame.resume===0?co(e,t):n?Ra(e,!1):so(e))}function uo(e,t){if(t.direct!==void 0)return t.direct;t.directStale&&=!1;let n=no(t);t.directCacheInvalid&&=(t.directCache!==void 0&&ir.clearCache(t.directCache),!1);let r=t.directCache??=ir.createCache(),i,a=[];try{i=ir.createSession(ao(t,n),r);for(let e of t.cache.values())Ua(t,e)&&a.push(e);a.length&&i.add(a.map(e=>Wa(t,e))),i.updateDelays(io(t,n))}catch(e){throw i?.dispose(),e}for(let e of a)t.directMemories.add(e.codeRegion?.memory??t.options.code);let o=Ma(t);o.stateIndex=n.states,o.memoryIndex=n.memories;let s=Math.ceil(n.stateNames.length/32),c=Math.ceil(n.memoryNames.length/32);o.stateMask.length!==s&&(o.stateMask=new Int32Array(s)),o.memoryMask.length!==c&&(o.memoryMask=new Int32Array(c)),Za(t);let l=fo(e,t,n,i,o),u={session:i,frame:l,get pcs(){return new Set(i.pcs)}};t.direct=u,t.directStale=!1;let d=Na(t);return d.directCompiles++,d.directSessions++,Ia(t,i),u}function fo(e,t,n,r,i){let a=t.instance,{pinObjects:o,pinNames:s,pinElectricalSlots:c}=n,l=e.checkpointDiagnostics?ka(t):void 0,u={states:n.stateValues,memories:[...n.memoryBanks],memoryViews:n.memoryViews,pins:o,resistors:[],locals:Array(r.localCount),stateDirty:new Int32Array(Math.ceil(n.stateNames.length/32)),memoryDirty:new Int32Array(Math.ceil(n.memoryNames.length/32)),time:e.time,due:e.time,resume:0,stopAfterInstruction:!1,boundarySettled:!1};if(u.writePinIntent=(t,n)=>{if(Object.hasOwn(a,`writeIntent`))e.time=u.time,a.writeIntent(s[t],n)&&(u.publishPending=!0);else{let e=o[t];if(e.intent===n)return;e.intent=n,a.board.markElectricalDirty(c[t]),u.publishPending=!0}},u.host=to(e,a,u),t.metadata===void 0&&(u.publishCheckpoint=()=>(l!==void 0&&l.publications++,ro(e,a,n,u),Qa(e,l,`checkpointPublish`),t.directStale||t.direct?.session!==r||!e.canContinueDirect(t,u.due)?(u.boundarySettled=!0,l!==void 0&&l.exits++,!1):(e.current=a,l!==void 0&&l.continues++,!0)),t.options.beforeInstruction===void 0)){let i=n.states.get(t.options.pc);u.finishCheckpoint=(o,s)=>{l!==void 0&&(l.finishes++,s&&l.emptySuffixes++),s?e.time=u.time:ro(e,a,n,u),Qa(e,l,`checkpointFinish`);let c=u.states[i];return t.directStale||t.direct?.session!==r||!r.has(c)||t.directSkip===c||u.time>=o||e.events.time<o||!s&&!e.canContinueDirect(t,u.time)||t.directObserverRevision!==a.observerRevision&&eo(t,void 0,!0)?(u.boundarySettled=!0,l!==void 0&&l.exits++,!1):(u.stopAfterInstruction=!1,e.current=a,l!==void 0&&l.continues++,!0)}}return u.blockedStates=i.stateMask,u.blockedMemories=i.memoryMask,u}function po(e,t,n){let r=t.instance,i=!!t.direct?.frame.resume;if(!i){t.directStale&&=(La(t),!1);let i=d(r.states.get(t.options.pc),`pc`),a=Va(t,i);if(e.execution!==`throughput`||e.jits.length!==1||a!==void 0&&a.memory!==t.options.code||Ka(t).has(i)||t.cache.get(i)?.polling||(eo(t,n),t.directSkip===i)||t.direct===void 0&&uo(e,t)===void 0)return`declined`}let a=t.direct,o=a.frame,s=t.directLayout;for(;;){i&&(o.stopAfterInstruction=!0),o.time=e.time;let n=e.time,c,l,u=Na(t);u.directCalls++;try{c=a.session.run(o,Math.min(e.executionEnd,e.events.time))}finally{l=ro(e,r,s,o)}let f=l||e.time!==n;if(o.boundarySettled?o.boundarySettled=!1:(c!==`fallback`&&c!==`untranslated`&&c!==`pending`||f)&&e.boundary(`runDirect`),c===`untranslated`||c===`pending`)return u.directDispatchMisses++,t.directStale&&o.resume===0&&(La(t),t.directStale=!1),f?`assembly-progressed`:`assembly`;if(c===`fallback`){let n=d(r.states.get(t.options.pc),`pc`);if(Ka(t).has(n)||t.cache.get(n)?.polling||(u.directFallbacks++,t.directSkip=n),!f&&e.time<e.executionEnd)return`fallback`}else if(c===`stopped`)return u.directStopped++,t.stopped=!0,t.directStale&&o.resume===0&&(La(t),t.directStale=!1),`ran`;else c===`invalidated`?(o.stopAfterInstruction=!1,t.directStale&&o.resume===0&&(La(t),t.directStale=!1)):u.directDeadlines++;if(t.direct===void 0)return e.queueJit(t),`ran`;if(o.resume){let n=Math.max(o.due,e.time);if(t.metadata===void 0&&!t.directStale&&e.canContinueDirect(t,n)){e.time=n,e.current=r,i=!0;continue}if(n>e.time)return e.events.push(n,()=>e.queueJit(t)),`ran`}return e.queueJit(t),`ran`}}function mo(e,t){let n=Va(e,t);return n!==void 0&&n.memory!==e.options.code||Ka(e).has(t)?!1:e.cache.get(t)?.polling!==!0}function ho(e,t,n){t.metadata!==void 0&&Xa(e,t,n);let r=t.direct;if(r===void 0||t.directStale||r.frame.resume!==0||!mo(t,n))return!1;let i=t.cache.get(n);return i===void 0?(bo(e,t,n),i=t.cache.get(n),i!==void 0):(r.session.has(n)||co(t,[i]),!0)}function go(e,t,n){if(n)return e.queueJit(t),!0;if(t.direct===void 0||t.directStale||!ho(e,t,d(t.instance.states.get(t.options.pc),`pc`)))return!1;let r=po(e,t);return r===`ran`||r===`assembly-progressed`&&(e.queueJit(t),!0)}function _o(e,t,n){let r=new Map(t),i=e.instance,a=i.stateResources.get(e.options.pc);r.set(a,a.version);let o=(n===void 0?void 0:Va(e,n))?.memory??e.options.code,s=i.memoryResources.get(o);return r.set(s,s.version),r}function vo(e,t,n,r,i){t.dependencies=n,t.pollingWait=!0,t.pollingPeriod=0,e.parkWaiter(t);let a=++t.pollingToken;if(e.boundary(`polling`),r===0||i===void 0)return;let o=fa(e.time+r);e.events.push(o,()=>{if(a!==t.pollingToken||!t.active||t.stopped||!e.waitingJits.has(t))return;let n=t.dependencies;delete t.dependencies,e.unparkWaiter(t),t.pollingToken++,e.current=t.instance,t.instance.dependenciesCurrent(n)&&(t.instance.syncCall(i,[r]),e.boundary(`polling`)),e.queueJit(t)})}function yo(e,t,n){if(n.kind===`elapse`){let r=fa(n.duration);if(r===0)return!1;let i=fa(e.time+r);return e.events.push(i,()=>e.queueJit(t)),e.boundary(`jitSignal`),!0}if(n.kind===`waitUntil`){let r=t.instance.evaluate(()=>Da(t,n.predicate));return r.value!==!0&&(t.predicate=n.predicate,t.pollingWait=!1,t.dependencies=r.dependencies,e.parkWaiter(t),e.boundary(`jitSignal`),!0)}if(n.kind===`stop`)return t.stopped=!0,t.execution=void 0,e.boundary(`jitSignal`),!0;if(n.kind===`redirect`){d(n.pc,`redirect target`);let r=fa(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?_o(t,i,t.currentPc):void 0;return t.automaticPolling=!1,t.pollReads=void 0,e.boundary(`jitSignal`),r===0?e.queueJit(t):e.events.push(fa(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.parkWaiter(t)):e.queueJit(t))}),!0}throw TypeError(`Invalid JIT suspension`)}function bo(e,t,n){let r=e.phase;e.phase=`translate`;let i=!0,a=!1;try{let r=Va(t,n),o=r?.memory??t.options.code,s=t.instance.memory(o),c=b(r===void 0||r.size>=s.length?s:s.subarray(0,r.size),()=>{if(!i)throw e.error(`OBJECT_DISPOSED`,`Translation view expired`,t.instance)}),l=t.options.shareDirectBodies===!0?[]:void 0;a=l!==void 0;let u=t.options.translate(Object.freeze({pc:n,code:c,codeBase:r?.base??0,codeVersion:t.instance.codeVersion(o),...l===void 0?{}:{markDirectBodyShareable:(e,n)=>{a&&(Na(t).directShareCallbacks++,l.push({pc:e,byteLength:n}))}}}),wt({device:t.model}));Ca(u),a=!1;let d=tt(u,t.model);if(d.instructions[0]?.pc!==n)throw TypeError(`Translated first pc does not match`);let f=d.instructions.map(e=>{let n=Va(t,e.pc);return{pc:e.pc,nextPc:e.nextPc,body:e.body,polling:Ea(e.body,e.pc,t.options.pc),execute:pa(e.body),codeRegion:n,codeVersion:t.instance.codeVersion(n?.memory??t.options.code)}});l!==void 0&&Ga(t,r,c.length,f,l);let p=f.some(e=>t.cache.has(e.pc));for(let e=f.length-1;e>=0;e--){let n=f[e];t.cache.set(n.pc,n),t.cacheMemories.add(n.codeRegion?.memory??t.options.code)}return f.some(e=>e.codeRegion===void 0||e.codeRegion.memory===t.options.code)&&t.revision++,t.directSkip=void 0,lo(t,f,p),f}catch(n){throw e.wrap(n,`JIT_FAILED`,`translate`,t.instance)}finally{i=!1,a=!1,e.phase=r}}function xo(e,t){if(t.queued=!1,t.active&&!t.stopped){if(e.current=t.instance,t.metadata!==void 0&&Xa(e,t,d(t.instance.states.get(t.options.pc),`pc`)),t.direct?.frame.resume){let n=po(e,t);(n===`assembly`||n===`assembly-progressed`)&&go(e,t,!0)}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||Ka(t).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,yo(e,t,r.value))return;throw TypeError(`Invalid hook suspension`)}}n=s?.dependencies,r=c}let a=d(t.instance.states.get(t.options.pc),`pc`);if(t.metadata!==void 0&&i!==void 0&&Xa(e,t,a),e.execution===`throughput`){let i=Ka(t).get(a);if(i){let r=t.instance.evaluate(()=>t.instance.syncCall(i.predicate));if(r.value!==!0){let o=new Map([...n??[],...r.dependencies]),s=0,c=i.wait;c&&(s=fa(t.instance.evaluate(()=>t.instance.syncCall(c.delay),o).value)),vo(e,t,_o(t,o,a),s,c?.advance);return}i.consume&&t.instance.syncCall(i.consume)}if(!r&&e.jits.length===1){let r=po(e,t,n);if(r===`ran`||(r===`assembly`||r===`assembly-progressed`)&&go(e,t,r===`assembly-progressed`))return}}let o=t.cache.get(a);o||=bo(e,t,a)[0],t.currentPc=a,e.execution===`throughput`&&e.jits.length===1&&Na(t).directGenericInstructions++,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.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(`runJit`),e.queueJit(t);return}if(yo(e,t,n.value))return}}}}let So=Object.freeze([]),Co=/* @__PURE__ */ new WeakMap;function wo(e,t){if(t.length===0)return e;let n=Co.get(e),r=n?.get(t);if(r!==void 0)return r;let i=Xe({...e,declarations:e.declarations.concat(t)});for(let t of i.declarations.slice(e.declarations.length))if(t.kind!==`function`)throw TypeError(`Expected JIT function declaration`);return n===void 0&&(n=/* @__PURE__ */ new WeakMap,Co.set(e,n)),n.set(t,i),i}function To(e,t){for(let n of t.keys())if(!e.has(n))return!1;return!0}function Eo(e,t){return Object.freeze({get props(){return t.assertReadAllowed(e),Object.freeze(Object.fromEntries([...e.props].map(([e,t])=>[e,ee(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 Do=class extends Map{names=[];bankValues=[];dirty=/* @__PURE__ */ new Int32Array;pending=!1;bindDirectBank(e,t){this.names=e,this.bankValues=t,this.dirty=new Int32Array(Math.ceil(e.length/32))}markDirectDirty(e,t){this.dirty[e]|=t,this.pending=!0}flush(){if(!this.pending)return;this.pending=!1;let{names:e,bankValues:t,dirty:n}=this;for(let r=0;r<n.length;r++){let i=n[r];if(i===0)continue;n[r]=0;let a=r<<5;for(;i!==0;){let n=a+31-Math.clz32(i&-i);super.set(e[n],t[n]),i&=i-1}}}get(e){return this.pending&&this.flush(),super.get(e)}set(e,t){return this.pending&&this.flush(),super.set(e,t)}entries(){return this.pending&&this.flush(),super.entries()}values(){return this.pending&&this.flush(),super.values()}forEach(e,t){this.pending&&this.flush(),super.forEach(e,t)}[Symbol.iterator](){return this.pending&&this.flush(),super[Symbol.iterator]()}},Oo=class{board;entry;id;declarations=/* @__PURE__ */ new Map;props=/* @__PURE__ */ new Map;constants=/* @__PURE__ */ new Map;states=new Do;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;derivedName;derivedEntry;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;intentEntries=/* @__PURE__ */ new Map;stateSlots=/* @__PURE__ */ new Map;resourceHandles=/* @__PURE__ */ new Map;memoryPlans=/* @__PURE__ */ new Map;codeVersions=/* @__PURE__ */ new Map;codeMemories=/* @__PURE__ */ new Set;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,waiters:void 0});u(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=te(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:(e,t)=>{this.writeIntent(e,t)},resistor:(e,t)=>{let n=Sa(t);if(n<.001||n>1e9)throw new xa(`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=h(r.bytes,n,i),o=this.dependencies();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=h(i.bytes,n,a),s=f(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,o,a)},copyBytes:(e,t,n)=>{this.track(this.memoryResources,String(e));let r=this.memory(e),i=h(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:()=>S(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=Eo(this,e)}track(e,t){this.trackSlot(e.get(t))}dependencies(){let e=this.dependencyStack;return e.length===0?void 0:e[e.length-1]}trackSlot(e){let t=this.dependencies();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}setDerived(e,t){(this.derivedName!==e||this.derivedEntry!==t)&&(this.derived.set(e,t),this.derivedName=e,this.derivedEntry=t)}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.dependencies();if(e)for(let[t,r]of n)e.set(t,r)}}evaluateSource(e,t){this.dependencyStack.push(t);try{return _(this.source(e))}finally{this.dependencyStack.pop();let e=this.dependencies();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:_(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||!To(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=t===this.derivedName?this.derivedEntry:this.derived.get(t),n=this.board.resourceEpoch;if(e===void 0||e.epoch!==n&&!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();let i=this.evaluate(()=>_a(n.value,this.host),r);e={value:i.value,dependencies:i.dependencies,epoch:this.board.resourceEpoch},this.setDerived(t,e)}else e.epoch!==n&&(e.epoch=n);let r=this.dependencies();if(r)for(let[t,n]of e.dependencies)r.set(t,n);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=x(e.type,this.rawProps[t],this.declarations,!0);else if(e.default)r=x(e.type,_a(e.default,this.host),this.declarations,!0);else throw TypeError(`Missing property ${t}`)}else r=_a(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 pa(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}writeIntent(e,t){let n=typeof e==`string`?e:String(e),r=this.board,i=this.intentEntries.get(n);if(i===void 0){let e=this.pin(n);i={pin:e,slot:r.electricalSlot(e)},this.intentEntries.set(n,i)}return i.pin.intent!==t&&(i.pin.intent=t,r.markElectricalDirty(i.slot),!0)}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.dependencies();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`}),t=Object.freeze(e),n=e.map(e=>this.states.get(e));this.states.bindDirectBank(t,n),this.directBank={stateNames:t,stateSlots:Object.freeze(e.map(e=>this.stateResources.get(e))),states:new Map(e.map((e,t)=>[e,t])),stateValues:n}}return this.directBank}commitDirectStates(e){let{stateSlots:t}=this.directBank,n=this.states,r=this.board,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===0)continue;e[a]=0,i=!0,n.markDirectDirty(a,o);let s=a<<5;for(;o!==0;){let e=t[s+31-Math.clz32(o&-o)];e.subscribers.size===0?(e.version++,r.noteResourceVersion(e)):r.invalidate(e),o&=o-1}}return i}writeState(e,t,n){let r=_(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}codeVersion(e){return this.codeVersions.get(e)??0}intersectsCodeRegion(e,t,n){return t===void 0||n===void 0||t<e.size&&t+n>0}hasCodeRegion(e,t,n){for(let r of this.jits)if(r.active){for(let i of r.codeRegions)if(i.memory===e&&this.intersectsCodeRegion(i,t,n))return!0}return!1}addMetadataChange(e,t){let n=e.pending,r=t.offset+t.length,i=t.offset;for(let e=0;e<n.length;){let a=n[e],o=a.offset+a.length;t.offset<=o&&a.offset<=r?(i=Math.min(i,a.offset),r=Math.max(r,o),n.splice(e,1)):e++}n.push({memory:t.memory,offset:i,length:r-i})}markMetadataChanged(e,t,n,r){if(e.metadata)for(let i of e.metadata.regions.values()){let a=i.region;if(a.memory!==t||i.appliedVersion===-1||(t===e.options.code&&(i.dirty=!0),!this.intersectsCodeRegion(a,n,r)))continue;i.dirty=!0;let o=n===void 0?0:Math.max(0,n),s=n===void 0?a.size:Math.min(a.size,n+(r??0));s>o&&this.addMetadataChange(i,{memory:t,offset:o,length:s-o})}}memoryChanged(e,t,n){this.memoryChangedSlot(e,this.memoryPlan(e).slot,t,n)}memoryChangedPlan(e,t,n){this.memoryChangedSlot(e.name,e.slot,t,n)}memoryChangedSlot(e,t,n,r){if(this.board.invalidate(t),this.codeMemories.has(e)){this.hasCodeRegion(e,n,r)&&this.codeVersions.set(e,this.codeVersion(e)+1);for(let t of this.jits){let i=!1;for(let a of t.codeRegions)if(a.memory===e&&this.intersectsCodeRegion(a,n,r)){i=!0;break}if(i){if(this.markMetadataChanged(t,e,n,r),t.options.code===e)t.cache.clear(),t.cacheMemories.clear(),t.revision++,za(t,!0);else if(t.cacheMemories.has(e)){for(let[n,r]of t.cache)r.codeRegion?.memory===e&&t.cache.delete(n);t.cacheMemories.delete(e),t.directMemories.has(e)&&za(t,!1),t.directMemories.delete(e)}}}}}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=this.pins.get(t),n=e===void 0?-1:this.board.electricalSlot(e),r=e===void 0?void 0:this.sampleResources.get(t),i,a,o=()=>(e===void 0&&(e=this.pin(t),n=this.board.electricalSlot(e),r=this.sampleResources.get(t)),e);return Object.freeze({sample:()=>{let e=o(),t=this.dependencies();return t&&t.set(r,r.version),e.sample},intent:e=>{let t=o();t.intent!==e&&(t.intent=e,this.board.markElectricalDirty(n))},resistor:e=>{if(a!==void 0&&e===i)return a;let n=Sa(e);if(n<.001||n>1e9)throw new xa(`Resistance outside [0.001, 1e9]`);let r=this.resistorIntent(t,n);return i=e,a=r,r}})}if(e===`state`){let e=this.states.has(t)?this.stateResources.get(t):void 0,n=e===void 0?-1:this.directBank?.states.get(t)??-2,r=()=>e??=this.stateSlot(t),i=this.states;return Object.freeze({read:()=>{let e=r(),a=this.dependencies();return a&&a.set(e,e.version),n===-2&&(n=this.directBank?.states.get(t)??-1),n<0?i.get(t):this.directBank.stateValues[n]},write:e=>{let n=r();this.writeState(t,e,n)}})}let n=this.memories.has(t)?this.memoryPlan(t):void 0,r=()=>n??=this.memoryPlan(t),i=(e,t,n)=>{let i=r(),a=h(i.bytes,n,e),o=this.dependencies();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=h(o.bytes,i,e),c=f(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,s,e)};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=h(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,_(_a(e.initial,this.host)));break;case`memory`:{let t=p(_a(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=Sa(_a(e.low,this.host)),r=Sa(_a(e.high,this.host));if(n>=r)throw new xa(`Pin thresholds must satisfy low < high`);Object.assign(t,{low:n,high:r})}e.initial&&(t.intent=_a(e.initial,this.host));break}case`channel`:{let t=p(_a(e.capacity,this.host),`capacity`);if(t===0)throw RangeError(`Capacity must be positive`);let n;if(e.maxLength&&(n=p(_a(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(_a(e.overflow,this.host)):`drop_new`,incoming:new Wi,pending:new Wi,outgoing:new Wi});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:ha(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:ma(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]=So);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:ee(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`&&!pa(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]=b(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=x(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})}captureCodeRegions(e){let t=this.memories.get(e.code),n=Object.freeze({memory:e.code,base:0,size:t.length}),r=[];if(Object.hasOwn(e,`codeRegions`)){if(!Array.isArray(e.codeRegions))throw TypeError(`codeRegions must be an array`);for(let t of e.codeRegions){u(t,[`memory`,`base`,`size`]);let e=m(t.memory),i=p(t.base,`code region base`),a=p(t.size,`code region size`);if(a===0)throw RangeError(`Code region size must be positive`);let o=this.memories.get(e)?.length;if(o===void 0)throw this.board.error(`INVALID_BINDING`,`Unknown code region memory`,this);if(a>o)throw this.board.error(`INVALID_BINDING`,`Code region exceeds memory`,this);if(i>2**53-1-a)throw this.board.error(`INVALID_BINDING`,`Code region range is not a safe integer`,this);let s=Object.freeze({memory:e,base:i,size:a});for(let e of[n,...r])if(s.base<e.base+e.size&&e.base<s.base+s.size)throw this.board.error(`INVALID_BINDING`,`Code regions overlap`,this);r.push(s)}}return{all:Object.freeze([n,...r]),additional:Object.freeze(r)}}capturePolling(e,t){let n=/* @__PURE__ */ new Map;if(!Array.isArray(e))throw TypeError(`polling must be an array`);for(let r of e){u(r,[`pc`,`predicate`,`consume`,`wait`]);let e=d(r.pc,`polling pc`);if(t!==void 0&&(e<t.base||e>=t.base+t.size))throw this.board.error(`INVALID_BINDING`,`Polling pc is outside its code region`,this);let i=m(r.predicate),a=this.declarations.get(i);if(n.has(e)||a?.kind!==`function`||!a.pure||a.params.length||a.returns?.kind!==`bool`)throw this.board.error(`INVALID_BINDING`,`Invalid polling declaration`,this);let o;if(Object.hasOwn(r,`consume`)){o=m(r.consume);let e=this.declarations.get(o);if(e?.kind!==`function`||e.params.length!==0||e.returns!==void 0)throw this.board.error(`INVALID_BINDING`,`Invalid polling consume function`,this)}let s;if(Object.hasOwn(r,`wait`)){u(r.wait,[`delay`,`advance`]);let e=m(r.wait.delay),t=m(r.wait.advance),n=this.declarations.get(e),i=this.declarations.get(t);if(n?.kind!==`function`||!n.pure||n.params.length!==0||n.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);s=Object.freeze({delay:e,advance:t})}n.set(e,Object.freeze({predicate:i,...o===void 0?{}:{consume:o},...s===void 0?{}:{wait:s}}))}return n}captureMetadataDelays(e,t){if(!(e instanceof Map))throw TypeError(`codeMetadata delays must be a Map`);let n=/* @__PURE__ */ new Map;for(let[r,i]of e){let e=d(r,`delay pc`);if(e<t.base||e>=t.base+t.size)throw this.board.error(`INVALID_BINDING`,`Delay pc is outside its code region`,this);u(i,[`counter`,`cycles`,`pending`]);let a=m(i.counter),o=f(i.cycles,`delay cycles`);if(o<=0)throw RangeError(`Delay cycles must be positive`);let s;Object.hasOwn(i,`pending`)&&(u(i.pending,[`state`,`period`,`active`]),s=Object.freeze({state:m(i.pending.state),period:m(i.pending.period),active:m(i.pending.active)})),n.set(e,Object.freeze({counter:a,cycles:o,...s?{pending:s}:{}}))}return n}captureCodeMetadata(e,t){if(u(t,[`polling`,`delays`]),!Object.hasOwn(t,`polling`)||!Object.hasOwn(t,`delays`))throw TypeError(`codeMetadata must contain polling and delays`);return{polling:this.capturePolling(t.polling,e),delays:this.captureMetadataDelays(t.delays,e)}}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(u(e,[`entry`,`code`,`codeRegions`,`codeMetadata`,`pc`,`functions`,`beforeInstruction`,`polling`,`delays`,`shareDirectBodies`,`translate`]),m(e.entry),m(e.code),m(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);let t=this.captureCodeRegions(e);if(Object.hasOwn(e,`codeMetadata`)){if(typeof e.codeMetadata!=`function`)throw this.board.error(`INVALID_BINDING`,`Invalid codeMetadata provider`,this);if(Object.hasOwn(e,`polling`)||Object.hasOwn(e,`delays`))throw this.board.error(`INVALID_BINDING`,`codeMetadata is mutually exclusive with static polling/delays`,this)}if(e.beforeInstruction!==void 0){u(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 n=Object.hasOwn(e,`polling`)?this.capturePolling(e.polling):/* @__PURE__ */ new Map;if(Object.hasOwn(e,`delays`)&&!(e.delays instanceof Map))throw TypeError(`delays must be a Map`);if(Object.hasOwn(e,`shareDirectBodies`)&&typeof e.shareDirectBodies!=`boolean`)throw TypeError(`shareDirectBodies must be a boolean`);let r=Object.hasOwn(e,`codeMetadata`)?{regions:new Map(t.all.map(e=>[e,{region:e,appliedVersion:-1,dirty:!1,pending:[],polling:/* @__PURE__ */ new Map,delays:/* @__PURE__ */ new Map}])),polling:/* @__PURE__ */ new Map,delays:/* @__PURE__ */ new Map}:void 0,i=this.entry.model,a=e.functions;if(Object.hasOwn(e,`functions`)&&typeof a!=`function`)throw TypeError(`functions must be a JIT function builder callback`);let o=i,s,c=this.host;if(a){let e=a(i);if(Ca(e),!Array.isArray(e))throw TypeError(`Expected JIT function declarations`);o=wo(i,e);let t=/* @__PURE__ */ new Map;for(let e of o.declarations.slice(i.declarations.length))e.kind===`function`&&t.set(e.name,e);s=t,c={...this.host,call:(e,n)=>{let r=t.get(e);return r?pa(r.body)(c,n):this.invoke(e,n)}}}let l={instance:this,model:o,host:c,...s===void 0?{}:{functions:s},options:Object.freeze({...e,...e.codeRegions===void 0?{}:{codeRegions:t.additional},...e.beforeInstruction?{beforeInstruction:Object.freeze({...e.beforeInstruction})}:{}}),codeRegions:t.all,cache:/* @__PURE__ */ new Map,cacheMemories:/* @__PURE__ */ new Set,metadata:r,polling:n,delays:e.delays??/* @__PURE__ */ new Map,revision:0,directObserverRevision:-1,directStateGuards:/* @__PURE__ */ new Set,directMemoryGuards:/* @__PURE__ */ new Set,directHookReads:/* @__PURE__ */ new Set,directMemories:/* @__PURE__ */ new Set,direct:void 0,directSkip:void 0,directStale:!1,directCacheInvalid:!1,pollReads:void 0,currentPc:void 0,automaticPolling:!1,pollingWait:!1,pollingPeriod:0,pollingOrigin:0,pollingToken:0,dependencyDirty:!0,waiterSlots:void 0,active:!0,stopped:!1,queued:!1,execution:void 0};this.jits.push(l),this.board.jits.push(l);for(let e of l.codeRegions)this.codeMemories.add(e.memory);let d={dispose:()=>{l.active&&(l.active=!1,l.execution=void 0,delete l.predicate,l.pollingToken++,this.board.unparkWaiter(l),l.cache.clear(),l.cacheMemories.clear(),Ba(l),l.pollReads=void 0)}};return this.resources.push(d),d}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.codeRegions.some(t=>t.memory===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=h(r,n,t.length);t.length&&(r.set(t.slice(),i),this.memoryChanged(e,i,t.length))}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 ko=/* @__PURE__ */ new WeakMap;function Ao(e,t){ko.set(e,t)}function jo(e){let t=ko.get(e);if(t===void 0)throw TypeError(`Topic bridge was not created by a board`);return t}let Mo=Symbol.for(`mica-js.simulator/observations`),No=Symbol.for(`mica-js.simulator/processes`),Po=Symbol.for(`mica-js.simulator/checkpoints`),Fo=Symbol.for(`mica-js.simulator/checkpoint-experiment`),Io=Object.freeze({checkpointPublish:0,checkpointFinish:0,jitSignal:0,runJit:0,runDirect:0,polling:0,process:0,other:0});function Lo(){return{calls:0,empty:0,publishes:0,batches:0,reactions:0,captures:0,sources:{...Io}}}function Ro(){let e=globalThis[Fo];return typeof e==`object`&&!!e&&e.diagnostics===!0}let zo=Object.freeze({}),Bo=/* @__PURE__ */ new WeakMap;function Vo(e){try{if(!Array.isArray(e))throw TypeError(`Expected device entries`);let t=/* @__PURE__ */ new Set,n=e.map(e=>{u(e,[`id`,`model`,`create`]);let n=m(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=Xe(e.model)}catch(e){throw Ta(e instanceof A&&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 Bo.set(r,n),r}catch(e){throw e instanceof va?e:Ta(`INVALID_CONFIGURATION`,e,`library`)}}var Ho=class{time=0;status=`ready`;phase=`assembly`;current;pendingElectricalSlot=-2;dirtyElectricalSlots=/* @__PURE__ */ new Int32Array;dirtyElectricalStamps=/* @__PURE__ */ new Int32Array;dirtyElectricalLength=0;dirtyElectricalEpoch=1;observations=new Ui;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 t;diagnostics=new t;listeners=/* @__PURE__ */ new Set;hostListeners=0;models=new Wi;events=new Hi;readyJits=new Wi;versionEpoch=0;waitingJits=/* @__PURE__ */ new Set;waiterEpoch=0;waitingScanEpoch=0;pollingWaiterCount=0;jits=[];instances=[];checkpointDiagnostics;boundaryStats;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{u(t,[`instances`,`nets`]),u(n,[`seed`,`execution`,`cpuQuantum`]),this.checkpointDiagnostics=Ro(),this.boundaryStats=this.checkpointDiagnostics?Lo():void 0;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`)?f(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`)?f(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){u(e,[`id`,`type`,`props`,`randomState`]);let t=m(e.id),n=m(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 Oo(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,p=/* @__PURE__ */ new Set;for(let e of t.nets){u(e,[`id`,`pins`,`voltage`]);let t=m(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`)&&d(e.voltage,`voltage`);for(let t of e.pins){u(t,[`instance`,`pin`]);let e=m(t.instance),n=m(t.pin);if(c.get(e)?.declarations.get(n)?.kind!==`pin`)throw TypeError(`Unknown pin endpoint`);let r=`${e}\\0${n}`;if(p.has(r))throw TypeError(`Duplicate connected endpoint`);p.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 h=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}:{}})),g=[];for(let e of this.instances)for(let t of e.pins.values()){let n=e.sampleResources.get(t.name);g.push(t),this.sampleSlots.set(t,n),this.electricalSlots.set(t,this.sampleSlotsBySlot.length),this.sampleSlotsBySlot.push(n)}this.network=Vi(g,h),this.dirtyElectricalSlots=new Int32Array(g.length),this.dirtyElectricalStamps=new Int32Array(g.length),this.phase=`initialize`;for(let e of this.instances){this.current=e;let t;try{if(t=e.entry.create(e.context),Ca(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,Mo,{value:()=>this.observationReport(),enumerable:!1}),Object.defineProperty(this,No,{value:()=>this.processReport(),enumerable:!1}),Object.defineProperty(this,Po,{value:()=>this.checkpointReport(),enumerable:!1})}catch(e){let t=e instanceof va?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=[],n=[];for(let r of this.instances)for(let i of r.processes){let a=`${r.id}/${i.declaration.kind===`on`?i.declaration.name:`start`}`;(i.resumable?e:t).push(a),n.push(Object.freeze({key:a,blocks:i.resumable?.blocks??0}))}return Object.freeze({resumable:Object.freeze(e),generic:Object.freeze(t),programs:Object.freeze(n),bindings:Object.freeze(this.instances.map(e=>e.bindingReport()))})}checkpointReport(){let e=this.boundaryStats;return Object.freeze({diagnostics:this.checkpointDiagnostics,boundary:Object.freeze({calls:e?.calls??0,empty:e?.empty??0,publishes:e?.publishes??0,batches:e?.batches??0,reactions:e?.reactions??0,captures:e?.captures??0,sources:Object.freeze({...e?.sources??Io})}),checkpoints:Object.freeze(this.instances.flatMap(e=>e.jits.map(t=>{let n=Aa(t);return Object.freeze({instance:e.id,publications:n?.publications??0,finishes:n?.finishes??0,emptySuffixes:n?.emptySuffixes??0,boundaryCalls:n?.boundaryCalls??0,continues:n?.continues??0,exits:n?.exits??0})})))})}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 xi?r:void 0;return new va(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},...wa(r),...r===void 0?{}:{cause:r},related:Object.freeze([])}))}wrap(e,t,n,r){if(e instanceof va&&![`DEVICE_CALLBACK_FAILED`,`JIT_FAILED`,`CLEANUP_FAILED`].includes(t))return e;let i=e instanceof xi||e instanceof xa||e instanceof ba?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&&Ca(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 Ao(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++,this.versionEpoch++,this.flagWaiters(e),e.subscribers.size!==0)for(let t of e.subscribers)this.observations.add(t.order)}noteResourceVersion(e){this.versionEpoch++,this.flagWaiters(e)}flagWaiters(e){let t=e.waiters;if(t!==void 0&&t.size!==0){for(let e of t)e.dependencyDirty=!0;this.waiterEpoch++}}watchWaiter(e){let t=e.dependencies;if(e.waiterSlots===t)return;let n=e.waiterSlots;if(n!==void 0)for(let t of n.keys())t.waiters?.delete(e);if(t!==void 0)for(let n of t.keys())(n.waiters??=/* @__PURE__ */ new Set).add(e);e.waiterSlots=t,e.dependencyDirty=!0}parkWaiter(e){this.waitingJits.has(e)||(this.waitingJits.add(e),e.pollingWait&&this.pollingWaiterCount++),this.watchWaiter(e),e.dependencyDirty=!0,this.waiterEpoch++}unparkWaiter(e){this.waitingJits.delete(e)&&e.pollingWait&&(e.pollingWait=!1,this.pollingWaiterCount--);let t=e.waiterSlots;if(t!==void 0){for(let n of t.keys())n.waiters?.delete(e);e.waiterSlots=void 0}}get resourceEpoch(){return this.versionEpoch}electricalSlot(e){return this.electricalSlots.get(e)}markElectricalDirty(e){let t=this.pendingElectricalSlot;if(t===e)return;let n=this.dirtyElectricalStamps;if(e>=n.length)throw RangeError(`Electrical slot is outside the board`);let r=this.dirtyElectricalEpoch;if(n[e]!==r){if(n[e]=r,t>=0){let i=this.dirtyElectricalSlots;i[0]=t,i[1]=e,n[t]=r,this.dirtyElectricalLength=2,this.pendingElectricalSlot=-2}else t===-1?this.pendingElectricalSlot=e:this.dirtyElectricalSlots[this.dirtyElectricalLength++]=e}}get dirtyElectricalCount(){return this.pendingElectricalSlot>=0?1:this.dirtyElectricalLength}publish(){let e=this.pendingElectricalSlot;e!==-1&&(e>=0?this.network.solveSlotInto(e,this.publishSlot):this.network.solveSlotBatchInto(this.dirtyElectricalSlots,this.dirtyElectricalLength,this.publishSlot),e===-2&&(this.dirtyElectricalLength=0),++this.dirtyElectricalEpoch===2147483647&&(this.dirtyElectricalStamps.fill(0),this.dirtyElectricalEpoch=1),this.pendingElectricalSlot=-1)}publishSlot=e=>{this.invalidate(this.sampleSlotsBySlot[e])};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=oa(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,epoch:-1},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(zo):(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?_(n):n,this.commitChain(e,n)}commitChain(e,t){let n=e.plan.path;if(n.length!==1)return;let r=e.plan.slots,i=e.dependencies;for(let e=0;e<r.length;e++){let t=r[e];i.set(t,t.version)}let a=e.entry;a.value!==t&&(a.value=t),a.dependencies=i,a.epoch=this.versionEpoch,e.instance.setDerived(n[0],a)}collectChain(e){let t=e.plan.evaluate(),n=e.plan.needsSnapshot?_(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(e=`other`){let t=this.boundaryStats;t!==void 0&&(t.calls++,t.sources[e]++);let n=!1;for(;;){if(this.pendingElectricalSlot!==-1&&(t!==void 0&&t.publishes++,this.publish(),n=!0),!this.observations.size){t!==void 0&&!n&&t.empty++;return}t!==void 0&&t.batches++,n=!0;let e=this.reactionBatch;e.length&&=0;let r=this.changeObservations;r.length&&=0,this.changePrevious.length&&(this.changePrevious.length=0),this.changeCurrent.length&&(this.changeCurrent.length=0),this.observations.drain(this.consumeObservation);let i=r.length;if(i){for(let e=0;e<i;e++)this.applyChange(r[e],this.changePrevious[e],this.changeCurrent[e]);r.length=0,this.changePrevious.length=0,this.changeCurrent.length=0}if(e.length)t!==void 0&&(t.reactions+=e.length),this.runBoundaryReactions(e);else return}}consumeObservation=e=>{if(`plan`in e){this.collectChain(e);return}let t=e.readSource();if(g(e.previous,t))return;let n=e.previous;e.previous=t,this.changeObservations.length?this.recordChange(e,n,t):this.applyChange(e,n,t)};runBoundaryReactions(e){try{let t=this.boundaryStats;for(let n of e)if(n.declaration.captures.length){t!==void 0&&(t.captures+=n.declaration.captures.length);let e=n.frame;e.captures=n.declaration.captures.map(e=>_(_a(e.value,n.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=ma(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??=pa(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??=pa(e.declaration.body)(e.instance.host);;){let n=e.execution.next(t);if(n.done){this.boundary(`process`),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(`process`);return}if(r.kind!==`ticks`)throw TypeError(`Invalid process suspension`);let i=fa(r.duration),a=fa(this.time+i);e.state=`waiting`,this.boundary(`process`),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){let r=e.instance;this.current=r,e.state=`running`;let i=e.frame??=ga(t),a=r.host,o=n;for(;;){if(i.value=o,!t.run(a,void 0,void 0,i)){this.boundary(`process`),e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}if(i.kind===2){let t=r.channels.get(i.channel);if(t.incoming.length){o=t.incoming.shift().value;continue}e.state=`waiting`,t.receiver=e,this.boundary(`process`);return}let n=i.duration,s=fa(this.time+n);e.state=`waiting`,this.boundary(`process`),n===0?(e.state=`queued`,this.models.push(e)):(e.wake??=()=>{e.state=`queued`,this.models.push(e)},this.events.push(s,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=fa(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&&(this.waiterEpoch!==this.waitingScanEpoch||this.pollingWaiterCount!==0)){this.waitingScanEpoch=this.waiterEpoch;for(let n=0;n<this.jits.length;n++){let r=this.jits[n];if(r.active&&!r.stopped&&this.waitingJits.has(r)&&(this.watchWaiter(r),r.dependencyDirty||r.pollingWait)){if(r.instance.dependenciesCurrent(r.dependencies)){if(r.dependencyDirty=!1,r.pollingWait&&r.pollingPeriod>0){let n=da-(da-r.pollingOrigin)%r.pollingPeriod;n<72e14&&n<t&&(n===this.time?(r.pollingToken++,delete r.dependencies,this.unparkWaiter(r),this.queueJit(r)):e=Math.min(e,n))}}else if(r.dependencyDirty=!1,r.pollingWait){r.pollingToken++,delete r.dependencies,this.unparkWaiter(r);let e=r.pollingPeriod>0?(this.time-r.pollingOrigin)%r.pollingPeriod:0;e?this.events.push(fa(this.time+(r.pollingPeriod-e)),()=>this.queueJit(r)):this.queueJit(r)}else if(r.predicate){let e=r.instance.evaluate(()=>Da(r,r.predicate));r.dependencies=e.dependencies,e.value===!0?(delete r.predicate,delete r.dependencies,this.unparkWaiter(r),this.queueJit(r)):(this.watchWaiter(r),this.waiterEpoch++)}}}}if(this.time<t&&this.readyJits.length){if(xo(this,this.readyJits.shift()),this.isFaulted)throw this.primary;continue}if(e<this.events.time&&e<=t){this.time=e;continue}let n=this.events.time;if(n<=t)for(this.time=n;this.events.time===this.time;)this.events.pop()();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{Ca(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 va(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{Ca(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 Uo(e,t,n){let r=Bo.get(e);if(!r)throw Ta(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Unknown device library`),`assembly`);if(arguments.length>=3&&n===void 0)throw Ta(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Explicit undefined options`),`assembly`);return new Ho(r,t,n??{})}var X=class extends Error{name=`SimulationRuntimeError`;code;deviceId;constructor(e,t,n={}){super(t,n.cause===void 0?void 0:{cause:n.cause}),this.code=e,this.deviceId=n.deviceId}};function Wo(e){return e instanceof Error&&e.message.length>0?e.message:String(e)}let Go=[`level`,`message`];function Ko(e){return Go.includes(e)?e:void 0}let qo={boolean:`level`,number:`level`,vec2d:`level`,vec3d:`level`,string:`message`,bytes:`message`,\"bytes<rgb565>\":`message`,\"bytes<segments>\":`message`};function Jo(e){return qo[e]}function Yo(e,t){return Ko(e)??Jo(t)}let Xo=[`file`,`inline`,`store`];function Zo(e){return typeof e==`string`&&Xo.includes(e)}function Qo(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.src==`string`&&Zo(t.mode)}function $o(e){if(e.startsWith(`/`))return`must be relative to the project root, not absolute`;if(/^[A-Za-z]:/.test(e))return`must not carry a drive letter`;if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return`must not be a URL`;if(e.includes(`\\\\`))return`must use POSIX separators`;let t=e.split(`/`).find(e=>e===`..`||e.startsWith(`~`));if(t!==void 0)return`must stay inside the project root (segment \"${t}\")`}function es(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)?void 0:`must be base64 text`}function ts(e,t){return e===`inline`?es(t):e===`file`?$o(t):void 0}var ns=class extends Error{diagnostics;constructor(e){super(rs(e)),this.name=`SchematicError`,this.diagnostics=e}get code(){return this.diagnostics[0]?.code}};function rs(e){let t=e.filter(e=>e.severity===`error`),[n,...r]=t.length>0?t:e;if(n===void 0)return`Schematic validation failed.`;let i=n.pointer===void 0||n.pointer===``?``:` at ${n.pointer}`,a=r.length===0?``:` (and ${r.length} more)`;return`${n.code}${i}: ${n.message}${a}`}function is(e){if(e.some(e=>e.severity===`error`))throw new ns(e)}function as(e,t){if(typeof e!=`string`)return{ok:!0,value:e};try{return{ok:!0,value:JSON.parse(e)}}catch(e){let n=e instanceof Error?e.message:String(e);return t.push({severity:`error`,code:`json/invalid`,message:`Invalid JSON: ${n}`}),{ok:!1,value:void 0}}}let os=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ss(e){return os.test(e)}let cs={\"builtin:label\":`label`,\"builtin:power\":`power`,\"builtin:ground\":`ground`},ls=/^@[A-Za-z0-9][A-Za-z0-9._+-]*$/,us=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,ds=/^(?:[A-Za-z0-9][A-Za-z0-9._+-]*|-[A-Za-z0-9-]*)$/;function fs(e){let t=e.indexOf(`:`);if(t<=0||t===e.length-1||e.indexOf(`:`,t+1)!==-1)return;let n=e.slice(0,t),r=e.slice(t+1);if(ps(n)&&ds.test(r))return{raw:e,packageId:n,deviceId:r}}function ps(e){if(e.startsWith(`@`)){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;return n!==void 0&&r!==void 0&&ls.test(n)&&us.test(r)}return us.test(e)}function ms(e){return e===`builtin:text`}function hs(e){return cs[e]}function gs(e){switch(hs(e)){case`label`:return`net-label`;case`power`:return`power`;case`ground`:return`ground`;default:return ms(e)?`text`:`component`}}function _s(e){return e===`component`}function vs(e){return e===`net-label`||e===`power`||e===`ground`}function ys(e){return _s(gs(e.device))?e.designator??e.id:void 0}function bs(e){switch(gs(e.device)){case`power`:return e.net??`VCC`;case`ground`:return e.net??`GND`;case`net-label`:return e.net;default:return}}function xs(e){return e.length===0?``:`/${e.map(e=>e.replace(/~/g,`~0`).replace(/\\//g,`~1`)).join(`/`)}`}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ss(e){return e.some(e=>e.severity===`error`)}function Q(e,t,n,r,i){let a={severity:`error`,code:t,message:n,pointer:xs(r)};e.push(i===void 0?a:{...a,entity:i})}function Cs(e,t,n,r){for(let i of Object.keys(e))t.includes(i)||Q(r,`schema/unknown-field`,`Unknown field \"${i}\".`,[...n,i])}function ws(e,t,n,r,i={}){let a=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(typeof o!=`string`)Q(r,`schema/invalid-type`,`Field \"${t}\" must be a string.`,a);else if(i.nonEmpty===!0&&o.length===0)Q(r,`schema/invalid-value`,`Field \"${t}\" must not be empty.`,a);else return o}function Ts(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(typeof a!=`number`)Q(r,`schema/invalid-type`,`Field \"${t}\" must be a number.`,i);else if(!Number.isFinite(a))Q(r,`schema/invalid-value`,`Field \"${t}\" must be a finite number.`,i);else return a}function Es(e,t,n,r){let i=Ts(e,t,n,r);if(i!==void 0){if(!Number.isInteger(i))Q(r,`schema/invalid-value`,`Field \"${t}\" must be an integer.`,[...n,t]);else return i}}function Ds(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!Array.isArray(a))Q(r,`schema/invalid-type`,`Field \"${t}\" must be an array.`,i);else return a}function Os(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!Z(a))Q(r,`schema/invalid-type`,`Field \"${t}\" must be an object.`,i);else return a}function ks(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Point must be an object.`,t);return}Cs(e,[`x`,`y`],t,n);let r=Ts(e,`x`,t,n),i=Ts(e,`y`,t,n);if(r!==void 0&&i!==void 0)return{x:r,y:i}}function As(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Resource reference must be an object.`,t);return}Cs(e,[`src`,`mode`],t,n);let r=ws(e,`src`,t,n,{nonEmpty:!0}),i;if(Object.prototype.hasOwnProperty.call(e,`mode`)?Zo(e.mode)?i=e.mode:Q(n,`schema/invalid-value`,`Field \"mode\" must be \"file\", \"inline\" or \"store\".`,[...t,`mode`]):Q(n,`schema/missing-field`,`Missing required field \"mode\".`,[...t,`mode`]),r===void 0||i===void 0)return;let a=ts(i,r);if(a!==void 0)Q(n,`schema/invalid-value`,`Field \"src\" ${a}.`,[...t,`src`]);else return{src:r,mode:i}}function js(e,t,n){if(!Z(e)){Q(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)){if(a.length===0){Q(n,`schema/invalid-value`,`Property keys must not be empty.`,t),i=!0;continue}let e=[...t,a];if(typeof o==`string`||typeof o==`boolean`)r[a]=o;else if(o===null)r[a]=null;else if(typeof o==`number`){if(!Number.isFinite(o)){Q(n,`schema/invalid-value`,`Property \"${a}\" must be a finite number.`,e),i=!0;continue}r[a]=o}else if(typeof o==`object`&&!Array.isArray(o)){let t=As(o,e,n);if(t===void 0){i=!0;continue}r[a]=t}else Q(n,`schema/invalid-value`,`Property \"${a}\" must be a string, finite number, boolean, resource reference or null.`,e),i=!0}return i?void 0:r}function Ms(e,t,n){let r=/* @__PURE__ */ new Set;for(let i of e)r.has(i.id)?Q(n,`id/duplicate`,`Duplicate ${t} id \"${i.id}\".`,i.path,{kind:t,id:i.id}):r.add(i.id)}function Ns(e){let t=[],n=as(e,t);if(!n.ok)throw new ns(t);let r=Ps(n.value,t);if(r===void 0||Ss(t))throw new ns(t);return r}function Ps(e,t){if(!Z(e)){Q(t,`json/not-object`,`Schematic must be a JSON object.`,[]);return}Cs(e,[`version`,`sheet`],[],t);let n=Fs(e,t),r=Is(Os(e,`sheet`,[],t),t);if(n!==void 0&&r!==void 0)return{version:n,sheet:r}}function Fs(e,t){let n=Es(e,`version`,[],t);if(n!==void 0){if(n!==1)Q(t,`schema/unsupported-version`,`Unsupported version ${n}; expected 1.`,[`version`]);else return 1}}function Is(e,t){if(e===void 0)return;Cs(e,[`symbols`,`wires`,`junctions`],[`sheet`],t);let n=Ds(e,`symbols`,[`sheet`],t)??[],r=Ds(e,`wires`,[`sheet`],t)??[],i=Ds(e,`junctions`,[`sheet`],t)??[],a=[],o=[];n.forEach((e,n)=>{let r=[`sheet`,`symbols`,String(n)],i=Rs(e,r,t);i!==void 0&&(a.push(i),o.push({id:i.id,path:[...r,`id`]}))});let s=[],c=[];r.forEach((e,n)=>{let r=[`sheet`,`wires`,String(n)],i=Bs(e,r,t);i!==void 0&&(s.push(i),c.push({id:i.id,path:[...r,`id`]}))});let l=new Set(s.map(e=>e.id)),u=[],d=[];return i.forEach((e,n)=>{let r=[`sheet`,`junctions`,String(n)],i=Vs(e,r,t);if(i===void 0)return;let a=/* @__PURE__ */ new Set;i.wires.forEach((e,n)=>{let o=[...r,`wires`,String(n)];a.has(e)?Q(t,`junction/duplicate-wire`,`Junction \"${i.id}\" references wire \"${e}\" more than once.`,o,{kind:`junction`,id:i.id}):a.add(e),l.has(e)||Q(t,`junction/unknown-wire`,`Junction \"${i.id}\" references unknown wire \"${e}\".`,o,{kind:`junction`,id:i.id})}),u.push(i),d.push({id:i.id,path:[...r,`id`]})}),Ms(o,`symbol`,t),Ls(a,t),Ms(c,`wire`,t),Ms(d,`junction`,t),{symbols:a,wires:s,junctions:u}}function Ls(e,t){let n=/* @__PURE__ */ new Set;e.forEach((e,r)=>{let i=ys(e);i!==void 0&&(n.has(i)?Q(t,`symbol/designator-duplicate`,`Reference designator ${JSON.stringify(i)} is used more than once.`,[`sheet`,`symbols`,String(r),`designator`],{kind:`symbol`,id:e.id}):n.add(i))})}function Rs(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Symbol must be an object.`,t);return}Cs(e,[`id`,`device`,`x`,`y`,`rotation`,`properties`,`designator`,`net`,`reference`],t,n);let r=Hs(e,t,n),i=ws(e,`device`,t,n,{nonEmpty:!0}),a=Ts(e,`x`,t,n),o=Ts(e,`y`,t,n),s=Ts(e,`rotation`,t,n),c=e.properties===void 0?void 0:js(e.properties,[...t,`properties`],n),l=e.reference===void 0?void 0:ks(e.reference,[...t,`reference`],n),u=zs(e,`designator`,i,t,n,_s),d=zs(e,`net`,i,t,n,vs);if(i!==void 0){let r=gs(i);vs(r)&&d===void 0&&e.net===void 0&&Q(n,`symbol/missing-net`,`Symbols of role \"${r}\" must name the net they attach to.`,[...t,`net`]),!_s(r)&&e.reference!==void 0&&Q(n,`symbol/unsupported-field`,`Symbols of role \"${r}\" carry no reference designator.`,[...t,`reference`])}if(!(r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||e.reference!==void 0&&l===void 0))return{id:r,device:i,x:a,y:o,rotation:s,...c===void 0?{}:{properties:c},...u===void 0?{}:{designator:u},...d===void 0?{}:{net:d},...l===void 0?{}:{reference:l}}}function zs(e,t,n,r,i,a){if(e[t]===void 0||n===void 0)return;let o=gs(n);if(!a(o))Q(i,`symbol/unsupported-field`,`Symbols of role \"${o}\" must not declare \"${t}\".`,[...r,t]);else return ws(e,t,r,i,{nonEmpty:!0})}function Bs(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Wire must be an object.`,t);return}Cs(e,[`id`,`points`],t,n);let r=Hs(e,t,n),i=Ds(e,`points`,t,n),a=[];if(i!==void 0&&(i.length<2&&Q(n,`wire/invalid-points`,`Wire must contain at least two points.`,[...t,`points`]),i.forEach((e,r)=>{let i=ks(e,[...t,`points`,String(r)],n);i!==void 0&&a.push(i)})),r!==void 0&&i!==void 0){for(let e=1;e<a.length;e+=1){let r=a[e-1],i=a[e];if(r!==void 0&&i!==void 0&&r.x!==i.x&&r.y!==i.y){Q(n,`wire/not-orthogonal`,`Wire segments must be horizontal or vertical.`,[...t,`points`,String(e)]);return}}return{id:r,points:a}}}function Vs(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Junction must be an object.`,t);return}Cs(e,[`id`,`x`,`y`,`wires`],t,n);let r=Hs(e,t,n),i=Ts(e,`x`,t,n),a=Ts(e,`y`,t,n),o=Ds(e,`wires`,t,n),s=[];if(o!==void 0&&(o.length<2&&Q(n,`schema/invalid-value`,`Junction must reference at least two wires.`,[...t,`wires`]),o.forEach((e,r)=>{let i=[...t,`wires`,String(r)];typeof e==`string`?e.length===0?Q(n,`schema/invalid-value`,`Junction wire reference must not be empty.`,i):s.push(e):Q(n,`schema/invalid-type`,`Junction wire reference must be a string.`,i)})),r!==void 0&&i!==void 0&&a!==void 0&&o!==void 0)return{id:r,x:i,y:a,wires:s}}function Hs(e,t,n){let r=ws(e,`id`,t,n,{nonEmpty:!0});if(r!==void 0){if(!ss(r))Q(n,`schema/invalid-value`,`Field \"id\" must be a UUID v4.`,[...t,`id`]);else return r}}function Us(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function Ws(e,t,n=0){return Us(e,t)<=n}function Gs(e,t,n,r=0){let i=n.x-t.x,a=n.y-t.y,o=Math.hypot(i,a);if(o===0)return Ws(e,t,r);let s=(e.x-t.x)*a-(e.y-t.y)*i;if(Math.abs(s)/o>r)return!1;let c=((e.x-t.x)*i+(e.y-t.y)*a)/(o*o),l=r/o;return c<-l||c>1+l?!1:Ks(e,t,n)<=r}function Ks(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=r*r+i*i;if(a===0)return Us(e,t);let o=((e.x-t.x)*r+(e.y-t.y)*i)/a,s=o<0?0:o>1?1:o;return Us(e,{x:t.x+s*r,y:t.y+s*i})}function qs(e,t,n=0){if(e.length===1){let[r]=e;return r!==void 0&&Ws(r,t,n)}for(let r=1;r<e.length;r+=1){let i=e[r-1],a=e[r];if(i!==void 0&&a!==void 0&&Gs(t,i,a,n))return!0}return!1}function Js(e){let[t,...n]=e;if(t===void 0)return;let r=t.x,i=t.y,a=t.x,o=t.y;for(let e of n)r=Math.min(r,e.x),i=Math.min(i,e.y),a=Math.max(a,e.x),o=Math.max(o,e.y);return{x:r,y:i,width:a-r,height:o-i}}function Ys(e,t){if(e===void 0)return t;if(t===void 0)return e;let n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),i=Math.max(e.x+e.width,t.x+t.width),a=Math.max(e.y+e.height,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}function Xs(e,t){let n=t*Math.PI/180,r=Math.cos(n),i=Math.sin(n);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}}function Zs(e,t){let n=Xs(t,e.rotation);return{x:e.x+n.x,y:e.y+n.y}}function Qs(e,t,n){if(t!==void 0)return Js([{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x,y:t.y+t.height},{x:t.x+t.width,y:t.y+t.height}].map(t=>Zs(e,t)));let r=Object.values(n).map(t=>Zs(e,t));return r.length>0?Js(r):{x:e.x,y:e.y,width:0,height:0}}function $s(e,t={}){let n=[],r=t.tolerance??0,{devices:i}=t,{symbols:a,wires:o,junctions:s}=e.sheet,c=[],l;for(let e of a){l=Ys(l,{x:e.x,y:e.y,width:0,height:0});let t=hs(e.device);if(t!==void 0){let n=bs(e);n!==void 0&&c.push({kind:t,symbolId:e.id,point:{x:e.x,y:e.y},name:n});continue}let r=fs(e.device);if(r===void 0){i!==void 0&&n.push({severity:`error`,code:`device/invalid-reference`,message:`Symbol \"${e.id}\" has an invalid device reference ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});continue}if(i===void 0)continue;let a=i.getDeviceSymbol(r);if(i.getDeviceName(r)===void 0)n.push({severity:`error`,code:`device/unresolved`,message:`Symbol \"${e.id}\" references unresolved device ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});else if(a!==void 0){l=Ys(l,Qs(e,a.bounds,a.pins));for(let[t,n]of Object.entries(a.pins)){let r=Zs(e,n);c.push({kind:`pin`,symbolId:e.id,pinId:t,point:r}),l=Ys(l,{x:r.x,y:r.y,width:0,height:0})}}}for(let e of o)l=Ys(l,Js(e.points));let u=/* @__PURE__ */ new Map;o.forEach((e,t)=>u.set(e.id,t));let d=o.length,f=Array(d+c.length);for(let e=0;e<f.length;e+=1)f[e]=e;let p=e=>{let t=e;for(;f[t]!==t;){let e=f[t];f[t]=f[e],t=e}return t},m=(e,t)=>{let n=p(e),r=p(t);n!==r&&(f[r]=n)};for(let e of s){let[t,...n]=e.wires.map(e=>u.get(e)).filter(e=>e!==void 0);if(t!==void 0)for(let e of n)m(t,e)}let h=/* @__PURE__ */ new Map;c.forEach((e,t)=>{o.forEach((n,i)=>{if(!qs(n.points,e.point,r))return;m(i,d+t);let a=h.get(i);a===void 0?h.set(i,[t]):a.push(t)})});let g=/* @__PURE__ */ new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n={wires:[],connections:[]};return g.set(e,n),n};o.forEach((e,t)=>{_(p(t)).wires.push(t)}),c.forEach((e,t)=>{_(p(d+t)).connections.push(t)});let v=/* @__PURE__ */ new Map,y=[];for(let e of ec(g,c,n)){let t=e.wires.length>0||e.connections.length>=2;if(e.connections.length===0||!t)continue;let n=e.name,r=e.connections.map(e=>c[e]).map(e=>{if(e!==void 0)return e.kind===`pin`?{kind:`pin`,symbolId:e.symbolId,pinId:e.pinId}:{kind:e.kind,symbolId:e.symbolId}}).filter(e=>e!==void 0).sort(nc),i={name:n,wireIds:e.wires.map(e=>o[e]?.id).filter(e=>e!==void 0).sort(),members:r};y.push(i);for(let t of e.connections)v.set(t,i)}let b=[];c.forEach((e,t)=>{if(e.kind!==`pin`)return;let n=v.get(t);b.push({symbolId:e.symbolId,pinId:e.pinId,position:e.point,open:n===void 0,netName:n?.name??null})}),b.sort((e,t)=>e.symbolId.localeCompare(t.symbolId)||e.pinId.localeCompare(t.pinId));let x=[];return o.forEach((e,t)=>{let n=[{end:`start`,point:e.points[0]},{end:`end`,point:e.points[e.points.length-1]}];for(let{end:i,point:a}of n){if(a===void 0)continue;let n=(h.get(t)??[]).some(e=>{let t=c[e];return t!==void 0&&Ws(t.point,a,r)}),o=s.some(t=>t.wires.includes(e.id)&&Ws({x:t.x,y:t.y},a,r));!n&&!o&&x.push({wireId:e.id,end:i,point:a})}}),x.sort((e,t)=>e.wireId.localeCompare(t.wireId)||e.end.localeCompare(t.end)),is(n),{nets:y.sort((e,t)=>rc(e.name,t.name)||nc(e.members[0],t.members[0])),pins:b,danglingWireEnds:x,bounds:l}}function ec(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let a of e.values()){let e=a.connections.map(e=>t[e]).filter(e=>e!==void 0&&e.kind!==`pin`).map(e=>e.name).sort();e.length>1&&n.push({severity:`error`,code:`net/naming-conflict`,message:`Net has conflicting names: ${e.map(e=>JSON.stringify(e)).join(`, `)}.`});let o=e.length===1?e[0]:null;if(o===null||a.wires.length===0&&a.connections.length<2){i.push({wires:a.wires,connections:a.connections,name:o});continue}let s=r.get(o);if(s===void 0){let e={wires:[...a.wires],connections:[...a.connections]};r.set(o,e),i.push({...e,name:o})}else s.wires.push(...a.wires),s.connections.push(...a.connections)}return i}let tc=[`label`,`power`,`ground`,`pin`];function nc(e,t){if(e===void 0||t===void 0)return e===void 0?t===void 0?0:1:-1;if(e.kind!==t.kind)return tc.indexOf(e.kind)-tc.indexOf(t.kind);let n=e.symbolId.localeCompare(t.symbolId);if(n!==0)return n;let r=e.kind===`pin`?e.pinId:``,i=t.kind===`pin`?t.pinId:``;return r.localeCompare(i)}function rc(e,t){return e===null||t===null?e===null?t===null?0:1:-1:e.localeCompare(t)}function ic(e,t={}){let n=t.pinPitch??10,r=t.stubLength??10,i=t.minWidth??60,a=t.minHeight??40,o=t.horizontalPadding??10,s=t.verticalPadding??10,c=t.characterWidth??5.5,l=t.labelCharacterWidth??4.5,u=t.nameGap??12,d=t.labelInset??10,f={left:[],right:[],top:[],bottom:[]};for(let[t,n]of Object.entries(e.pins))f[n.side??`left`].push(t);let p=Math.max(f.left.length,f.right.length),m=Math.max(f.top.length,f.bottom.length),h=Math.max(a,s*2+Math.max(p-1,0)*n+n,2*(1*c+n/2+d+oc(f,l))),g=Math.max(i,o*2+Math.max(m-1,0)*n+n),_=(ac(f.left)+ac(f.right))*l+e.name.length*c+o*2+u*2,v=Math.ceil(Math.max(g,_)/n)*n,y=Math.ceil(h/n)*n,b={x:-v/2,y:-y/2,width:v,height:y},x=Object.create(null),ee=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`left`?b.x-r:b.x+b.width+r;x[e]={x:s,y:o,side:t}})};ee(f.left,`left`),ee(f.right,`right`);let te=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`top`?b.y-r:b.y+b.height+r;x[e]={x:o,y:s,side:t}})};return te(f.top,`top`),te(f.bottom,`bottom`),{name:e.name,pins:x,bounds:b}}function ac(e){return e.reduce((e,t)=>Math.max(e,t.length),0)}function oc(e,t){return Math.max(ac(e.top),ac(e.bottom))*t/2}let $=(e,t,n)=>{t.push({severity:`error`,code:`device/invalid-description`,pointer:e,message:n})},sc=(e,t,n)=>{typeof e!=`string`&&$(t,n,`Expected a string.`)},cc=(e,t,n)=>{(typeof e!=`string`||e.length===0)&&$(t,n,`Expected a nonempty string.`)},lc=(e,t,n)=>{(typeof e!=`number`||!Number.isFinite(e))&&$(t,n,`Expected a finite number.`)},uc=(e,t,n)=>{lc(e,t,n),typeof e==`number`&&e<=0&&$(t,n,`Expected a positive number.`)},dc=(e,t,n)=>{typeof e!=`boolean`&&$(t,n,`Expected a boolean.`)},fc=(...e)=>(t,n,r)=>{e.includes(t)||$(n,r,`Expected one of ${e.join(`, `)}.`)},pc=e=>e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`),mc=(e,t=[])=>(n,r,i)=>{if(!Z(n))$(r,i,`Expected an object.`);else{for(let e of t)Object.hasOwn(n,e)||$(`${r}/${pc(e)}`,i,`Required field is missing.`);for(let[t,a]of Object.entries(n)){let n=Object.hasOwn(e,t)?e[t]:void 0;n===void 0?$(`${r}/${pc(t)}`,i,`Unknown field.`):n(a,`${r}/${pc(t)}`,i)}}},hc=e=>(t,n,r)=>{if(!Z(t))$(n,r,`Expected a map.`);else for(let[i,a]of Object.entries(t))e(a,`${n}/${pc(i)}`,r)},gc=(e,t,n)=>{!Array.isArray(e)||e.length!==2?$(t,n,`Expected two coordinates.`):e.forEach((e,r)=>lc(e,`${t}/${r}`,n))},_c=(e,t,n)=>{Array.isArray(e)?(e.forEach((e,r)=>cc(e,`${t}/${r}`,n)),new Set(e).size!==e.length&&$(t,n,`Values must be unique.`)):$(t,n,`Expected an array.`)},vc=fc(`left`,`center`,`right`),yc=mc({visible:dc,position:gc,align:vc},[`visible`]),bc=(e,t,n)=>{let r={kind:fc(`number`,`text`,`textarea`,`checkbox`,`file`,`select`)};Z(e)&&e.kind===`number`&&Object.assign(r,{min:lc,max:lc,step:uc}),Z(e)&&e.kind===`file`&&(r.extensions=(e,t,n)=>{_c(e,t,n),Array.isArray(e)&&e.forEach((e,r)=>{typeof e==`string`&&!/^\\.[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*$/.test(e)&&$(`${t}/${r}`,n,`Expected a dotted filename extension.`)})},r.maxSize=(e,t,n)=>{uc(e,t,n),typeof e==`number`&&!Number.isInteger(e)&&$(t,n,`Expected an integer byte count.`)}),Z(e)&&e.kind===`select`&&(r.labels=hc(sc)),mc(r,[`kind`])(e,t,n)},xc=(e,t,n)=>{mc({type:fc(`number`,`boolean`,`string`,`enum`,`bytes`),required:dc,nullable:dc,default:()=>{},enumName:cc,values:_c,title:sc,description:sc,unit:sc,group:sc,order:(e,t,n)=>{(typeof e!=`number`||!Number.isInteger(e)||e<0)&&$(t,n,`Expected a nonnegative integer.`)},editor:bc},[`type`,`required`])(e,t,n),Z(e)&&(e.required===!0&&Object.hasOwn(e,`default`)&&$(`${t}/default`,n,`Required properties cannot declare defaults.`),e.type===`enum`?((!Object.hasOwn(e,`enumName`)||!Object.hasOwn(e,`values`))&&$(t,n,`Enum properties require enumName and values.`),Array.isArray(e.values)&&e.values.length===0&&$(`${t}/values`,n,`Enum values cannot be empty.`)):(Object.hasOwn(e,`enumName`)||Object.hasOwn(e,`values`))&&$(t,n,`Only enum properties declare enumName and values.`))},Sc=(e,t,n)=>{let r={type:fc(`line`,`polyline`,`rect`,`circle`,`arc`,`text`),fill:fc(`none`,`foreground`,`background`),strokeWidth:uc},i={line:{fields:{from:gc,to:gc},required:[`from`,`to`]},polyline:{fields:{points:(e,t,n)=>{!Array.isArray(e)||e.length<2?$(t,n,`Expected at least two points.`):e.forEach((e,r)=>gc(e,`${t}/${r}`,n))},closed:dc},required:[`points`]},rect:{fields:{x:lc,y:lc,width:uc,height:uc},required:[`x`,`y`,`width`,`height`]},circle:{fields:{center:gc,radius:uc},required:[`center`,`radius`]},arc:{fields:{center:gc,radius:uc,startAngle:lc,sweepAngle:(e,t,n)=>{lc(e,t,n),typeof e==`number`&&(e===0||e<-360||e>360)&&$(t,n,`Sweep must be nonzero and within [-360, 360].`)}},required:[`center`,`radius`,`startAngle`,`sweepAngle`]},text:{fields:{position:gc,text:sc,align:vc,fontSize:uc},required:[`position`,`text`]}},a=Z(e)&&typeof e.type==`string`&&Object.hasOwn(i,e.type)?i[e.type]:void 0;mc({...r,...a?.fields},[`type`,...a?.required??[]])(e,t,n)},Cc=(e,t,n)=>{Array.isArray(e)?e.forEach((e,r)=>Sc(e,`${t}/${r}`,n)):$(t,n,`Expected graphics array.`)},wc=mc({designator:mc({position:gc,align:vc},[`position`])}),Tc=mc({kind:fc(`device`),id:(e,t,n)=>{(typeof e!=`string`||!/^[A-Za-z0-9-]+$/.test(e))&&$(t,n,`Invalid device id.`)},version:cc,displayName:cc,description:cc,license:cc,tags:_c,templates:_c,recommends:mc({widgets:_c}),designatorPrefix:(e,t,n)=>{(typeof e!=`string`||!/^\\S+$/.test(e))&&$(t,n,`Expected a nonempty prefix without whitespace.`)},properties:hc(xc),pins:hc(mc({label:sc,description:sc,group:sc})),ports:hc(mc({direction:fc(`input`,`output`),type:fc(`boolean`,`number`,`string`,`vec2d`,`vec3d`,`bytes`,`bytes<rgb565>`,`bytes<segments>`),title:sc,description:sc,delivery:fc(`level`,`message`)},[`direction`,`type`])),symbol:mc({bounds:mc({x:lc,y:lc,width:uc,height:uc},[`x`,`y`,`width`,`height`]),graphics:Cc,pins:hc(mc({position:gc,direction:fc(`left`,`right`,`up`,`down`),label:yc},[`position`,`direction`])),annotations:wc},[`bounds`,`graphics`,`pins`])},[`kind`,`id`,`version`,`displayName`]);function Ec(e){let t=[],n=as(e,t);if(n.ok&&Tc(n.value,``,t),t.length>0)throw new ns(t);return n.value}function Dc(e){let t=e.symbol,n=t===void 0?ic({name:e.displayName,pins:Object.fromEntries(Object.keys(e.pins??{}).map(e=>[e,{}]))}):void 0,r=Object.create(null);for(let[i,a]of Object.entries(t?.pins??n.pins)){let n=e.pins?.[i]?.label;if(t!==void 0){let e=t.pins[i];r[i]={x:e.position[0],y:e.position[1],side:e.direction===`up`?`top`:e.direction===`down`?`bottom`:e.direction,...e.label===void 0?{}:{label:e.label},...n===void 0?{}:{displayName:n}}}else r[i]={...a,...n===void 0?{}:{displayName:n}}}return t===void 0?{...n,pins:r}:{name:e.displayName,bounds:t.bounds,graphics:t.graphics,pins:r,...t.annotations===void 0?{}:{annotations:t.annotations}}}async function Oc(e,t,n){if(!Nc(e)||!Array.isArray(e.devices))throw new X(`invalid-input`,`Expected schematic and devices`);let r=Ns(e.schematic),i=jc(e.assets),a=Ac(e.voltageReferences),o=/* @__PURE__ */ new Map;for(let t of e.devices){if(!Nc(t)||typeof t.id!=`string`||fs(t.id)===void 0||o.has(t.id)||typeof t.code!=`string`||t.code.trim().length===0)throw new X(`invalid-input`,`Expected unique device ids and self-contained ESM code`);let e;try{e=structuredClone(Ec(t.definition))}catch(e){throw new X(`invalid-device`,`Invalid metadata for \"${t.id}\": ${Wo(e)}`,{cause:e})}if(e.id!==fs(t.id).deviceId)throw new X(`invalid-device`,`Metadata id does not match \"${t.id}\"`,{deviceId:t.id});o.set(t.id,{definition:e,code:t.code})}let s=/* @__PURE__ */ new Map,c=r.sheet.symbols.filter(e=>gs(e.device)===`component`);for(let e of c){if(s.has(e.device))continue;let r=o.get(e.device);if(r===void 0)throw new X(`unresolved-device`,`Missing prepared device \"${e.device}\"`,{deviceId:e.device});n();try{let i=await t(r.code,e.device);if(n(),!Nc(i)||!Object.hasOwn(i,`model`)||!Object.hasOwn(i,`create`)||typeof i.create!=`function`)throw TypeError(`SDK device modules must export named model and synchronous create`);let a=Xe(i.model),o=a.declarations.filter(e=>e.kind===`pin`).map(e=>e.name),c=r.definition.pins;if(c!==void 0&&!Mc(Object.keys(c),o))throw TypeError(`Metadata pins do not match model pins`);let l={...r.definition,pins:c??Object.fromEntries(o.map(e=>[e,{}]))},u=Dc(l);if(!Mc(Object.keys(u.pins),o))throw TypeError(`Symbol pins do not match model pins`);s.set(e.device,{id:e.device,definition:l,model:a,create:i.create,topics:new Map(Object.entries(l.ports??{}).map(([e,t])=>[e,{port:e,...t,delivery:Yo(t.delivery,t.type)}]))})}catch(t){throw n(),new X(`invalid-device`,`Device \"${e.device}\" failed to load: ${Wo(t)}`,{deviceId:e.device,cause:t})}}let l=$s(r,{devices:{getDeviceName:e=>s.get(e.raw)?.definition.displayName,getDeviceSymbol:e=>{let t=s.get(e.raw);return t===void 0?void 0:Dc(t.definition)}}}),u=r.sheet.symbols.length===0&&r.sheet.wires.length===0&&r.sheet.junctions.length===0;for(let e of a.keys())if(!u&&!l.nets.some(t=>t.name===e))throw new X(`invalid-input`,`Voltage reference names missing schematic net \"${e}\"`);return{instances:c.map(e=>({symbol:e.id,device:s.get(e.device)})),...e.execution===void 0?{}:{execution:e.execution},description:{instances:c.map(e=>({id:e.id,type:e.id,props:kc(e,s.get(e.device),i.get(e.id))})),nets:l.nets.map((e,t)=>{let n=e.name===null?void 0:a.get(e.name),r=e.members.some(e=>e.kind===`ground`);if(r&&n!==void 0&&n!==0)throw new X(`invalid-input`,`Conflicting voltage references on ground net \"${e.name}\": 0 and ${n}`);let i=r?0:n;return{id:`net:${t}`,pins:e.members.flatMap(e=>e.kind===`pin`?[{instance:e.symbolId,pin:e.pinId}]:[]),...i===void 0?{}:{voltage:i}}})}}}function kc(e,t,n){let r=Object.create(null);for(let[e,n]of Object.entries(t.definition.properties??{}))Object.hasOwn(n,`default`)&&(r[e]=n.default);Object.assign(r,e.properties);let i=Object.create(null);for(let[a,o]of Object.entries(r))if(Qo(o)){let r=ts(o.mode,o.src);if(r!==void 0)throw new X(`invalid-input`,r,{deviceId:t.id});let s=n?.get(o.src);if(s===void 0)throw new X(`unresolved-asset`,`Symbol \"${e.id}\" is missing resource \"${o.src}\"`,{deviceId:t.id});i[a]=new Uint8Array(s)}else if(o instanceof Uint8Array)i[a]=new Uint8Array(o);else if(o===null||typeof o==`number`||typeof o==`boolean`||typeof o==`string`)i[a]=o;else throw new X(`invalid-input`,`Unsupported property \"${e.id}.${a}\"`,{deviceId:t.id});return i}function Ac(e){if(e===void 0)return/* @__PURE__ */ new Map;if(!Nc(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new X(`invalid-input`,`Expected a plain voltageReferences map`);let t=/* @__PURE__ */ new Map;for(let n of Reflect.ownKeys(e)){let r=typeof n==`string`?e[n]:void 0;if(typeof n!=`string`||n.trim().length===0||typeof r!=`number`||!Number.isFinite(r))throw new X(`invalid-input`,`Expected voltageReferences with nonempty net names and finite numeric voltages`);t.set(n,r)}return t}function jc(e){let t=/* @__PURE__ */ new Map;if(e===void 0)return t;if(!Nc(e))throw new X(`invalid-input`,`Expected assets keyed by symbol id`);for(let[n,r]of Object.entries(e)){if(!Nc(r))throw new X(`invalid-input`,`Expected asset entries keyed by src`);let e=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(r)){if(!t||!(n instanceof Uint8Array))throw new X(`invalid-input`,`Resource bytes must be Uint8Array`);e.set(t,new Uint8Array(n))}t.set(n,e)}return t}function Mc(e,t){return e.length===t.length&&e.every(e=>t.includes(e))}function Nc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pc(e={}){let n=new t,r=new t,i=[],a=/* @__PURE__ */ new Map,o,s=ce(0),c=!1,l=0,u=()=>{if(c)throw new X(`disposed`,`Simulation runtime has been disposed`)},d=e=>{if(n.hasListeners)for(let t of e.outputs.splice(0)){if(t.delivery===`level`){let e=C(t.symbol,t.port);if(a.has(e)&&ne(a.get(e),t.payload))continue;n.hasListeners&&a.set(e,D(t.payload))}n.fire({target:{symbol:t.symbol,port:t.port},payload:t.payload,simTime:s})}else e.outputs.length=0;for(let t of e.diagnostics.splice(0))r.fire(t.runtimeCode===void 0?{...t,simTime:s}:t)},f=e=>{if(e!==void 0)try{e.board.dispose()}catch(e){r.fire({code:`board/diagnostic`,symbol:``,message:Wo(e),simTime:s,phase:`dispose`})}finally{for(let t of e.subscriptions)t.dispose()}},p=e=>{let t=o;o=e,i.length=0,a.clear(),s=ce(0),f(t)};return{async load(t){u();let r=++l,i=await Oc(t,e.importer??Rc,u);u(),r===l&&p(Fc(i,()=>n.hasListeners))},async reset(){u(),++l,o===void 0?(i.length=0,a.clear(),s=ce(0)):p(Fc(o.prepared,()=>n.hasListeners))},async tick(e){if(u(),!Number.isSafeInteger(e)||e<=0)throw TypeError(`tick expects a positive integer dt in picoseconds`);let t=le(s,e),n=o;if(n===void 0)return s=t,{simTime:s,executed:0};try{for(let e of i.splice(0))n.board.topics.publish(Lc(e.symbol,e.port),e.payload);n.board.runUntil(t)}finally{s=ce(n.board.time),d(n)}return{simTime:s,executed:1}},async deliver(e){if(u(),typeof e!=`object`||!e||e.target===null||typeof e.target!=`object`||typeof e.target.symbol!=`string`||typeof e.target.port!=`string`)throw new X(`invalid-input`,`Expected a message with string symbol and port`);if(o===void 0)throw new X(`not-loaded`,`No simulation loaded`);let{symbol:t,port:n}=e.target,r=o.inputs.get(C(t,n));if(r===void 0||!E(r.type,e.payload))throw new X(`invalid-input`,`Unknown input or invalid payload for ${t}.${n}`);if(r.delivery===`level`){let e=i.findIndex(e=>e.symbol===t&&e.port===n);e!==-1&&i.splice(e,1)}i.push({symbol:t,port:n,payload:D(e.payload)})},onDidPublish:n.event,onDidDiagnostic:r.event,async dispose(){c||(c=!0,++l,i.length=0,a.clear(),f(o),o=void 0,n.dispose(),r.dispose())}}}function Fc(e,t){let n=[],r=[],i=/* @__PURE__ */ new Map,a=Uo(Vo(e.instances.map(e=>{for(let t of e.device.topics.values())t.direction===`input`&&i.set(C(e.symbol,t.port),t);return{id:e.symbol,model:e.device.model,create:i=>e.device.create({...i,topics:Ic(i.topics,e,n,r,t)})}})),{...e.description,instances:e.description.instances.map(e=>({...e,props:Object.fromEntries(Object.entries(e.props??{}).map(([e,t])=>[e,t instanceof Uint8Array?new Uint8Array(t):t]))}))},e.execution===void 0?{}:{execution:e.execution}),o=(e,t)=>{r.push({code:t?e.phase===`topic`?`device/input-failed`:e.phase===`sync`?`device/output-failed`:`board/error`:`board/diagnostic`,symbol:e.instanceId??``,message:e.message,simTime:ce(e.time??a.time),runtimeCode:e.code,phase:e.phase})};return{prepared:e,board:a,inputs:i,outputs:n,diagnostics:r,subscriptions:[a.onDidError(e=>o(e,!0)),a.onDidDiagnostic(e=>o(e,!1))]}}function Ic(e,t,n,r,i){let a=`${encodeURIComponent(t.symbol)}/`,o=jo(e),s=0,c=()=>s===0&&o.hostListeners()===0&&!i();return{onDidReceive:((n,r,i)=>{let o=e.onDidReceive(e=>{if(!e.topic.startsWith(a))return;let i=e.topic.slice(a.length);if(t.device.topics.get(i)?.direction===`input`)return n.call(r,{topic:i,payload:D(e.payload)})},void 0,void 0);s++;let c=!0,l={dispose:()=>{c&&(c=!1,s--,o.dispose())}};return i?.push(l),l}),publish(i,a){let s=t.device.topics.get(i);if(s?.direction!==`output`||!E(s.type,a)){r.push({code:`device/output-failed`,symbol:t.symbol,port:i,message:`Unknown output or invalid payload for ${t.symbol}.${i}`,simTime:ce(0)});return}if(c()){o.assertPublishAllowed();return}let l=D(a);e.publish(Lc(t.symbol,i),l),n.push({symbol:t.symbol,port:i,payload:l,delivery:s.delivery})}}}function Lc(e,t){return`${encodeURIComponent(e)}/${t}`}function Rc(e){if(typeof URL>`u`||typeof URL.createObjectURL!=`function`||typeof Blob>`u`)return Promise.reject(/* @__PURE__ */ Error(`Inject a module importer outside a browser worker`));let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}function zc(e,t,n){let r=Hc(t),i=e.register(ie,r,{transfer:oe}),a=n===void 0?void 0:n.register(ae,{deliver:r.deliver,onDidPublish:r.onDidPublish,async flushPublishes(){}},{transfer:oe}),o=!1;return{dispose(){if(!o){o=!0;try{a?.dispose()}finally{i.dispose()}}}}}function Bc(e,t={}){let n=a(e),r=Pc(Vc(t)),i=t.ports??[],o=i[0],s=o===void 0?void 0:a(o),c=zc(n,r,s),l=!1;return{rpc:n,ports:i,runtime:r,async dispose(){if(!l){l=!0;try{c.dispose(),await r.dispose()}finally{s?.dispose(),n.dispose(),e.close();for(let e of i)e.close()}}}}}function Vc(e){return{...e.importer===void 0?{}:{importer:e.importer}}}function Hc(e){return{load:t=>e.load(t),reset:()=>e.reset(),tick:t=>e.tick(t),deliver:t=>e.deliver(t),onDidPublish:t=>{let n=e.onDidPublish(e=>t(Uc(e)));return()=>n.dispose()},onDidDiagnostic(t){let n=e.onDidDiagnostic(t);return()=>n.dispose()},dispose:()=>e.dispose()}}function Uc(e){let t=re(e.payload);return t===e.payload?e:{...e,payload:t}}globalThis.addEventListener(`message`,function e(t){let[n,...r]=t.ports;n!==void 0&&(globalThis.removeEventListener(`message`,e),Bc(n,{ports:r}))})})();";
|
|
7
7
|
//#endregion
|
|
8
8
|
//#region src/simulation-runtime/adapter.ts
|
|
9
9
|
/**
|