@volter/browser-substrate 0.1.115 → 0.1.116

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.
Files changed (25) hide show
  1. package/dist/cli/package-packs.js +4 -4
  2. package/dist/cli/package-packs.js.map +1 -1
  3. package/dist/shell/assets/browser-opfs-filesystem-worker-CivfnvV7.js +3 -0
  4. package/dist/shell/assets/{browser-sandbox-bridge-CmMlTDpO.js → browser-sandbox-bridge-BOyO6Vq0.js} +2 -2
  5. package/dist/shell/assets/filesystem-host-B-fDKRNE.js +3 -0
  6. package/dist/shell/assets/{filesystem-host-D98WfBoD.js → filesystem-host-Cngy2ePX.js} +1 -1
  7. package/dist/shell/assets/filesystem-worker-BQAYsjDk.js +5 -0
  8. package/dist/shell/assets/{fork-worker-hBikLg_q.js → fork-worker-BOu5dHuR.js} +1 -1
  9. package/dist/shell/assets/{node-execution-worker-714dbca4282e90ae.js → node-execution-worker-e4ab9bf7f09262f8.js} +2 -2
  10. package/dist/shell/assets/{sandbox-qgjYY5Gr.js → sandbox-C41DorhH.js} +1 -1
  11. package/dist/shell/assets/{shell-C0qfPTpQ.js → shell-CdIq-SFl.js} +4 -4
  12. package/dist/shell/assets/worker-BCIFrV5h.js +816 -0
  13. package/dist/shell/assets/worker-program-worker-BEQYJYct.js +27 -0
  14. package/dist/shell/index.html +2 -2
  15. package/dist/shell/node-execution-worker.js +25 -9
  16. package/dist/shell/python-execution-worker.js +24 -8
  17. package/dist/shell/python-runtime-snapshot.bin +0 -0
  18. package/dist/shell/python-runtime-snapshot.json +1 -1
  19. package/dist/shell/sandbox.html +2 -2
  20. package/package.json +1 -1
  21. package/dist/shell/assets/browser-opfs-filesystem-worker-TLQsaODy.js +0 -3
  22. package/dist/shell/assets/filesystem-host-EfkgP9Jh.js +0 -3
  23. package/dist/shell/assets/filesystem-worker-51BLqPs5.js +0 -5
  24. package/dist/shell/assets/worker-BZ-Txq9L.js +0 -816
  25. package/dist/shell/assets/worker-program-worker-B_u8gbzh.js +0 -27
@@ -0,0 +1,27 @@
1
+ const Ks=["file","directory","symlink"],dc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,uc=new TextEncoder,mc=new TextDecoder;function oa(s){let e=2166136261;for(let t=0;t<s.length;t+=1)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function Ri(s,e){const t=[...s.keys()];for(const v of t)if(dc.test(v))throw new Error("A path in the store is not well-formed UTF-16.");const r=new Map;for(let v=0;v<t.length;v+=1)r.set(t[v],v);for(const v of e.keys())r.has(v)||(r.set(v,t.length),t.push(v));const n=t.length,i=new Map,o=new Uint32Array(n);let a=0;for(let v=0;v<n;v+=1){const T=t[v];let Q=!0;for(let ae=0;ae<T.length;ae+=1)if(T.charCodeAt(ae)>=128){Q=!1;break}Q||i.set(v,uc.encode(T)),o[v]=Q?T.length:i.get(v).length,a+=o[v]}let c=0;for(const v of e.values())c+=v.size;let f=1;for(;f<n*2;)f<<=1;const d=24,y=Xs(d+n*6*4,8),p=y+n*3*8,A=p+f*4,k=A+c*4,_=new SharedArrayBuffer(Xs(k+a,8));new Uint32Array(_,0,6).set([2019846480,n,f,c,a,s.size]);const L=new Uint32Array(_,d,n*6),x=new Float64Array(_,y,n*3),D=new Uint32Array(_,p,f),z=new Uint32Array(_,A,c),oe=new Uint8Array(_,k,a);let fe=0,j=0;for(let v=0;v<n;v+=1){const T=t[v],Q=v*6,ae=i.get(v);if(ae)oe.set(ae,fe);else for(let re=0;re<T.length;re+=1)oe[fe+re]=T.charCodeAt(re);const Ae=o[v];L[Q+0]=fe,L[Q+1]=Ae,fe+=Ae;let Me=ae?0:32;const F=s.get(T);if(F){Me|=1|Ks.indexOf(F.type)<<3,F.pack&&(Me|=4),L[Q+3]=F.mode;const re=v*3;x[re+0]=F.mtimeMs,x[re+1]=F.offset,x[re+2]=F.length}const W=e.get(T);if(W){Me|=2,L[Q+4]=j,L[Q+5]=W.size;for(const re of W){const mt=r.get(`${T}/${re}`);if(mt===void 0)throw new Error(`The store's children name ${T}/${re}, which its index does not hold.`);z[j++]=mt}}L[Q+2]=Me;let ue=oa(T)&f-1;for(;D[ue]!==0;)ue=ue+1&f-1;D[ue]=v+1}if(j!==c)throw new Error("The shared index's children did not add up.");return _}function Xs(s,e){return Math.ceil(s/e)*e}class Yt{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,6);if(t[0]!==2019846480)throw new Error("Not a shared store index.");const[,r,n,i,o,a]=t;this.buffer=e,this.count=r,this.entryCount=a;const c=24,f=Xs(c+r*6*4,8),d=f+r*3*8,y=d+n*4,p=y+i*4;this.records=new Uint32Array(e,c,r*6),this.numbers=new Float64Array(e,f,r*3),this.table=new Uint32Array(e,d,n),this.childList=new Uint32Array(e,y,i),this.strings=new Uint8Array(e,p,o),this.mask=n-1}find(e){let t=oa(e)&this.mask;for(;;){const r=this.table[t];if(r===0)return-1;if(this.pathIs(r-1,e))return r-1;t=t+1&this.mask}}entry(e){const t=e*6,r=this.records[t+2];if(!(r&1))return;const n=e*3,i={type:Ks[r>>>3&3],mode:this.records[t+3],mtimeMs:this.numbers[n+0],offset:this.numbers[n+1],length:this.numbers[n+2]};return r&4&&(i.pack="packages"),i}typeAt(e){const t=this.records[e*6+2];return t&1?Ks[t>>>3&3]:void 0}hasEntry(e){return(this.records[e*6+2]&1)!==0}childNames(e){const t=e*6;if(!(this.records[t+2]&2))return;const r=this.records[t+4],n=this.records[t+1]+1,i=[];for(let o=0;o<this.records[t+5];o+=1){const a=this.childList[r+o]*6;i.push(this.decode(this.records[a+0]+n,this.records[a+1]-n,(this.records[a+2]&32)!==0))}return i}path(e){const t=e*6;return this.decode(this.records[t+0],this.records[t+1],(this.records[t+2]&32)!==0)}decode(e,t,r){if(!r)return mc.decode(this.strings.slice(e,e+t));let n="";for(let i=e,o=e+t;i<o;i+=4096)n+=String.fromCharCode.apply(null,this.strings.subarray(i,Math.min(o,i+4096)));return n}pathIs(e,t){const r=e*6,n=this.records[r+0],i=this.records[r+1];if(!(this.records[r+2]&32))return this.path(e)===t;if(i!==t.length)return!1;for(let o=0;o<i;o+=1)if(this.strings[n+o]!==t.charCodeAt(o))return!1;return!0}}const Ze=Symbol("deleted");function aa(s,e){return s===e||!!s&&!!e&&s.type===e.type&&s.offset===e.offset&&s.length===e.length&&s.pack===e.pack&&s.mode===e.mode&&s.mtimeMs===e.mtimeMs&&s.capacity===e.capacity}class rr{base;overlay=new Map;delta=0;constructor(e){this.base=e}get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===Ze?void 0:t;const r=this.base.find(e);return r<0?void 0:this.base.entry(r)}typeOf(e){const t=this.overlay.get(e);if(t!==void 0)return t===Ze?void 0:t.type;const r=this.base.find(e);return r<0?void 0:this.base.typeAt(r)}has(e){const t=this.overlay.get(e);if(t!==void 0)return t!==Ze;const r=this.base.find(e);return r>=0&&this.base.hasEntry(r)}set(e,t){this.has(e)||(this.delta+=1);const r=this.base.find(e);return r>=0&&aa(this.base.entry(r),t)?this.overlay.delete(e):this.overlay.set(e,t),this}delete(e){if(!this.has(e))return!1;const t=this.base.find(e);return t>=0&&this.base.hasEntry(t)?this.overlay.set(e,Ze):this.overlay.delete(e),this.delta-=1,!0}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[e,t]of this.overlay)t!==Ze&&(yield[e,t]);for(let e=0;e<this.base.count;e+=1){if(!this.base.hasEntry(e))continue;const t=this.base.path(e);this.overlay.has(t)||(yield[t,this.base.entry(e)])}}*keys(){for(const[e]of this.entries())yield e}*values(){for(const[,e]of this.entries())yield e}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[r,n]of this.entries())e.call(t,n,r,this)}*changed(){for(const[e,t]of this.overlay)t!==Ze&&(yield[e,t])}*changes(){for(const[e,t]of this.overlay)yield[e,t===Ze?null:t]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const e=[];let t=0;for(const[r,n]of this.changes()){if(t+=r.length*2+128,t>8*1024*1024)return;e.push([r,n])}return e}}class Jr{base;overlay=new Map;constructor(e){this.base=e}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===Ze?void 0:t;const r=this.base.find(e),n=r<0?void 0:this.base.childNames(r);return n?new Set(n):void 0}mutable(e){const t=this.overlay.get(e);if(t!==void 0&&t!==Ze)return t;const r=new Set(t===Ze?[]:this.get(e)??[]);return this.overlay.set(e,r),r}delete(e){this.overlay.set(e,Ze)}}function vi(s){const e=s.lastIndexOf("/");return e<=0?"/":s.slice(0,e)}function dr(s){return s==="/"?"":s}const yc="/opt/tree";function wc(s){return`volter-tree-store-use:${s}`}function pc(s,e=globalThis.navigator?.locks){if(!e)return Promise.resolve();let t=Ti.get(e);t||Ti.set(e,t=new Map);let r=t.get(s);if(!r){r=new Promise((i,o)=>{e.request(wc(s),{mode:"shared"},()=>(i(),new Promise(()=>{}))).catch(o)});const n=t;r.catch(()=>n.delete(s)),t.set(s,r)}return r}const Ti=new WeakMap;function gc(s,e){const t=new Yt(s.index),r=new rr(t),n=new Jr(t),i={childrenOf:a=>[...n.get(dr(a))??[]].sort(),descendants(a){const c=[],f=d=>{const y=r.get(d);y&&c.push([d,y]);for(const p of n.get(dr(d))??[])f(`${dr(d)}/${p}`)};return f(a),c}};if(s.store!==void 0){const a=e?.get(s.store),c=s.roots?.[0]??"/",f=s.storeRoot??c,d=p=>f+p.slice(c==="/"?0:c.length),y=p=>{const A=r.get(p);if(!A||A.type==="directory")throw new Error(`The shared layer holds no file at ${p}.`);if(!a)throw new Error(`${p} is in the store ${s.store}, which this realm did not open.`);return a};return{entries:r,read:p=>y(p).read(d(p)),readRange:(p,A,k)=>y(p).readRange(d(p),A,k),readsByRange:()=>!0,...i}}if(!s.bytes)throw new Error("A shared layer holds neither its bytes nor a store of them.");const o=new Uint8Array(s.bytes);return{entries:r,read(a){const c=r.get(a);if(!c||c.type==="directory")throw new Error(`The shared layer holds no file at ${a}.`);return o.slice(c.offset,c.offset+c.length)},view(a){const c=r.get(a);if(!c||c.type==="directory")throw new Error(`The shared layer holds no file at ${a}.`);return o.subarray(c.offset,c.offset+c.length)},readRange(a,c,f){const d=r.get(a);if(!d||d.type==="directory")throw new Error(`The shared layer holds no file at ${a}.`);const y=Math.min(Math.max(0,c),d.length);return o.slice(d.offset+y,d.offset+Math.min(d.length,y+Math.max(0,f)))},childrenOf:a=>[...n.get(dr(a))??[]].sort(),descendants(a){const c=[],f=d=>{const y=r.get(d);y&&c.push([d,y]);for(const p of n.get(dr(d))??[])f(`${dr(d)}/${p}`)};return f(a),c}}}function Sc(s){if(s.length===1)return s[0];const e=(o,a)=>{if(o===0)return!1;for(let c=vi(a);;c=vi(c)){for(let f=0;f<o;f+=1){const d=s[f].entries.get(c);if(d&&d.type!=="directory")return!0}if(c==="/")return!1}},t=o=>{for(let a=0;a<s.length;a+=1)if(s[a].entries.has(o)&&!e(a,o))return a;return-1},r=o=>s[t(o)],n={get:o=>r(o)?.entries.get(o),has:o=>t(o)>=0,get size(){let o=0;for(const a of n)o+=1;return o},*[Symbol.iterator](){const o=new Set;for(let a=0;a<s.length;a+=1)for(const[c,f]of s[a].entries)o.has(c)||t(c)!==a||(o.add(c),yield[c,f])},*entries(){yield*n[Symbol.iterator]()},*keys(){for(const[o]of n)yield o},*values(){for(const[,o]of n)yield o},forEach(o){for(const[a,c]of n)o(c,a,n)}},i=o=>{const a=r(o)?.entries.get(o);return a&&a.type!=="directory"?[]:s.filter((c,f)=>{const d=c.entries.get(o);return(!d||d.type==="directory")&&!e(f,o)})};return{entries:n,read:o=>{const a=r(o);if(!a)throw new Error(`No lower tree holds ${o}.`);return a.read(o)},view:o=>{const a=r(o);if(!a)throw new Error(`No lower tree holds ${o}.`);return a.view?a.view(o):a.read(o)},readRange:(o,a,c)=>{const f=r(o);if(!f)throw new Error(`No lower tree holds ${o}.`);if(f.readRange)return f.readRange(o,a,c);const d=f.read(o),y=Math.min(Math.max(0,a),d.byteLength);return d.slice(y,Math.min(d.byteLength,y+Math.max(0,c)))},readsByRange:o=>r(o)?.readsByRange?.(o)??!1,childrenOf:o=>[...new Set(i(o).flatMap(a=>a.childrenOf(o)))].sort(),descendants:o=>{const a=[],c=new Set;for(const d of s)for(const[y]of d.descendants(o)){if(c.has(y))continue;c.add(y);const p=n.get(y);p&&a.push([y,p])}const f=a.findIndex(([d])=>d===o);return f>0&&a.unshift(...a.splice(f,1)),a}}}function Fi(s,e,t){const r=[...s?[s]:[],...(e??[]).map(n=>gc(n,t))];return r.length===0?void 0:Sc(r)}const bc="supercode-browser-filesystems",Ct="packages",Ec="state.json",Bi="/image-range-worker.js",Oi="image-ranges.json",Ac=2;function ls(s){const e=s;if(!e||e.version!==1||!Number.isSafeInteger(e.bytes)||e.bytes<0||!Array.isArray(e.parts)||e.image!==void 0&&(typeof e.image!="string"||!/^[a-f0-9]{16,64}$/u.test(e.image))||e.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let t=0;for(const r of e.parts){if(!r||r.offset!==t||!Number.isSafeInteger(r.raw)||r.raw<0||!Number.isSafeInteger(r.bytes)||r.bytes<0||r.bytes>1024*1024*1024||r.raw>1024*1024*1024||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/u.test(r.sha256)||typeof r.url!="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(r.url)||r.url.split("/").some(n=>n==="."||n===".."))throw new Error("Invalid immutable image part.");if(t+=r.raw,!Number.isSafeInteger(t))throw new Error("Immutable image ranges exceed the offset limit.")}if(t!==e.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return e}const Di=new Map;class _c{ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=!1;ready=!1;startup;cancelStartup;sharedCompletion;constructor(e,t,r,n,i,o){if(this.ranges=e,this.directory=t,this.identity=r,this.receiptKey=i,this.client=o,typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("This browser cannot materialize an immutable image during a synchronous read.");if(this.state=new Int32Array(o?.state??new SharedArrayBuffer(e.parts.length*Int32Array.BYTES_PER_ELEMENT)),this.state.length!==e.parts.length)throw new Error("The image reader's line has the wrong range count.");const a=e.parts.length,c=n??new SharedArrayBuffer((2*a+1)*Int32Array.BYTES_PER_ELEMENT);if(c.byteLength!==a*Int32Array.BYTES_PER_ELEMENT&&c.byteLength!==(2*a+1)*Int32Array.BYTES_PER_ELEMENT)throw new Error("The image completion seed has the wrong range count.");this.completed=new Int32Array(c,0,a),this.firstRead=c.byteLength>a*Int32Array.BYTES_PER_ELEMENT?new Int32Array(c,a*Int32Array.BYTES_PER_ELEMENT,a+1):void 0,this.sharedCompletion=n!==void 0;for(const f of e.parts)Object.freeze(f);Object.freeze(e.parts),Object.freeze(e)}get completionBuffer(){return this.completed.buffer}get verifiedRanges(){return this.ranges}async initialize(){if(this.closed)throw new Error("This immutable image reader is closed.");if(this.ready)return;if(this.startup)return this.startup;let e=!1;for(let t=0;t<this.completed.length;t+=1)if(Atomics.load(this.completed,t)!==2){e=!0;break}if(!e){this.ready=!0,this.client?.port.close();return}if(this.client){const t=this.port=this.client.port;t.onmessage=r=>{r.data?.type!=="closing"||this.port!==t||(t.close(),this.port=void 0,this.closed||this.startMaterializer().catch(n=>console.warn("This process's image reader could not start its own materializer after its line closed.",n)))},t.start(),this.ready=!0;return}return this.startMaterializer()}startMaterializer(){const e=Date.now(),t=new Worker(Bi,{type:"module",name:"immutable-image-materializer"}),r=this.ready;return r||(this.worker=t),t.addEventListener("error",()=>this.fail()),t.addEventListener("messageerror",()=>this.fail()),this.startup=new Promise((n,i)=>{const o=()=>{clearTimeout(d),t.removeEventListener("message",f),t.removeEventListener("error",a),t.removeEventListener("messageerror",a),this.cancelStartup=void 0},a=()=>c(new Error("The immutable image materializer could not initialize; reload to retry.")),c=y=>{o(),t.terminate(),r||(this.closed=!0,this.fail()),i(y)},f=y=>{if(y.data?.identity===this.identity){if(y.data.type==="init-error"){c(new Error(`The immutable image materializer could not initialize: ${String(y.data.error)}`));return}y.data.type==="ready"&&(console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-e})}`),o(),this.ready=!0,this.worker=t,n())}},d=setTimeout(()=>c(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=c,t.addEventListener("message",f),t.addEventListener("error",a),t.addEventListener("messageerror",a);try{t.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:this.state.buffer,completed:this.completed.buffer,sharedCompletion:this.sharedCompletion,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}catch(y){c(y instanceof Error?y:new Error(String(y)))}}),this.startup}readDigests(){const e=this.firstRead;if(!e)return;const t=this.ranges.parts.length,r=[];for(let n=0;n<t;n+=1){const i=Atomics.load(e,n),o=this.ranges.parts[n];i>0&&o.raw>0&&r.push([i,o.sha256])}return r.sort((n,i)=>n[0]-i[0]).map(([,n])=>n)}completedDigests(){const e=[];for(let t=0;t<this.completed.length;t+=1){const r=this.ranges.parts[t];r.raw>0&&Atomics.load(this.completed,t)===2&&e.push(r.sha256)}return e}prefetch(e,t=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const r=new Map;for(let a=0;a<this.ranges.parts.length;a+=1){const c=this.ranges.parts[a];if(c.raw===0)continue;const f=r.get(c.sha256);f?f.push(a):r.set(c.sha256,[a])}const n=[];for(const a of new Set(e))for(const c of r.get(a)??[])Atomics.load(this.completed,c)!==2&&n.push(c);const i=t.length>0&&n.length>0?Math.min(t.length,8):Math.min(Ac,Math.ceil(n.length/32)),o=[];for(let a=0;a<i;a+=1){const c=n.filter((p,A)=>A%i===a),f=new Worker(Bi,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(f);let d;o.push(new Promise(p=>{d=p}));const y=()=>{f.terminate(),this.prefetchers=this.prefetchers.filter(p=>p!==f),d()};f.addEventListener("error",y),f.addEventListener("messageerror",y),f.addEventListener("message",p=>{p.data?.identity===this.identity&&(p.data.type==="ready"?f.postMessage(t.length>0?{type:"prefetch-stream",url:t[a]}:{type:"prefetch",indices:c}):(p.data.type==="prefetched"||p.data.type==="init-error")&&y())}),f.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:new SharedArrayBuffer(this.state.byteLength),completed:this.completed.buffer,sharedCompletion:!0,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}return{queued:n.length,done:Promise.all(o).then(()=>{})}}ensure(e,t){if(this.closed)throw new Error("This immutable image reader is closed.");if(!this.ready)throw new Error("This immutable image reader has not finished asynchronous initialization.");if(t===0||e>=this.ranges.bytes)return;const r=Math.min(e+t,this.ranges.bytes);let n=0,i=this.ranges.parts.length;for(;n<i;){const o=n+i>>>1,a=this.ranges.parts[o];a.offset+a.raw<=e?n=o+1:i=o}for(let o=n;o<this.ranges.parts.length;o+=1){const a=this.ranges.parts[o];if(a.offset>=r)break;const c=this.firstRead;if(c&&Atomics.load(c,o)===0&&Atomics.compareExchange(c,o,0,Atomics.add(c,this.ranges.parts.length,1)+1),Atomics.load(this.completed,o)===2)continue;const f=this.worker??this.port;if(!f)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");f.postMessage({type:"read",index:o});const d=performance.now(),y=d+3e4;for(;Atomics.load(this.state,o)===0;){const k=y-performance.now();if(k<=0||Atomics.wait(this.state,o,0,k)==="timed-out")throw this.close(),new Error(`The image's immutable part ${a.url} did not arrive within 30 seconds; reload to retry.`)}const p=performance.now()-d,A=Di.get(this.identity)??{ranges:0,ms:0};if(A.ranges+=1,A.ms+=p,Di.set(this.identity,A),console.log(`[boot-trace] ${JSON.stringify({event:"image-blocked",at:Date.now(),reader:this.identity,index:o,range:a.sha256.slice(0,16),ms:Math.round(p)})}`),Atomics.load(this.state,o)!==2)throw new Error(`The image's immutable part ${a.url} could not be verified or stored; see the worker error and reload to retry.`)}}lineForReader(){const e=this.worker??this.port;if(this.closed||!this.ready||!e)return;const t=new MessageChannel,r=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);return e.postMessage({type:"client",port:t.port1,state:r},[t.port1]),{port:t.port2,state:r}}fail(){for(let e=0;e<this.state.length;e+=1)Atomics.compareExchange(this.state,e,0,-1)===0&&Atomics.notify(this.state,e)}close(){if(this.closed)return;if(this.closed=!0,this.cancelStartup){this.cancelStartup(new Error("This immutable image reader closed during initialization."));return}this.fail(),this.port?.close();const e=this.worker;e&&(e.postMessage({type:"closing"}),setTimeout(()=>e.terminate(),250));for(const t of this.prefetchers)t.dispatchEvent(new Event("error"));this.prefetchers=[]}}const fs="/packages",En="supercode-browser-packages",Qt=new TextEncoder,ur=new TextDecoder("utf-8",{fatal:!0}),Nc=bc,An="generations",Yi="atomic-staging",mr=Ec,at="index.json",hs="index-log.bin",yr="pack.bin",_n=8,Ci=64*1024*1024,We=1024*1024*1024,Ic=.95,ca=["/workspace","/home","/opt"],Zt=0,Ui=1,ds=1e6,Wi=8*1024*1024,$i=250,kc=64*1024*1024,Mc=256*1024*1024,zi=4*1024*1024,wr=493,Nn=420;function Js(s,e={}){const t=e.limits?.maxBytes,r=e.limits?.maxEntries??ds;if(t!==void 0&&(!Number.isSafeInteger(t)||t<1)||!Number.isSafeInteger(r)||r<1||r>ds)throw new Error("Invalid OPFS workspace limits.");let n=Number.MAX_SAFE_INTEGER,i,o,a=!1,c=!1,f=!1,d,y=0,p=0,A,k,_,E=new Map,L=new In,x,D,z,oe,fe,j,v=0,T,Q=0;const ae=new Map,Ae=256*1024,Me=32;let F=0,W,ue=-1/0,re=0,mt=0,$=0,V=0,me=0,tt=0,Oe=0,Se,Mr,xe,Pt=!1,Rt,He=Promise.resolve(),_e=0,se=!1,ce=!1,ye,Le=0,K=!1;function Ve(){if(!(!ye||K)){if($>2147483647){Pe();return}Atomics.store(ye,Ui,$)}}function Pe(){!ye||K||(K=!0,(Atomics.load(ye,Zt)&1)===0&&Atomics.add(ye,Zt,1))}function Re(){Le+=1,Le===1&&ye&&!K&&Atomics.add(ye,Zt,1)}function yt(){Le-=1,!(Le>0||!ye||K)&&(Ve(),K||Atomics.add(ye,Zt,1))}function xr(){if(c)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");return ye||(ye=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT)),ye[Zt]=Le>0||K?1:0,Ve()),ye.buffer}let be;const an=8*1024*1024;let Ne=!1;function or(l){if(c||!ye||!_||Pt||Le>0||K||se)return;const h=Atomics.load(ye,Zt);if(h&1)return;if(l?.overlays&&E instanceof rr){const w=E.boundedChanges();if(w)return Lr({generation:_,index:E.base.buffer,changes:w,packBytes:F,logBytes:$,epoch:h,liveBytes:V,linked:y,linkedBytes:p})}if(be&&be.generation===_&&be.epoch===h&&$>=be.logBytes&&$-be.logBytes<=(l?.current?0:an))return Lr(be);let u;try{u=Ri(E,ts())}catch(w){console.warn(`[pack-store] no reader seed: ${w instanceof Error?w.message:String(w)}`);return}return be={generation:_,index:u,packBytes:F,logBytes:$,epoch:h,liveBytes:V,linked:y,linkedBytes:p},cn(u),Lr(be)}function Lr(l){const h=e.packages?.imageCompletionSeed();return h?{...l,packagesImage:h}:l}function es(){if(!(!z||!D||!_||Pt||Le>0||se))return{generation:_,rangesDigest:D,completed:z.completionBuffer,...z.receiptKey?{metadata:{ranges:z.verifiedRanges,receiptKey:z.receiptKey}}:{}}}function cn(l){const h=[];if(E instanceof rr)for(const[w,m]of E.changed())m.capacity!==void 0&&h.push([w,m]);else for(const[w,m]of E)m.capacity!==void 0&&h.push([w,m]);const u=new Yt(l);E=new rr(u),L=new Jr(u);for(const[w,m]of h)E.set(w,m)}function ts(){if(L instanceof In)return L.map;const l=new Map;for(const h of E.keys()){const u=Xt(h);if(u===h)continue;let w=l.get(u);w||(w=new Set,l.set(u,w)),w.add(h.slice(u.length+1))}return l}function ln(){!c||f||se||!T||nt($)}async function Ht(l){if(se)throw new Error("This OPFS workspace is closing.");_e+=1;let h,u=!1;try{return await l()}catch(w){throw u=!0,h=w,w}finally{if(_e-=1,se&&_e===0)try{xi()}catch(w){throw u?new AggregateError([h,w],"OPFS operation and deferred close both failed."):w}}}async function rt(l){return je(),_e!==0?Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation.")):(ce=!0,Ht(async()=>{try{return await l()}finally{ce=!1}}))}function fn(l){if(se)throw new Error("This OPFS workspace is closing.");const h=E.get(l);if(!h||h.type==="directory")throw new Error(`OPFS workspace file does not exist: ${l}`);return pt(h)}function wt(l,h,u){if(se)throw new Error("This OPFS workspace is closing.");const w=E.get(l);if(!w||w.type==="directory")throw new Error(`OPFS workspace file does not exist: ${l}`);const m=Math.min(Math.max(0,h),w.length),S=Math.min(Math.max(0,u),w.length-m);if(w.pack){const b=e.packages;if(!b)throw new Error("This store has no shared package store to read from.");return b.readExtent(w.offset+m,S)}return gt(w.offset+m,S)}function pt(l){if(l.pack){const h=e.packages;if(!h)throw new Error("This store has no shared package store to read from.");return h.readExtent(l.offset,l.length)}return gt(l.offset,l.length)}function gt(l,h){if(se)throw new Error("This OPFS workspace is closing.");const u=x;if(!u)throw new Error("OPFS filesystem worker is not initialized.");const w=new Uint8Array(h);if(h>0&&h<=Ae&&l>=0&&l+h<=Q){let m=0;for(;m<h;){const S=l+m,b=Math.floor(S/Ae)*Ae;let I=ae.get(b);if(!I&&(I=new Uint8Array(Math.min(Ae,Q-b)),z?.ensure(b,I.byteLength),u.read(I,{at:b})!==I.byteLength))throw new Error("An OPFS package range could not be read completely.");ae.delete(b),ae.set(b,I),ae.size>Me&&ae.delete(ae.keys().next().value);const M=S-b,R=Math.min(h-m,I.byteLength-M);w.set(I.subarray(M,M+R),m),m+=R}return w}if(z?.ensure(l,h),h>0&&u.read(w,{at:l})!==h)throw new Error("An OPFS workspace file could not be read completely.");return w}async function vt(l,h={}){if(se&&o||!o&&_e!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(Pt)throw new Error("This OPFS store is already opening a workspace.");if(o){if(k!==Tt(l))throw new Error("Close this OPFS store before opening another workspace.");return E.size>0}Pt=!0,se=!1;const u=new AbortController;Rt=u;try{E=new Map,L=new In,_=void 0,D=void 0,d=void 0,Se=void 0,xe=void 0,F=$=V=me=y=p=0,N=void 0,tt=Oe=re=mt=0,ue=-1/0,k=Tt(l),c=h.readOnly===!0,fe=c?h.imageCompletion:void 0,j=c?h.imageLine:void 0,f=c&&h.extentsOnly===!0,a=h.shared===!0||c,i=void 0;try{const b=await s.navigator.storage.estimate?.();b?.quota&&(n=Math.max(0,Math.floor(b.quota*Ic)-(b.usage??0)))}catch{}a||await di(u.signal),u.signal.throwIfAborted();const w=await ve();u.signal.throwIfAborted();try{const b=await w.getDirectoryHandle(Nc,{create:!c});u.signal.throwIfAborted(),o=await b.getDirectoryHandle(k,{create:!c})}catch(b){if(u.signal.throwIfAborted(),c&&hr(b))return!1;throw b}u.signal.throwIfAborted();let m=Sn(await Kt(o,mr));if(u.signal.throwIfAborted(),!m&&c)return await Tr(),!1;if(!m&&a&&(await s.navigator.locks.request(En,{mode:"exclusive",signal:u.signal},async()=>{u.signal.throwIfAborted(),m=Sn(await Kt(o,mr)),u.signal.throwIfAborted(),m||(await Tr(),await yi({files:[],pack:new ArrayBuffer(0)}),await Pc(o))}),u.signal.throwIfAborted(),!m))return d=await De(_,!1),u.signal.throwIfAborted(),!1;if(!m)return await Tr(),u.signal.throwIfAborted(),!1;const S=async b=>{let I;try{I=await De(b.generation,!1)}catch(O){throw u.signal.throwIfAborted(),hr(O)?new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause:O}):O}if(u.signal.throwIfAborted(),_=b.generation,v=b.initializedAt,D=b.imageRanges,d=I,f)return k===Ct&&s.navigator.locks?await s.navigator.locks.request(En,{mode:"shared",signal:u.signal},async()=>{await Ge(I),Q=x.getSize()}):await Ge(I),u.signal.throwIfAborted(),!0;const M=c?h.seed:void 0;if(M&&M.generation===b.generation){const O=new Yt(M.index);return E=new rr(O),L=new Jr(O),F=M.packBytes,M.changes&&ar({packBytes:M.packBytes,changes:M.changes}),await Ge(I),u.signal.throwIfAborted(),$=M.logBytes,{liveBytes:V,linked:y,linkedBytes:p}=M,me=Math.max(0,F-V),Ne=!0,E.size>0}const R=c?void 0:await sc(I);if(u.signal.throwIfAborted(),R){const O=new Yt(R.index);E=new rr(O),L=new Jr(O),{packBytes:F,liveBytes:V,linked:y,linkedBytes:p}=R;const B=Atomics.load(new Int32Array(xr()),Zt);be={generation:_,index:R.index,packBytes:F,liveBytes:V,linked:y,linkedBytes:p,logBytes:0,epoch:B}}else E=os(await Kt(I,at)),u.signal.throwIfAborted(),Ye(),F=vr(E);await Ge(I),u.signal.throwIfAborted();const C=R?await ic(R):0;return u.signal.throwIfAborted(),C&&(N={generation:_,bytes:C},be&&(be.logBytes=C)),nt(C,!!R),R?me=Math.max(0,F-V):bt(),ui(),a&&!c&&!R&&E.size>=1e4&&(Ft(),await Or(I,E,{access:T,bytes:$,packBytes:F})),a||(x.truncate(F),await Si(o,Yi,!0),await cr(_),u.signal.throwIfAborted(),me>kc&&me>V&&await Ka()),u.signal.throwIfAborted(),E.size>0};return a&&!c?await s.navigator.locks.request(En,{mode:"exclusive",signal:u.signal},async()=>{if(m=Sn(await Kt(o,mr)),!m)throw new Error("The committed package store state is missing. Stored data was retained.");return S(m)}):await S(m)}catch(w){const m=[w];try{St()}catch(S){m.push(S)}try{A?.()}catch(S){m.push(S)}throw A=void 0,o=void 0,m.length>1?new AggregateError(m,"OPFS workspace open and cleanup failed."):w}finally{Pt=!1,Rt=void 0}}function rs(l){return Ht(()=>Pr(l?.whole===!0))}async function Pr(l=!1){if(f)throw new Error("A store opened for its extents alone has no index to follow.");if(c&&o){const S=Sn(await Kt(o,mr));if(!S)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(S.generation!==_||l){const b=await De(S.generation,!1),I=os(await Kt(b,at));F=vr(I),S.generation!==_&&(_=S.generation,v=S.initializedAt,D=S.imageRanges,await Ge(b)),_=S.generation,d=b,E=I,Ye(),nt(),bt();return}}const h=T;if(!h||!d)return;const u=h.getSize();let w=!1;u<$&&(E=os(await Kt(d,at)),Ye(),F=vr(E),$=0,w=!0);const m=$;nt($),(w||$!==m)&&bt()}async function ve(){let l;for(let h=0;h<10;h+=1){Rt?.signal.throwIfAborted();try{return await s.navigator.storage.getDirectory()}catch(u){l=u,await new Promise(w=>setTimeout(w,200))}}throw l instanceof Error?l:new Error("This browser workspace's storage is unavailable.")}const Rr=1e4;async function we(l,h){let u;const w=Rt?.signal;for(let S=0;S<2;S+=1){w?.throwIfAborted();const b=l.createSyncAccessHandle({mode:"readwrite-unsafe"});let I,M,R=!1;try{const C=new Promise((B,ne)=>{M=()=>ne(w?.reason??new DOMException("Workspace open was cancelled.","AbortError")),w?.addEventListener("abort",M,{once:!0}),w?.aborted&&M()}),O=await Promise.race([b.then(B=>({access:B})).catch(B=>{u=B}),new Promise(B=>{I=setTimeout(()=>B(void 0),Rr)}),C]);if(w?.throwIfAborted(),O)return R=!0,O.access}finally{I!==void 0&&clearTimeout(I),M&&w?.removeEventListener("abort",M),R||b.then(C=>C.close(),()=>{}).catch(C=>console.error("Late workspace handle cleanup failed.",C))}if(u instanceof TypeError)throw new Error(`This browser cannot share a workspace's files between pages: its file access handles have no readwrite-unsafe mode (Chrome 121 or newer has one). ${u.message}`);await new Promise(C=>setTimeout(C,500))}const m=u instanceof Error?` (${u.message})`:"";throw new Error(`This browser workspace's ${h} is held by another page${m}.`)}async function Ge(l){St();const h=await l.getFileHandle(yr);x=await we(h,"store");try{if(x.getSize()<F)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const u=await l.getFileHandle(hs);if(T=await we(u,"record of changes"),$=T.getSize(),D){const w=fe,m=w&&w.generation===_&&w.rangesDigest===D?w:void 0;let S,b;if(m?.metadata){if(S=ls(m.metadata.ranges),b=m.metadata.receiptKey,!/^[a-f0-9]{64}$/u.test(b))throw new Error("The owner's immutable receipt key is invalid.")}else{const M=await(await l.getFileHandle(Oi)).getFile(),R=new Uint8Array(await M.arrayBuffer());if(await It(R)!==D)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");S=ls(JSON.parse(ur.decode(R))),b=await It(Qt.encode(JSON.stringify(S)))}if(S.bytes>x.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const I=m?j:void 0;I||j?.port.close(),j=void 0,z=new _c(S,l,`${k}.${_}`,m?.completed,b,I),console.log(`[boot-trace] ${JSON.stringify({event:"image-reader-open",at:Date.now(),reader:`${k}.${_}`,offered:w!==void 0,shared:m!==void 0,...w&&!m?{offeredGeneration:w.generation,generation:_,rangesMatch:w.rangesDigest===D}:{}})}`),await z.initialize(),oe=S.image}}catch(u){throw St(),u}}function St(){z?.close(),z=void 0,oe=void 0;const l=x,h=T;x=void 0,T=void 0,$=0,Q=0,ae.clear();try{l?.close()}finally{h?.close()}}function nt(l=0,h=!1){const u=T;if(!u)throw new Error("OPFS filesystem worker is not initialized.");const w=u.getSize();if(w<=l){$=w;return}const m=new Uint8Array(w-l);if(u.read(m,{at:l})!==m.byteLength)throw new Error("The OPFS workspace index log could not be read.");const S=x?.getSize()??1/0,b=new DataView(m.buffer);let I=0;const M=m.byteLength;for(;I+_n<=M;){const R=b.getUint32(I,!0),C=b.getUint32(I+4,!0),O=I+_n;if(R===0||R>Ci||O+R>M)break;const B=m.subarray(O,O+R);if(Ii(B)!==C)break;let ne;try{ne=cc(JSON.parse(ur.decode(B)))}catch{break}if(ne.packBytes>S)break;ar(ne,h),I=O+R}I!==M&&!a&&u.truncate(l+I),$=l+I}function ar(l,h=!1){for(const[u,w]of l.changes){const m=E.get(u);if(w&&aa(m,w)){he(u);continue}h&&(m?.pack?(y-=1,p-=m.length):m&&(V-=m.length),w?.pack?(y+=1,p+=w.length):w&&(V+=w.length)),w===null?(E.delete(u),Te(u)):(E.set(u,w),he(u))}F=Math.max(F,l.packBytes)}function bt(){V=0,y=0,p=0;for(const l of E.values())l.pack?(y+=1,p+=l.length):V+=l.length;me=Math.max(0,F-V)}function vr(l){let h=0;for(const u of l.values())u.pack||(h=Math.max(h,u.offset+u.length));return h}const ns=5e3;async function di(l){if(!s.navigator.locks)return;if(!k)throw new Error("OPFS filesystem project is not initialized.");const h=new AbortController,u=setTimeout(()=>h.abort(),ns);try{await new Promise((w,m)=>{s.navigator.locks.request(`supercode-browser-filesystem-${k}`,{mode:"exclusive",signal:l?AbortSignal.any([l,h.signal]):h.signal},async()=>{clearTimeout(u),w(),await new Promise(S=>{A=S})}).catch(()=>m(l?.aborted?l.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(u)}}function Tt(l){if(typeof l!="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(l))throw new Error("OPFS filesystem projectId is invalid.");return l}async function Et(){if(!o)throw new Error("OPFS filesystem worker is not initialized.");return o}async function De(l,h){return(await(await Et()).getDirectoryHandle(An,{create:h})).getDirectoryHandle(l,{create:h})}async function Tr(){let l;try{l=await(await Et()).getDirectoryHandle(An)}catch(h){if(hr(h))return;throw h}for await(const h of l.entries())throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}async function cr(l){const h=await Et();let u;try{u=await h.getDirectoryHandle(An)}catch(w){if(hr(w))return;throw w}for await(const[w]of u.entries())w!==l&&await bi(u,w)}function je(){if(se)throw new Error("This OPFS workspace is closing.");if(ce)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(c)throw new Error("This store is open for reading; its owner writes it.");if(xe)throw xe}async function Fr(l){ki(l)}let lr=!1,g=0,N,P=!1;function U(){if(g>0)return;const l=N&&N.generation===_&&N.bytes<=$?N.bytes:0;$-l>Wi&&!lr&&(lr=!0,(a?s.navigator.locks.request(En,{mode:"exclusive"},async()=>{if(!o||se)return;await Pr();const u=N,w=u&&u.generation===_&&u.bytes<=$?u.bytes:0;$-w>Wi&&await yn()}):yn()).catch(u=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",u)).finally(()=>{lr=!1})),!a&&!P&&me>Mc&&me>V&&(P=!0,Ht(Xa).catch(h=>console.error("The workspace could not be compacted; it keeps its generation.",h)).finally(()=>{P=!1}))}async function X(l){je(),g+=1;try{return await l()}finally{g-=1,g===0&&!se&&o&&U()}}function le(l,h){const u=kt(l.path);if(l.operation==="write"){if(E.get(u)?.type==="directory")throw new Error(`OPFS write target is a directory: ${u}`);if(!(l.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const m=l.content;if(m.byteLength>We)throw new Error(`${u} is ${m.byteLength} bytes; an OPFS workspace file holds at most ${We}.`);dn(u,m.byteLength),Ce(u,h);const S=mn(m);J(u,{type:l.symlink?"symlink":"file",mode:l.mode??E.get(u)?.mode??Nn,mtimeMs:l.mtimeMs??Date.now(),offset:S,length:m.byteLength},h);return}if(l.operation==="append"){const m=E.get(u);if(m&&m.type!=="file")throw new Error(`OPFS append target is not a file: ${u}`);if(!(l.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const S=l.content,b=(m?.length??0)+S.byteLength;if(b>We)throw new Error(`${u} is ${b} bytes; an OPFS workspace file holds at most ${We}.`);dn(u,b),Ce(u,h);const I=l.mode??m?.mode??Nn,M=l.mtimeMs??Date.now(),R=m&&!m.pack?m.capacity??m.length:0;if(k!==Ct&&m&&!m.pack&&m.length>0&&(b<=R||m.offset+R===F)){un(m.offset+m.length,S),J(u,{...m,mode:I,mtimeMs:M,length:b,capacity:Math.max(R,b)},h),me-=Math.max(m.length,m.capacity??0),tt-=1,Oe-=m.length;return}const C=new Uint8Array(b);m&&m.length>0&&C.set(pt(m),0),C.set(S,b-S.byteLength);const O=mn(C),B=Math.min(We,Math.max(b,b*2,64*1024));B>b&&mi(O+B),J(u,{type:"file",mode:I,mtimeMs:M,offset:O,length:b,capacity:B},h);return}if(l.operation==="write-at"){const m=E.get(u);if(m&&m.type!=="file")throw new Error(`OPFS write target is not a file: ${u}`);if(!(l.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const S=l.content,b=l.position,I=m?.length??0;if(S.byteLength===0&&m)return;const M=S.byteLength===0?I:Math.max(I,b+S.byteLength);if(M>We)throw new Error(`${u} is ${M} bytes; an OPFS workspace file holds at most ${We}.`);dn(u,M),Ce(u,h);const R=l.mode??m?.mode??Nn,C=l.mtimeMs??Date.now(),O=m&&!m.pack?m.capacity??m.length:0;if(k!==Ct&&m&&!m.pack&&I>0&&(M<=O||m.offset+O===F)){if(b>I&&un(m.offset+I,new Uint8Array(b-I)),Mr&&b<I){const Ue=Math.min(I,b+S.byteLength);Mr.push([m.offset+b,gt(m.offset+b,Ue-b)])}un(m.offset+b,S),J(u,{...m,mode:R,mtimeMs:C,length:M,capacity:Math.max(O,M)},h),M!==I&&(me-=Math.max(m.length,m.capacity??0),tt-=1,Oe-=m.length);return}const B=new Uint8Array(M);m&&I>0&&B.set(pt(m),0),S.byteLength>0&&B.set(S,b);const ne=mn(B),ie=Math.min(We,Math.max(M,M*2,64*1024));ie>M&&mi(ne+ie),J(u,{type:"file",mode:R,mtimeMs:C,offset:ne,length:M,capacity:ie},h);return}if(l.operation==="mkdir"){Ce(u,h);const m=E.get(u);if(m&&m.type!=="directory")throw new Error(`OPFS path is a file: ${u}`);J(u,{type:"directory",mode:l.mode??m?.mode??wr,mtimeMs:l.mtimeMs??m?.mtimeMs??Date.now(),offset:0,length:0},h);return}if(l.operation==="remove"){Vt(u,h),Fe().includes(u)&&J(u,{type:"directory",mode:wr,mtimeMs:Date.now(),offset:0,length:0},h);return}if(l.operation==="link"){hn(u,Gt(l.source),h);return}if(l.operation==="rename"){fr(u,kt(l.destination),h);return}const w=E.get(u);if(!w)throw new Error(`OPFS metadata target does not exist: ${u}`);J(u,{...w,mode:l.mode??w.mode,mtimeMs:l.mtimeMs??w.mtimeMs},h)}function J(l,h,u){const w=E.get(l);Se&&!Se.has(l)&&Se.set(l,w);const m=w!==void 0&&w.type===h.type&&w.offset===h.offset&&w.length===h.length&&w.pack===h.pack;w&&!m&&(_t(w),w.type!=="directory"&&h.type!=="directory"&&w.length>0&&!w.pack&&(tt+=1,Oe+=w.length)),E.set(l,h),he(l),m||(h.pack?(y+=1,p+=h.length):V+=h.length),u.push([l,h])}function he(l){const h=Xt(l);h!==l&&L.mutable(h).add(l.slice(h.length+1))}function Te(l){const h=Xt(l);L.get(h)?.has(l.slice(h.length+1))&&L.mutable(h).delete(l.slice(h.length+1)),L.delete(l)}function Ye(){L=new In;for(const l of E.keys())he(l)}function At(l){const h=[],u=w=>{const m=E.get(w);if(!m)return;h.push([w,m]);const S=L.get(w);if(S)for(const b of S)u(`${w}/${b}`)};return u(l),h}function _t(l,h){if(l.pack){y-=1,p-=l.length;return}V-=l.length,me+=Math.max(l.length,l.capacity??0)}function st(l,h){const u=E.get(l);u&&(Se&&!Se.has(l)&&Se.set(l,u),E.delete(l),Te(l),_t(u),h.push([l,null]))}function hn(l,h,u){const w=e.packages;if(!w)throw new Error("This store has no shared package store to link from.");const m=Gt(h),S=w.descendants(m);if(S.length===0)throw new Error(`The shared package store does not hold ${h}.`);Ce(l,u),Vt(l,u),Nt(E.size+S.length);for(const[b,I]of S){const M=b===m?l:`${l}${b.slice(m.length)}`;J(M,I.type==="directory"?{type:"directory",mode:I.mode,mtimeMs:I.mtimeMs,offset:0,length:0}:{type:I.type,mode:I.mode,mtimeMs:I.mtimeMs,offset:I.offset,length:I.length,pack:Ct},u)}}function Ce(l,h){const u=Xt(l);if(u!==l&&E.get(u)?.type==="directory"){Nt(E.size+(E.has(l)?0:1));return}const w=[];let m=it(l)??Fe()[0];if(E.has(m)||w.push(m),l!==m)for(const b of as(_i(Xt(l)))){m=`${m}/${b}`;const I=E.get(m);if(I&&I.type!=="directory")throw new Error(`OPFS path parent is a file: ${m}`);I||w.push(m)}Nt(E.size+w.length+(E.has(l)?0:1));const S=Date.now();for(const b of w)J(b,{type:"directory",mode:wr,mtimeMs:S,offset:0,length:0},h)}function Vt(l,h){for(const[u]of At(l))st(u,h)}function fr(l,h,u){if(l===h)return;if(h.startsWith(`${l}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const w=At(l);if(w.length===0){if(E.has(h))return;throw new Error(`OPFS rename source does not exist: ${l}`)}Ce(h,u),Vt(h,u);for(const[m]of w)st(m,u);for(const[m,S]of w)J(`${h}${m.slice(l.length)}`,S,u);Nt(E.size)}function Gt(l){if(typeof l!="string"||!l.startsWith(`${fs}/`)||l.includes("\0")||l.length>4096)throw new Error("Invalid shared store path.");return as(l.slice(fs.length+1)),l}function Fe(){return k===Ct?[fs]:ca}function it(l){return Fe().find(h=>l===h||l.startsWith(`${h}/`))}function ot(){return t!==void 0?t:(i??=V,Math.min(Number.MAX_SAFE_INTEGER,i+n))}function jt(){return t!==void 0?"its configured limit":"the origin's storage quota"}function dn(l,h){const u=E.get(l),w=u&&!u.pack?u.length:0,m=ot();if(V-w+h>m){const S=a?"the origin's shared packages":"the project's own files";throw new Error(`OPFS workspace exceeds ${jt()}: writing ${l} (${h} bytes) would take ${S} past ${m} bytes (${V} bytes held, ${w} replaced).`)}}function Nt(l){if(l>r)throw new Error("OPFS workspace exceeds its entry limit.")}function ui(){Nt(E.size);const l=ot();if(V>l)throw new Error(`OPFS workspace exceeds ${jt()}: ${a?"the origin's shared packages":"the project's own files"} hold ${V} bytes, past ${l}.`)}function un(l,h){const u=x;if(!u)throw new Error("OPFS filesystem worker is not initialized.");let w=0;for(;w<h.byteLength;){const m=u.write(h.subarray(w),{at:l+w});if(m<=0)throw new Error("An OPFS workspace file could not be written completely.");w+=m}F=Math.max(F,l+h.byteLength)}function mi(l){const h=x;if(!h)throw new Error("OPFS filesystem worker is not initialized.");l<=F||(h.truncate(l),F=l)}function mn(l){const h=x;if(!h)throw new Error("OPFS filesystem worker is not initialized.");const u=F;let w=0;for(;w<l.byteLength;){const m=h.write(l.subarray(w),{at:u+w});if(m<=0)throw new Error("An OPFS workspace file could not be written completely.");w+=m}return F=u+l.byteLength,u}function Ha(l){const h=x;if(h.getSize()>=F&&l.getSize()>=$)return;h.flush(),l.flush();const u=h.getSize(),w=l.getSize();if(!(u>=F&&w>=$))throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${u} of ${F} bytes, its log ${w} of ${$}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function Va(l,h={}){const u=T;if(!u||!x)throw new Error("OPFS filesystem worker is not initialized.");if(l.length===0)return;const w=Qt.encode(JSON.stringify({packBytes:F,changes:l}));if(w.byteLength>Ci)throw new Error("An OPFS workspace index record exceeds its size limit.");const m=new Uint8Array(_n+w.byteLength),S=new DataView(m.buffer);S.setUint32(0,w.byteLength,!0),S.setUint32(4,Ii(w),!0),m.set(w,_n);let b=0;for(;b<m.byteLength;){const I=u.write(m.subarray(b),{at:$+b});if(I<=0)throw new Error("The OPFS workspace index log could not be written completely.");b+=I}$+=m.byteLength,Ha(u),h.publish!==!1&&Ve(),performance.now()-ue>=$i?Ft():W===void 0&&(W=setTimeout(Ft,$i))}function Ft(){if(W!==void 0&&(clearTimeout(W),W=void 0),xe)throw xe;const l=performance.now();x?.flush(),T?.flush(),ue=performance.now(),re+=1,mt+=ue-l}function yn(){const l=He,h=Ht(()=>l.catch(()=>{}).then(Ga));return He=h,h}async function Ga(){if(je(),!_)return;const l=_,h=T,u=await De(l,!1);if(!h||h!==T||l!==_)throw new Error("OPFS workspace changed generations before its checkpoint could start.");Ft();const w=$;if(await Or(u,E,{access:h,bytes:w,packBytes:F}),l===_&&(N={generation:l,bytes:w}),h===T&&l===_&&w===$){Re();try{h.truncate(0),h.flush(),$=0,N={generation:l,bytes:0}}finally{yt()}}}function yi(l){return rt(()=>ja(ss(l)))}async function ja(l){const h=crypto.randomUUID(),u=await De(h,!0),w=await u.getFileHandle(yr,{create:!0}),m=await we(w,"store"),S=new Map;let b=0;try{for(const M of l.files){let R=0,C=0;if(M.type!=="directory"){const O=new Uint8Array(l.pack,M.offset??0,M.length??0);R=b,C=O.byteLength;let B=0;for(;B<C;){const ne=m.write(O.subarray(B),{at:R+B});if(ne<=0)throw new Error("An OPFS workspace file could not be written completely.");B+=ne}b+=C}S.set(M.path,{type:M.type,mode:M.mode??(M.type==="directory"?wr:Nn),mtimeMs:M.mtimeMs??Date.now(),offset:R,length:C})}for(const M of Fe())S.has(M)||S.set(M,{type:"directory",mode:wr,mtimeMs:Date.now(),offset:0,length:0});Nt(S.size),m.truncate(b),m.flush()}finally{m.close()}const I=await Or(u,S);await wn(h,u,S,b,I)}async function Ka(){await wi(()=>!0)}async function Xa(){let l=!1,h=!1,u=!1;try{await Ja(()=>{l=!0},()=>{h=!0},()=>{u=!0})}finally{l&&(h||u)?yt():l&&Pe()}}async function Ja(l,h,u){const w=crypto.randomUUID(),m=await De(w,!0),S=await we(await m.getFileHandle(yr,{create:!0}),"store");let b,I=!1;try{b=await we(await m.getFileHandle(hs,{create:!0}),"record of changes"),b.truncate(0);const M=new Uint8Array(zi);let R=0;const C=q=>{if(q.pack)return{...q};if(q.type==="directory"||q.length===0)return{...q,offset:0,length:0};const Ee=x;if(!Ee)throw new Error("OPFS filesystem worker is not initialized.");const Jt=R;let Ke=0;for(;Ke<q.length;){const Dr=Math.min(M.byteLength,q.length-Ke),Li=M.subarray(0,Dr);if(z?.ensure(q.offset+Ke,Dr),Ee.read(Li,{at:q.offset+Ke})!==Dr)throw new Error("An OPFS workspace file could not be read completely.");let bn=0;for(;bn<Dr;){const Pi=S.write(Li.subarray(bn),{at:Jt+Ke+bn});if(Pi<=0)throw new Error("An OPFS workspace file could not be written completely.");bn+=Pi}Ke+=Dr}R+=q.length;const{capacity:cs,...hc}=q;return{...hc,offset:Jt}},O=new Map;let B=performance.now();for(const[q,Ee]of[...E]){if(se||ce)return;E.get(q)===Ee&&(O.set(Ee,C(Ee)),performance.now()-B>8&&(await new Promise(Jt=>setTimeout(Jt,0)),B=performance.now()))}if(se||ce||!x||!T)return;Re(),l();const ne=new Map;for(const[q,Ee]of E)ne.set(q,O.get(Ee)??C(Ee));S.truncate(R),S.flush(),b.flush(),Ft();const ie={pack:x,log:T};x=S,T=b,$=0,E=ne,Ye(),F=R,_=w,d=m,bt(),I=!0;const Ue=new Map(ne);try{ie.pack.close()}finally{ie.log.close()}try{await Or(m,Ue);const q={storageVersion:4,generation:w,initializedAt:Date.now()};await Br(await Et(),mr,q)}catch(q){throw xe=new Error("The workspace moved to a compacted generation it could not record; it takes no more writes, which its next open would discard.",{cause:q}),xe}h(),await cr(w)}finally{if(!I){u();try{S.close()}finally{b?.close()}await bi(await(await Et()).getDirectoryHandle(An),w)}}}async function Qa(l){je(),Re();try{await Za(l)}finally{yt()}}async function Za(l){let h=!1;for(const[u,w]of E){if(!w.pack||w.length===0)continue;const m=l.get(w.offset);if(m===void 0)throw new Error(`The shared store no longer holds the bytes of ${u}.`);m!==w.offset&&(E.set(u,{...w,offset:m}),h=!0)}h&&await yn()}function wi(l){return rt(()=>qa(l))}async function qa(l){const h=x;if(!h)throw new Error("OPFS filesystem worker is not initialized.");const u=new Map,w=crypto.randomUUID(),m=await De(w,!0),S=await m.getFileHandle(yr,{create:!0}),b=await we(S,"store"),I=new Map,M=new Uint8Array(zi);let R=0;try{for(const[O,B]of E){if(!l(O,B))continue;if(B.pack){I.set(O,{...B});continue}if(B.type==="directory"||B.length===0){I.set(O,{...B,offset:0,length:0});continue}const ne=R;u.set(B.offset,ne);let ie=0;for(;ie<B.length;){const Ee=Math.min(M.byteLength,B.length-ie),Jt=M.subarray(0,Ee);if(z?.ensure(B.offset+ie,Ee),h.read(Jt,{at:B.offset+ie})!==Ee)throw new Error("An OPFS workspace file could not be read completely.");let Ke=0;for(;Ke<Ee;){const cs=b.write(Jt.subarray(Ke),{at:ne+ie+Ke});if(cs<=0)throw new Error("An OPFS workspace file could not be written completely.");Ke+=cs}ie+=Ee}R+=B.length;const{capacity:Ue,...q}=B;I.set(O,{...q,offset:ne,length:B.length})}b.truncate(R),b.flush()}finally{b.close()}const C=await Or(m,I);return await wn(w,m,I,R,C),u}async function wn(l,h,u,w,m,S){Re();try{await ec(l,h,u,w,m,S)}finally{yt()}}async function ec(l,h,u,w,m,S){const b=await h.getFileHandle(hs,{create:!0}),I=await we(b,"record of changes");try{I.truncate(0),I.flush()}finally{I.close()}const M={storageVersion:S?5:4,generation:l,initializedAt:Date.now(),...S?{imageRanges:S}:{}};if(await Br(await Et(),mr,M),St(),_=l,v=M.initializedAt,D=S,m){const R=new Yt(m.index);E=new rr(R),L=new Jr(R),be=void 0}else E=u,Ye();F=w,d=h,await Ge(h),m?({liveBytes:V,linked:y,linkedBytes:p}=m,me=Math.max(0,F-V)):bt(),a||await cr(l)}async function tc(l,h,u,w,m=!1){if(je(),!a||k!==Ct)throw new Error("Only the shared package store can reserve immutable image extents.");if(F!==0||[...E.values()].some(O=>O.type!=="directory"))return!1;const S=ls(w);if(S.bytes!==l.packBytes||l.entries>ds||l.liveBytes>l.packBytes||h.byteLength!==l.json.raw||u.byteLength!==l.binary.raw||!await gn(h,l.json.sha256,m)||!await gn(u,l.binary.sha256,m))throw new Error("The image's prepared metadata does not match its document.");const b=h.subarray(0,4096).indexOf(10);if(b<0)throw new Error("The prepared index has no bounded retained header.");const I=JSON.parse(`${ur.decode(h.subarray(0,b-1))}}`),M={packBytes:l.packBytes,liveBytes:l.liveBytes,linked:0,linkedBytes:0},R=I.retainedIndex;if(R.version!==1||R.digest!==await pi(l.binary.sha256,M)||R.packBytes!==M.packBytes||R.liveBytes!==M.liveBytes||R.linked!==0||R.linkedBytes!==0)throw new Error("The prepared index's retained measures are inconsistent.");const C=new SharedArrayBuffer(u.byteLength);if(new Uint8Array(C).set(u),new Yt(C).entryCount!==l.entries)throw new Error("The prepared index has the wrong number of entries.");return rt(async()=>{const O=crypto.randomUUID(),B=await De(O,!0),ne=await B.getFileHandle(yr,{create:!0}),ie=await we(ne,"immutable image reservation");try{ie.truncate(l.packBytes),ie.flush()}finally{ie.close()}const Ue=Qt.encode(JSON.stringify(S));return await Bt(B,Oi,Ue),await Bt(B,pn,u),await Bt(B,at,h),await wn(O,B,new Map,l.packBytes,{index:C,...M},await It(Ue)),!0})}async function rc(l,h,u,w=!1,m){if(je(),a||!e.packages||!m&&!e.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(F!==0||[...E.values()].some(R=>R.type!=="directory"))return!1;if(h.byteLength!==l.json.raw||u.byteLength!==l.binary.raw||!await gn(h,l.json.sha256,w)||!await gn(u,l.binary.sha256,w))throw new Error("The image's prepared project does not match its descriptor.");const S=h.subarray(0,4096).indexOf(10);if(S<0)throw new Error("The prepared project has no bounded retained header.");const b=JSON.parse(`${ur.decode(h.subarray(0,S-1))}}`).retainedIndex,I={packBytes:0,liveBytes:0,linked:l.linked,linkedBytes:l.linkedBytes};if(b.version!==1||b.digest!==await pi(l.binary.sha256,I)||b.packBytes!==0||b.liveBytes!==0||b.linked!==l.linked||b.linkedBytes!==l.linkedBytes)throw new Error("The prepared project's retained measures are inconsistent.");const M=new SharedArrayBuffer(u.byteLength);if(new Uint8Array(M).set(u),new Yt(M).entryCount!==l.entries||l.entries>r)throw new Error("The prepared project has invalid entry bounds.");return rt(async()=>{const R=crypto.randomUUID(),C=await De(R,!0),O=await C.getFileHandle(yr,{create:!0}),B=await we(O,"prepared project");try{B.truncate(0),B.flush()}finally{B.close()}if(await Bt(C,pn,u),await Bt(C,at,h),m&&!await m)return!1;if(!e.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");return await wn(R,C,new Map,0,{index:M,...I}),!0})}async function nc(){if(se)throw new Error("This OPFS workspace is closing.");if(!x)throw new Error("OPFS filesystem worker is not initialized.");const l=[],h=[...E.keys()].sort((b,I)=>Ni(b)-Ni(I)||(b<I?-1:1));let u=0;for(const b of E.values())b.type!=="directory"&&(u+=b.length);const w=new ArrayBuffer(u),m=new Uint8Array(w);let S=0;for(const b of h){const I=E.get(b);if(I.type==="directory"){l.push({path:b,type:"directory",mode:I.mode,mtimeMs:I.mtimeMs});continue}I.length>0&&m.set(pt(I),S),l.push({path:b,type:I.type,offset:S,length:I.length,mode:I.mode,mtimeMs:I.mtimeMs}),S+=I.length}for(const b of[...Fe()].reverse())E.has(b)||l.unshift({path:b,type:"directory",mode:wr,mtimeMs:Date.now()});return ss({files:l,pack:w})}async function Br(l,h,u){await Bt(l,h,Qt.encode(JSON.stringify(u)))}async function Bt(l,h,u){const w=await(await Et()).getDirectoryHandle(Yi,{create:!0}),m=crypto.randomUUID(),S=await w.getFileHandle(m,{create:!0}),b=await we(S,"index");try{let I=0;for(;I<u.byteLength;){const M=b.write(u.subarray(I),{at:I});if(M<=0)throw new Error("An OPFS workspace file could not be written completely.");I+=M}b.truncate(u.byteLength),b.flush()}finally{b.close()}try{await S.move(l,h)}finally{await Si(w,m,!1)}}const pn="index.shared";async function It(l){const h=await crypto.subtle.digest("SHA-256",l);return Array.from(new Uint8Array(h),u=>u.toString(16).padStart(2,"0")).join("")}async function gn(l,h,u){return u||await It(l)===h}function pi(l,h){const{packBytes:u,liveBytes:w,linked:m,linkedBytes:S,journalPrefix:b}=h;return It(Qt.encode(`${JSON.stringify({packBytes:u,liveBytes:w,linked:m,linkedBytes:S,...b?{journalPrefix:b}:{}})}:${l}`))}async function gi(l,h){const{packBytes:u,liveBytes:w,linked:m,linkedBytes:S,journalPrefix:b}=h;return It(Qt.encode(`${JSON.stringify({packBytes:u,liveBytes:w,linked:m,linkedBytes:S,...b?{journalPrefix:b}:{}})}:${await It(l)}`))}async function Or(l,h,u){const w=ac(h);if(typeof SharedArrayBuffer>"u"||h.size<1e4){await Br(l,at,w);return}const m=new Map(w.entries),S=new Map,b={packBytes:u?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[ne,ie]of m){const Ue=Xt(ne);if(Ue!==ne){let q=S.get(Ue);q||(q=new Set,S.set(Ue,q)),q.add(ne.slice(Ue.length+1))}ie.pack?(b.linked+=1,b.linkedBytes+=ie.length):(b.liveBytes+=ie.length,b.packBytes=Math.max(b.packBytes,ie.offset+ie.length))}let I;try{I=Ri(m,S)}catch{await Br(l,at,w);return}const M=JSON.stringify(w.entries),R=u?new Uint8Array(u.bytes):void 0;if(R&&u.access.read(R,{at:0})!==R.byteLength)throw new Error("The checkpoint's journal prefix could not be read completely.");const C=R?{bytes:R.byteLength,digest:await It(R)}:void 0,O=new Uint8Array(I).slice(),B={version:C?2:1,digest:await gi(O,{...b,...C?{journalPrefix:C}:{}}),...b,...C?{journalPrefix:C}:{}};try{await Bt(l,pn,O)}catch{await Br(l,at,{entries:JSON.parse(M)});return}return await Bt(l,at,Qt.encode(`{"retainedIndex":${JSON.stringify(B)},
2
+ "entries":${M}}`)),{index:I,...b}}async function sc(l){if(!(typeof SharedArrayBuffer>"u"))try{const h=await l.getFileHandle(at),u=await we(h,"index");let w;try{const O=new Uint8Array(Math.min(512,u.getSize())),B=u.read(O,{at:0});w=ur.decode(O.subarray(0,B))}finally{u.close()}const m=w.split(`
3
+ `,1)[0];if(!m.startsWith('{"retainedIndex":')||!m.endsWith(","))return;const S=JSON.parse(m.slice(0,-1)+"}").retainedIndex;if(S.version!==1&&S.version!==2||!/^[a-f0-9]{64}$/u.test(S.digest)||![S.packBytes,S.liveBytes,S.linked,S.linkedBytes].every(O=>Number.isSafeInteger(O)&&O>=0)||S.version===1&&S.journalPrefix!==void 0||S.version===2&&(!S.journalPrefix||!Number.isSafeInteger(S.journalPrefix.bytes)||S.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(S.journalPrefix.digest)))return;const b=await l.getFileHandle(pn),I=await we(b,"index");let M;try{const O=I.getSize();if(O>256*1024*1024||(M=new Uint8Array(O),I.read(M,{at:0})!==O))return}finally{I.close()}if(await gi(M,S)!==S.digest)return;const R=new SharedArrayBuffer(M.byteLength);new Uint8Array(R).set(M);const C=new Yt(R);return Nt(C.entryCount),{...S,index:R}}catch{return}}async function ic(l){const h=l.journalPrefix;if(!h||!T||!x||h.bytes>T.getSize()||l.packBytes>x.getSize())return 0;const u=new Uint8Array(h.bytes);return T.read(u,{at:0})!==u.byteLength?0:await It(u)===h.digest?h.bytes:0}async function Kt(l,h){let u;try{u=await l.getFileHandle(h)}catch(S){if(hr(S))return;throw S}let w;if(c){w=await(await u.getFile()).text();try{return JSON.parse(w)}catch(S){throw new Error(`Invalid OPFS workspace metadata (${h}). Stored data was retained.`,{cause:S})}}const m=await we(u,"index");try{const S=m.getSize(),b=new Uint8Array(S);if(S>0&&m.read(b,{at:0})!==S)throw new Error("An OPFS workspace file could not be read completely.");w=ur.decode(b)}finally{m.close()}try{return JSON.parse(w)}catch(S){throw new Error(`Invalid OPFS workspace metadata (${h}). Stored data was retained.`,{cause:S})}}async function Si(l,h,u){try{await l.removeEntry(h,{recursive:u})}catch(w){if(!hr(w))throw w}}async function bi(l,h){try{await l.removeEntry(h,{recursive:!0})}catch{}}function Ei(l){if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Invalid OPFS filesystem mutation.");if(l.operation!=="write"&&l.operation!=="append"&&l.operation!=="write-at"&&l.operation!=="mkdir"&&l.operation!=="remove"&&l.operation!=="rename"&&l.operation!=="metadata"&&l.operation!=="link")throw new Error("Invalid OPFS filesystem mutation.");if(kt(l.path),l.operation==="rename"&&kt(l.destination),(l.operation==="write"||l.operation==="append"||l.operation==="write-at")&&!(l.content instanceof Uint8Array))throw new Error("Invalid OPFS file content.");if(l.operation==="write-at"&&(!Number.isSafeInteger(l.position)||l.position<0))throw new Error("Invalid OPFS write position.");return is(l),l}function oc(l){if(!Array.isArray(l)||l.length===0||l.length>128)throw new Error("Invalid OPFS filesystem mutation batch.");return l.map(h=>Ei(h))}function ss(l){if(!l||!Array.isArray(l.files)||l.files.length>r||!(l.pack instanceof ArrayBuffer))throw new Error("Invalid OPFS workspace snapshot.");const h=new Set,u=new Map(Fe().map(m=>[m,"directory"]));let w=0;for(const m of l.files){if(!m||typeof m!="object")throw new Error("Invalid OPFS workspace snapshot entry.");if(kt(m.path),m.type!=="file"&&m.type!=="directory"&&m.type!=="symlink"||h.has(m.path))throw new Error("Invalid or duplicate OPFS workspace entry.");if(h.add(m.path),u.set(m.path,m.type),Fe().includes(m.path)&&m.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(m.type!=="directory"){const S=m.offset??0,b=m.length??0;if(!Number.isSafeInteger(S)||!Number.isSafeInteger(b)||S<0||b<0||b>We||S+b>l.pack.byteLength)throw new Error("Invalid OPFS workspace file.");if(w+=b,w>ot())throw new Error(`OPFS workspace exceeds ${jt()}.`)}else if((m.offset??0)!==0||(m.length??0)!==0)throw new Error("An OPFS workspace directory cannot contain file bytes.");is(m)}Nt(u.size);for(const m of l.files)if(!Fe().includes(m.path)&&u.get(Xt(m.path))!=="directory")throw new Error(`An OPFS workspace snapshot has no directory parent for ${m.path}.`);return l}function is(l){if(l.mode!==void 0&&(!Number.isSafeInteger(l.mode)||l.mode<0||l.mode>4095))throw new Error("Invalid OPFS file mode.");if(l.mtimeMs!==void 0&&(typeof l.mtimeMs!="number"||!Number.isFinite(l.mtimeMs)||l.mtimeMs<0))throw new Error("Invalid OPFS modification time.")}function ac(l){return{entries:[...l]}}function os(l){const h=new Map;if(l===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!l||typeof l!="object"||!Array.isArray(l.entries))throw new Error("Invalid OPFS workspace index.");const u=l.entries;Nt(u.length);for(const w of u){if(!Array.isArray(w)||w.length!==2)throw new Error("Invalid OPFS workspace index entry.");const m=kt(w[0]);if(h.has(m))throw new Error("Duplicate OPFS workspace index entry.");h.set(m,Ai(w[1]))}return h}function Ai(l){if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Invalid OPFS workspace index entry.");const h=l;if(h.type!=="file"&&h.type!=="directory"&&h.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");if(is(h),h.mode===void 0||h.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(h.offset)||h.offset<0||!Number.isSafeInteger(h.length)||h.length<0||h.length>We)throw new Error("Invalid OPFS workspace index extent.");if(h.pack!==void 0&&h.pack!==Ct)throw new Error("Invalid OPFS workspace index entry.");return{type:h.type,mode:h.mode,mtimeMs:h.mtimeMs,offset:h.offset,length:h.length,...h.pack?{pack:h.pack}:{}}}function cc(l){if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Invalid OPFS workspace index record.");const h=l;if(!Number.isSafeInteger(h.packBytes)||h.packBytes<0||!Array.isArray(h.changes))throw new Error("Invalid OPFS workspace index record.");const u=[];for(const w of h.changes){if(!Array.isArray(w)||w.length!==2)throw new Error("Invalid OPFS workspace index record.");u.push([kt(w[0]),w[1]===null?null:Ai(w[1])])}return{packBytes:h.packBytes,changes:u}}function Sn(l){if(l===void 0)return;if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const h=l;if(h.storageVersion!==4&&h.storageVersion!==5||h.storageVersion===5&&(typeof h.imageRanges!="string"||!/^[a-f0-9]{64}$/u.test(h.imageRanges))||h.storageVersion===4&&h.imageRanges!==void 0||typeof h.generation!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(h.generation)||typeof h.initializedAt!="number"||!Number.isFinite(h.initializedAt))throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.");return h}function kt(l){if(typeof l!="string"||it(l)===void 0||l.includes("\0")||l.length>4096)throw new Error("Invalid OPFS workspace path.");return _i(l),l}function _i(l){const h=it(l);if(h===void 0)throw new Error("Invalid OPFS workspace path.");const u=l===h?"":l.slice(h.length+1);return as(u),u}function as(l){const h=l===""?[]:l.split("/");if(h.some(u=>!u||u==="."||u===".."||u.includes("\0")))throw new Error("Invalid OPFS workspace path segment.");return h}function Xt(l){const h=l.slice(0,l.lastIndexOf("/"));return h===""||it(h)===void 0?it(l)??l:h}function Ni(l){let h=1;for(let u=0;u<l.length;u+=1)l.charCodeAt(u)===47&&(h+=1);return h}function hr(l){return l instanceof DOMException&&l.name==="NotFoundError"}function Ii(l){let h=2166136261;for(let u=0;u<l.byteLength;u+=1)h^=l[u],h=Math.imul(h,16777619);return h>>>0}typeof addEventListener=="function"&&addEventListener("close",()=>{x?.flush(),T?.flush(),St(),A?.()});function ki(l,h={}){if(je(),Se)throw new Error("An OPFS mutation batch cannot be nested.");for(const u of l)Ei(u);return l.length?Mi(u=>{for(const w of l)le(w,u)},h):[]}function lc(l,h,u={}){if(je(),Se)throw new Error("An OPFS mutation batch cannot be nested.");for(const w of h){if(kt(w.path),w.type!=="file"&&w.type!=="directory"&&w.type!=="symlink")throw new Error(`OPFS extent ${w.path} has no valid type.`);if(w.type==="directory")continue;const{offset:m,length:S}=w;if(m===void 0||S===void 0||!Number.isSafeInteger(m)||!Number.isSafeInteger(S)||m<0||S<0||m+S>l.byteLength)throw new Error(`OPFS extent ${w.path} lies outside its bytes.`);if(S>We)throw new Error(`${w.path} is ${S} bytes; an OPFS workspace file holds at most ${We}.`)}return h.length?Mi(w=>{const m=l.byteLength>0?mn(l):F;for(const S of h){const b=kt(S.path);Ce(b,w);const I=E.get(b);if(S.type==="directory"){if(I&&I.type!=="directory")throw new Error(`OPFS path is a file: ${b}`);J(b,{type:"directory",mode:S.mode,mtimeMs:S.mtimeMs,offset:0,length:0},w);continue}if(I?.type==="directory")throw new Error(`OPFS write target is a directory: ${b}`);dn(b,S.length),J(b,{type:S.type,mode:S.mode,mtimeMs:S.mtimeMs,offset:m+S.offset,length:S.length},w)}},u):[]}function Mi(l,h){if(!x||!T)throw new Error("OPFS filesystem worker is not initialized.");const u={packBytes:F,logBytes:$,liveBytes:V,deadBytes:me,rewrites:tt,rewrittenBytes:Oe,linked:y,linkedBytes:p},w=new Map;Se=w;const m=[];Mr=m;const S=[];try{return l(S),ui(),Va(S,{publish:!h.durable}),h.durable&&(Ft(),Ve()),U(),S}catch(b){const I=ye!==void 0&&!K&&Atomics.load(ye,Ui)!==u.logBytes;I&&Re();for(const[M,R]of w)R===void 0?E.delete(M):E.set(M,R);Ye();try{for(let M=m.length-1;M>=0;M-=1)un(m[M][0],m[M][1])}catch(M){b=new AggregateError([b,M],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes:F,logBytes:$,liveBytes:V,deadBytes:me,rewrites:tt,rewrittenBytes:Oe,linked:y,linkedBytes:p}=u),W!==void 0&&(clearTimeout(W),W=void 0);try{T.truncate($),T.flush(),x.truncate(F),x.flush()}catch(M){throw Pe(),xe=new AggregateError([b,M],"OPFS could not roll back a failed batch; reopen this workspace before writing again."),xe}throw I&&yt(),b}finally{Se=void 0,Mr=void 0}}function fc(){if(Pt){Rt?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}se||(se=!0,_e===0&&xi())}function xi(){Pe();try{Ft()}finally{try{St()}finally{const l=A;A=void 0,o=void 0;try{l?.()}finally{e.ownsPackages&&e.packages?.close()}}}}return{initialize:vt,opened:()=>o!==void 0&&!se,stats:()=>({entries:E.size,liveBytes:V,deadBytes:me,packBytes:F,rewrites:tt,rewrittenBytes:Oe,linked:y,linkedBytes:p,flushes:re,flushMs:mt}),applyNow:ki,applyExtentsNow:lc,close:fc,readExtent:gt,descendants:At,retain:wi,remapLinks:Qa,childrenOf:l=>[...L.get(l)??[]].sort(),refresh:rs,follow:ln,clock:xr,readerSeed:or,imageCompletionSeed:es,imageLine:()=>z?.lineForReader()??e.packages?.imageLine(),imageStartupSet:()=>z?.readDigests()??z?.completedDigests()??[],prefetchImage:(l,h)=>z?.prefetch(l,h)??{queued:0,done:Promise.resolve()},seeded:()=>Ne,get logBytes(){return $},checkpoint:yn,deferMaintenance:X,installPreparedImage:tc,installPreparedProject:rc,get deferredImage(){return oe},get imagePlacedAt(){return o&&D?v:void 0},get entries(){return E},get packBytes(){return F},read:fn,readRange:wt,snapshot:nc,replace:yi,apply:Fr,flush:()=>{if(se||!o)throw new Error("This OPFS workspace is not open.");if(ce)throw new Error("Wait for the OPFS generation replacement before flushing it.");Ft()},validateSnapshot:ss,validateMutationBatch:oc}}async function xc(s,e,t,r){const n=Js(s);await n.initialize(Ct,{readOnly:!0,extentsOnly:!0});const i=Js(s,{packages:n,ownsPackages:!0});let o;try{o=await i.initialize(e,{readOnly:!0,...t?{seed:t}:{}})}catch(a){throw i.close(),n.close(),a}if(!o&&!i.opened()){n.close();return}return i}const Lc="sweep.json";async function Pc(s){const t=await(await s.getFileHandle(Lc,{create:!0})).createWritable();await t.write(JSON.stringify({at:Date.now()})),await t.close()}class In{map=new Map;get(e){return this.map.get(e)}mutable(e){let t=this.map.get(e);return t||(t=new Set,this.map.set(e,t)),t}delete(e){this.map.delete(e)}}let Be;function Hi(s){Be=s}const Rc=5,vc=20;function _r(s,e,t,r,n){if(!Be)return Atomics.wait(s,e,t,r);const i=r===void 0?Number.POSITIVE_INFINITY:performance.now()+r,o=n===void 0?Rc:vc;for(;;){const a=Atomics.load(Be.doorbell,0);if(Be.pump(),Atomics.load(s,e)!==t)return"not-equal";const c=i-performance.now();if(c<=0)return"timed-out";if(n!==void 0&&Atomics.store(Be.doorbell,1,n+1),Atomics.load(Be.doorbell,0)!==a){n!==void 0&&Atomics.store(Be.doorbell,1,0);continue}let f;try{f=Atomics.wait(s,e,t,Math.min(o,c))}finally{n!==void 0&&Atomics.store(Be.doorbell,1,0)}if(f!=="timed-out")return f}}function Tc(s){if(!Be)return!1;for(;;){const e=Atomics.load(Be.doorbell,0);Be.pump();const t=s-performance.now();if(t<=0)return!0;Atomics.load(Be.doorbell,0)===e&&Atomics.wait(Be.doorbell,0,e,Math.min(100,t))}}const Qr=24,la=12,fa=4,Vi=17,Fc=0x10000000n,tn=s=>1n<<BigInt(s-1),Bc=tn(9)|tn(19),Oc=new Set([17,18,19,20,21,22,23,28]),Dc=s=>!Oc.has(s);function Yc(){return new SharedArrayBuffer((fa+64*la)*4)}class us{buffer;words;constructor(e){this.buffer=e,this.words=new Int32Array(e)}offset(e){return fa+(e-1)*la}locked(e){for(;Atomics.compareExchange(this.words,0,0,1)!==0;)Atomics.wait(this.words,0,1);try{return e()}finally{Atomics.store(this.words,0,0),Atomics.notify(this.words,0)}}changed(){Atomics.add(this.words,1,1),Atomics.notify(this.words,1)}action(e,t){return this.locked(()=>{const r=this.offset(e),n=new Uint8Array(this.buffer,(r+1)*4,Qr),i=Uint8Array.from(n);return t&&(n.set(t),new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!0)<=1&&Atomics.exchange(this.words,r,0)!==0&&Atomics.sub(this.words,2,1),this.changed()),i})}raise(e,t=0,r=0){return this.locked(()=>{const n=this.offset(e),i=Atomics.load(this.words,n+1)>>>0;return i<=1?i===1?"ignored":"default":(Atomics.load(this.words,n)!==0||(Atomics.store(this.words,n+7,t),Atomics.store(this.words,n+8,r),Atomics.store(this.words,n,1),Atomics.add(this.words,2,1),this.changed()),"handled")})}anyPending(){return Atomics.load(this.words,2)!==0}pending(){if(Atomics.load(this.words,2)===0)return 0n;let e=0n;for(let t=1;t<=64;t++)Atomics.load(this.words,this.offset(t))&&(e|=tn(t));return e}take(e){if((this.pending()&~e)!==0n)return this.locked(()=>{for(let t=1;t<=64;t++){const r=this.offset(t);if((e&tn(t))!==0n||Atomics.load(this.words,r)===0)continue;Atomics.store(this.words,r,0),Atomics.sub(this.words,2,1);const n=Uint8Array.from(new Uint8Array(this.buffer,(r+1)*4,Qr));return(new DataView(n.buffer).getBigUint64(4,!0)&0x80000000n)!==0n&&Atomics.store(this.words,r+1,0),{signal:t,action:n,pid:Atomics.load(this.words,r+7),status:Atomics.load(this.words,r+8)}}})}}class Cc{signals;memory;table;allocateScratch;held;mask=0n;delivering=!1;scratch=0;constructor(e,t,r,n,i=()=>!1){this.signals=e,this.memory=t,this.table=r,this.allocateScratch=n,this.held=i}range(e,t){return Number.isSafeInteger(e)&&e>0&&e+t<=this.memory().buffer.byteLength}imports(){return{SYS_rt_sigaction:(e,t,r,n)=>{const i=Number(e),o=Number(t),a=Number(r);if(i<1||i>64||Number(n)!==8||o!==0&&[9,19].includes(i))return-22n;if(o&&!this.range(o,Qr)||a&&!this.range(a,Qr))return-14n;const c=o?new Uint8Array(this.memory().buffer).slice(o,o+Qr):void 0;if(c){const d=new DataView(c.buffer),y=d.getUint32(0,!0),p=d.getBigUint64(4,!0);if(i===Vi&&(y===1||(p&2n)!==0n)||y>1&&(p&(0x08000000n|0x40000000n))!==0n)return-95n}const f=this.signals.action(i,c);return a&&new Uint8Array(this.memory().buffer).set(f,a),0n},SYS_rt_sigprocmask:(e,t,r,n)=>{const i=Number(t),o=Number(r),a=Number(e);if(Number(n)!==8||i&&![0,1,2].includes(a))return-22n;if(i&&!this.range(i,8)||o&&!this.range(o,8))return-14n;const c=new DataView(this.memory().buffer),f=i?c.getBigUint64(i,!0):0n;return o&&c.setBigUint64(o,this.mask,!0),i&&(this.mask=(a===0?this.mask|f:a===1?this.mask&~f:f)&~Bc,this.signals.changed()),0n},SYS_rt_sigpending:(e,t)=>Number(t)!==8?-22n:this.range(Number(e),8)?(new DataView(this.memory().buffer).setBigUint64(Number(e),this.signals.pending(),!0),0n):-14n}}deliver(e=!1){if(this.delivering||!this.signals.anyPending()||(this.signals.pending()&~this.mask)===0n||!e&&this.held())return!1;this.delivering=!0;let t=!1,r=!0;try{for(let n=0;n<64;n++){const i=this.signals.take(this.mask);if(!i)return t&&r;const o=new DataView(i.action.buffer),a=o.getUint32(0,!0);if(a<=1)continue;t=!0,(o.getBigUint64(4,!0)&Fc)===0n&&(r=!1);const c=this.table()?.get(a);if(typeof c!="function")throw new Error(`Invalid WALI signal handler ${a}.`);const f=this.mask;this.mask|=o.getBigUint64(16,!0)|tn(i.signal);try{if((o.getBigUint64(4,!0)&4n)!==0n){if(this.scratch||(this.scratch=this.allocateScratch()),this.scratch<=0)throw new Error("Cannot allocate WALI signal information.");new Uint8Array(this.memory().buffer).fill(0,this.scratch,this.scratch+128);const d=new DataView(this.memory().buffer);d.setInt32(this.scratch,i.signal,!0),d.setInt32(this.scratch+8,i.signal===Vi?1:0,!0),d.setInt32(this.scratch+16,i.pid,!0),d.setInt32(this.scratch+20,1e3,!0),d.setInt32(this.scratch+24,i.status,!0),c(i.signal,this.scratch,0)}else c(i.signal)}finally{this.mask=f}}return t&&r}finally{this.delivering=!1}}}function Uc(s,e){let t;return()=>{if(t===void 0){const r=s()?.__wali_private_tree_busy;if(typeof r!="function")return!1;t=Number(r())>>>2}return Atomics.load(new Int32Array(e().buffer),t)!==0}}function nr(s){if(!s||typeof s!="object"||Object.keys(s).some(t=>t!=="writableRoots")||!Array.isArray(s.writableRoots)||s.writableRoots.length>128)throw new TypeError("Invalid process filesystem policy: expected up to 128 writableRoots.");const e=[...new Set(Array.from(s.writableRoots,ha))].sort();return Object.freeze({writableRoots:Object.freeze(e.filter(t=>!e.some(r=>r!==t&&Gn(t,r))))})}function Wc(s,e){const t=nr(s);if(e===void 0)return t;const r=nr(e);return nr({writableRoots:t.writableRoots.flatMap(n=>r.writableRoots.flatMap(i=>Gn(n,i)?[n]:Gn(i,n)?[i]:[]))})}function $c(s,e){const t=nr(e),r=n=>t.writableRoots.some(i=>Gn(n,i));return n=>{const i=ha(n);r(i)||ms(i);let o="";for(const a of i.split("/").filter(Boolean)){o+=`/${a}`;try{s.lstatSync(o).isSymbolicLink()&&ms(i)}catch(c){if(c.code!=="ENOENT")throw c;r(o)||ms(o)}}return i}}function ha(s){if(typeof s!="string"||!s.startsWith("/")||s.includes("\0")||s.length>8192)throw new TypeError("Filesystem policy paths must be absolute paths without NUL bytes.");const e=[];for(const t of s.split("/"))t===".."?e.pop():t&&t!=="."&&e.push(t);return`/${e.join("/")}`}function Gn(s,e){return e==="/"||s===e||s.startsWith(`${e}/`)}function ms(s){throw Object.assign(new Error(`EACCES: process filesystem policy denies mutation of '${s}'`),{code:"EACCES",path:s})}function zc(s,e,t){return(...r)=>{if(!e())return-95;if(r.length!==9)return-22;const n=Number(r[7]),i=Number(r[8]);if(!Number.isSafeInteger(i)||i<1||i>65536)return-22;const o=s().buffer;if(!Number.isSafeInteger(n)||n<=0||n>o.byteLength-i)return-14;let a;try{const c=new Uint8Array(o,n,i).slice();a=nr(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c)))}catch{return-22}return t(r.slice(0,7),a)}}const Hc=new Set(["_Unwind_Backtrace","_Unwind_FindEnclosingFunction","_Unwind_GetCFA"]);function Vc(s){return s.module==="env"&&(s.kind==="function"&&Hc.has(s.name)||s.kind==="memory"&&s.name==="memory")}async function Gc(s){if(s instanceof WebAssembly.Module)return s;const e=s instanceof Uint8Array?s:new Uint8Array(s);return WebAssembly.compile(e)}function jc(s){return WebAssembly.Module.imports(s).map(({module:e,name:t,kind:r})=>({module:e,name:t,kind:r}))}function Kc(s){const e=s.filter(t=>!(t.kind==="function"&&t.module==="wali"||Vc(t)));if(e.length!==0)throw new Error(`Not a supported WALI module: ${e.map(Xc).join(", ")}`)}function Xc(s){return`${s.module}.${s.name} (${s.kind})`}const Jc=new Set(["SYS_rt_sigreturn","SYS_futex","SYS_pause","SYS_rt_sigsuspend"]),Qc=-38n;function Zc(s){return!s.startsWith("SYS_")||Jc.has(s)}class ii{nextId=1;pipeMetadata;constructor(e=new SharedArrayBuffer(65536*3*4)){this.pipeMetadata=new Int32Array(e)}descriptions=new Map;create(e,t,r){for(;this.nextId<65536&&this.descriptions.has(this.nextId);)this.nextId++;if(this.nextId>=65536){for(this.nextId=1;this.descriptions.has(this.nextId);)this.nextId++;if(this.nextId>=65536)throw new Error("EMFILE")}const n={id:this.nextId++,kind:e,value:t,references:0,release:r};return this.descriptions.set(n.id,n),e==="special"&&typeof t=="object"&&t!==null&&"stdio"in t&&Atomics.store(this.pipeMetadata,n.id*3+2,Number(t.stdio)+1),n}get(e){return this.descriptions.get(e)}retain(e){const t=this.descriptions.get(e);if(!t)throw new Error(`Unknown open description ${e}`);t.references++}release(e){const t=this.descriptions.get(e);if(!t||t.references<=0)throw new Error(`Unbalanced description release ${e}`);--t.references===0&&(this.descriptions.delete(e),Atomics.store(this.pipeMetadata,e*3,0),Atomics.store(this.pipeMetadata,e*3+1,0),Atomics.store(this.pipeMetadata,e*3+2,0),t.release?.())}}class on{registry;entries=[];named=new Map;sharedEntries;constructor(e,t=new SharedArrayBuffer(65536*4)){this.registry=e,this.sharedEntries=new Int32Array(t)}get(e){const t=this.entries[e];return t&&this.registry.get(t.description)}set(e,t,r=0){this.registry.retain(t.id),this.close(e),this.entries[e]={description:t.id,flags:r},this.named.set(t.id,(this.named.get(t.id)??0)+1),Atomics.store(this.sharedEntries,e,t.id)}close(e){const t=this.entries[e];if(!t)return!1;delete this.entries[e];const r=(this.named.get(t.description)??1)-1;return r>0?this.named.set(t.description,r):this.named.delete(t.description),Atomics.store(this.sharedEntries,e,0),this.registry.release(t.description),!0}names(e){return this.named.has(e)}copy(){const e=new on(this.registry);return this.entries.forEach((t,r)=>{t&&e.set(r,this.registry.get(t.description),t.flags)}),e}exec(){this.entries.forEach((e,t)=>{e&&e.flags&1&&this.close(t)})}exit(){this.entries.forEach((e,t)=>{e&&this.close(t)})}view(e,t){return new qc(this,e,t)}}class qc{table;kind;release;constructor(e,t,r){this.table=e,this.kind=t,this.release=r}resolvedEntries=[];resolvedValues=[];resolvedOwn=[];resolve(e){const t=this.table.entries[e];if(t===void 0)return this.resolvedEntries[e]!==void 0&&(this.resolvedEntries[e]=void 0,this.resolvedValues[e]=void 0),!1;if(this.resolvedEntries[e]!==t){const r=this.table.registry.get(t.description),n=r?.kind===this.kind;this.resolvedEntries[e]=t,this.resolvedValues[e]=n?r.value:void 0,this.resolvedOwn[e]=n}return this.resolvedOwn[e]}get(e){return this.resolve(e)?this.resolvedValues[e]:void 0}has(e){return this.resolve(e)}set(e,t){const r=this.table.registry.create(this.kind,t,()=>this.release?.(t));this.table.set(e,r)}delete(e){return this.has(e)?(this.resolvedEntries[e]=void 0,this.resolvedValues[e]=void 0,this.table.close(e)):!1}*values(){for(let e=0;e<this.table.entries.length;e++)this.has(e)&&(yield this.get(e))}}function jn(){return typeof performance>"u"?Date.now():performance.timeOrigin+performance.now()}function ge(){return typeof performance>"u"?Date.now():performance.timeOrigin+performance.now()}const ys=0,Gi=1,ji=2,Yr=3,el=4,tl=5,ws=6;class Qs{buffer;control;bytes;constructor(e){if(this.buffer=e,e.byteLength<=Int32Array.BYTES_PER_ELEMENT*ws+1)throw new Error("WALI stdin shared buffer is too small.");this.control=new Int32Array(e,0,ws),this.bytes=new Uint8Array(e,Int32Array.BYTES_PER_ELEMENT*ws)}read(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("WALI stdin read length is invalid.");if(e===0)return new Uint8Array;for(;;){const t=Atomics.load(this.control,ys),r=Atomics.load(this.control,Gi),n=Ki(t,r,this.bytes.byteLength);if(n>0){const o=Math.min(e,n),a=new Uint8Array(o);for(let c=0;c<o;c+=1)a[c]=this.bytes[(t+c)%this.bytes.byteLength];return Atomics.store(this.control,ys,(t+o)%this.bytes.byteLength),a}if(Atomics.load(this.control,ji)!==0)return new Uint8Array;const i=Atomics.load(this.control,Yr);_r(this.control,Yr,i)}}poll(){return Atomics.load(this.control,ji)!==0||this.available()>0}wait(e){if(this.poll())return!0;const t=Atomics.load(this.control,Yr);return this.poll()?!0:(_r(this.control,Yr,t,e<0?void 0:Math.max(0,e)),this.poll())}available(){return Ki(Atomics.load(this.control,ys),Atomics.load(this.control,Gi),this.bytes.byteLength)}generation(){return Atomics.load(this.control,Yr)}terminalSize(){return{columns:Atomics.load(this.control,tl)||80,rows:Atomics.load(this.control,el)||24}}}class da{bytes;offset=0;constructor(e){this.bytes=e}read(e){const t=this.bytes.slice(this.offset,this.offset+Math.max(0,e));return this.offset+=t.byteLength,t}poll(){return this.offset<this.bytes.byteLength}wait(){return this.poll()}available(){return Math.max(0,this.bytes.byteLength-this.offset)}}function Ki(s,e,t){return e>=s?e-s:t-s+e}const de=new TextEncoder().encode("\0supercode-wali-symlink-v1\0"),ua=40,Kn=4096;function rl(s,e,t){if(s.existsSync(t))throw Xn("EEXIST");const r=new TextEncoder().encode(e);if(r.byteLength>=Kn)throw Xn("ENAMETOOLONG");const n=new Uint8Array(de.byteLength+r.byteLength);n.set(de),n.set(r,de.byteLength),s.writeFileSync(t,n)}function Cn(s,e){if(s.linkTargetSync)return s.linkTargetSync(e,de.byteLength,de.byteLength+Kn,ma);if(!s.existsSync(e))return;const t=s.statSync(e);if(!t.isFile()||t.size<de.byteLength||t.size>de.byteLength+Kn)return;if(s.readRangeSync){const n=s.readRangeSync(e,0,de.byteLength);for(let i=0;i<de.byteLength;i+=1)if(n[i]!==de[i])return}const r=s.readFileSync(e);if(!(r.byteLength<de.byteLength)){for(let n=0;n<de.byteLength;n+=1)if(r[n]!==de[n])return;return new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(de.byteLength,ya(r)))}}function ma(s){if(!(s.byteLength<de.byteLength)){for(let e=0;e<de.byteLength;e+=1)if(s[e]!==de[e])return;return new TextDecoder("utf-8",{fatal:!0}).decode(s.slice(de.byteLength,ya(s)))}}function ya(s){const e=s.indexOf(0,de.byteLength);return e<0?s.byteLength:e}function nl(s,e,t=!0){if(s.linkTargetSync&&il(e))return sl(s,e,t);let r=e;for(let n=0;n<ua;n+=1){const i=r.split("/").filter(Boolean);let o=!1;for(let a=0;a<i.length&&!(!t&&a===i.length-1);a+=1){const c=`/${i.slice(0,a+1).join("/")}`,f=Cn(s,c);if(f===void 0)continue;const d=`/${i.slice(0,a).join("/")}`,y=f.startsWith("/")?Er(f):Er(`${d}/${f}`);r=Er(`${y}/${i.slice(a+1).join("/")}`),o=!0;break}if(!o)return r}throw Xn("ELOOP")}function sl(s,e,t){let r=e;for(let n=0;n<ua;n+=1){let i=!1,o=1;for(;o<=r.length;){const a=r.indexOf("/",o),c=a===-1;if(!t&&c)break;const f=c?r:r.slice(0,a),d=f.length>1?s.linkTargetSync(f,de.byteLength,de.byteLength+Kn,ma,!0):void 0;if(d!==void 0){const y=f.slice(0,f.lastIndexOf("/"))||"/",p=d.startsWith("/")?Er(d):Er(`${y}/${d}`);r=Er(c?p:`${p}/${r.slice(a+1)}`),i=!0;break}if(c)break;o=a+1}if(!i)return r}throw Xn("ELOOP")}function il(s){if(s.charCodeAt(0)!==47)return!1;if(s.length===1)return!0;let e=1;for(let t=1;t<=s.length;t+=1){const r=t<s.length?s.charCodeAt(t):47;if(r===92)return!1;if(r!==47)continue;const n=t-e;if(n===0||s.charCodeAt(e)===46&&(n===1||n===2&&s.charCodeAt(e+1)===46))return!1;e=t+1}return!0}function Er(s){const e=[];for(const t of s.replaceAll("\\","/").split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}function Xn(s){return Object.assign(new Error(s),{code:s})}const wa=1463897161,ol=1,al=2,cl=3,ll=4,Zr=5e4,Zs=4096,fl=1<<24,pa=827479120;function ze(s){return s>=Zr&&s<Zr+Zs}function hl(s,e=[]){const t=new TextEncoder,r=s.map(A=>t.encode(A.path)),n=e.map(A=>t.encode(A.path));let i=12;s.forEach((A,k)=>{i+=4+r[k].byteLength+4+4+8+8+8+4+(A.directory?0:A.content.byteLength)}),e.forEach((A,k)=>{i+=16+n[k].byteLength+4+8+4});const o=new Uint8Array(i),a=new DataView(o.buffer);let c=0;const f=A=>{a.setUint32(c,A,!0),c+=4},d=A=>{a.setFloat64(c,A,!0),c+=8},y=A=>{a.setBigUint64(c,BigInt(A),!0),c+=8},p=A=>{o.set(A,c),c+=A.byteLength};return f(pa),f(s.length),f(e.length),s.forEach((A,k)=>{f(r[k].byteLength),p(r[k]),f(A.directory?1:0),f(A.mode),d(A.atimeMs),d(A.mtimeMs),y(A.ino);const _=A.directory?new Uint8Array:A.content;f(_.byteLength),p(_)}),e.forEach((A,k)=>{f(A.fd),f(A.group),f(A.closeOnExec?1:0),f(n[k].byteLength),p(n[k]),f(A.flags>>>0),d(A.position),f(A.directory?1:0)}),o}function dl(s,e){const t=new DataView(s.buffer,s.byteOffset,s.byteLength),r=new TextDecoder("utf-8",{fatal:!0});let n=0;const i=_=>{if(_<0||n+_>s.byteLength)throw Cr()},o=()=>{i(4);const _=t.getUint32(n,!0);return n+=4,_},a=()=>{i(8);const _=t.getFloat64(n,!0);return n+=8,_},c=()=>{i(8);const _=Number(t.getBigUint64(n,!0));return n+=8,_},f=_=>{i(_);const E=s.slice(n,n+_);return n+=_,E},d=()=>{const _=r.decode(f(o()));if(_!==e&&!_.startsWith(`${e}/`))throw Cr();return _};if(o()!==pa)throw Cr();const y=o(),p=o(),A=[];for(let _=0;_<y;_+=1){const E=d(),L=o()===1,x=o(),D=a(),z=a(),oe=c(),fe=f(o());A.push({path:E,directory:L,mode:x,atimeMs:D,mtimeMs:z,ino:oe,content:fe})}const k=[];for(let _=0;_<p;_+=1){const E=o(),L=o(),x=o()===1,D=d(),z=o()|0,oe=a(),fe=o()===1;if(!ze(E)||!ze(L)||L>E||!Number.isSafeInteger(oe)||oe<0)throw Cr();k.push({fd:E,group:L,closeOnExec:x,path:D,flags:z,position:oe,directory:fe})}if(n!==s.byteLength)throw Cr();return{nodes:A,descriptors:k}}function Cr(){return Object.assign(new Error("EINVAL: the private tree handed back is not one"),{errnoName:"EINVAL"})}let Xi=!1;const ps=-100,Ot=3,Ji=1,ul=2,gs=64,ml=128,yl=512,Ur=1024,wl=2048,pl=65536,Ss=0,Qi=1,Zi=2,qi=524288,bs=5,gl=6,eo=7,kn=36,Sl=37,to=38,Es=2,ro=0,no=1,bl=1,El=2,Al=4,_l=8,pr=256,so=512,Nl=0x3fffffffn,Il=0x3ffffffen,kl=32768,Ml=16384,xl=40960;function Ll(){const s=new Int32Array(new SharedArrayBuffer(65536*Int32Array.BYTES_PER_ELEMENT));return s.fill(-1),s[0]=0,s[1]=1,s[2]=2,s}class Jn{options;descriptors;files;specialDescriptors;stdioAliases;descriptorStatusFlags=new Map;stdin;nextDescription=1;cwd;guestFilesystem;assertWritable;privateTree;privateTreeDeclined=!1;constructor(e){this.options=e,this.descriptors=e.descriptors??new on(new ii),this.files=this.descriptors.view("file"),this.specialDescriptors=this.descriptors.view("special",r=>r.close?.()),this.stdioAliases=this.descriptors.view("stdio"),this.cwd=gr("/",e.cwd);const t=e.filesystem;if(this.assertWritable=e.filesystemPolicy?$c({lstatSync:r=>{if(!t)throw Y("ENOSYS");const n=t.lstatSync?.(r)??t.statSync(r);return{isSymbolicLink:()=>n.isSymbolicLink?.()===!0||Cn(t,r)!==void 0}}},e.filesystemPolicy):r=>r,this.guestFilesystem=t&&e.filesystemPolicy?{existsSync:t.existsSync.bind(t),statSync:t.statSync.bind(t),...t.lstatSync?{lstatSync:t.lstatSync.bind(t)}:{},readFileSync:t.readFileSync.bind(t),readFile:t.readFile.bind(t),readdirSync:t.readdirSync.bind(t),writeFileSync:(r,n)=>t.writeFileSync(this.assertWritable(r),n),...t.readRangeSync?{readRangeSync:t.readRangeSync.bind(t)}:{},...t.linkTargetSync?{linkTargetSync:t.linkTargetSync.bind(t)}:{},...t.viewRangeSync?{viewRangeSync:t.viewRangeSync.bind(t)}:{},...t.writeRangeSync?{writeRangeSync:(r,n,i)=>t.writeRangeSync(this.assertWritable(r),n,i)}:{},...t.truncateSync?{truncateSync:(r,n)=>t.truncateSync(this.assertWritable(r),n)}:{},mkdirSync:(r,n)=>t.mkdirSync(this.assertWritable(r),n),unlinkSync:r=>t.unlinkSync(this.assertWritable(r)),rmdirSync:r=>t.rmdirSync(this.assertWritable(r)),renameSync:(r,n)=>t.renameSync(this.assertWritable(r),this.assertWritable(n)),...t.chmodSync?{chmodSync:(r,n)=>t.chmodSync(this.assertWritable(r),n)}:{},...t.utimesSync?{utimesSync:(r,n,i)=>t.utimesSync(this.assertWritable(r),n,i)}:{},...t.reserveInodes?{reserveInodes:t.reserveInodes.bind(t)}:{},...t.restoreNodeSync?{restoreNodeSync:(r,n)=>t.restoreNodeSync(this.assertWritable(r),n)}:{}}:t,this.stdin="read"in e.stdin?e.stdin:new da(e.stdin),e.descriptors){if(this.descriptors.entries.length===0&&!e.descriptorState)for(const r of[0,1,2])this.specialDescriptors.set(r,{stdio:r})}else for(const r of[0,1,2])this.specialDescriptors.set(r,{stdio:r})}ownsFile(e){return this.files.has(e)}imports(){return{SYS_open:(e,t,r)=>this.open(this.readCString(Number(e)),Number(t),Number(r)),SYS_openat:(e,t,r,n)=>this.openAt(Number(e),this.readCString(Number(t)),Number(r),Number(n)),SYS_close:e=>this.close(Number(e)),SYS_read:(e,t,r)=>this.read(Number(e),Number(t),Number(r)),SYS_pread64:(e,t,r,n)=>this.pread(Number(e),Number(t),Number(r),Number(n)),SYS_write:(e,t,r)=>this.write(Number(e),Number(t),Number(r)),SYS_pwrite64:(e,t,r,n)=>this.pwrite(Number(e),Number(t),Number(r),Number(n)),SYS_readv:(e,t,r)=>this.readv(Number(e),Number(t),Number(r)),SYS_writev:(e,t,r)=>this.writev(Number(e),Number(t),Number(r)),SYS_preadv:(e,t,r,n,i)=>this.preadv(Number(e),Number(t),Number(r),io(n,i)),SYS_pwritev:(e,t,r,n,i)=>this.pwritev(Number(e),Number(t),Number(r),io(n,i)),SYS_lseek:(e,t,r)=>this.lseek(Number(e),Number(t),Number(r)),SYS_ftruncate:(e,t)=>this.ftruncate(Number(e),Number(t)),SYS_fstat:(e,t)=>this.fstat(Number(e),Number(t)),SYS_stat:(e,t)=>this.stat(this.readCString(Number(e)),Number(t),!1),SYS_lstat:(e,t)=>this.stat(this.readCString(Number(e)),Number(t),!0),SYS_newfstatat:(e,t,r,n)=>this.statAt(Number(e),this.readCString(Number(t)),Number(r),Number(n)),SYS_access:e=>this.access(this.readCString(Number(e))),SYS_faccessat:(e,t)=>this.accessAt(Number(e),this.readCString(Number(t))),SYS_faccessat2:(e,t)=>this.accessAt(Number(e),this.readCString(Number(t))),SYS_chmod:(e,t)=>this.chmod(this.readCString(Number(e)),Number(t)),SYS_fchmod:(e,t)=>this.fchmod(Number(e),Number(t)),SYS_fchmodat:(e,t,r,n)=>this.chmodAt(Number(e),this.readCString(Number(t)),Number(r),Number(n)),SYS_chdir:e=>this.chdir(this.readCString(Number(e))),SYS_fchdir:e=>this.fchdir(Number(e)),SYS_getcwd:(e,t)=>this.getcwd(Number(e),Number(t)),SYS_mkdir:(e,t)=>this.mkdir(this.readCString(Number(e)),Number(t)),SYS_mkdirat:(e,t,r)=>this.mkdirAt(Number(e),this.readCString(Number(t)),Number(r)),SYS_statfs:(e,t)=>this.statfs(this.readCString(Number(e)),Number(t)),SYS_fstatfs:(e,t)=>this.fstatfs(Number(e),Number(t)),SYS_inotify_init:()=>this.inotifyInit(),SYS_inotify_init1:()=>this.inotifyInit(),SYS_inotify_add_watch:(e,t)=>this.inotifyAddWatch(Number(e),this.readCString(Number(t))),SYS_inotify_rm_watch:e=>this.specialDescriptors.has(Number(e))?0n:-9n,SYS_rmdir:e=>this.mutate(()=>this.fs().rmdirSync(this.resolveFilesystemPath(this.resolve(this.readCString(Number(e))),!1))),SYS_unlink:e=>this.mutate(()=>this.fs().unlinkSync(this.resolveFilesystemPath(this.resolve(this.readCString(Number(e))),!1))),SYS_unlinkat:(e,t,r)=>this.unlinkAt(Number(e),this.readCString(Number(t)),Number(r)),SYS_rename:(e,t)=>this.rename(this.readCString(Number(e)),this.readCString(Number(t))),SYS_utimensat:(e,t,r,n)=>this.utimensat(Number(e),Number(t),Number(r),Number(n)),SYS_symlink:(e,t)=>this.symlink(this.readCString(Number(e)),this.readCString(Number(t)),ps),SYS_symlinkat:(e,t,r)=>this.symlink(this.readCString(Number(e)),this.readCString(Number(r)),Number(t)),SYS_readlink:(e,t,r)=>this.readlink(this.readCString(Number(e)),Number(t),Number(r),ps),SYS_readlinkat:(e,t,r,n)=>this.readlink(this.readCString(Number(t)),Number(r),Number(n),Number(e)),SYS_dup:e=>this.dup(Number(e)),SYS_dup2:(e,t)=>this.dup(Number(e),Number(t)),SYS_dup3:(e,t,r)=>{const n=Number(r);return(n&~qi)!==0||Number(e)===Number(t)?-22n:this.markCloseOnExec(this.dup(Number(e),Number(t)),n)},SYS_fcntl:(e,t,r)=>this.fcntl(Number(e),Number(t),vl(r)),SYS_poll:(e,t,r)=>this.poll(Number(e),Number(t),Number(r)),SYS_getdents64:(e,t,r)=>this.getdents64(Number(e),Number(t),Number(r)),SYS_fsync:e=>this.hasFd(Number(e))?0n:-9n,SYS_fdatasync:e=>this.hasFd(Number(e))?0n:-9n,SYS_flock:(e,t)=>this.flock(Number(e),Number(t)),SYS_prctl:(e,t,r,n)=>Number(e)===wa?this.privateTreeCall(Number(t),Number(r),Number(n)):0n}}writeEnvironmentFile(e,t){if(!this.options.filesystem||Object.keys(e).length===0)return;const r=`/tmp/.browser-runtime-wali-env-${t}-${crypto.randomUUID()}`;try{this.options.filesystem.mkdirSync("/tmp",{recursive:!0})}catch{}const n=[],i=[];for(const[o,a]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(o)||/[\u0000\r\n]/u.test(a)){n.push(o);continue}i.push(`${o}=${a}`)}return n.length>0&&!Xi&&(Xi=!0,console.warn(`[WALI] environment entries a process cannot receive were dropped: ${n.join(", ")}`)),this.options.filesystem.writeFileSync(r,`${i.join(`
4
+ `)}
5
+ `),this.options.filesystem.chmodSync?.(r,384),r}copyCString(e,t,r){const n=new TextEncoder().encode(`${t}\0`);return r<n.byteLength?0:(this.copyIn(e,n),1)}readForMapping(e,t,r){const n=this.files.get(e);if(!n||n.directory||t<0||r<0)return;const i=this.fs();return i.readRangeSync?i.readRangeSync(n.path,t,r):i.readFileSync(n.path).slice(t,t+r)}mappingPath(e){const t=this.files.get(e);return t&&!t.directory?t.path:void 0}writeForMapping(e,t,r){try{if(!Number.isSafeInteger(t)||t<0||!this.fs().existsSync(e)||!this.fs().statSync(e).isFile())return!1;const i=this.fs().readFileSync(e),o=new Uint8Array(Math.max(i.byteLength,t+r.byteLength));return o.set(i),o.set(r,t),this.fs().writeFileSync(e,o),!0}catch{return!1}}markCloseOnExecNumber(e,t){return t&qi&&(this.descriptors.entries[e].flags=1),e}markCloseOnExec(e,t){return e>=0n&&this.markCloseOnExecNumber(Number(e),t),e}allocateSpecial(e,t=3){const r=this.allocateFd(Math.max(t,this.options.specialDescriptorMinimum??3));return this.specialDescriptors.set(r,e),r}exportBrowserProcessPipe(e){return this.specialDescriptors.get(e)?.browserProcessPipe}copyForFork(e){return new Jn({...this.options,cwd:this.cwd,memory:e,descriptors:this.descriptors.copy()})}copyForExec(e,t){const r=this.descriptors.copy();return t&&t.map(i=>this.descriptors.get(i)).forEach((i,o)=>{i&&t[o]!==o&&r.set(o,i)}),r.exec(),new Jn({...this.options,cwd:this.cwd,memory:e,descriptors:r})}currentWorkingDirectory(){return this.cwd}ioctl(e,t){if(this.hasFd(e)&&(t===21537||t===21585||t===21584))return 0n}pollDescriptor(e,t){if(e<0||!this.hasFd(e))return 32;const r=this.specialDescriptors.get(e);if(r&&r.stdio===void 0)return r.poll?.(t)??0;const n=this.stdioFd(e);let i=0;return t&1&&n===0&&this.stdin.poll()&&(i|=1),t&4&&n!==0&&(i|=4),i}fs(){if(!this.guestFilesystem)throw Y("ENOSYS");return this.guestFilesystem}viewedBuffer;viewedBytes=new Uint8Array;viewedData=new DataView(new ArrayBuffer(0));memoryBytes(){return this.viewMemory(),this.viewedBytes}memoryView(){return this.viewMemory(),this.viewedData}viewMemory(){const e=this.options.memory().buffer;e!==this.viewedBuffer&&(this.viewedBuffer=e,this.viewedBytes=new Uint8Array(e),this.viewedData=new DataView(e))}copyOut(e,t){return ct(this.options.memory(),e,t),this.memoryBytes().slice(e,e+t)}copyIn(e,t){ct(this.options.memory(),e,t.byteLength),this.memoryBytes().set(t,e)}readCString(e){const t=this.memoryBytes();if(!Number.isSafeInteger(e)||e<0||e>=t.byteLength)throw new WebAssembly.RuntimeError("WALI string pointer is out of bounds.");const r=t.indexOf(0,e);if(r<0||r-e>1048576)throw new WebAssembly.RuntimeError("WALI string is not null terminated.");let n="";for(let i=e;i<r;i+=1){const o=t[i];if(o>=128)return Bl.decode(t.slice(e,r));n+=String.fromCharCode(o)}return n}resolve(e){return gr(this.cwd,e)}resolveAt(e,t){if(t.startsWith("/"))return gr("/",t);if(e===ps)return this.resolve(t);const r=this.files.get(e);if(!r?.directory)throw Y("ENOTDIR");return gr(r.path,t)}open(e,t,r){try{return BigInt(this.openResolved(this.resolveFilesystemPath(this.resolve(e)),t,r))}catch(n){return ee(n)}}openAt(e,t,r,n){try{return BigInt(this.openResolved(this.resolveFilesystemPath(this.resolveAt(e,t)),r,n))}catch(i){return ee(i)}}openResolved(e,t,r){if(e==="/dev/null")return this.markCloseOnExecNumber(this.allocateSpecial({read:()=>new Uint8Array,write:y=>BigInt(y.byteLength),poll:y=>(y&1?1:0)|(y&4?4:0),fcntl:y=>y===3?BigInt(t):[1,2,4].includes(y)?0n:-22n}),t);if(e==="/dev/urandom"||e==="/dev/random")return this.markCloseOnExecNumber(this.allocateSpecial({read:y=>{if(!Number.isSafeInteger(y)||y<0)return-22n;const p=new Uint8Array(y);for(let A=0;A<p.byteLength;A+=65536)crypto.getRandomValues(p.subarray(A,Math.min(A+65536,p.byteLength)));return p},write:y=>BigInt(y.byteLength),poll:y=>(y&1?1:0)|(y&4?4:0),fcntl:y=>y===3?BigInt(t):[1,2,4].includes(y)?0n:-22n}),t);const n=this.fs();let i=n.linkTargetSync?Tl(n,e):n.existsSync(e)?n.statSync(e):void 0;const o=i!==void 0;if(((t&Ot)!==0||!o&&t&gs)&&this.assertWritable(e),!o&&!(t&gs))throw Y("ENOENT");if(o&&t&gs&&t&ml)throw Y("EEXIST");o||(n.writeFileSync(e,new Uint8Array),n.chmodSync?.(e,r&4095),this.options.fileLocks?.created?.(e),i=n.statSync(e));const a=i;if(t&pl&&!a.isDirectory())throw Y("ENOTDIR");if(a.isDirectory()&&(t&Ot)!==0)throw Y("EISDIR");const c=(t&yl)!==0&&(t&Ot)!==0&&a.isFile();c&&(n.truncateSync?n.truncateSync(e,0):n.writeFileSync(e,new Uint8Array));const f=this.allocateFd(),d=a.isDirectory();return this.files.set(f,{path:e,flags:t,position:t&Ur&&!c&&a.isFile()?a.size:0,directory:d,description:this.nextDescription++}),this.descriptors.entries[f].flags=t&524288?1:0,f}allocateFd(e=3){const t=this.options.descriptorMaximum??65535;for(let r=Math.max(e,0);r<=t;r+=1){if(ze(r)){r=Zr+Zs-1;continue}if(!(this.descriptors.get(r)||this.files.has(r)||this.specialDescriptors.has(r)||this.stdioFd(r)!==void 0))return r}throw Y("EMFILE")}close(e){if(this.stdioAliases.delete(e))return this.descriptorStatusFlags.delete(e),this.setSharedStdioAlias(e,void 0),0n;if(this.specialDescriptors.get(e))return this.specialDescriptors.delete(e),0n;const r=this.files.get(e);if(!r)return-9n;const n=this.descriptors.get(e);return this.files.delete(e),this.releasePosixLocks(r.path),this.lockingOwners.size>0&&(!n||!this.descriptors.names(n.id))&&(this.releaseLockOwner(this.lockOwner("ofd",r)),this.releaseLockOwner(this.lockOwner("flock",r))),0n}read(e,t,r){try{if(r<0)throw Y("EINVAL");if(this.stdioFd(e)===0){if(this.statusFlags(e)&wl&&!this.stdin.poll())return-11n;const c=this.stdin.read(r);return this.copyIn(t,c),BigInt(c.byteLength)}const n=this.specialDescriptors.get(e);if(n){const c=n.read?.(r);if(c===void 0)throw Y("EBADF");if(typeof c=="bigint")return c;const f=c.subarray(0,r);return this.copyIn(t,f),BigInt(f.byteLength)}const i=this.files.get(e);if(!i)throw Y("EBADF");if(i.directory)throw Y("EISDIR");if((i.flags&Ot)===Ji)throw Y("EBADF");const o=this.fs(),a=o.viewRangeSync?o.viewRangeSync(i.path,i.position,r):o.readRangeSync?o.readRangeSync(i.path,i.position,r):o.readFileSync(i.path).subarray(i.position,i.position+r);return this.copyIn(t,a),i.position+=a.byteLength,BigInt(a.byteLength)}catch(n){return ee(n)}}write(e,t,r){try{const n=this.stdioFd(e);if(n===1||n===2)return this.options.emit(n,this.copyOut(t,r));const i=this.specialDescriptors.get(e);if(i)return i.write?.(this.copyOut(t,r))??-9n;const o=this.files.get(e);if(!o)throw Y("EBADF");if(o.directory)throw Y("EISDIR");if((o.flags&Ot)===0)throw Y("EBADF");const a=this.fs();if(a.writeRangeSync)return o.flags&Ur&&(o.position=a.statSync(o.path).size),ct(this.options.memory(),t,r),a.writeRangeSync(o.path,o.position,this.memoryBytes().subarray(t,t+r)),o.position+=r,BigInt(r);const c=this.copyOut(t,r),f=a.readFileSync(o.path);o.flags&Ur&&(o.position=f.byteLength);const d=Math.max(f.byteLength,o.position+c.byteLength),y=new Uint8Array(d);return y.set(f),y.set(c,o.position),a.writeFileSync(o.path,y),o.position+=c.byteLength,BigInt(c.byteLength)}catch(n){return ee(n)}}pread(e,t,r,n){const i=this.files.get(e);if(!i)return-9n;if(i.directory||!Number.isSafeInteger(n)||n<0)return-22n;const o=i.position;i.position=n;try{return this.read(e,t,r)}finally{i.position=o}}pwrite(e,t,r,n){const i=this.files.get(e);if(!i)return-9n;if(i.directory||!Number.isSafeInteger(n)||n<0)return-22n;const o=i.position,a=i.flags;i.position=n,i.flags&=~Ur;try{return this.write(e,t,r)}finally{i.position=o,i.flags=a}}preadv(e,t,r,n){const i=this.files.get(e);if(!i)return-9n;if(i.directory||!Number.isSafeInteger(n)||n<0)return-22n;const o=i.position;i.position=n;try{return this.readv(e,t,r)}finally{i.position=o}}pwritev(e,t,r,n){const i=this.files.get(e);if(!i)return-9n;if(i.directory||!Number.isSafeInteger(n)||n<0)return-22n;const o=i.position,a=i.flags;i.position=n,i.flags&=~Ur;try{return this.writev(e,t,r)}finally{i.position=o,i.flags=a}}readv(e,t,r){let n=0n;for(let i=0;i<r;i+=1){const o=t+i*8;ct(this.options.memory(),o,8);const a=this.read(e,this.memoryView().getUint32(o,!0),this.memoryView().getUint32(o+4,!0));if(a<0n)return n>0n?n:a;if(n+=a,a===0n)break}return n}writev(e,t,r){let n=0n;for(let i=0;i<r;i+=1){const o=t+i*8;ct(this.options.memory(),o,8);const a=this.write(e,this.memoryView().getUint32(o,!0),this.memoryView().getUint32(o+4,!0));if(a<0n)return n>0n?n:a;n+=a}return n}getdents64(e,t,r){try{const n=this.files.get(e);if(!n)throw Y("EBADF");if(!n.directory)throw Y("ENOTDIR");const i=[".","..",...this.fs().readdirSync(n.path)];let o=0;for(;n.position<i.length;){const a=i[n.position],c=new TextEncoder().encode(a),f=Rl(19+c.byteLength+1,8);if(f>r-o){if(o===0)throw Y("EINVAL");break}const d=t+o;ct(this.options.memory(),d,f);const y=a==="."?n.path:a===".."?gr(n.path,".."):gr(n.path,a),p=this.fs().statSync(y);this.memoryView().setBigUint64(d,BigInt(n.position+1),!0),this.memoryView().setBigInt64(d+8,BigInt(n.position+1),!0),this.memoryView().setUint16(d+16,f,!0),this.memoryView().setUint8(d+18,p.isDirectory()?4:8),this.memoryBytes().fill(0,d+19,d+f),this.memoryBytes().set(c,d+19),n.position+=1,o+=f}return BigInt(o)}catch(n){return ee(n)}}lseek(e,t,r){try{const n=this.files.get(e);if(!n)throw Y("EBADF");if(n.directory)throw Y("EINVAL");const i=r===Ss?0:r===Qi?n.position:r===Zi?this.fs().statSync(n.path).size:void 0;if(i===void 0||!Number.isSafeInteger(t)||i+t<0||!Number.isSafeInteger(i+t))throw Y("EINVAL");return n.position=i+t,BigInt(n.position)}catch(n){return ee(n)}}ftruncate(e,t){try{const r=this.files.get(e);if(!r)throw Y("EBADF");if(r.directory)throw Y("EISDIR");if((r.flags&Ot)===0)throw Y("EBADF");if(!Number.isSafeInteger(t)||t<0)throw Y("EINVAL");const n=this.fs();if(n.truncateSync)return n.statSync(r.path).size!==t&&n.truncateSync(r.path,t),0n;const i=n.readFileSync(r.path);if(i.byteLength===t)return 0n;const o=new Uint8Array(t);return o.set(i.subarray(0,t)),this.fs().writeFileSync(r.path,o),0n}catch(r){return ee(r)}}stat(e,t,r){try{const n=this.resolveFilesystemPath(this.resolve(e),!r),i=this.fs();if(!i.linkTargetSync&&!i.existsSync(n))throw Y("ENOENT");const o=r?this.readSymlink(n):void 0;return Mn(this.memoryView(),t,o===void 0?r&&i.lstatSync?i.lstatSync(n):i.statSync(n):ao(o)),0n}catch(n){return ee(n)}}statAt(e,t,r,n){try{if(n&~pr)throw Y("EINVAL");const i=!!(n&pr),o=this.resolveFilesystemPath(this.resolveAt(e,t),!i),a=this.fs();if(!a.linkTargetSync&&!a.existsSync(o))throw Y("ENOENT");const c=i?this.readSymlink(o):void 0;return Mn(this.memoryView(),r,c===void 0?a.statSync(o):ao(c)),0n}catch(i){return ee(i)}}fstat(e,t){try{if(this.stdioFd(e)!==void 0)return Mn(this.memoryView(),t,Fl()),0n;const r=this.files.get(e);if(!r)throw Y("EBADF");return Mn(this.memoryView(),t,this.fs().statSync(r.path)),0n}catch(r){return ee(r)}}access(e){try{return this.fs().existsSync(this.resolveFilesystemPath(this.resolve(e)))?0n:-2n}catch(t){return ee(t)}}accessAt(e,t){try{return this.fs().existsSync(this.resolveFilesystemPath(this.resolveAt(e,t)))?0n:-2n}catch(r){return ee(r)}}chmod(e,t){try{const r=this.resolveFilesystemPath(this.resolve(e));return this.fs().existsSync(r)?(this.fs().chmodSync?.(r,t&4095),0n):-2n}catch(r){return ee(r)}}chmodAt(e,t,r,n){try{if(n&~pr)throw Y("EINVAL");const i=this.resolveFilesystemPath(this.resolveAt(e,t),!(n&pr));return this.fs().existsSync(i)?(this.fs().chmodSync?.(i,r&4095),0n):-2n}catch(i){return ee(i)}}fchmod(e,t){if(this.stdioFd(e)!==void 0||this.specialDescriptors.has(e))return 0n;const r=this.files.get(e);if(!r)return-9n;try{return this.fs().chmodSync?.(r.path,t&4095),0n}catch(n){return ee(n)}}chdir(e){try{const t=this.resolveFilesystemPath(this.resolve(e));if(!this.fs().statSync(t).isDirectory())throw Y("ENOTDIR");return this.cwd=t,0n}catch(t){return ee(t)}}fchdir(e){const t=this.files.get(e);return t?t.directory?(this.cwd=t.path,0n):-20n:-9n}getcwd(e,t){const r=new TextEncoder().encode(`${this.cwd}\0`);return r.byteLength>t?-34n:(this.copyIn(e,r),BigInt(r.byteLength))}mkdir(e,t){return this.mutate(()=>{const r=this.resolveFilesystemPath(this.resolve(e),!1);this.fs().mkdirSync(r),this.fs().chmodSync?.(r,t&4095)})}mkdirAt(e,t,r){try{const n=this.resolveFilesystemPath(this.resolveAt(e,t),!1);return this.fs().mkdirSync(n),this.fs().chmodSync?.(n,r&4095),0n}catch(n){return ee(n)}}statfs(e,t){try{if(!this.fs().existsSync(this.resolveFilesystemPath(this.resolve(e))))throw Y("ENOENT");return co(this.memoryView(),t),0n}catch(r){return ee(r)}}fstatfs(e,t){return this.hasFd(e)?(co(this.memoryView(),t),0n):-9n}inotifyInit(){return BigInt(this.allocateSpecial({read:()=>-11n,poll:()=>0,fcntl:e=>e===3||[1,2,4].includes(e)?0n:-22n}))}inotifyAddWatch(e,t){if(!this.specialDescriptors.has(e))return-9n;try{return this.fs().existsSync(this.resolveFilesystemPath(this.resolve(t)))?1n:-2n}catch(r){return ee(r)}}unlinkAt(e,t,r){try{if(r&~so)throw Y("EINVAL");const n=this.resolveFilesystemPath(this.resolveAt(e,t),!1);return r&so?this.fs().rmdirSync(n):this.fs().unlinkSync(n),0n}catch(n){return ee(n)}}rename(e,t){return this.mutate(()=>{const r=this.resolveFilesystemPath(this.resolve(e),!1),n=this.resolveFilesystemPath(this.resolve(t),!1);if(this.privateTree&&(Wr(this.privateTree.root,r)||Wr(this.privateTree.root,n)))throw Y("EREMOTE");const i=this.fs();if(i.existsSync(r)){if(r===n)return;const o=i.statSync(r).isDirectory();if(o&&n.startsWith(`${r}/`))throw Y("EINVAL");if(i.existsSync(n)){const a=i.statSync(n).isDirectory();if(o&&!a)throw Y("ENOTDIR");if(!o&&a)throw Y("EISDIR");if(o&&i.readdirSync(n).length>0)throw Y("ENOTEMPTY")}}i.renameSync(r,n)})}utimensat(e,t,r,n){try{if(n&~pr)throw Y("EINVAL");const i=t===0?this.files.get(e):void 0;if(t===0&&!i)throw Y("EBADF");const o=i?.path??this.resolveAt(e,this.readCString(t)),a=this.resolveFilesystemPath(o,!(n&pr)),c=this.fs(),f=c.statSync(a),d=ge(),y=(k,_)=>{if(r===0)return d;const E=r+k*16;ct(this.options.memory(),E,16);const L=this.memoryView().getBigInt64(E,!0),x=this.memoryView().getBigInt64(E+8,!0);if(x===Nl)return d;if(x===Il)return _;if(x<0||x>=1000000000n)throw Y("EINVAL");const D=Number(L)*1e3+Number(x)/1e6;if(!Number.isFinite(D))throw Y("EINVAL");return D},p=y(0,f.atimeMs??f.mtimeMs??d),A=y(1,f.mtimeMs??d);return c.utimesSync?c.utimesSync(a,new Date(p),new Date(A)):f.isFile()&&c.writeFileSync(a,c.readFileSync(a)),0n}catch(i){return ee(i)}}readlink(e,t,r,n){try{if(!Number.isSafeInteger(r)||r<0)throw Y("EINVAL");const i=this.resolveAt(n,e);if(this.privateTree&&Wr(i,this.privateTree.root))throw Y("EREMOTE");let o;i==="/proc/self/exe"&&(o=this.options.executablePath??"/usr/bin/wali-program");const a=/^\/proc\/self\/fd\/(\d+)$/u.exec(i);if(!o&&a){const f=this.files.get(Number(a[1]));f&&(o=f.path)}if(o??=this.readSymlink(i),!o)return this.fs().existsSync(i)?-22n:-2n;const c=new TextEncoder().encode(o).subarray(0,r);return this.copyIn(t,c),BigInt(c.byteLength)}catch(i){return ee(i)}}symlink(e,t,r){try{const n=this.resolveFilesystemPath(this.resolveAt(r,t),!1);return rl(this.fs(),e,n),0n}catch(n){return ee(n)}}resolveFilesystemPath(e,t=!0){const r=nl(this.fs(),e,t);if(this.privateTree&&Wr(r,this.privateTree.root))throw Y("EREMOTE");return r}readSymlink(e){return Cn(this.fs(),e)}dup(e,t,r=3){const n=this.options.descriptorMaximum??65535,i=this.stdioFd(e);if(i!==void 0){const a=t??this.allocateFd(r);return a<0||a>n&&!ze(a)?-9n:(a===e||(this.descriptors.set(a,this.descriptors.get(e)),this.descriptorStatusFlags.set(a,this.statusFlags(e)),this.setSharedStdioAlias(a,i)),BigInt(a))}if(!this.descriptors.get(e))return-9n;const o=t??this.allocateFd(r);return o<0||o>n&&!ze(o)?-9n:(o===e||(this.close(o),this.descriptors.set(o,this.descriptors.get(e))),BigInt(o))}fcntl(e,t,r){if(!this.hasFd(e))return-9n;const n=this.specialDescriptors.get(e);if(n&&n.stdio===void 0&&t!==1&&t!==2)return t===0||t===1030?n.duplicate?.(Math.max(r,3),t===1030)??-22n:n.fcntl?.(t,r)??-22n;const i=this.files.get(e);if(t===0||t===1030){const o=this.dup(e,void 0,Math.max(r,3));return o>=0n&&t===1030&&(this.descriptors.entries[Number(o)].flags=1),o}if(t===1)return BigInt(this.descriptors.entries[e]?.flags??0);if(t===2){const o=this.descriptors.entries[e];return o&&(o.flags=r&1),0n}if(t===3)return BigInt(this.statusFlags(e));if(t===4){if(this.stdioFd(e)!==void 0)this.descriptorStatusFlags.set(e,r);else{const a=this.files.get(e);a&&(a.flags=a.flags&Ot|r&~Ot)}return 0n}return t===bs||t===kn||t===gl||t===eo||t===Sl||t===to?i?this.recordLock(i,t,r):-9n:-22n}recordLock(e,t,r){try{const n=this.readRecordLock(e,r),i=t>=kn?"ofd":"posix",o=this.lockOwner(i,e),a=this.options.fileLocks;if(!a||!o)return(t===bs||t===kn)&&this.memoryView().setInt16(r,Es,!0),0n;if(n.mode===void 0)return BigInt(a.request({operation:"unlock",owner:o,namespace:i,path:e.path,range:n.range}).result);if(t===bs||t===kn){const d=a.request({operation:"query",owner:o,namespace:i,path:e.path,range:n.range,mode:n.mode,pid:this.options.pid??1});return d.result<0?BigInt(d.result):(d.conflict?this.writeRecordLock(r,d.conflict.mode,d.conflict,d.conflict.pid):this.memoryView().setInt16(r,Es,!0),0n)}const c=t===eo||t===to,f=a.request({operation:"set",owner:o,namespace:i,path:e.path,range:n.range,mode:n.mode,pid:this.options.pid??1,blocking:c}).result;return f>=0&&this.heldLock(i,o,e.path),BigInt(f)}catch(n){return ee(n)}}readRecordLock(e,t){ct(this.options.memory(),t,28);const r=this.memoryView(),n=r.getInt16(t,!0),i=r.getInt16(t+2,!0),o=oo(r.getBigInt64(t+8,!0)),a=oo(r.getBigInt64(t+16,!0)),c=i===Ss?0:i===Qi?e.position:i===Zi?this.fs().statSync(e.path).size:void 0;if(c===void 0)throw Y("EINVAL");let f=c+o,d;if(a<0?(d=f,f+=a):a>0&&(d=f+a),!Number.isSafeInteger(f)||f<0||d!==void 0&&(!Number.isSafeInteger(d)||d<=f))throw Y("EINVAL");const y=n===ro?"read":n===no?"write":n===Es?void 0:!1;if(y===!1)throw Y("EINVAL");return{...y?{mode:y}:{},range:{start:f,...d===void 0?{}:{end:d}}}}writeRecordLock(e,t,r,n){const i=this.memoryView();i.setInt16(e,t==="read"?ro:no,!0),i.setInt16(e+2,Ss,!0),i.setBigInt64(e+8,BigInt(r.start),!0),i.setBigInt64(e+16,BigInt(r.end===void 0?0:r.end-r.start),!0),i.setInt32(e+24,n,!0)}flock(e,t){const r=this.files.get(e);if(!r)return this.hasFd(e)?0n:-9n;const n=this.options.fileLocks,i=this.lockOwner("flock",r);if(!n||!i)return 0n;if(t&_l)return BigInt(n.request({operation:"unlock",owner:i,namespace:"flock",path:r.path,range:{start:0}}).result);const o=t&El?"write":t&bl?"read":void 0;if(!o||t&-16)return-22n;const a=n.request({operation:"set",owner:i,namespace:"flock",path:r.path,range:{start:0},mode:o,pid:this.options.pid??1,blocking:!(t&Al)}).result;return a>=0&&this.heldLock("flock",i,r.path),BigInt(a)}posixLockedPaths=new Set;lockingOwners=new Set;heldLock(e,t,r){e==="posix"?this.posixLockedPaths.add(r):this.lockingOwners.add(t)}lockOwner(e,t){const r=this.options.lockOwner;if(r)return e==="posix"?`${r}:posix`:`${r}:${e}:${t.description}`}releasePosixLocks(e){const t=this.options.lockOwner?`${this.options.lockOwner}:posix`:void 0;!t||!this.options.fileLocks||!this.posixLockedPaths.delete(e)||this.options.fileLocks.request({operation:"unlock",owner:t,namespace:"posix",path:e,range:{start:0}})}releaseLockOwner(e){e&&this.options.fileLocks&&this.lockingOwners.delete(e)&&this.options.fileLocks.request({operation:"release-owner",owner:e})}poll(e,t,r){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(r))return-22n;const n=()=>{let o=0;for(let a=0;a<t;a+=1){const c=e+a*8;ct(this.options.memory(),c,8);const f=this.memoryView().getInt32(c,!0),d=this.memoryView().getInt16(c+4,!0),y=this.pollDescriptor(f,d);this.memoryView().setInt16(c+6,y,!0),y!==0&&(o+=1)}return o},i=n();return i!==0||r===0?BigInt(i):(this.stdin.wait?.(r),BigInt(n()))}hasFd(e){return this.descriptors.get(e)!==void 0}stdioFd(e){if(this.options.descriptorState){const t=this.options.descriptorState;if(e<0||e>=65536)return;const r=Atomics.load(new Int32Array(t.table),e),n=Atomics.load(new Int32Array(t.descriptions),r*3+2)-1;return n>=0&&n<=2?n:void 0}return this.specialDescriptors.get(e)?.stdio}setSharedStdioAlias(e,t){e<0||e>=(this.options.stdioAliasRegistry?.length??0)||Atomics.store(this.options.stdioAliasRegistry,e,t??-1)}statusFlags(e){const t=this.descriptorStatusFlags.get(e);if(t!==void 0)return t;const r=this.stdioFd(e);return r!==void 0?r===0?0:Ji:this.files.get(e)?.flags??ul}mutate(e){try{return e(),0n}catch(t){return ee(t)}}privateTreeCall(e,t,r){try{if(e===ol)return this.adoptPrivateTree(t,r);if(e===al)return this.releasePrivateTree(t,r);if(e===cl)return this.confirmPrivateTree();if(e===ll){const n=this.privateTree?.handed;if(!n)return-22n;const i=this.fs();for(const o of n)i.existsSync(o.path)||(i.restoreNodeSync?i.restoreNodeSync(o.path,o):(o.directory?i.mkdirSync(o.path,{recursive:!0}):i.writeFileSync(o.path,o.content),i.chmodSync?.(o.path,o.mode&4095),i.utimesSync?.(o.path,new Date(o.atimeMs),new Date(o.mtimeMs))));return this.privateTree=void 0,0n}return-22n}catch(n){return ee(n)}}adoptPrivateTree(e,t){const r=L=>(this.privateTreeDeclined||(this.privateTreeDeclined=!0,this.options.onDiagnostic?.(`[WALI] the private tree is not the program's (ADR-0047): ${L}; its file calls cross into the kernel.`)),0n);if(this.privateTree)return r("it is held already");const n=this.options.privateRoots?.[0];if(!n)return r("the run names no private root");if(n==="/")return r("the root is the whole filesystem");if(this.options.privateTreeAdoptable&&!this.options.privateTreeAdoptable())return r("a forked process shares the filesystem");const i=this.fs();for(let L=0;L<this.descriptors.entries.length;L+=1){const x=this.files.get(L);if(x&&Wr(x.path,n))return r(`a descriptor is open under ${n}`)}try{this.assertWritable(`${n}/.wali-private-tree`)}catch{return r(`the run's filesystem grant does not allow writes under ${n}`)}if(i.existsSync(n)&&(!i.statSync(n).isDirectory()||Cn(i,n)!==void 0))return r(`${n} is not a directory`);i.existsSync(n)||i.mkdirSync(n,{recursive:!0});const o=[],a=L=>{const x=i.statSync(L),D=x.isDirectory();if(o.push({path:L,directory:D,mode:x.mode??(D?493:420),atimeMs:x.atimeMs??x.mtimeMs??0,mtimeMs:x.mtimeMs??0,ino:x.ino??1,content:D?new Uint8Array:i.readFileSync(L)}),D)for(const z of i.readdirSync(L))a(`${L==="/"?"":L}/${z}`)};a(n);const c=hl(o),f=new TextEncoder,d=f.encode(n),y=f.encode(this.cwd),p=20+d.byteLength+4+y.byteLength+c.byteLength;if(p>t)return r(`what ${n} already holds is larger than the libc's ${t}-byte reply`);const A=i.reserveInodes?.(fl)??2**40,k=new Uint8Array(p),_=new DataView(k.buffer);let E=0;return _.setUint32(E,Zr,!0),E+=4,_.setUint32(E,Zs,!0),E+=4,_.setBigUint64(E,BigInt(A),!0),E+=8,_.setUint32(E,d.byteLength,!0),E+=4,k.set(d,E),E+=d.byteLength,_.setUint32(E,y.byteLength,!0),E+=4,k.set(y,E),E+=y.byteLength,k.set(c,E),this.copyIn(e,k),this.privateTree={root:n,handed:o},BigInt(Zr)}confirmPrivateTree(){const e=this.privateTree;if(!e?.handed)return-22n;const t=this.fs();for(const r of e.handed.slice(1).reverse())r.directory?t.rmdirSync(r.path):t.unlinkSync(r.path);return e.handed=void 0,0n}releasePrivateTree(e,t){const r=this.privateTree;if(!r||r.handed)return-22n;ct(this.options.memory(),e,t);const{nodes:n,descriptors:i}=dl(this.copyOut(e,t),r.root),o=this.fs();for(const a of n)a.directory||this.options.fileLocks?.created?.(a.path),o.restoreNodeSync?o.restoreNodeSync(a.path,a):(a.directory?o.mkdirSync(a.path,{recursive:!0}):o.writeFileSync(a.path,a.content),o.chmodSync?.(a.path,a.mode&4095),o.utimesSync?.(a.path,new Date(a.atimeMs),new Date(a.mtimeMs)));for(const a of i){if(this.descriptors.get(a.fd)&&this.descriptors.close(a.fd),a.group===a.fd)this.files.set(a.fd,{path:a.path,flags:a.flags,position:a.position,directory:a.directory,description:this.nextDescription++});else{const c=this.descriptors.get(a.group);if(!c)throw Y("EINVAL");this.descriptors.set(a.fd,c)}this.descriptors.entries[a.fd].flags=a.closeOnExec?1:0}return this.privateTree=void 0,0n}}function io(s,e){return Number(e===void 0?s:(BigInt(e)&0xffffffffn)<<32n|BigInt(s)&0xffffffffn)}function Wr(s,e){return s===e||s.startsWith(e==="/"?"/":`${e}/`)}function gr(s,e){if(!e)return s;if(Pl(e))return e;const t=[],r=e.startsWith("/")?e:`${s}/${e}`;for(const n of r.replaceAll("\\","/").split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return`/${t.join("/")}`}function Pl(s){if(s.charCodeAt(0)!==47)return!1;if(s.length===1)return!0;let e=1;for(let t=1;t<=s.length;t+=1){const r=t<s.length?s.charCodeAt(t):47;if(r===92)return!1;if(r!==47)continue;const n=t-e;if(n===0||s.charCodeAt(e)===46&&(n===1||n===2&&s.charCodeAt(e+1)===46))return!1;e=t+1}return!0}function Rl(s,e){return Math.ceil(s/e)*e}function vl(s){return Number(BigInt.asIntN(32,typeof s=="bigint"?s:BigInt(s)))}function oo(s){const e=Number(s);if(!Number.isSafeInteger(e))throw Y("EINVAL");return e}function ct(s,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e+t>s.buffer.byteLength)throw new WebAssembly.RuntimeError("WALI filesystem memory access is out of bounds.")}function Tl(s,e){try{return s.statSync(e)}catch(t){if(/\bENOENT\b/u.test(t instanceof Error?t.message:String(t)))return;throw t}}function Mn(s,e,t){if(e<0||e+144>s.byteLength)throw new WebAssembly.RuntimeError("WALI stat pointer is out of bounds.");xt(s,e,t.dev??1),xt(s,e+8,t.ino??1),xt(s,e+16,t.nlink??1);const r=t.isSymbolicLink?.()?xl:t.isDirectory()?Ml:kl;s.setUint32(e+24,r|(t.mode??(t.isDirectory()?493:420)),!0),s.setUint32(e+28,t.uid??1e3,!0),s.setUint32(e+32,t.gid??1e3,!0),s.setUint32(e+36,0,!0),xt(s,e+40,t.rdev??0),xt(s,e+48,t.size),xt(s,e+56,t.blksize??4096),xt(s,e+64,t.blocks??Math.ceil(t.size/512)),As(s,e+72,t.atimeMs??t.mtimeMs??ge()),As(s,e+88,t.mtimeMs??ge()),As(s,e+104,t.ctimeMs??t.mtimeMs??ge());for(let n=120;n<144;n+=4)s.setUint32(e+n,0,!0)}function xt(s,e,t){s.setUint32(e,t>>>0,!0),s.setUint32(e+4,Math.floor(t/4294967296)>>>0,!0)}function ao(s){return{isFile:()=>!1,isDirectory:()=>!1,isSymbolicLink:()=>!0,size:new TextEncoder().encode(s).byteLength,mode:511}}function co(s,e){if(e<0||e+120>s.byteLength)throw new WebAssembly.RuntimeError("WALI statfs pointer is out of bounds.");for(let t=0;t<120;t+=4)s.setUint32(e+t,0,!0);s.setBigInt64(e,0x01021994n,!0),s.setBigInt64(e+8,4096n,!0),s.setBigUint64(e+16,262144n,!0),s.setBigUint64(e+24,196608n,!0),s.setBigUint64(e+32,196608n,!0),s.setBigUint64(e+40,1048576n,!0),s.setBigUint64(e+48,1048000n,!0),s.setBigUint64(e+64,255n,!0),s.setBigUint64(e+72,4096n,!0)}function As(s,e,t){const r=Math.floor(t/1e3);xt(s,e,r),xt(s,e+8,Math.min(999999999,Math.floor((t-r*1e3)*1e6)))}function Fl(){return{isFile:()=>!1,isDirectory:()=>!1,size:0,mode:8630,mtimeMs:ge()}}const Bl=new TextDecoder("utf-8",{fatal:!0}),lo=new Map;function Y(s){let e=lo.get(s);return e||(e=Object.assign(new Error(s),{errnoName:s}),lo.set(s,e)),e}const Ol={EPERM:1n,ENOENT:2n,EIO:5n,EBADF:9n,EAGAIN:11n,ENOMEM:12n,EACCES:13n,EFAULT:14n,EBUSY:16n,EEXIST:17n,EXDEV:18n,ENOTDIR:20n,EISDIR:21n,EINVAL:22n,EMFILE:24n,ENOSPC:28n,ESPIPE:29n,EROFS:30n,ERANGE:34n,ENOSYS:38n,ENOTEMPTY:39n,ELOOP:40n,ENAMETOOLONG:36n,EREMOTE:66n};function ee(s){const t=(typeof s=="object"&&s!==null?"errnoName"in s?String(s.errnoName):"code"in s?String(s.code):void 0:void 0)??/\b(E[A-Z]+)\b/u.exec(s instanceof Error?s.message:String(s))?.[1]??"",r=Ol;if(t in r)return-r[t];if(s instanceof WebAssembly.RuntimeError||s instanceof RangeError)throw s;return-5n}const fo=new WeakMap;function Dl(s){let e=fo.get(s);if(e!==void 0)return e;try{const t=typeof SharedArrayBuffer<"u"&&s.buffer instanceof SharedArrayBuffer,n=new WebAssembly.Instance(new WebAssembly.Module(Yl(t)),{e:{m:s}}).exports;e={fill:n.fill,copy:n.copy}}catch{e=null}return fo.set(s,e),e}function Yl(s){return new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,3,127,127,127,0,...s?[2,11,1,1,101,1,109,2,3,0,128,128,4]:[2,8,1,1,101,1,109,2,0,0],3,3,2,0,0,7,15,2,4,102,105,108,108,0,0,4,99,111,112,121,0,1,10,26,2,11,0,32,0,32,1,32,2,252,11,0,11,12,0,32,0,32,1,32,2,252,10,0,0,11])}const Xe=22n,lt=12n,Cl=19n,xn=5n,Ul=1,Wl=16,$l=32,ho=1,$r=2,zl=65536,Ut=4096,_s=256*1024*1024,ft=0,Ns=1,Ln=2,uo=3,mo=4,Is=5,ks=6,Hl=7,Vl=8,Gl=9,Ms=10,yo=11,ga=12,Un=16384,Pn=-1,Sa=2,ba=ga+Un*Sa,Wn=256,oi=8,ai=1,xs=0,wo=1,po=2,go=3,So=4,Ls=5,Ps=6,zr=7;class jl{all=new Set;byStart=new Map;add(e){this.all.add(e),this.byStart.set(e.start,e)}remove(e){this.all.delete(e),this.byStart.get(e.start)===e&&this.byStart.delete(e.start)}moveStart(e,t){this.byStart.get(e.start)===e&&this.byStart.delete(e.start),e.start=t,this.all.has(e)&&this.byStart.set(t,e)}startingAt(e){const t=this.byStart.get(e);return t&&t.start===e&&this.all.has(t)?t:void 0}containing(e,t){const r=this.startingAt(e);if(r&&t<=r.end)return r;for(const n of this.all)if(e>=n.start&&t<=n.end)return n}find(e){for(const t of this.all)if(e(t))return t}some(e){return this.find(e)!==void 0}map(e){return[...this.all].map(e)}[Symbol.iterator](){return this.all.values()}}function Kl(){return new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*(ai+Wn*oi))}function Ea(){return new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*ba)}class Xl{memory;readFile;fileKey;writeSharedFile;report;mappings=new jl;allocatorState;allocatorInitialized=!1;constructor(e,t,r,n,i,o,a){this.memory=e,this.readFile=t,this.fileKey=n,this.writeSharedFile=i,this.report=a;const c=r??Ea();if(this.allocatorState=new Int32Array(c),this.allocatorState.length<ba)throw new Error("WALI allocator control must contain the process mmap cursor and program break.");if(this.sharedRegistry=o?new Int32Array(o):void 0,this.sharedRegistry&&this.sharedRegistry.length<ai+Wn*oi)throw new Error("WALI shared mmap registry is too small.")}sharedRegistry;allocatorControl(){return this.initializeAllocator(),this.allocatorState.buffer}forkSnapshot(){return{mappings:this.mappings.map(e=>({...e})),...this.sharedRegistry?{registry:this.sharedRegistry.buffer.slice(0)}:{}}}restoreFork(e){for(const t of e.mappings)this.mappings.add({...t});e.registry&&this.sharedRegistry&&this.sharedRegistry.set(new Int32Array(e.registry))}imports(){return{SYS_brk:e=>this.brk(Number(e)),SYS_mmap:(e,t,r,n,i,o)=>this.mmap(Number(e),Number(t),Number(r),Number(n),Number(i),Number(o)),SYS_mprotect:(e,t,r)=>this.mprotect(Number(e),Number(t),Number(r)),SYS_munmap:(e,t)=>this.munmap(Number(e),Number(t)),SYS_mremap:(e,t,r,n,i)=>this.mremap(Number(e),Number(t),Number(r),Number(n),Number(i)),SYS_madvise:(e,t,r)=>this.madvise(Number(e),Number(t),Number(r)),SYS_msync:(e,t,r)=>this.msync(Number(e),Number(t),Number(r))}}brk(e){this.initializeAllocator();const t=Atomics.load(this.allocatorState,Ns);return e===0||!$n(e)||e>_s||!this.ensureCapacity(e)?BigInt(t):(Atomics.store(this.allocatorState,Ns,e),BigInt(e))}mmap(e,t,r,n,i,o){if(this.initializeAllocator(),!Number.isSafeInteger(t)||t<=0)return-Xe;const a=!!(n&$l);if(a&&i!==-1||!a&&i<0)return-Cl;let c;if(!a){try{c=this.readFile(i,o,t)}catch(E){return this.say(`[WALI] mmap of fd ${i}, ${t} bytes at ${o}, could not read the file: ${E instanceof Error?E.message:String(E)}`),-xn}if(!c)return-9n}const f=Hr(t,Ut),d=!!(n&Wl),y=!!(n&Ul),p=!a&&y?this.fileKey?.(i):void 0;let A;if(y&&p&&!d&&this.sharedRegistry){if(A=this.claimSharedMapping(p,o,f),!A)return-lt}else if(y&&p&&!d){const E=this.mappings.find(L=>L.shared&&L.fileKey===p&&L.fileOffset===o&&L.end-L.start===f);if(E)return E.references+=1,E.protection=r,BigInt(E.start)}const k=d?e:A?.start??this.reserve(f);if(k===Pn)return-lt;if(!$n(k)||d&&k%Ut!==0)return-Xe;const _=k+f;return!Number.isSafeInteger(_)||!this.ensureCapacity(_)?(!d&&!A&&this.release(k,_),-lt):(this.mappings.add({start:k,end:_,protection:r,fixed:d,...p?{fileKey:p}:{},fileOffset:o,shared:y,references:1,...A?{registrySlot:A.slot}:{}}),A?.existing||(this.zeroForHandout(k,_),c&&new Uint8Array(this.memory().buffer).set(c,k)),BigInt(k))}mprotect(e,t,r){if(!Vr(e,t))return-Xe;const n=e+t,i=this.mappings.containing(e,n);if(i)i.protection=r;else if(n>this.memory().buffer.byteLength)return-lt;return 0n}munmap(e,t){if(!Vr(e,t))return-Xe;const r=e+Hr(t,Ut),n=this.mappings.containing(e,r);return n?n.registrySlot!==void 0?e!==n.start||r!==n.end?-Xe:this.flushMapping(n,e,r)?(this.releaseSharedMapping(n.registrySlot),this.mappings.remove(n),0n):-xn:n.shared&&n.references>1?(n.references-=1,0n):n.shared&&!this.flushMapping(n,e,r)?-xn:(e===n.start&&r===n.end?this.mappings.remove(n):e===n.start?(n.fileOffset+=r-n.start,this.mappings.moveStart(n,r)):(r===n.end||this.mappings.add({...n,start:r,fileOffset:n.fileOffset+(r-n.start)}),n.end=e),this.release(e,r),0n):this.sharedRegistryCovers(e,r)?(this.noteRetainedMunmap(r-e),0n):(this.release(e,r),0n)}zeroForHandout(e,t){if(t=Math.min(t,this.memory().buffer.byteLength),t<=e)return;let r=Atomics.load(this.allocatorState,yo)>>>0;for(e<r&&this.zero(e,Math.min(t,r));t>r;){const n=Atomics.compareExchange(this.allocatorState,yo,r|0,t|0)>>>0;if(n===r)break;r=n}}growAhead(){const e=Atomics.load(this.allocatorState,ft)>>>0;if(e===0)return;const t=this.memory().buffer.byteLength;if(t===this.growAheadRefusedAt)return;const r=Math.min(96*1024*1024,Math.floor(t/5));t-e>=r/2||this.ensureCapacity(Math.min(e+r,4294901760))||(this.growAheadRefusedAt=t)}growAheadRefusedAt=-1;zero(e,t){const r=Dl(this.memory());if(r){r.fill(e,0,t-e);return}const n=this.memory().buffer,i=new Uint8Array(n),o=e+7&-8,a=t&-8;if(a<=o){i.fill(0,e,t);return}o>e&&i.fill(0,e,o),new Float64Array(n,o,(a-o)/8).fill(0),t>a&&i.fill(0,a,t)}sharedRegistryCovers(e,t){const r=this.sharedRegistry;if(!r)return!1;this.lockSharedRegistry();try{for(let n=0;n<Wn;n+=1){const i=Rn(n);if(Atomics.load(r,i+xs)===0||!(Atomics.load(r,i+zr)>>>0))continue;const o=Atomics.load(r,i+Ps)>>>0,a=o+(Atomics.load(r,i+Ls)>>>0);if(e<a&&t>o)return!0}return!1}finally{this.unlockSharedRegistry()}}mremap(e,t,r,n,i){if(!Vr(e,t)||!Number.isSafeInteger(r)||r<=0||n&-4||n&$r&&!(n&ho))return-Xe;const o=Hr(t,Ut),a=Hr(r,Ut),c=this.mappings.startingAt(e),f=c&&c.end>=e+o?c:void 0;if(f?.registrySlot!==void 0)return-lt;const d=e+o;if(d>this.memory().buffer.byteLength)return-lt;if(a<=o)return f&&(f.end=e+a),this.release(e+a,d),BigInt(e);const y=e+a,p=this.reserveTail(d,y);if(p&&this.ensureCapacity(y))return this.zeroForHandout(e+o,y),f&&(f.end=y),BigInt(e);if(p&&this.release(d,y),!(n&ho))return-lt;const k=n&$r?i:this.reserve(a);if(k===Pn)return-lt;const _=k+a;if(!$n(k)||k%Ut!==0||this.overlaps(k,_,f))return-Xe;if(!this.ensureCapacity(_))return n&$r||this.release(k,_),-lt;const E=new Uint8Array(this.memory().buffer).slice(e,e+Math.min(o,a));return this.zeroForHandout(k,_),new Uint8Array(this.memory().buffer).set(E,k),this.release(e,d),f?(this.mappings.moveStart(f,k),f.end=_,f.fixed=!!(n&$r)):this.mappings.add({start:k,end:_,protection:0,fixed:!!(n&$r),fileOffset:0,shared:!1,references:1}),BigInt(k)}madvise(e,t,r){return!Vr(e,t)||!Number.isSafeInteger(r)||r<0?-Xe:0n}msync(e,t,r){if(!Vr(e,t)||!Number.isSafeInteger(r)||r<0)return-Xe;const n=e+t,i=this.mappings.containing(e,n);return i?!i.shared||this.flushMapping(i,e,n)?0n:-xn:-lt}flushMapping(e,t,r){if(!e.fileKey||!this.writeSharedFile)return!0;const n=Math.min(r,e.end),i=new Uint8Array(this.memory().buffer).slice(t,n);return this.writeSharedFile(e.fileKey,e.fileOffset+t-e.start,i)}claimSharedMapping(e,t,r){const n=this.sharedRegistry,[i,o]=Jl(e),a=t>>>0,c=Math.floor(t/4294967296)>>>0;this.lockSharedRegistry();try{let f=-1;for(let p=0;p<Wn;p+=1){const A=Rn(p);if(Atomics.load(n,A+xs)===0){f<0&&(f=p);continue}if(Atomics.load(n,A+wo)>>>0===i&&Atomics.load(n,A+po)>>>0===o&&Atomics.load(n,A+go)>>>0===a&&Atomics.load(n,A+So)>>>0===c&&Atomics.load(n,A+Ls)>>>0===r){const _=Atomics.add(n,A+zr,1);return{start:Atomics.load(n,A+Ps)>>>0,slot:p,existing:_>0}}}if(f<0)return;const d=this.reserve(r);if(d===Pn)return;const y=Rn(f);return Atomics.store(n,y+wo,i|0),Atomics.store(n,y+po,o|0),Atomics.store(n,y+go,a|0),Atomics.store(n,y+So,c|0),Atomics.store(n,y+Ls,r|0),Atomics.store(n,y+Ps,d|0),Atomics.store(n,y+zr,1),Atomics.store(n,y+xs,1),{start:d,slot:f,existing:!1}}finally{this.unlockSharedRegistry()}}releaseSharedMapping(e){const t=this.sharedRegistry,r=Rn(e);this.lockSharedRegistry();try{const n=Atomics.load(t,r+zr);n>0&&Atomics.store(t,r+zr,n-1)}finally{this.unlockSharedRegistry()}}lockSharedRegistry(){const e=this.sharedRegistry;for(;Atomics.compareExchange(e,0,0,1)!==0;)Atomics.wait(e,0,1,100)}unlockSharedRegistry(){const e=this.sharedRegistry;Atomics.store(e,0,0),Atomics.notify(e,0,1)}reserve(e){this.lockAllocator();try{const t=this.freeRangeCount(),r=this.allocatorState;for(let i=0;i<t;i+=1){const o=qt(i),a=r[o]>>>0,c=r[o+1]>>>0;if(!(c<e))return c===e?this.removeFreeRange(i):(Atomics.store(this.allocatorState,o,a+e|0),Atomics.store(this.allocatorState,o+1,c-e|0)),a}let n=Atomics.load(this.allocatorState,ft)>>>0;return n===0&&(n=Hr(Math.max(this.memory().buffer.byteLength,_s),Ut)),n+e>4294967295?(this.noteCeiling(n,e),Pn):(Atomics.store(this.allocatorState,ft,n+e|0),this.noteCursor(n+e),n)}finally{this.unlockAllocator()}}initializeAllocator(){this.allocatorInitialized||(Atomics.compareExchange(this.allocatorState,Ns,0,this.memory().buffer.byteLength),this.allocatorInitialized=!0)}release(e,t){if(!(e<_s||t<=e)){this.lockAllocator();try{let r=e,n=t;for(;;){let o=!1;const a=this.allocatorState;for(let c=0;c<this.freeRangeCount();c+=1){const f=qt(c),d=a[f]>>>0,y=d+(a[f+1]>>>0);y<r||d>n||(r=Math.min(r,d),n=Math.max(n,y),this.removeFreeRange(c),c-=1,o=!0)}if(!o)break}const i=Atomics.load(this.allocatorState,ft)>>>0;if(n===i)Atomics.store(this.allocatorState,ft,r|0),this.collapseFreeTail();else if(n<=i){const o=this.freeRangeCount();if(o<Un){this.storeFreeRange(o,r,n-r),Atomics.store(this.allocatorState,Ms,o+1),this.noteFreeRangeOccupancy(o+1);return}let a=0,c=1/0;for(let f=0;f<o;f+=1){const d=Atomics.load(this.allocatorState,qt(f)+1)>>>0;d<c&&(a=f,c=d)}c<n-r?(this.storeFreeRange(a,r,n-r),this.noteDroppedRelease(c)):this.noteDroppedRelease(n-r)}else this.noteDroppedRelease(n-r)}finally{this.unlockAllocator()}}}reserveTail(e,t){if(t>4294967295)return!1;this.lockAllocator();try{return Atomics.load(this.allocatorState,ft)>>>0!==e?!1:(Atomics.store(this.allocatorState,ft,t|0),!0)}finally{this.unlockAllocator()}}noteDroppedRelease(e){const t=Atomics.add(this.allocatorState,uo,1)+1,r=Atomics.add(this.allocatorState,mo,Math.round(e/1024))+Math.round(e/1024);(t&t-1)===0&&this.say(`[WALI] the mmap free-range table is full (${Un} slots): ${t} released range${t===1?"":"s"} could not be recorded, ${(r/1024).toFixed(1)} MiB of address space unreusable.`)}noteCursor(e){const t=Math.round(e/1024),r=Atomics.load(this.allocatorState,Is)>>>0;t>r&&Atomics.store(this.allocatorState,Is,t|0)}noteRetainedMunmap(e){const t=Atomics.add(this.allocatorState,Hl,1)+1,r=Atomics.add(this.allocatorState,Vl,Math.round(e/1024))+Math.round(e/1024);(t&t-1)===0&&this.say(`[WALI] munmap of a range this thread did not map: ${t} retained, ${(r/1024).toFixed(1)} MiB of address space never released.`)}noteCeiling(e,t){const r=Atomics.add(this.allocatorState,Gl,1)+1;this.say(`[WALI] mmap cursor ${(e/1048576).toFixed(0)} MiB + ${(t/1048576).toFixed(2)} MiB passes the 4096 MiB wasm32 ceiling (${r}).`)}say(e){const t=`${e} ${this.stateSuffix()}`;console.error(t),this.report?.(t)}stateSuffix(){const e=this.freeRangeCount();let t=0;for(let n=0;n<e;n+=1)t+=Atomics.load(this.allocatorState,qt(n)+1)>>>0;return`{cursor ${((Atomics.load(this.allocatorState,ft)>>>0)/1048576).toFixed(0)} MiB, memory ${(this.memory().buffer.byteLength/1048576).toFixed(0)} MiB, free table ${e}/${Un} ranges holding ${(t/1048576).toFixed(1)} MiB}`}noteFreeRangeOccupancy(e){e>Atomics.load(this.allocatorState,ks)>>>0&&Atomics.store(this.allocatorState,ks,e|0)}addressSpaceReport(){return{droppedReleases:Atomics.load(this.allocatorState,uo)>>>0,droppedKiB:Atomics.load(this.allocatorState,mo)>>>0,cursorHighWaterKiB:Atomics.load(this.allocatorState,Is)>>>0,freeRangePeak:Atomics.load(this.allocatorState,ks)>>>0}}freeRangeCount(){return Atomics.load(this.allocatorState,Ms)}storeFreeRange(e,t,r){const n=qt(e);Atomics.store(this.allocatorState,n,t|0),Atomics.store(this.allocatorState,n+1,r|0)}removeFreeRange(e){const t=this.freeRangeCount()-1;if(e!==t){const r=qt(t);this.storeFreeRange(e,Atomics.load(this.allocatorState,r)>>>0,Atomics.load(this.allocatorState,r+1)>>>0)}this.storeFreeRange(t,0,0),Atomics.store(this.allocatorState,Ms,t)}collapseFreeTail(){for(;;){const e=Atomics.load(this.allocatorState,ft)>>>0;let t=!1;for(let r=0;r<this.freeRangeCount();r+=1){const n=qt(r),i=Atomics.load(this.allocatorState,n)>>>0,o=Atomics.load(this.allocatorState,n+1)>>>0;if(i+o===e){this.removeFreeRange(r),Atomics.store(this.allocatorState,ft,i|0),t=!0;break}}if(!t)return}}lockAllocator(){for(;Atomics.compareExchange(this.allocatorState,Ln,0,1)!==0;)Atomics.wait(this.allocatorState,Ln,1,100)}unlockAllocator(){Atomics.store(this.allocatorState,Ln,0),Atomics.notify(this.allocatorState,Ln,1)}overlaps(e,t,r){return this.mappings.some(n=>n!==r&&e<n.end&&t>n.start)}ensureCapacity(e){const t=this.memory().buffer.byteLength;if(e<=t)return!0;try{return this.memory().grow(Math.ceil((e-t)/zl)),!0}catch{return e<=this.memory().buffer.byteLength}}}function Hr(s,e){return Math.ceil(s/e)*e}function $n(s){return Number.isSafeInteger(s)&&s>=0&&s<=4294967295}function Vr(s,e){return $n(s)&&s%Ut===0&&Number.isSafeInteger(e)&&e>0&&s+e<=4294967296}function Rn(s){return ai+s*oi}function qt(s){return ga+s*Sa}function Jl(s){let e=2166136261,t=2654435769;for(let r=0;r<s.length;r+=1){const n=s.charCodeAt(r);e=Math.imul(e^n,16777619)>>>0,t=Math.imul(t^n,2246822507)>>>0}return[e,t]}const zn=11n,bo=3n,$e=22n,Ql=110n,Zl=127,ql=256,ef=0,tf=1,rf=3,Aa=4,Eo=9,nf=10,sf=new TextEncoder;class _a extends Error{code;constructor(e){super(`WALI pthread requested process exit ${e}.`),this.code=e,this.name="WaliPthreadProcessExit"}}class of extends Error{value;constructor(e){super(`longjmp(${e}) is not supported in the tab: the program took an internal error path it cannot recover from here.`),this.value=e,this.name="WaliLongjmpUnsupported"}}function af(s,e,t,r,n,i){if(t===Aa&&Atomics.load(s,e)!==i)return-zn;const o=Math.max(0,r)+Math.max(0,n);return BigInt(Atomics.notify(s,e,o))}class cf{memory;pid;terminal;pthreadFatal;terminalAttached;threadPoolSize;whileSleeping;limits=new Map;signalMask=new Uint8Array(8);alternateSignalStack=new Uint8Array(12);fileCreationMask=18;sleepWord=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));termios=new Uint8Array(36);termios2=new Uint8Array(44);constructor(e,t,r,n,i=!1,o=1,a){this.memory=e,this.pid=t,this.terminal=r,this.pthreadFatal=n,this.terminalAttached=i,this.threadPoolSize=o,this.whileSleeping=a}imports(){return{setjmp:()=>0,longjmp:(e,t)=>{throw new of(Number(t))},SYS_sched_getaffinity:(e,t,r)=>this.schedGetAffinity(Number(e),Number(t),Number(r)),SYS_rt_sigprocmask:(e,t,r,n)=>this.signalMaskCall(Number(t),Number(r),Number(n)),SYS_sigaltstack:(e,t)=>this.signalStack(Number(e),Number(t)),SYS_clock_getres:(e,t)=>this.clockGetResolution(Number(e),Number(t)),SYS_clock_nanosleep:(e,t,r,n)=>this.clockNanosleep(Number(e),Number(t),Number(r),Number(n)),SYS_nanosleep:(e,t)=>this.clockNanosleep(1,0,Number(e),Number(t)),SYS_getrlimit:(e,t)=>this.getLimit(Number(e),Number(t)),SYS_prlimit64:(e,t,r,n)=>this.processLimit(Number(e),Number(t),Number(r),Number(n)),SYS_setrlimit:(e,t)=>this.setLimit(Number(e),Number(t)),SYS_getrusage:(e,t)=>this.getUsage(Number(e),Number(t)),SYS_uname:e=>this.uname(Number(e)),SYS_sysinfo:e=>this.sysinfo(Number(e)),SYS_ioctl:(e,t,r)=>this.ioctl(Number(e),Number(t),Number(r)),SYS_umask:e=>this.umask(Number(e)),SYS_set_robust_list:()=>0n,SYS_futex:(e,t,r,n,i,o)=>this.futex(Number(e),Number(t),Number(r),Number(n),Number(i??0n),Number(o??0n))}}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}range(e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e+t>this.memory().buffer.byteLength)throw new WebAssembly.RuntimeError(`WALI memory access is out of bounds: ${e}+${t}.`)}reportedCpuCount(){return Math.min(lf(),Math.max(1,this.threadPoolSize))}schedGetAffinity(e,t,r){if(e!==0&&e!==this.pid)return-bo;if(t<4)return-$e;this.range(r,t),this.bytes().fill(0,r,r+t);const n=Math.min(this.reportedCpuCount(),t*8),i=this.bytes();for(let o=0;o*8<n;o+=1)i[r+o]=(1<<Math.min(8,n-o*8))-1;return BigInt(Math.min(t,8))}signalMaskCall(e,t,r){return r!==8?-$e:(t!==0&&(this.range(t,r),this.bytes().set(this.signalMask,t)),e!==0&&(this.range(e,r),this.signalMask=this.bytes().slice(e,e+r)),0n)}signalStack(e,t){return t!==0&&(this.range(t,this.alternateSignalStack.byteLength),this.bytes().set(this.alternateSignalStack,t)),e!==0&&(this.range(e,this.alternateSignalStack.byteLength),this.alternateSignalStack=this.bytes().slice(e,e+this.alternateSignalStack.byteLength)),0n}clockGetResolution(e,t){return[0,1,2,3,4,7].includes(e)?(t!==0&&(this.range(t,16),this.view().setBigInt64(t,0n,!0),this.view().setBigInt64(t+8,1000000n,!0)),0n):-$e}clockNanosleep(e,t,r,n){if(![0,1,4].includes(e)||(t&-2)!==0)return-$e;this.range(r,16);const i=this.view().getBigInt64(r,!0),o=this.view().getBigInt64(r+8,!0);if(i<0n||o<0n||o>=1000000000n)return-$e;let a=Number(i)*1e3+Number(o)/1e6;if(t&1){const c=e===0?ge():jn();a=Math.max(0,a-c)}try{const c=er()+a;a>=1&&this.whileSleeping?.();do this.throwIfPthreadFailed(),!Tc(Math.min(c,er()+100))&&Atomics.wait(this.sleepWord,0,0,Math.min(100,Math.max(0,c-er())));while(er()<c);this.throwIfPthreadFailed()}catch(c){if(c instanceof WebAssembly.RuntimeError)throw c}return n!==0&&(this.range(n,16),this.bytes().fill(0,n,n+16)),0n}defaultLimit(e){if(!(e<0||e>=16))return e===7?[65536n,65536n]:e===3?[8n*1024n*1024n,8n*1024n*1024n]:[0xffffffffffffffffn,0xffffffffffffffffn]}getLimit(e,t){const r=this.limits.get(e)??this.defaultLimit(e);return r?(this.range(t,16),this.view().setBigUint64(t,r[0],!0),this.view().setBigUint64(t+8,r[1],!0),0n):-$e}setLimit(e,t){if(!this.defaultLimit(e))return-$e;this.range(t,16);const r=this.view().getBigUint64(t,!0),n=this.view().getBigUint64(t+8,!0);return r>n?-$e:(this.limits.set(e,[r,n]),0n)}processLimit(e,t,r,n){if(e!==0&&e!==this.pid)return-bo;if(n!==0){const i=this.getLimit(t,n);if(i!==0n)return i}return r===0?0n:this.setLimit(t,r)}getUsage(e,t){return e!==-1&&e!==0&&e!==1?-$e:(this.range(t,144),this.bytes().fill(0,t,t+144),0n)}uname(e){return this.range(e,390),this.bytes().fill(0,e,e+390),["Linux","browser-runtime","6.1.0-wali","#1 WALI","wasm32","localdomain"].forEach((t,r)=>{this.bytes().set(sf.encode(t).subarray(0,64),e+r*65)}),0n}sysinfo(e){return this.range(e,112),this.bytes().fill(0,e,e+112),this.view().setBigInt64(e,BigInt(Math.floor(er()/1e3)),!0),this.view().setBigUint64(e+32,BigInt(this.memory().buffer.byteLength),!0),this.view().setUint32(e+104,1,!0),0n}ioctl(e,t,r){if(e<0||e>2)return-9n;const n=t>>>0;if(n!==21531&&!this.terminalAttached)return-25n;if(n===21523){this.range(r,8);const i=this.terminal?.terminalSize?.()??{rows:24,columns:80};return this.view().setUint16(r,i.rows,!0),this.view().setUint16(r+2,i.columns,!0),this.view().setUint32(r+4,0,!0),0n}return n===21505?(this.range(r,36),this.bytes().set(this.termios,r),0n):n===21506||n===21507||n===21508?(this.range(r,36),this.termios=this.bytes().slice(r,r+36),0n):n===2150388778?(this.range(r,44),this.bytes().set(this.termios2,r),0n):n===1076646955||n===1076646956||n===1076646957?(this.range(r,44),this.termios2=this.bytes().slice(r,r+44),0n):n===21531?(this.range(r,4),this.view().setInt32(r,this.terminal?.available?.()??0,!0),0n):-25n}umask(e){const t=this.fileCreationMask;return this.fileCreationMask=e&511,BigInt(t)}futex(e,t,r,n,i=0,o=0){if(e%4!==0)return-$e;this.range(e,4);const a=new Int32Array(this.memory().buffer),c=e/4,f=t&Zl;if(f===tf||f===nf)return BigInt(Atomics.notify(a,c,Math.max(0,r)));if(f===rf||f===Aa)return i%4!==0?-$e:(this.range(i,4),af(a,c,f,r,n,o));if(f!==ef&&f!==Eo)return-38n;let d;if(n!==0){this.range(n,16);const y=this.view().getBigInt64(n,!0),p=this.view().getBigInt64(n+8,!0);if(y<0n||p<0n||p>=1000000000n)return-$e;const A=Number(y)*1e3+Number(p)/1e6;d=f===Eo?Math.max(0,A-((t&ql)!==0?ge():jn())):A}try{if(Atomics.load(a,c)!==r)return-zn;const y=d===void 0?Number.POSITIVE_INFINITY:er()+d;for(;;){this.throwIfPthreadFailed();const p=y-er();if(p<=0)return-Ql;const A=_r(a,c,r,Math.min(100,p),c);if(this.throwIfPthreadFailed(),A==="not-equal")return-zn;if(A==="ok")return 0n}}catch{return this.throwIfPthreadFailed(),-zn}}throwIfPthreadFailed(){const e=this.pthreadFatal?Atomics.load(this.pthreadFatal,0):0;if(e===2)throw new _a(Atomics.load(this.pthreadFatal,2));if(e!==0)throw new WebAssembly.RuntimeError("A WALI pthread terminated unexpectedly.")}}function lf(){const s=typeof navigator>"u"?void 0:navigator.hardwareConcurrency;return Number.isSafeInteger(s)&&s>0?s:Number.MAX_SAFE_INTEGER}function er(){return typeof performance>"u"?Date.now():performance.now()}const Rs=9n,vs=11n,ff=17n,Ie=22n,Ao=2n,_o=1,hf=2,No=3,Gr=16,Io=8,ko=0,df=1,uf=7,Mo=1,mf=524288,Ts=2048,xo=0xffffffffffffffffn;class yf{memory;descriptors;externalPoll;epolls=new Map;timers=new Map;constructor(e,t,r){this.memory=e,this.descriptors=t,this.externalPoll=r}imports(){return{SYS_epoll_create:e=>Number(e)>0?this.createEpoll():-Ie,SYS_epoll_create1:()=>this.createEpoll(),SYS_epoll_ctl:(e,t,r,n)=>this.epollControl(Number(e),Number(t),Number(r),Number(n)),SYS_epoll_wait:(e,t,r,n)=>this.epollWait(Number(e),Number(t),Number(r),Number(n)),SYS_epoll_pwait:(e,t,r,n)=>this.epollWait(Number(e),Number(t),Number(r),Number(n)),SYS_eventfd:e=>this.createEventFd(Number(e),0),SYS_eventfd2:(e,t)=>this.createEventFd(Number(e),Number(t)),SYS_timerfd_create:(e,t)=>this.createTimerFd(Number(e),Number(t)),SYS_timerfd_settime:(e,t,r,n)=>this.setTimerFd(Number(e),Number(t),Number(r),Number(n))}}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}range(e,t){if(e<0||t<0||e+t>this.memory().buffer.byteLength)throw new WebAssembly.RuntimeError("WALI event memory access is out of bounds.")}createEpoll(){return BigInt(this.registerEpoll({registrations:new Map}))}registerEpoll(e,t=3){let r=-1;const n={poll:()=>this.epollReady(r)?1:0,close:()=>{this.epolls.delete(r)},fcntl:i=>i===3||[1,2,4].includes(i)?0n:-Ie,duplicate:i=>BigInt(this.registerEpoll(e,i))};return r=this.descriptors.allocateSpecial(n,t),this.epolls.set(r,e),r}epollControl(e,t,r,n){const i=this.epolls.get(e);if(!i)return-Rs;const o=i.registrations.get(r);return t===hf?o?(i.registrations.delete(r),0n):-Ao:t!==_o&&t!==No?-Ie:t===_o&&o?-ff:t===No&&!o?-Ao:(this.range(n,Gr),i.registrations.set(r,{fd:r,events:this.view().getUint32(n,!0),data:this.bytes().slice(n+Io,n+Gr)}),0n)}epollReady(e){const t=this.epolls.get(e);return t?[...t.registrations.values()].some(r=>this.readyEvents(r)!==0):!1}epollWait(e,t,r,n){const i=this.epolls.get(e);if(!i)return-Rs;if(r<=0)return-Ie;let o=0;for(const a of i.registrations.values()){if(o>=r)break;const c=this.readyEvents(a);if(c===0)continue;const f=t+o*Gr;this.range(f,Gr),this.bytes().fill(0,f,f+Gr),this.view().setUint32(f,c,!0),this.bytes().set(a.data,f+Io),o+=1}return BigInt(o)}readyEvents(e){const t=(e.events&1?1:0)|(e.events&4?4:0),r=this.externalPoll?.(e.fd,t)??this.descriptors.pollDescriptor(e.fd,t);let n=0;return r&1&&(n|=1),r&4&&(n|=4),r&8&&(n|=8),r&16&&(n|=16),r&32&&(n|=8),n&(e.events|24)}createEventFd(e,t){if(!Number.isSafeInteger(e)||e<0)return-Ie;let r=BigInt(e>>>0);const n=!!(t&1),i=!!(t&2048),o={poll:a=>(a&1&&r>0n?1:0)|(a&4?4:0),read:a=>{if(a<8)return-Ie;if(r===0n)return-vs;const c=n?1n:r;r-=c;const f=new Uint8Array(8);return new DataView(f.buffer).setBigUint64(0,c,!0),f},write:a=>{if(a.byteLength<8)return-Ie;const c=new DataView(a.buffer,a.byteOffset,a.byteLength).getBigUint64(0,!0);return c===0xffffffffffffffffn?-Ie:(r+=c,8n)},fcntl:a=>a===3?BigInt(i?2048:0):0n};return BigInt(this.descriptors.allocateSpecial(o))}createTimerFd(e,t){return![ko,df,uf].includes(e)||(t&-526337)!==0?-Ie:BigInt(this.registerTimer({clockId:e,nonblocking:!!(t&Ts),intervalNanoseconds:0n,deadlineNanoseconds:void 0,expirations:0n},3,!!(t&mf)))}registerTimer(e,t=3,r=!1){let n=-1,i=r;const o={poll:a=>(this.updateTimer(e),a&1&&e.expirations>0n?1:0),read:a=>{if(a<8)return-Ie;if(this.updateTimer(e),e.expirations===0n)return-vs;const c=e.expirations;e.expirations=0n;const f=new Uint8Array(8);return new DataView(f.buffer).setBigUint64(0,c,!0),f},close:()=>{this.timers.delete(n)},fcntl:(a,c)=>a===1?BigInt(i?1:0):a===2?(i=!!(c&1),0n):a===3?BigInt(e.nonblocking?Ts:0):a===4?(e.nonblocking=!!(c&Ts),0n):-Ie,duplicate:(a,c)=>BigInt(this.registerTimer(e,a,c))};return n=this.descriptors.allocateSpecial(o,t),this.timers.set(n,e),n}setTimerFd(e,t,r,n){const i=this.timers.get(e);if(!i)return-Rs;if((t&~Mo)!==0)return-Ie;this.range(r,32);const o=this.readTimespec(r),a=this.readTimespec(r+16);return o===void 0||a===void 0?-Ie:(this.updateTimer(i),n!==0&&(this.range(n,32),this.writeTimespec(n,i.intervalNanoseconds),this.writeTimespec(n+16,this.timerRemaining(i))),i.intervalNanoseconds=o,i.deadlineNanoseconds=a===0n?void 0:t&Mo?a:this.nowNanoseconds(i.clockId)+a,i.expirations=0n,0n)}updateTimer(e){if(e.deadlineNanoseconds===void 0)return;const t=this.nowNanoseconds(e.clockId);if(t<e.deadlineNanoseconds)return;const r=t-e.deadlineNanoseconds,n=e.intervalNanoseconds===0n?1n:1n+r/e.intervalNanoseconds;e.expirations=e.expirations+n>xo?xo:e.expirations+n,e.deadlineNanoseconds=e.intervalNanoseconds===0n?void 0:e.deadlineNanoseconds+n*e.intervalNanoseconds}timerRemaining(e){if(e.deadlineNanoseconds===void 0)return 0n;const t=e.deadlineNanoseconds-this.nowNanoseconds(e.clockId);return t>0n?t:0n}readTimespec(e){const t=this.view().getBigInt64(e,!0),r=this.view().getBigInt64(e+8,!0);if(!(t<0n||r<0n||r>=1000000000n))return t*1000000000n+r}writeTimespec(e,t){this.view().setBigInt64(e,t/1000000000n,!0),this.view().setBigInt64(e+8,t%1000000000n,!0)}nowNanoseconds(e){if(e===ko){const t=typeof performance>"u"?Date.now():performance.timeOrigin+performance.now();return BigInt(Math.floor(t*1e6))}return BigInt(Math.floor(jn()*1e6))}}function wf(s,e){if(e)return e;if(s instanceof WebAssembly.Module)return;const t=s instanceof Uint8Array?s:new Uint8Array(s),r=Qn(t);return r?Na(r):void 0}function Na(s){if(s.shared&&s.maximum===void 0)throw new Error("A shared WALI memory import must declare a maximum.");return new WebAssembly.Memory({initial:s.initial,...s.maximum===void 0?{}:{maximum:s.maximum},...s.shared?{shared:!0}:{}})}function Qn(s){const e={offset:0},t=[0,97,115,109,1,0,0,0];if(!ka(s,e,8).every((n,i)=>n===t[i]))throw new Error("Not a WebAssembly binary.");let r;for(;e.offset<s.byteLength;){const n=s[e.offset++],i=et(s,e),o=e.offset+i;if(o>s.byteLength)throw new Error("Malformed WebAssembly section size.");if(n===11&&r)return r.passiveData=pf(s,e),r;if(n!==2||r){e.offset=o;continue}const a=et(s,e);for(let c=0;c<a;c+=1){const f=Lo(s,e),d=Lo(s,e),y=s[e.offset++];if(y===void 0)throw new Error("Malformed WebAssembly import section.");if(y===2){const p=Ia(s,e);f==="env"&&d==="memory"&&(r=p)}else gf(s,e,y)}if(!r)return;e.offset=o}return r&&(r.passiveData=!0),r}function pf(s,e){const t=et(s,e);for(let r=0;r<t;r+=1){if(et(s,e)!==1)return!1;const i=et(s,e);e.offset+=i}return!0}function Ia(s,e){const t=et(s,e),r=et(s,e),n=t&1?et(s,e):void 0;return{initial:r,...n===void 0?{}:{maximum:n},shared:!!(t&2)}}function gf(s,e,t){if(t===0){et(s,e);return}if(t===1){e.offset+=1,Ia(s,e);return}if(t===3){e.offset+=2;return}if(t===4){e.offset+=1,et(s,e);return}throw new Error(`Unsupported WebAssembly import kind: ${t}.`)}function et(s,e){let t=0,r=0;for(;;){const n=s[e.offset++];if(n===void 0||r>35)throw new Error("Malformed WebAssembly ULEB128 value.");if(t+=(n&127)*2**r,(n&128)===0)return t;r+=7}}function ka(s,e,t){const r=e.offset+t;if(r>s.byteLength)throw new Error("Unexpected end of WebAssembly binary.");const n=s.subarray(e.offset,r);return e.offset=r,n}function Lo(s,e){return new TextDecoder("utf-8",{fatal:!0}).decode(ka(s,e,et(s,e)))}const Sf=2*1024*1024,qr=16*1024*1024,ke=1024*1024;var G;(function(s){s[s.Exists=1]="Exists",s[s.Stat=2]="Stat",s[s.Lstat=3]="Lstat",s[s.ReadFile=4]="ReadFile",s[s.WriteFile=5]="WriteFile",s[s.Mkdir=6]="Mkdir",s[s.Readdir=7]="Readdir",s[s.Unlink=8]="Unlink",s[s.Rmdir=9]="Rmdir",s[s.Rename=10]="Rename",s[s.Snapshot=11]="Snapshot",s[s.ReplaceSnapshot=12]="ReplaceSnapshot",s[s.Syscall=13]="Syscall",s[s.ReadForMapping=14]="ReadForMapping",s[s.SnapshotSize=15]="SnapshotSize",s[s.SnapshotChunk=16]="SnapshotChunk",s[s.ReplaceSnapshotStart=17]="ReplaceSnapshotStart",s[s.ReplaceSnapshotChunk=18]="ReplaceSnapshotChunk",s[s.MappingPath=19]="MappingPath",s[s.WriteForMapping=20]="WriteForMapping",s[s.FinalSnapshotSize=21]="FinalSnapshotSize",s[s.ImportPeerPatch=22]="ImportPeerPatch",s[s.ImportPeerPatchStart=23]="ImportPeerPatchStart",s[s.ImportPeerPatchChunk=24]="ImportPeerPatchChunk",s[s.PrepareSpawn=25]="PrepareSpawn",s[s.ReadRange=26]="ReadRange",s[s.WriteRange=27]="WriteRange",s[s.CopyForExec=28]="CopyForExec",s[s.CloseProcess=29]="CloseProcess",s[s.CopyForFork=30]="CopyForFork",s[s.GetCwd=31]="GetCwd",s[s.SyscallBinary=32]="SyscallBinary",s[s.ReadForMappingBinary=33]="ReadForMappingBinary",s[s.WriteForMappingBinary=34]="WriteForMappingBinary"})(G||(G={}));const Zn=new Set;let Fs=!1,Ma=!1;function bf(){Ma=!0,addEventListener("pagehide",()=>{Fs=Zn.size>0||Fs;for(const s of[...Zn])s.terminate()}),addEventListener("pageshow",s=>{s.persisted&&Fs&&location.reload()})}function rn(s){if(typeof document>"u")return s;Ma||bf();const e=s.terminate.bind(s);return s.terminate=()=>{Zn.delete(s),e()},Zn.add(s),s}class Ef{options;slots=[];slotStates;nextTid;coordinator;constructor(e){this.options=e;const t=Af(e.size);this.slotStates=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*t)),this.nextTid=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),Atomics.store(this.nextTid,0,e.pid+1)}async initialize(){if(typeof Worker>"u")throw new Error("WALI pthreads require Web Workers.");if(!(this.options.memory.buffer instanceof SharedArrayBuffer))throw new Error("WALI pthreads require shared WebAssembly memory.");const e=this.slotStates.length,t=rn(new Worker(new URL("/assets/thread-coordinator-worker-BB39uwBb.js",import.meta.url),{type:"module",name:"wali-pthread-coordinator"}));this.coordinator=t;const r=[],n=[];for(let i=0;i<e;i+=1){const o=this.options.network?.createChannel(),a=this.options.filesystem?.createChannel(Sf),c=this.options.codec?.createChannel(),f=new MessageChannel,d=this.options.browserProcessPorts?.[i],y=this.options.outputPorts?.[i],p=new SharedArrayBuffer(16384);r[i]=f.port2,this.slots.push({index:i,diagnostic:p}),n.push({message:{kind:"initialize",module:this.options.module,memory:this.options.memory,mmapCursor:this.options.mmapCursor,sharedMmapRegistry:this.options.sharedMmapRegistry,fatalState:this.options.fatalState,imports:this.options.imports,pid:this.options.pid,executablePath:this.options.executablePath,argv:[...this.options.argv],cwd:this.options.cwd,stdioAliasRegistry:this.options.stdioAliasRegistry,sharedPipes:this.options.sharedPipes,signals:this.options.signals,childPidAllocator:this.options.childPidAllocator,childFilesystemPolicyVersion:this.options.childFilesystemPolicyVersion,...this.options.inheritedFilesystemPolicy?{inheritedFilesystemPolicy:this.options.inheritedFilesystemPolicy}:{},...d?{browserProcessPort:d}:{},...y?{outputPort:y}:{},slotIndex:i,poolSize:e,coordinatorPort:f.port1,diagnostic:p,...this.options.stdin?{stdin:this.options.stdin}:{},terminal:this.options.terminal,...o?{network:o}:{},...a?{filesystem:a}:{},...c?{codec:c}:{}},transfer:[f.port1,...o?[o.port]:[],...a?[a.port]:[],...c?[c.port]:[],...d?[d]:[],...y?[y]:[]]})}if(this.options.onDemand){t.addEventListener("message",i=>{i.data.kind==="thread"&&i.data.message&&this.threadMessage(i.data.message)}),await this.startCoordinator(r,n);return}await Promise.all(n.map(async({message:i,transfer:o},a)=>{const c=rn(new Worker(new URL("/assets/thread-worker-1vORHul8.js",import.meta.url),{type:"module",name:`wali-pthread-${a+1}`}));await new Promise((f,d)=>{const y=p=>{p.data.kind==="ready"?(c.removeEventListener("message",y),f()):p.data.kind==="error"&&(c.removeEventListener("message",y),d(new Error(p.data.message??"WALI pthread worker failed to initialize.")))};c.addEventListener("message",y),c.addEventListener("error",p=>d(p.error??new Error(p.message)),{once:!0}),c.postMessage(i,o)}),c.addEventListener("message",f=>this.threadMessage(f.data)),this.slots[a].worker=c})),await this.startCoordinator(r,[])}startCoordinator(e,t){const r=this.coordinator;return new Promise((n,i)=>{const o=a=>{a.data.kind==="ready"?(r.removeEventListener("message",o),n()):a.data.kind==="error"&&(r.removeEventListener("message",o),i(new Error(a.data.message)))};r.addEventListener("message",o),r.addEventListener("error",a=>i(a.error??new Error(a.message)),{once:!0}),r.postMessage({kind:"initialize",ports:e,slotStates:this.slotStates.buffer,nextTid:this.nextTid.buffer,threads:t.map(a=>({message:a.message,transfer:a.transfer}))},[...e,...t.flatMap(a=>a.transfer)])})}threadMessage(e){if(e.kind==="stdout"&&e.bytes&&this.options.onStdout?.(e.bytes),e.kind==="stderr"&&e.bytes&&this.options.onStderr?.(e.bytes),e.kind==="error"&&e.message){const t=e.message.split(`
6
+ `).slice(0,8).join(`
7
+ `);this.options.onStderr?.(new TextEncoder().encode(`
8
+ WALI pthread ${e.tid??"unknown"} error summary:
9
+ ${t}
10
+ `))}}spawn(e,t,r=0n){const n=this.slots.find(a=>Atomics.compareExchange(this.slotStates,a.index,0,1)===0);if(!n)return-11;const i=Atomics.add(this.nextTid,0,1),o={kind:"start",functionPointer:e,argumentPointer:t,tid:i,signalMask:r};return n.worker?n.worker.postMessage(o):this.coordinator.postMessage({...o,slotIndex:n.index}),i}diagnostics(e){const t=new TextDecoder,r=32,n=480;return this.slots.filter(i=>e===void 0||i.index===e).flatMap(i=>{const o=Atomics.load(new Int32Array(i.diagnostic,0,1),0);if(o<=0)return[];const a=new Uint8Array(i.diagnostic,Int32Array.BYTES_PER_ELEMENT),c=[];for(let f=Math.max(0,o-r);f<o;f+=1){const d=f%r*n,y=Math.min(a[d]|a[d+1]<<8,n-2);c.push(t.decode(Uint8Array.from(a.subarray(d+2,d+2+y))))}return[`slot ${i.index+1}: ${c.join(`
11
+ `)}`]})}terminate(){this.coordinator?.terminate(),this.coordinator=void 0;for(const e of this.slots)e.worker?.terminate();this.slots.length=0}}function Af(s){if(!Number.isSafeInteger(s)||s<1||s>64)throw new Error("WALI threadPoolSize must be an integer between 1 and 64.");return s}function dt(s){const e=s.toBase64;if(typeof e=="function")return e.call(s);let t="";for(let r=0;r<s.byteLength;r+=32768)t+=String.fromCharCode(...s.subarray(r,r+32768));return btoa(t)}function sr(s){const e=Uint8Array.fromBase64;if(typeof e=="function")return e(s);const t=atob(s),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.charCodeAt(n);return r}function _f(s,e,t){const{appended:r,superseded:n}=t?Nf(s,e,t):{appended:new Map,superseded:new Set},i=[...e.removed].sort((a,c)=>vn(c)-vn(a));for(const a of i)s.existsSync(a)&&(s.statSync(a).isDirectory()?s.rmdirSync(a):s.unlinkSync(a));const o=[...e.files].filter(a=>!n.has(a.path)).sort((a,c)=>vn(a.path)-vn(c.path));for(const a of o){if(a.type==="directory")s.existsSync(a.path)&&!s.statSync(a.path).isDirectory()&&s.unlinkSync(a.path),s.mkdirSync(a.path,{recursive:!0});else if(ir(a)){s.existsSync(a.path)&&s.statSync(a.path).isDirectory()&&s.rmdirSync(a.path);const c=a.path.slice(0,a.path.lastIndexOf("/"))||"/";c!=="/"&&!s.existsSync(c)&&s.mkdirSync(c,{recursive:!0});const f=s.existsSync(a.path)?s.statSync(a.path).mode:void 0,d=f!==void 0&&(f&128)===0;d&&s.chmodSync?.(a.path,f&4095|128),s.writeFileSync(a.path,r.get(a.path)??nn(a)),d&&a.mode===void 0&&s.chmodSync?.(a.path,f&4095)}else if(!s.existsSync(a.path)||s.statSync(a.path).isDirectory())continue;a.mode!==void 0&&s.chmodSync?.(a.path,a.mode),a.mtimeMs!==void 0&&s.utimesSync?.(a.path,new Date(a.mtimeMs),new Date(a.mtimeMs))}}function Nf(s,e,t){const r=new Map,n=new Set,i=t.byPath,o=i instanceof Map?i:new Map(t.files.map(f=>[f.path,f])),a=new Map(e.files.map(f=>[f.path,f])),c=new Set([...e.files.map(f=>f.path),...e.removed]);for(const f of c){const d=o.get(f),y=Mf(s,f);if(d!==void 0&&Os(d,a.get(f))||y===void 0&&a.get(f)!==void 0)continue;const p=a.get(f);if(!(y!==void 0&&p!==void 0&&p.type===y.type&&(Z(p).mtimeMs??0)>(Z(y).mtimeMs??0))&&!(d!==void 0&&y!==void 0&&d.type===y.type&&(Z(y).mtimeMs??0)<(Z(d).mtimeMs??0))&&!Os(d,y)&&!Os(a.get(f),y)){if(kf(d,y,a.get(f)))continue;const A=If(s,f,d,y,a.get(f),t.bytesOf?.bind(t));if(A){r.set(f,A);continue}const k=a.get(f);if(d!==void 0&&y!==void 0&&k!==void 0&&k.type===y.type&&(Z(k).mtimeMs??0)>=(Z(d).mtimeMs??0)&&(Z(y).mtimeMs??0)>(Z(k).mtimeMs??0)&&(Z(y).mtimeMs??0)>(Z(d).mtimeMs??0)){n.add(f);continue}throw new Error(`Browser filesystem write conflict at ${f}. ${JSON.stringify({base:Bs(d),current:Bs(y),proposed:Bs(a.get(f))})}`)}}return{appended:r,superseded:n}}function If(s,e,t,r,n,i){if(t?.type!=="file"||r?.type!=="file"||n?.type!=="file"||!ir(n)||!s.readFileSync||Z(r).mode!==Z(n).mode)return;const o=ir(t)?nn(t):i?.(e);if(!o||o.length===0)return;const a=nn(n),c=s.readFileSync(e),f=typeof c=="string"?new TextEncoder().encode(c):c,d=p=>p.length>=o.length&&La(p.subarray(0,o.length),o);if(a.length<=o.length||!d(a)||!d(f))return;const y=new Uint8Array(f.length+a.length-o.length);return y.set(f,0),y.set(a.subarray(o.length),f.length),y}function Bs(s){return s?{type:s.type,...Z(s)}:null}function kf(s,e,t){return e?.type!=="directory"||t?.type!=="directory"?!1:s===void 0?Z(e).mode===Z(t).mode:Z(e).mode===Z(t).mode&&s.type==="directory"&&Z(s).mode===Z(e).mode}function Po(s,e,t={}){const r=new Map(s.files.map(i=>[i.path,i])),n=new Map(e.files.map(i=>[i.path,i]));return{files:e.files.filter(i=>{const o=r.get(i.path);return i.path==="/"&&!o?!1:!o||o.type!==i.type||!xa(o,i)||t.written===!0&&i.type==="file"&&!ir(o)&&ir(i)||Z(o).mode!==Z(i).mode||Z(o).mtimeMs!==Z(i).mtimeMs}),removed:s.files.flatMap(i=>n.has(i.path)?[]:[i.path])}}function vn(s){let e=1;for(let t=0;t<s.length;t+=1)s.charCodeAt(t)===47&&(e+=1);return e}function Mf(s,e){if(!s.existsSync(e))return;const t=s.statSync(e),r={...t.mode!==void 0?{mode:t.mode}:{},...t.mtimeMs!==void 0?{mtimeMs:t.mtimeMs}:{}};return t.isDirectory()?{path:e,type:"directory",...r}:{path:e,type:"file",...t.size!==void 0?{size:t.size}:{},...r}}function Os(s,e){return s===void 0?e===void 0:e!==void 0&&s.type===e.type&&xa(s,e)&&Z(s).mode===Z(e).mode&&Z(s).mtimeMs===Z(e).mtimeMs}function Z(s){const e=s;return{...e.mode===void 0?{}:{mode:e.mode&4095},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs}}}function xa(s,e){return s.type!=="file"||e.type!=="file"?!0:s.content!==void 0&&e.content!==void 0?s.content===e.content:ir(s)&&ir(e)?La(nn(s),nn(e)):Ro(s)===Ro(e)}function Ro(s){if(s.size!==void 0)return s.size;if(s.bytes!==void 0)return s.bytes.byteLength;if(s.content===void 0)return;const e=s.content.endsWith("==")?2:s.content.endsWith("=")?1:0;return Math.floor(s.content.length*3/4)-e}function ir(s){return s!==void 0&&(s.bytes!==void 0||s.content!==void 0)}function nn(s){return s.bytes??(s.content===void 0?void 0:sr(s.content))}function La(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;let t=0;if(s.byteOffset%4===0&&e.byteOffset%4===0){const r=s.byteLength>>>2,n=new Uint32Array(s.buffer,s.byteOffset,r),i=new Uint32Array(e.buffer,e.byteOffset,r);for(let o=0;o<r;o+=1)if(n[o]!==i[o])return!1;t=r<<2}for(;t<s.byteLength;t+=1)if(s[t]!==e[t])return!1;return!0}const vo=0,To=1,ut=2,Nr=3,Ir=4,Pa=5,Ra=6,qs=16*1024*1024,xf=1024*1024;function Lf(){const s=new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),e=new SharedArrayBuffer(xf),t=new Int32Array(s);return Atomics.store(t,Nr,1),Atomics.store(t,Ir,1),{reader:{control:s,payload:e,role:"reader"},writer:{control:s,payload:e,role:"writer"}}}function va(s){const e=kr(s);return Atomics.add(e,s.role==="reader"?Nr:Ir,1),s}function en(s){const e=kr(s),t=s.role==="reader"?Nr:Ir;Atomics.sub(e,t,1)<=1&&Atomics.store(e,t,0),Atomics.add(e,s.role==="reader"?Ra:Pa,1),Atomics.notify(e,ut)}function Ta(s,e){const t=kr(s),r=Atomics.load(t,ut);let n=0;return s.role==="reader"?(e&1&&(r>0||Atomics.load(t,Ir)===0)&&(n|=1),Atomics.load(t,Ir)===0&&(n|=16)):(e&4&&Atomics.load(t,Nr)>0&&r<Rf(s)&&(n|=4),Atomics.load(t,Nr)===0&&(n|=16)),n}function ci(s,e){if(s.role!=="reader")return-9n;if(e===0)return new Uint8Array;const t=kr(s),r=Ba(s),n=Atomics.load(t,ut);if(n===0)return Atomics.load(t,Ir)===0?new Uint8Array:-11n;const i=Math.min(Math.max(0,e),n),o=Atomics.load(t,vo),a=Math.min(i,r.byteLength-o),c=new Uint8Array(i);return c.set(r.subarray(o,o+a)),a<i&&c.set(r.subarray(0,i-a),a),Atomics.store(t,vo,(o+i)%r.byteLength),Atomics.sub(t,ut,i),i>0&&Atomics.add(t,Ra,1),Atomics.notify(t,ut),c}function Pf(s,e){const t=kr(s);for(;;){const r=ci(s,e);if(r!==-11n)return r;_r(t,ut,0,50)}}function Fa(s,e){if(s.role!=="writer")return-9n;const t=kr(s),r=Ba(s);let n=0;for(;n<e.byteLength;){if(Atomics.load(t,Nr)===0)return n>0?BigInt(n):-32n;const i=Atomics.load(t,ut),o=r.byteLength-i;if(o===0){_r(t,ut,i,50);continue}const a=Atomics.load(t,To),c=Math.min(e.byteLength-n,o,r.byteLength-a);r.set(e.subarray(n,n+c),a),Atomics.store(t,To,(a+c)%r.byteLength),Atomics.add(t,ut,c),Atomics.add(t,Pa,1),Atomics.notify(t,ut),n+=c}return BigInt(n)}const Fo=new WeakMap;function kr(s){const e=s.controlOffset??0;let t=Fo.get(s.control);t||(t=new Map,Fo.set(s.control,t));let r=t.get(e);return r||(r=new Int32Array(s.control,e,8),t.set(e,r)),r}function Rf(s){return s.payloadLength??s.payload.byteLength-(s.payloadOffset??0)}function Ba(s){const e=s.payloadOffset??0,t=s.payloadLength??s.payload.byteLength-e;return new Uint8Array(s.payload,e,t)}function vf(s){const e=Atomics.load(new Int32Array(s.control),2);if(e<=0||e>s.response.byteLength)return;const t=Uint8Array.from(new Uint8Array(s.response,0,e));return JSON.parse(new TextDecoder().decode(t))}const Tf=1,Ff=15,Bf=1,Of=97n,Df=93n,Yf=11n,Cf=32n,Bo=1,Oo=4,Uf=16;class Wf{memory;descriptors;constructor(e,t){this.memory=e,this.descriptors=t}imports(){return{SYS_socketpair:(e,t,r,n)=>this.socketpair(Number(e),Number(t),Number(r),Number(n)),SYS_pipe:e=>this.pipe(Number(e),0),SYS_pipe2:(e,t)=>this.pipe(Number(e),Number(t))}}pipe(e,t){if((t&-526337)!==0)return-22n;if(!Number.isSafeInteger(e)||e<0||e+8>this.memory().buffer.byteLength)return-14n;const r=Lf(),n=this.descriptors.allocateSpecial(this.pipeEndpoint(r.reader)),i=this.descriptors.allocateSpecial(this.pipeEndpoint(r.writer)),o=new DataView(this.memory().buffer);return o.setInt32(e,n,!0),o.setInt32(e+4,i,!0),0n}pipeEndpoint(e){return{browserProcessPipe:e,read:t=>ci(e,t),write:t=>Fa(e,t),poll:t=>Ta(e,t),fcntl:t=>t===3?0x800n:[1,2,4].includes(t)?0n:-22n,duplicate:t=>(va(e),BigInt(this.descriptors.allocateSpecial(this.pipeEndpoint(e),t))),close:()=>en(e)}}socketpair(e,t,r,n){if(e!==Tf)return-Of;if((t&Ff)!==Bf||r!==0)return-Df;if(!Number.isSafeInteger(n)||n<0||n+8>this.memory().buffer.byteLength)return-14n;const i={chunks:[],byteLength:0,closed:!1,peerClosed:!1,references:1},o={chunks:[],byteLength:0,closed:!1,peerClosed:!1,references:1};i.peer=o,o.peer=i;const a=this.descriptors.allocateSpecial(this.endpoint(i)),c=this.descriptors.allocateSpecial(this.endpoint(o)),f=new DataView(this.memory().buffer);return f.setInt32(n,a,!0),f.setInt32(n+4,c,!0),0n}endpoint(e){return{read:t=>$f(e,t),write:t=>zf(e,t),poll:t=>Hf(e,t),fcntl:t=>t===3?0x802n:[1,2,4].includes(t)?0n:-22n,duplicate:t=>{const r=this.descriptors.allocateSpecial(this.endpoint(e),t);return e.references+=1,BigInt(r)},close:()=>{e.references-=1,!(e.references>0||e.closed)&&(e.closed=!0,e.peer&&(e.peer.peerClosed=!0))}}}}function $f(s,e){if(s.closed)return-9n;if(e<0)return-22n;if(s.byteLength===0)return s.peerClosed?new Uint8Array:-Yf;const t=new Uint8Array(Math.min(e,s.byteLength));let r=0;for(;r<t.byteLength;){const n=s.chunks[0],i=Math.min(n.byteLength,t.byteLength-r);t.set(n.subarray(0,i),r),r+=i,s.byteLength-=i,i===n.byteLength?s.chunks.shift():s.chunks[0]=n.subarray(i)}return t}function zf(s,e){if(s.closed)return-9n;const t=s.peer;if(!t||t.closed)return-Cf;const r=e.slice();return t.chunks.push(r),t.byteLength+=r.byteLength,BigInt(r.byteLength)}function Hf(s,e){let t=s.peerClosed?Uf:0;return e&Bo&&(s.byteLength>0||s.peerClosed)&&(t|=Bo),e&Oo&&!s.peerClosed&&(t|=Oo),t}const Vf=2e4,Oa=256*1024;var H;(function(s){s[s.Socket=1]="Socket",s[s.Connect=2]="Connect",s[s.Send=3]="Send",s[s.Receive=4]="Receive",s[s.Close=5]="Close",s[s.Fcntl=6]="Fcntl",s[s.Poll=7]="Poll",s[s.Shutdown=8]="Shutdown",s[s.Duplicate=9]="Duplicate",s[s.SocketName=10]="SocketName",s[s.EpollControl=11]="EpollControl",s[s.EpollWait=12]="EpollWait",s[s.EpollCreate=13]="EpollCreate",s[s.EventFd=14]="EventFd",s[s.SocketPair=15]="SocketPair",s[s.TimerFdCreate=16]="TimerFdCreate",s[s.TimerFdSetTime=17]="TimerFdSetTime",s[s.Bind=18]="Bind",s[s.Listen=19]="Listen",s[s.Accept=20]="Accept",s[s.ChildRegister=21]="ChildRegister",s[s.ChildForget=22]="ChildForget",s[s.ChildWait=23]="ChildWait",s[s.ChildExists=24]="ChildExists",s[s.PidFdOpen=25]="PidFdOpen",s[s.PollMany=26]="PollMany"})(H||(H={}));const Ds=new Map;function Da(s,e){const t=Ds.get(s);Ds.delete(s);const r=t??e();return Ds.set(s,e()),r}const Dt=9n,pe=22n,Do=16,Mt=38n;class li{worker;constructor(e){this.worker=e}static async create(e,t,r,n,i){if(typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("WALI networking requires Web Workers and SharedArrayBuffer.");const o=[...new Set(e?.allowedHosts.map(f=>f.toLowerCase())??[])];if(e&&(!e.loopbackPort&&o.length===0||o.some(f=>!/^[a-z0-9.-]+$/u.test(f))))throw new Error("WALI networking requires a loopback attachment or at least one valid hostname.");if(e&&(!Number.isSafeInteger(e.maxConnections)||e.maxConnections<1||e.maxConnections>1024||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1024||e.maxBytes>1024*1024*1024))throw new Error("WALI networking requires bounded connection and byte quotas.");const a=Da("network",()=>rn(new Worker(new URL("/assets/network-worker-DuuxEt8T.js",import.meta.url),{type:"module",name:"wali-network"}))),c=new li(a);return await new Promise((f,d)=>{const y=p=>{p.data.kind==="ready"&&(a.removeEventListener("message",y),f()),p.data.kind==="error"&&(a.removeEventListener("message",y),d(new Error(p.data.message)))};a.addEventListener("message",y),a.addEventListener("error",p=>d(p.error??new Error(p.message)),{once:!0}),a.postMessage({kind:"initialize",allowedHosts:o,relayUrl:e?.relayUrl??"/api/wali/tcp",maxConnections:e?.maxConnections??0,maxBytes:e?.maxBytes??0,...t?{sharedPipes:t}:{},...r?{stdin:r}:{},...n?{stdioAliasRegistry:n}:{},...i?{signals:i}:{},...e?.loopbackPort?{loopbackPort:e.loopbackPort}:{}},e?.loopbackPort?[e.loopbackPort]:[])}).catch(f=>{throw a.terminate(),f}),c}createChannel(){const e=new MessageChannel,t={port:e.port1,control:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*16),payload:new SharedArrayBuffer(Oa)};return this.worker.postMessage({kind:"attach",port:e.port2,control:t.control,payload:t.payload},[e.port2]),t.port.start(),t}terminate(){this.worker.terminate()}}class Gf{channel;control;payload;nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload)}call(e,t=[],r,n){if((r?.byteLength??0)>this.payload.byteLength)return{result:-Number(pe),output:new Uint8Array};if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent WALI network RPC on one pthread channel.");const i=this.nextRequestId;this.nextRequestId=i>=2147483645?1:i+2,this.control.fill(0),Atomics.store(this.control,1,e),Atomics.store(this.control,3,r?.byteLength??0),t.slice(0,10).forEach((d,y)=>Atomics.store(this.control,5+y,d|0)),r&&this.payload.set(r),Atomics.store(this.control,0,i),this.channel.port.postMessage(n?{requestId:i,process:n}:i);const o=Date.now()+3e4;for(;;){const d=Atomics.load(this.control,0);if(d===i+1)break;if(d!==i&&d!==-i)throw new Error(`Invalid WALI network RPC state ${d} for request ${i}.`);const y=Math.max(0,o-Date.now());if(y===0&&d===i&&Atomics.compareExchange(this.control,0,i,0)===i)return{result:-110,output:new Uint8Array};try{_r(this.control,0,d,d===-i?void 0:y)}catch{if(Atomics.compareExchange(this.control,0,i,0)===i)return{result:-Number(Mt),output:new Uint8Array}}}const a=Atomics.load(this.control,2),c=Atomics.load(this.control,4),f=this.payload.slice(0,Math.max(0,c));return Atomics.store(this.control,0,0),{result:a,output:f}}}class jf{memory;signals;client;waitBuffer;constructor(e,t,r){this.memory=e,this.signals=r,this.client=new Gf(t)}isNetworkFd(e){return e>=Vf&&!ze(e)}registerChild(e,t){return this.client.call(H.ChildRegister,[e],void 0,t).result}forgetChild(e){this.client.call(H.ChildForget,[e])}hasChild(e){return this.client.call(H.ChildExists,[e]).result===1}waitChild(e,t,r=0n){const n=this.waitBuffer??={control:new SharedArrayBuffer(32),response:new SharedArrayBuffer(qs)};return{result:this.client.call(H.ChildWait,[e,t,Number(r&0xffffffffn),Number(r>>32n)],void 0,n).result,process:n}}imports(e={}){const t=(r,n)=>e[r]?.(...n)??-Mt;return{SYS_pidfd_open:(r,n)=>BigInt(this.client.call(H.PidFdOpen,[Number(r),Number(n)]).result),SYS_dup:r=>this.isNetworkFd(Number(r))?BigInt(this.client.call(H.Duplicate,[Number(r)]).result):e.SYS_dup?.(r)??-Mt,SYS_socket:(r,n,i)=>BigInt(this.client.call(H.Socket,[Number(r),Number(n),Number(i)]).result),SYS_socketpair:(r,n,i,o)=>this.socketPair(Number(r),Number(n),Number(i),Number(o)),SYS_connect:(r,n,i)=>this.withAddress(Number(r),Number(n),Number(i)),SYS_bind:(r,n,i)=>this.bind(Number(r),Number(n),Number(i),()=>t("SYS_bind",[r,n,i])),SYS_listen:(r,n)=>this.networkOr(Number(r),()=>this.client.call(H.Listen,[Number(r),Number(n)]).result,()=>t("SYS_listen",[r,n])),SYS_accept:(r,n,i)=>this.accept(Number(r),Number(n),Number(i),0,()=>t("SYS_accept",[r,n,i])),SYS_accept4:(r,n,i,o)=>this.accept(Number(r),Number(n),Number(i),Number(o),()=>t("SYS_accept4",[r,n,i,o])),SYS_send:(r,n,i,o)=>this.send(Number(r),Number(n),Number(i),Number(o)),SYS_sendto:(r,n,i,o)=>this.send(Number(r),Number(n),Number(i),Number(o)),SYS_recv:(r,n,i,o)=>this.receive(Number(r),Number(n),Number(i),Number(o)),SYS_recvfrom:(r,n,i,o,a,c)=>this.receiveFrom(Number(r),Number(n),Number(i),Number(o),Number(a),Number(c)),SYS_sendmsg:(r,n,i)=>this.sendMessage(Number(r),Number(n),Number(i)),SYS_recvmsg:(r,n,i)=>this.receiveMessage(Number(r),Number(n),Number(i)),SYS_shutdown:(r,n)=>this.networkOr(Number(r),()=>this.client.call(H.Shutdown,[Number(r),Number(n)]).result,()=>t("SYS_shutdown",[r,n])),SYS_setsockopt:(r,n,i,o,a)=>this.isNetworkFd(Number(r))?0n:t("SYS_setsockopt",[r,n,i,o,a]),SYS_getsockopt:(r,n,i,o,a)=>this.getSocketOption(Number(r),Number(o),Number(a)),SYS_getsockname:(r,n,i)=>this.getSocketName(Number(r),Number(n),Number(i)),SYS_getpeername:(r,n,i)=>this.getSocketName(Number(r),Number(n),Number(i)),SYS_close:r=>this.isNetworkFd(Number(r))?BigInt(this.client.call(H.Close,[Number(r)]).result):e.SYS_close?.(r)??-Mt,SYS_read:(r,n,i)=>this.isNetworkFd(Number(r))?this.receive(Number(r),Number(n),Number(i),0):e.SYS_read?.(r,n,i)??-Mt,SYS_write:(r,n,i)=>this.isNetworkFd(Number(r))?this.send(Number(r),Number(n),Number(i),0):e.SYS_write?.(r,n,i)??-Mt,SYS_readv:(r,n,i)=>this.isNetworkFd(Number(r))?this.readv(Number(r),Number(n),Number(i)):e.SYS_readv?.(r,n,i)??-Mt,SYS_writev:(r,n,i)=>this.isNetworkFd(Number(r))?this.writev(Number(r),Number(n),Number(i)):e.SYS_writev?.(r,n,i)??-Mt,SYS_fcntl:(r,n,i)=>this.isNetworkFd(Number(r))?BigInt(this.client.call(H.Fcntl,[Number(r),Number(n),Kf(i)]).result):e.SYS_fcntl?.(r,n,i)??-Mt,SYS_poll:(r,n,i)=>this.poll(Number(r),Number(n),Number(i),()=>t("SYS_poll",[r,n,0])),SYS_epoll_create:r=>Number(r)>0?BigInt(this.client.call(H.EpollCreate).result):-pe,SYS_epoll_create1:()=>BigInt(this.client.call(H.EpollCreate).result),SYS_eventfd:r=>BigInt(this.client.call(H.EventFd,[Number(r),0]).result),SYS_eventfd2:(r,n)=>BigInt(this.client.call(H.EventFd,[Number(r),Number(n)]).result),SYS_timerfd_create:(r,n)=>BigInt(this.client.call(H.TimerFdCreate,[Number(r),Number(n)]).result),SYS_timerfd_settime:(r,n,i,o)=>this.setTimerFd(Number(r),Number(n),Number(i),Number(o)),SYS_epoll_ctl:(r,n,i,o)=>this.epollControl(Number(r),Number(n),Number(i),Number(o),()=>t("SYS_epoll_ctl",[r,n,i,o])),SYS_epoll_wait:(r,n,i,o)=>this.epollWait(Number(r),Number(n),Number(i),Number(o),()=>t("SYS_epoll_wait",[r,n,i,o])),SYS_epoll_pwait:(r,n,i,o,a,c)=>{const f=()=>this.epollWait(Number(r),Number(n),Number(i),Number(o),()=>t("SYS_epoll_pwait",[r,n,i,o,a,c]));if(!a)return f();if(!this.signals)return-38n;const d=this.signals.mask,y=this.signals.imports().SYS_rt_sigprocmask(2,a,0,c);if(y!==0n)return y;try{const p=f();return this.signals.deliver(p===-4n),p}finally{this.signals.mask=d}}}}pollFd(e,t){return this.isNetworkFd(e)?this.client.call(H.Poll,[e,t]).result:32}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}copy(e,t){if(e<0||t<0||e+t>this.bytes().byteLength)throw new WebAssembly.RuntimeError("WALI network memory access is out of bounds.");return this.bytes().slice(e,e+t)}networkOr(e,t,r){return this.isNetworkFd(e)?BigInt(t()):r()}withAddress(e,t,r){return this.isNetworkFd(e)?BigInt(this.client.call(H.Connect,[e],this.copy(t,r)).result):-Dt}bind(e,t,r,n){return this.isNetworkFd(e)?BigInt(this.client.call(H.Bind,[e],this.copy(t,r)).result):n()}accept(e,t,r,n,i){if(!this.isNetworkFd(e))return i();if(t!==0&&(r<=0||r+4>this.bytes().byteLength))return-pe;const o=t===0?0:this.view().getUint32(r,!0);if(t!==0&&(t<0||t+o>this.bytes().byteLength))return-pe;const{result:a,output:c}=this.client.call(H.Accept,[e,n]);return a<0||t===0||(this.bytes().set(c.subarray(0,o),t),this.view().setUint32(r,c.byteLength,!0)),BigInt(a)}socketPair(e,t,r,n){const{result:i,output:o}=this.client.call(H.SocketPair,[e,t,r]);if(i===0){if(n<0||n+8>this.bytes().byteLength)return-pe;this.bytes().set(o,n)}return BigInt(i)}setTimerFd(e,t,r,n){if(!this.isNetworkFd(e)||r<0||r+32>this.bytes().byteLength)return-Dt;const{result:i,output:o}=this.client.call(H.TimerFdSetTime,[e,t],this.copy(r,32));if(i===0&&n!==0){if(n<0||n+32>this.bytes().byteLength||o.byteLength!==32)return-pe;this.bytes().set(o,n)}return BigInt(i)}send(e,t,r,n){return this.isNetworkFd(e)?BigInt(this.client.call(H.Send,[e,n],this.copy(t,r)).result):-Dt}receive(e,t,r,n){if(!this.isNetworkFd(e))return-Dt;const{result:i,output:o}=this.client.call(H.Receive,[e,r,n]);return i>0&&this.bytes().set(o.subarray(0,i),t),BigInt(i)}receiveFrom(e,t,r,n,i,o){const a=this.receive(e,t,r,n);if(a<0n||i===0||o===0)return a;if(o<0||o+4>this.bytes().byteLength)return-pe;const c=this.view().getUint32(o,!0);return this.writeDnsPeer(i,c)?(this.view().setUint32(o,16,!0),a):-pe}sendMessage(e,t,r){if(!this.isNetworkFd(e)||t<0||t+28>this.bytes().byteLength)return-Dt;const n=this.view().getUint32(t+8,!0),i=this.view().getUint32(t+12,!0);if(i>1024)return-pe;const o=[];let a=0;for(let d=0;d<i;d+=1){const y=n+d*8,p=this.copy(this.view().getUint32(y,!0),this.view().getUint32(y+4,!0));o.push(p),a+=p.byteLength}const c=new Uint8Array(a);let f=0;for(const d of o)c.set(d,f),f+=d.byteLength;return BigInt(this.client.call(H.Send,[e,r],c).result)}receiveMessage(e,t,r){if(!this.isNetworkFd(e)||t<0||t+28>this.bytes().byteLength)return-Dt;const n=this.view().getUint32(t+8,!0),i=this.view().getUint32(t+12,!0);if(i>1024)return-pe;let o=0;for(let p=0;p<i;p+=1)o+=this.view().getUint32(n+p*8+4,!0);const{result:a,output:c}=this.client.call(H.Receive,[e,o,r]);if(a<=0)return BigInt(a);let f=0;for(let p=0;p<i&&f<a;p+=1){const A=n+p*8,k=this.view().getUint32(A,!0),_=Math.min(this.view().getUint32(A+4,!0),a-f);this.bytes().set(c.subarray(f,f+_),k),f+=_}const d=this.view().getUint32(t,!0),y=this.view().getUint32(t+4,!0);return d!==0&&this.writeDnsPeer(d,y)&&this.view().setUint32(t+4,16,!0),this.view().setUint32(t+20,0,!0),this.view().setInt32(t+24,0,!0),BigInt(a)}writeDnsPeer(e,t){return t<16||e<0||e+16>this.bytes().byteLength?!1:(this.bytes().fill(0,e,e+16),this.view().setUint16(e,2,!0),this.view().setUint16(e+2,53,!1),this.bytes().set([127,0,0,1],e+4),!0)}getSocketOption(e,t,r){return this.isNetworkFd(e)?r<=0||r+4>this.bytes().byteLength||this.view().getUint32(r,!0)<4||t<0||t+4>this.bytes().byteLength?-pe:(this.view().setInt32(t,0,!0),this.view().setUint32(r,4,!0),0n):-Dt}getSocketName(e,t,r){if(!this.isNetworkFd(e))return-Dt;if(r<0||r+4>this.bytes().byteLength)return-pe;const n=this.view().getUint32(r,!0),{result:i,output:o}=this.client.call(H.SocketName,[e]);return i<0?BigInt(i):n<o.byteLength||t<0||t+o.byteLength>this.bytes().byteLength?-pe:(this.bytes().set(o,t),this.view().setUint32(r,o.byteLength,!0),0n)}writev(e,t,r){if(r<0||r>1024)return-pe;const n=[];let i=0;for(let c=0;c<r;c+=1){const f=t+c*8,d=this.copy(this.view().getUint32(f,!0),this.view().getUint32(f+4,!0));n.push(d),i+=d.byteLength}const o=new Uint8Array(i);let a=0;for(const c of n)o.set(c,a),a+=c.byteLength;return BigInt(this.client.call(H.Send,[e,0],o).result)}readv(e,t,r){if(r<0||r>1024)return-pe;let n=0;for(let c=0;c<r;c+=1)n+=this.view().getUint32(t+c*8+4,!0);const{result:i,output:o}=this.client.call(H.Receive,[e,n,0]);if(i<=0)return BigInt(i);let a=0;for(let c=0;c<r&&a<i;c+=1){const f=t+c*8,d=this.view().getUint32(f,!0),y=Math.min(this.view().getUint32(f+4,!0),i-a);this.bytes().set(o.subarray(a,a+y),d),a+=y}return BigInt(i)}poll(e,t,r,n){if(t<0||t>Oa/8)return-pe;this.copy(e,t*8),n();const i=this.signals?.mask??0n,{result:o,output:a}=this.client.call(H.PollMany,[r,Number(i&0xffffffffn),Number(i>>32n)],this.copy(e,t*8));return o>=0&&this.bytes().set(a,e),BigInt(o)}epollControl(e,t,r,n,i){if(!this.isNetworkFd(e)&&!this.isNetworkFd(r))return i();const o=t===2?void 0:this.copy(n,Do);return BigInt(this.client.call(H.EpollControl,[e,t,r],o).result)}epollWait(e,t,r,n,i){if(r<=0)return-pe;const o=this.signals?.mask??0n,{result:a,output:c}=this.client.call(H.EpollWait,[e,r,n,Number(o&0xffffffffn),Number(o>>32n)]);return a===-9?i():(a>0&&this.bytes().set(c.subarray(0,a*Do),t),BigInt(a))}}function Kf(s){return typeof s=="bigint"?Number(BigInt.asIntN(32,s)):s|0}const Yo=-4,Ys=3;class qe{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder("utf-8",{fatal:!0});nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload)}static waited={calls:0,ms:0};request(e){const t=performance.now();try{return this.requestNow(e)}finally{qe.waited.calls+=1,qe.waited.ms+=performance.now()-t}}requestNow(e){if(Atomics.load(this.control,Ys))return{result:Yo};const t=this.encoder.encode(JSON.stringify(e));if(t.byteLength>this.payload.byteLength)return{result:-90};if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent file-lock RPC on one channel.");const r=this.nextRequestId;this.nextRequestId=r>=1073741821?1:r+2,this.control.fill(0,0,Ys),this.payload.set(t),Atomics.store(this.control,1,t.byteLength),Atomics.store(this.control,0,r);try{for(this.channel.port.postMessage(r);Atomics.load(this.control,0)!==r+1;){if(Atomics.load(this.control,Ys))return{result:Yo};const o=Atomics.load(this.control,0);o!==r+1&&Atomics.wait(this.control,0,o)}const n=Atomics.load(this.control,2);if(n<1||n>this.payload.byteLength)return{result:-5};const i=JSON.parse(this.decoder.decode(this.payload.slice(0,n)));return!i||!Number.isSafeInteger(i.result)?{result:-5}:i}finally{Atomics.store(this.control,0,0)}}}class ei{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder;nextRequestId=1;bell;wakeMemory;directSyscall(e){const t=this.channel.local;if(!(!t||e==="SYS_flock"||e==="SYS_fcntl"))return r=>{const{imports:n,errno:i}=t.handlers(),o=n[e];if(!o)throw ht(-38);let a;try{a=o(...r)}catch(c){throw ht(i(c))}return typeof a=="bigint"?a:BigInt(a??0)}}ownsLocalFile(e){const t=this.channel.local;return t!==void 0&&t.handlers().owns(e)}localHandlers(){const e=this.channel.local;return e?()=>e.handlers():void 0}wakeThrough(e){this.wakeMemory=e}constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload),this.bell=e.doorbell?new Int32Array(e.doorbell):void 0}attachMemory(e){this.channel.port.postMessage({memory:e})}copyForExec(e){return this.call(G.CopyForExec,{stdio:e}).process}currentWorkingDirectory(){return this.call(G.GetCwd)}copyForForkChannel(){return this.createChannel(qr,this.call(G.CopyForFork).process)}createChannel(e,t){const r=Hn(e),n=this.channel.sharedPipes&&{...this.channel.sharedPipes,table:t===void 0?this.channel.sharedPipes.table:new SharedArrayBuffer(65536*4)},i=t===void 0?void 0:new MessageChannel,o={...r.server,...t===void 0?{}:{process:t},...n?{sharedPipes:n}:{},...i?{releasePort:i.port2}:{}};this.channel.local?this.channel.local.attach(o):this.channel.port.postMessage({kind:"attach",...o},[r.server.port,...i?[i.port2]:[]]);const a=this.channel.local?.doorbell??this.channel.doorbell;return{...r.client,...n?{sharedPipes:n}:{},...i?{releasePort:i.port1}:{},...a?{doorbell:a}:{}}}copyForExecChannel(e){return this.createChannel(qr,this.copyForExec(e))}closeProcess(){this.call(G.CloseProcess)}existsSync(e){return this.call(G.Exists,{path:e})}statSync(e){return Uo(this.call(G.Stat,{path:e}))}lstatSync(e){return Uo(this.call(G.Lstat,{path:e}))}readFileSync(e){const t=this.statSync(e).size;if(t<=ke)return sr(this.call(G.ReadFile,{path:e}).content);const r=new Uint8Array(t);for(let n=0;n<t;n+=ke){const i=this.readRangeSync(e,n,Math.min(ke,t-n));if(r.set(i,n),i.byteLength<Math.min(ke,t-n))return r.subarray(0,n+i.byteLength)}return r}async readFile(e){return this.readFileSync(e)}readRangeSync(e,t,r){const n=new Uint8Array(r);let i=0;for(;i<r;){const o=Math.min(ke,r-i),a=sr(this.call(G.ReadRange,{path:e,offset:t+i,length:o}).content);if(n.set(a,i),i+=a.byteLength,a.byteLength<o)break}return i===r?n:n.subarray(0,i)}writeRangeSync(e,t,r){for(let n=0;(n<r.byteLength||n===0&&r.byteLength===0)&&(this.call(G.WriteRange,{path:e,offset:t+n,content:dt(r.subarray(n,n+ke))}),r.byteLength!==0);n+=ke);}writeFileSync(e,t){const r=typeof t=="string"?this.encoder.encode(t):t;if(r.byteLength<=ke){this.call(G.WriteFile,{path:e,content:dt(r)});return}this.call(G.WriteFile,{path:e,content:""}),this.writeRangeSync(e,0,r)}mkdirSync(e,t){this.call(G.Mkdir,{path:e,recursive:t?.recursive===!0})}readdirSync(e){return this.call(G.Readdir,{path:e})}unlinkSync(e){this.call(G.Unlink,{path:e})}rmdirSync(e){this.call(G.Rmdir,{path:e})}renameSync(e,t){this.call(G.Rename,{from:e,to:t})}toSnapshot(){return JSON.parse(this.decoder.decode(this.readChunked(G.SnapshotSize)))}finalSnapshot(){return JSON.parse(this.decoder.decode(this.readChunked(G.FinalSnapshotSize)))}readChunked(e){const{length:t}=this.call(e);if(!Number.isSafeInteger(t)||t<0)throw ht(-5);const r=new Uint8Array(t);for(let n=0;n<t;n+=ke){const i=Math.min(ke,t-n),{content:o}=this.call(G.SnapshotChunk,{offset:n,length:i}),a=sr(o);if(a.byteLength!==i)throw ht(-5);r.set(a,n)}return r}prepareSpawn(){this.call(G.PrepareSpawn)}importPeerPatch(e){const t=this.encoder.encode(JSON.stringify(e));this.call(G.ImportPeerPatchStart,{length:t.byteLength});for(let r=0;r<t.byteLength;r+=ke)this.call(G.ImportPeerPatchChunk,{offset:r,content:dt(t.subarray(r,r+ke))})}replaceSnapshot(e){const t=this.encoder.encode(JSON.stringify(e));this.call(G.ReplaceSnapshotStart,{length:t.byteLength});for(let r=0;r<t.byteLength;r+=ke){const n=t.subarray(r,r+ke);this.call(G.ReplaceSnapshotChunk,{offset:r,content:dt(n)})}}syscall(e,t){const r=this.channel.local;if(r)for(;;){const o=r.syscall(e,t);if(typeof o=="bigint")return o;if(o!==void 0)throw ht(o.failed);const a=performance.now();r.idle(),qe.waited.ms+=performance.now()-a}let n=this.names.get(e);n||(n=this.encoder.encode(e),this.names.set(e,n));const i=this.view??=new DataView(this.payload.buffer,this.payload.byteOffset,this.payload.byteLength);this.payload[0]=t.length,this.payload[1]=n.byteLength;for(let o=0;o<t.length;o+=1)i.setBigInt64(8+o*8,BigInt(t[o]),!0);return this.payload.set(n,8+t.length*8),this.exchange(G.SyscallBinary,8+t.length*8+n.byteLength,Xf(e,t)||this.bell?null:3e4),i.getBigInt64(0,!0)}names=new Map;lastResult=0;view;readForMapping(e,t,r){const n=new Uint8Array(r),i=this.view??=new DataView(this.payload.buffer,this.payload.byteOffset,this.payload.byteLength);let o=0;for(;o<r;){const a=Math.min(this.payload.byteLength,r-o);i.setInt32(0,e,!0),i.setFloat64(8,t+o,!0),i.setInt32(16,a,!0);const c=this.exchange(G.ReadForMappingBinary,20,3e4);if(this.lastResult===1)return o===0?void 0:n.subarray(0,o);if(n.set(this.payload.subarray(0,c),o),o+=c,c<a)break}return o===r?n:n.subarray(0,o)}mappingPath(e){return this.call(G.MappingPath,{fd:e}).path}writeForMapping(e,t,r){const n=this.encoder.encode(e);if(16+n.byteLength+r.byteLength>this.payload.byteLength)return this.call(G.WriteForMapping,{path:e,offset:t,content:dt(r)}).written;const i=this.view??=new DataView(this.payload.buffer,this.payload.byteOffset,this.payload.byteLength);return i.setFloat64(0,t,!0),i.setUint32(8,n.byteLength,!0),i.setUint32(12,r.byteLength,!0),this.payload.set(n,16),this.payload.set(r,16+n.byteLength),this.exchange(G.WriteForMappingBinary,16+n.byteLength+r.byteLength,3e4),this.payload[0]===1}call(e,t={},r=3e4){const n=this.encoder.encode(JSON.stringify(t));if(n.byteLength>this.payload.byteLength)throw ht(-90);if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent WALI filesystem RPC on one channel.");this.payload.set(n);const i=this.exchange(e,n.byteLength,r);return i>0?JSON.parse(this.decoder.decode(this.payload.slice(0,i))):void 0}exchange(e,t,r){if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent WALI filesystem RPC on one channel.");const n=this.nextRequestId;this.nextRequestId=n>=1073741821?1:n+2,this.control.fill(0),Atomics.store(this.control,1,e),Atomics.store(this.control,3,t),Atomics.store(this.control,0,n);const i=this.channel.local;if(i)for(;i.serveNow(),Atomics.load(this.control,0)!==n+1;)i.idle();else if(this.bell){Atomics.add(this.bell,0,1),Atomics.notify(this.bell,0);const f=Atomics.load(this.bell,1);f!==0&&this.wakeMemory&&Atomics.notify(new Int32Array(this.wakeMemory.buffer),f-1)}else this.channel.port.postMessage(n);const o=r===null?void 0:Date.now()+r;for(;;){const f=Atomics.load(this.control,0);if(f===n+1)break;if(f!==n&&f!==-n)throw new Error(`Invalid WALI filesystem RPC state ${f} for request ${n}.`);const d=o===void 0?void 0:Math.max(0,o-Date.now());if(d===0&&f===n&&Atomics.compareExchange(this.control,0,n,0)===n)throw ht(-110);Atomics.wait(this.control,0,f,f===-n?void 0:d)}const a=Atomics.load(this.control,2),c=Atomics.load(this.control,4);if(Atomics.store(this.control,0,0),a<0)throw ht(a);return this.lastResult=a,c}}function Xf(s,e){if(s==="SYS_flock"){const r=Number(e[1]??0);return(r&4)===0&&(r&8)===0}if(s!=="SYS_fcntl")return!1;const t=Number(e[1]??0);return t===7||t===38}const Jf=5;class sn{sink;root;sharedPipes;constructor(e,t,r){this.sink=e,this.root=t,this.sharedPipes=r}static async createInThread(e,t){const r=await import("./filesystem-host-Cngy2ePX.js"),n=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),i=new Int32Array(n);r.hostInThread(n),await r.initializeHost({kind:"initialize",snapshot:e,...t});const o=Hn(qr),a=r.attachChannel({...o.server,...t.sharedPipes?{sharedPipes:t.sharedPipes}:{}}),c=new ei({...o.client,...t.sharedPipes?{sharedPipes:t.sharedPipes}:{},local:{doorbell:n,serveNow:()=>r.serveNow(a),attach:d=>{r.attachChannel(d)},syscall:(d,y)=>r.syscallNow(a,d,y),handlers:()=>r.handlersNow(a),idle:()=>{r.pumpHost(!0),Atomics.wait(i,0,Atomics.load(i,0),Jf)}}}),f={attach:d=>{r.attachChannel(d)},terminate:()=>r.resetHost(),doorbell:n,host:r};return new sn(f,c,t.sharedPipes)}closePort(){this.sink.host?.closeHostPort()}pump(e=!1){(this.sink.host?.hostWaiting()||e)&&this.sink.host?.pumpHost(e)}doorbell(){return this.sink.doorbell?new Int32Array(this.sink.doorbell):void 0}static async create(e,t){const r=Da("filesystem",()=>rn(new Worker(new URL("/assets/filesystem-worker-BQAYsjDk.js",import.meta.url),{type:"module",name:"wali-filesystem"})));await new Promise((o,a)=>{const c=d=>{d.data.kind==="ready"&&(r.removeEventListener("message",c),o()),d.data.kind==="error"&&(r.removeEventListener("message",c),a(new Error(d.data.message)))};r.addEventListener("message",c),r.addEventListener("error",d=>a(d.error??new Error(d.message)),{once:!0});const f=[...t.updatePort?[t.updatePort]:[],...t.fileLocks?[t.fileLocks.channel.port]:[],...t.fileCoherence?[t.fileCoherence.port]:[]];r.postMessage({kind:"initialize",snapshot:e,...t},f)});const n=Hn(qr);r.postMessage({kind:"attach",...n.server},[n.server.port]);const i={attach:(o,a)=>r.postMessage({kind:"attach",...o},a),terminate:()=>r.terminate()};return new sn(i,new ei({...n.client,...t.sharedPipes?{sharedPipes:t.sharedPipes}:{}}),t.sharedPipes)}createChannel(e,t=0){const r=Hn(e),n=this.sharedPipes&&{...this.sharedPipes,table:t===0?this.sharedPipes.table:new SharedArrayBuffer(65536*4)};return this.sink.attach({process:t,...r.server,...n?{sharedPipes:n}:{}},[r.server.port]),{...r.client,...n?{sharedPipes:n}:{},...this.sink.doorbell?{doorbell:this.sink.doorbell}:{}}}copyForExec(){return this.createChannel(qr,this.root.copyForExec())}filesystem(){return this.root}snapshot(){return this.root.toSnapshot()}finalSnapshot(){return this.root.finalSnapshot()}replaceSnapshot(e){this.root.replaceSnapshot(e)}terminate(){this.sink.terminate()}}const jr=1e4,Qf=new Set([5,6,7,36,37,38]),Zf=new Set(["SYS_open","SYS_openat","SYS_stat","SYS_lstat","SYS_newfstatat","SYS_access","SYS_faccessat","SYS_faccessat2","SYS_chmod","SYS_fchmodat","SYS_chdir","SYS_getcwd","SYS_mkdir","SYS_mkdirat","SYS_statfs","SYS_rmdir","SYS_unlink","SYS_unlinkat","SYS_rename","SYS_utimensat","SYS_symlink","SYS_symlinkat","SYS_readlink","SYS_readlinkat","SYS_inotify_init","SYS_inotify_init1"]),Co=new Set(["SYS_close","SYS_read","SYS_pread64","SYS_write","SYS_pwrite64","SYS_readv","SYS_writev","SYS_preadv","SYS_pwritev","SYS_lseek","SYS_fstat","SYS_fchmod","SYS_fchdir","SYS_fstatfs","SYS_inotify_add_watch","SYS_inotify_rm_watch","SYS_dup","SYS_dup2","SYS_dup3","SYS_fcntl","SYS_getdents64","SYS_fsync","SYS_fdatasync","SYS_flock","SYS_ftruncate"]);class qf{client;stdioAliasRegistry;descriptorState;memory;constructor(e,t,r,n){this.client=e,this.stdioAliasRegistry=t,this.descriptorState=r,this.memory=n}poll(e,t,r,n){const i=this.memory?.();if(!i||!Number.isSafeInteger(r)||r<=0||t<0||t+r*8>i.buffer.byteLength)return e(t,r,n);const o=this.descriptorState?new Int32Array(this.descriptorState.table):void 0,a=this.descriptorState?new Int32Array(this.descriptorState.descriptions):void 0,c=this.client.localHandlers(),f=new Map;let d=new DataView(i.buffer);for(let E=0;E<r;E+=1){const L=d.getInt32(t+E*8,!0);if(L<3||L>=jr&&!ze(L))continue;const x=this.stdioAliasRegistry&&L<this.stdioAliasRegistry.length?Atomics.load(this.stdioAliasRegistry,L):-1;if(x===0||x===1||x===2||o&&a&&Atomics.load(a,Atomics.load(o,L)*3+2))continue;const D=c?c().owns(L):Number(this.client.syscall("SYS_fcntl",[L,1,0]))>=0;f.set(E,D?d.getInt16(t+E*8+4,!0)&4:32)}if(f.size===0)return e(t,r,n);const y=[...f.values()].filter(E=>E!==0).length,p=new Uint8Array(i.buffer,t,r*8).slice(),A=[];for(let E=0;E<r;E+=1)f.has(E)||A.push(E);const k=new Uint8Array(i.buffer);A.forEach((E,L)=>k.set(p.subarray(E*8,E*8+8),t+L*8));let _;try{_=e(t,A.length,y?0:n)}finally{const E=new Uint8Array(i.buffer,t,A.length*8).slice();new Uint8Array(i.buffer).set(p,t),d=new DataView(i.buffer),A.forEach((L,x)=>d.setInt16(t+L*8+6,E[x*8+6]|E[x*8+7]<<8,!0));for(const[L,x]of f)d.setInt16(t+L*8+6,x,!0)}return typeof _!="bigint"&&typeof _!="number"||Number(_)<0?_:BigInt(Number(_)+y)}ownedFileImports(e){const t={};for(const r of Co){const n=r==="SYS_fcntl",i=n?void 0:this.client.directSyscall(r),o=e[r];if(!i&&!n||!o||r==="SYS_flock")continue;const a=this.client.localHandlers();a&&(t[r]=(...c)=>{const f=Number(c[0]);if(f<3||f>=jr&&!ze(f)||n&&Qf.has(Number(c[1])))return o(...c);const{imports:d,errno:y,owns:p}=a();if(!p(f))return o(...c);const A=d[r];if(!A)throw ht(-38);let k;try{k=A(...c)}catch(_){throw ht(y(_))}return typeof k=="bigint"?k:BigInt(k??0)})}return t}imports(e){const t={};for(const o of Zf){const a=this.client.directSyscall(o);t[o]=a?(...c)=>a(c):(...c)=>this.client.syscall(o,c)}const r=this.descriptorState?new Int32Array(this.descriptorState.table):void 0,n=this.descriptorState?new Int32Array(this.descriptorState.descriptions):void 0;for(const o of Co){const a=this.client.directSyscall(o),c=o==="SYS_read"||o==="SYS_readv"||o==="SYS_write"||o==="SYS_writev"||o==="SYS_fstat",f=o==="SYS_write"||o==="SYS_writev",d=o==="SYS_pread64"||o==="SYS_pwrite64"||o==="SYS_preadv"||o==="SYS_pwritev";t[o]=(...y)=>{const p=Number(y[0]);if(r&&n&&p>=0&&(p<2e4||ze(p))){const k=Atomics.load(r,p),_=Atomics.load(n,k*3+2);return _&&d?-29n:_&&c?(f&&this.client.prepareSpawn(),e[o]?.(...y)??-9n):a?a(y):this.client.syscall(o,y)}const A=this.stdioAliasRegistry&&p>=0&&p<this.stdioAliasRegistry.length?Atomics.load(this.stdioAliasRegistry,p):-1;return p<3||p>=jr&&!ze(p)||A===0||A===1||A===2?((o==="SYS_write"||o==="SYS_writev")&&this.client.prepareSpawn(),e[o]?.(...y)??-9n):a?a(y):this.client.syscall(o,y)}}const i=e.SYS_poll;return this.memory&&i&&(t.SYS_poll=(o,a,c)=>this.poll(i,Number(o),Number(a),Number(c))),{...e,...t}}readForMapping(e,t,r){if(!(e<3||e>=jr&&!ze(e)))return this.client.readForMapping(e,t,r)}mappingPath(e){if(!(e<3||e>=jr&&!ze(e)))return this.client.mappingPath(e)}writeForMapping(e,t,r){return this.client.writeForMapping(e,t,r)}}function Hn(s){const e=new MessageChannel,t=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*8),r=new SharedArrayBuffer(s);return e.port1.start(),{client:{port:e.port1,control:t,payload:r},server:{port:e.port2,control:t,payload:r}}}function Uo(s){return{isFile:()=>s.file,isDirectory:()=>s.directory,isSymbolicLink:()=>s.symbolicLink===!0,size:s.size,...eh(s,"mode","mtimeMs","atimeMs","ctimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks")}}function eh(s,...e){return Object.fromEntries(e.flatMap(t=>s[t]===void 0?[]:[[t,s[t]]]))}function ht(s){const e={2:"ENOENT",9:"EBADF",13:"EACCES",17:"EEXIST",20:"ENOTDIR",21:"EISDIR",22:"EINVAL",24:"EMFILE",28:"ENOSPC",29:"ESPIPE",34:"ERANGE",38:"ENOSYS",39:"ENOTEMPTY",90:"EMSGSIZE",110:"ETIMEDOUT"}[-s]??"EIO";return Object.assign(new Error(e),{code:e})}const Wo=1e4,th=19999,Cs=64,ti=64*1024,Vn=8,$o=3,zo=4,Us=2048,Ws=524288,rh=0,nh=1,sh=2,ih=3,oh=4,Ho=1030,ah=1,ch=4096;function lh(s=new on(new ii)){const e={table:s.sharedEntries.buffer,descriptions:s.registry.pipeMetadata.buffer,slots:new SharedArrayBuffer(Cs*Int32Array.BYTES_PER_ELEMENT),controls:new SharedArrayBuffer(Cs*Vn*Int32Array.BYTES_PER_ELEMENT),payloads:new SharedArrayBuffer(Cs*ti)};return Ya.set(e.table,s),e}const Ya=new WeakMap,Vo=new WeakMap;let ri,ni;function fh(s,e){if(!Number.isSafeInteger(e)||e<0||e>=65536)return 0;let t=s===ri?ni:Vo.get(s);t||(t={table:new Int32Array(s.table),descriptions:new Int32Array(s.descriptions)},Vo.set(s,t)),ri=s,ni=t;const r=Atomics.load(t.table,e);return Atomics.load(t.descriptions,r*3)}function hh(){ri=void 0,ni=void 0}class dh{memory;state;remote;table;slots;constructor(e,t,r,n){this.memory=e,this.state=t,this.remote=n,this.table=r??Ya.get(t.table),this.slots=new Int32Array(t.slots)}isPipeFd(e){return this.entry(e)!==0}exportBrowserProcessPipe(e){const t=this.entry(e);return t===0?void 0:this.handle(t)}pollDescriptor(e,t){const r=this.entry(e);return r===0?void 0:Ta(this.handle(r),t)}ioctl(e,t){if(this.isPipeFd(e))return t===21537||t===21585||t===21584?0n:-25n}imports(e={}){const t=(n,i)=>e[n]?.(...i)??-38n,r={...e,SYS_pipe:n=>this.pipe(Number(n),0),SYS_pipe2:(n,i)=>this.pipe(Number(n),Number(i)),SYS_close:n=>this.isPipeFd(Number(n))?this.close(Number(n)):e.SYS_close?.(n)??-38n,SYS_read:(n,i,o)=>this.isPipeFd(Number(n))?this.read(Number(n),Number(i),Number(o)):e.SYS_read?.(n,i,o)??-38n,SYS_pread64:(n,i,o,a)=>this.isPipeFd(Number(n))?-29n:e.SYS_pread64?.(n,i,o,a)??-38n,SYS_write:(n,i,o)=>this.isPipeFd(Number(n))?this.write(Number(n),Number(i),Number(o)):e.SYS_write?.(n,i,o)??-38n,SYS_pwrite64:(n,i,o,a)=>this.isPipeFd(Number(n))?-29n:e.SYS_pwrite64?.(n,i,o,a)??-38n,SYS_preadv:(n,i,o,a,c)=>this.isPipeFd(Number(n))?-29n:e.SYS_preadv?.(n,i,o,a,c)??-38n,SYS_pwritev:(n,i,o,a,c)=>this.isPipeFd(Number(n))?-29n:e.SYS_pwritev?.(n,i,o,a,c)??-38n,SYS_readv:(n,i,o)=>this.isPipeFd(Number(n))?this.readv(Number(n),Number(i),Number(o)):e.SYS_readv?.(n,i,o)??-38n,SYS_writev:(n,i,o)=>this.isPipeFd(Number(n))?this.writev(Number(n),Number(i),Number(o)):e.SYS_writev?.(n,i,o)??-38n,SYS_lseek:(n,i,o)=>this.isPipeFd(Number(n))?-29n:e.SYS_lseek?.(n,i,o)??-38n,SYS_fstat:(n,i)=>this.isPipeFd(Number(n))?this.fstat(Number(i)):e.SYS_fstat?.(n,i)??-38n,SYS_dup:n=>this.isPipeFd(Number(n))?this.duplicate(Number(n)):e.SYS_dup?.(n)??-38n,SYS_dup2:(n,i)=>this.isPipeFd(Number(n))?this.duplicate(Number(n),Number(i),3,!1,e):e.SYS_dup2?.(n,i)??-38n,SYS_dup3:(n,i,o)=>this.isPipeFd(Number(n))?Number(n)===Number(i)||(Number(o)&~Ws)!==0?-22n:this.duplicate(Number(n),Number(i),3,!!(Number(o)&Ws),e):e.SYS_dup3?.(n,i,o)??-38n,SYS_fcntl:(n,i,o)=>this.isPipeFd(Number(n))?this.fcntl(Number(n),Number(i),Number(BigInt.asIntN(32,BigInt(o))),e):e.SYS_fcntl?.(n,i,o)??-38n,SYS_poll:(n,i,o)=>this.poll(Number(n),Number(i),Number(o),()=>t("SYS_poll",[n,i,o]))};if(this.remote)for(const n of["SYS_pipe","SYS_pipe2","SYS_close","SYS_dup","SYS_dup2","SYS_dup3","SYS_fcntl"]){const i=r[n];r[n]=(...o)=>n==="SYS_pipe"||n==="SYS_pipe2"||this.isPipeFd(Number(o[0]))?this.remote.syscall(n,o):i(...o)}return r}pipe(e,t){if((t&-526337)!==0)return-22n;if(!this.validRange(e,8))return-14n;const r=this.allocateSlot();if(r<0)return-24n;const n=this.control(r);n.fill(0),Atomics.store(n,$o,1),Atomics.store(n,zo,1);const i=this.allocateDescriptor(r+1),o=i>=0?this.allocateDescriptor(-(r+1)):-1;if(i<0||o<0)return i>=0&&this.table.close(i),Atomics.store(this.slots,r,0),-24n;for(const c of[i,o])this.table.entries[c].flags=t&Ws?1:0,Atomics.store(new Int32Array(this.state.descriptions),this.table.entries[c].description*3+1,t&Us);const a=this.view();return a.setInt32(e,i,!0),a.setInt32(e+4,o,!0),0n}read(e,t,r){if(!Number.isSafeInteger(r)||r<0||!this.validRange(t,r))return-22n;const i=(this.statusFlags(e)&Us?ci:Pf)(this.handle(this.entry(e)),r);return typeof i=="bigint"?i:(this.bytes().set(i,t),BigInt(i.byteLength))}write(e,t,r){return!Number.isSafeInteger(r)||r<0||!this.validRange(t,r)?-22n:Fa(this.handle(this.entry(e)),this.bytes().slice(t,t+r))}readv(e,t,r){if(!Number.isSafeInteger(r)||r<0||r>1024||!this.validRange(t,r*8))return-22n;let n=0n;for(let i=0;i<r;i+=1){const o=t+i*8,a=this.read(e,this.view().getUint32(o,!0),this.view().getUint32(o+4,!0));if(a<0n)return n>0n?n:a;if(n+=a,a<BigInt(this.view().getUint32(o+4,!0)))break}return n}writev(e,t,r){if(!Number.isSafeInteger(r)||r<0||r>1024||!this.validRange(t,r*8))return-22n;let n=0n;for(let i=0;i<r;i+=1){const o=t+i*8,a=this.write(e,this.view().getUint32(o,!0),this.view().getUint32(o+4,!0));if(a<0n)return n>0n?n:a;n+=a}return n}fstat(e){if(!this.validRange(e,144))return-14n;const t=this.view();for(let r=0;r<144;r+=4)t.setUint32(e+r,0,!0);return t.setBigUint64(e+16,1n,!0),t.setUint32(e+24,ch|438,!0),t.setUint32(e+28,1e3,!0),t.setUint32(e+32,1e3,!0),t.setBigInt64(e+56,4096n,!0),0n}statusFlags(e){const t=Atomics.load(new Int32Array(this.state.table),e);return Atomics.load(new Int32Array(this.state.descriptions),t*3+1)}fcntl(e,t,r,n){if(t===rh||t===Ho)return this.duplicate(e,void 0,Math.max(3,r),t===Ho,n);const i=this.table.entries[e];return t===nh?BigInt(i.flags):t===sh?(i.flags=r&ah,0n):t===ih?BigInt(this.statusFlags(e)|(this.entry(e)<0?1:0)):t===oh?(Atomics.store(new Int32Array(this.state.descriptions),i.description*3+1,r&Us),0n):-22n}duplicate(e,t,r=Wo,n=!1,i={}){const o=this.table.get(e);if(!o)return-9n;if(t===e)return BigInt(e);const a=t===void 0?this.freeDescriptor(r):t;return a<0||a>=65536?-9n:(this.table.set(a,o,n?1:0),BigInt(a))}close(e){return this.table.close(e)?0n:-9n}poll(e,t,r,n){if(!Number.isSafeInteger(t)||t<0||t>65536||!this.validRange(e,t*8))return-22n;const i=n();let o=typeof i=="bigint"?Number(i):typeof i=="number"?i:0;o<0&&(o=0);for(let a=0;a<t;a+=1){const c=e+a*8,f=this.view().getInt32(c,!0),d=this.pollDescriptor(f,this.view().getInt16(c+4,!0));d!==void 0&&(this.view().getInt16(c+6,!0)!==0&&(o-=1),this.view().setInt16(c+6,d,!0),d!==0&&(o+=1))}return BigInt(o)}allocateSlot(){for(let e=0;e<this.slots.length;e+=1)if(Atomics.compareExchange(this.slots,e,0,1)===0)return e;return-1}freeDescriptor(e){for(let t=Math.max(3,e);t<=th;t++)if(!this.table.get(t))return t;return-1}allocateDescriptor(e,t=Wo){const r=this.freeDescriptor(t);if(r<0)return r;const n=Math.abs(e)-1,i=this.table.registry.create("pipe",{pipe:n,side:e>0?"reader":"writer"},()=>{en(this.handle(e));const o=this.control(n);Atomics.load(o,$o)===0&&Atomics.load(o,zo)===0&&Atomics.store(this.slots,n,0)});return Atomics.store(this.table.registry.pipeMetadata,i.id*3,e),this.table.set(r,i),r}entry(e){return fh(this.state,e)}handle(e){const t=Math.abs(e)-1;return{control:this.state.controls,payload:this.state.payloads,role:e>0?"reader":"writer",controlOffset:t*Vn*Int32Array.BYTES_PER_ELEMENT,payloadOffset:t*ti,payloadLength:ti}}control(e){return new Int32Array(this.state.controls,e*Vn*Int32Array.BYTES_PER_ELEMENT,Vn)}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}validRange(e,t){return Number.isSafeInteger(e)&&Number.isSafeInteger(t)&&e>=0&&t>=0&&e+t<=this.memory().buffer.byteLength}}const $s=64*1024,uh=1e4;var Wt;(function(s){s[s.Query=1]="Query",s[s.Open=2]="Open",s[s.Push=3]="Push",s[s.Pull=4]="Pull",s[s.Flush=5]="Flush",s[s.Close=6]="Close"})(Wt||(Wt={}));var Go;(function(s){s[s.VideoDecoder=0]="VideoDecoder",s[s.VideoEncoder=1]="VideoEncoder",s[s.AudioDecoder=2]="AudioDecoder",s[s.AudioEncoder=3]="AudioEncoder"})(Go||(Go={}));const jo=1;var Qe;(function(s){s[s.State=0]="State",s[s.Operation=1]="Operation",s[s.Result=2]="Result",s[s.Argument0=3]="Argument0",s[s.Argument1=4]="Argument1",s[s.Argument2=5]="Argument2",s[s.Argument3=6]="Argument3",s[s.Argument4=7]="Argument4",s[s.Argument5=8]="Argument5"})(Qe||(Qe={}));const mh=6,yh=9,wh=-5,zs=-9,ph=-11,Tn=-14,tr=-22,Sr=-95,gh=-110,Ko=3e4,Sh=uh+5e3;class bh{channel;control;nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control)}call(e,t,r){if(Atomics.load(this.control,Qe.State)!==0)return ph;const n=this.nextRequestId;this.nextRequestId=n>=1073741821?1:n+2,this.control.fill(0);for(let a=0;a<mh;a+=1)Atomics.store(this.control,Qe.Argument0+a,t[a]??0);Atomics.store(this.control,Qe.Operation,e),Atomics.store(this.control,Qe.State,n),this.channel.port.postMessage(n);const i=Date.now()+r;for(;;){const a=Atomics.load(this.control,Qe.State);if(a===n+1)break;if(a!==n&&a!==-n)return wh;const c=Math.max(0,i-Date.now());if(c===0&&a===n&&Atomics.compareExchange(this.control,Qe.State,n,0)===n)return gh;Atomics.wait(this.control,Qe.State,a,a===-n?void 0:c)}const o=Atomics.load(this.control,Qe.Result);return Atomics.store(this.control,Qe.State,0),o}}function Eh(s,e,t){const r=()=>s().buffer.byteLength,n=(c,f)=>Number.isSafeInteger(c)&&c>0&&f>=0&&c<=r()-f,i=(c,f)=>f===0?Number.isSafeInteger(c)&&c>=0:n(c,f),o=(c,f,d=Ko)=>{const y=t();return BigInt(y?y.call(c,f,d):Sr)},a=c=>(f,d,y)=>{if(!e())return BigInt(Sr);const p=Number(f),A=Number(d),k=Number(y);return!Number.isInteger(p)||p<0||p>3||!Number.isSafeInteger(k)||k<1||k>$s?BigInt(tr):n(A,k)?o(c,[p,A,k]):BigInt(Tn)};return{SYS_browser_codec_query_v1:a(Wt.Query),SYS_browser_codec_open_v1:a(Wt.Open),SYS_browser_codec_push_v1:(c,f,d,y,p)=>{if(!e())return BigInt(Sr);const A=Number(c),k=Number(f),_=Number(d),E=Number(y),L=Number(p);return!Number.isInteger(A)||A<=0?BigInt(zs):!Number.isSafeInteger(_)||_<0||!Number.isSafeInteger(L)||L<1||L>$s?BigInt(tr):_>0&&!n(k,_)||!n(E,L)?BigInt(Tn):o(Wt.Push,[A,k,_,E,L])},SYS_browser_codec_pull_v1:(c,f,d,y,p,A)=>{if(!e())return BigInt(Sr);const k=Number(c),_=Number(f),E=Number(d),L=Number(y),x=Number(p),D=Number(A);return!Number.isInteger(k)||k<=0?BigInt(zs):!Number.isInteger(_)||(_&~jo)!==0||!Number.isSafeInteger(L)||L<0||!Number.isSafeInteger(D)||D<0||D>$s?BigInt(tr):!i(E,L)||!i(x,D)?BigInt(Tn):o(Wt.Pull,[k,_,E,L,x,D],(_&jo)===0?Ko:Sh)},SYS_browser_codec_flush_v1:c=>{if(!e())return BigInt(Sr);const f=Number(c);return!Number.isInteger(f)||f<=0?BigInt(zs):o(Wt.Flush,[f])},SYS_browser_codec_close_v1:c=>{if(!e())return BigInt(Sr);const f=Number(c);return!Number.isInteger(f)||f<=0?0n:o(Wt.Close,[f])}}}class fi{worker;constructor(e){this.worker=e}static async create(e){const t=rn(new Worker(new URL("/assets/codec-worker-CbrC58Ct.js",import.meta.url),{type:"module",name:"wali-codec"}));return await new Promise((r,n)=>{const i=o=>{o.data.kind==="ready"&&(t.removeEventListener("message",i),r()),o.data.kind==="error"&&(t.removeEventListener("message",i),n(new Error(o.data.message)))};t.addEventListener("message",i),t.addEventListener("error",o=>n(o.error??new Error(o.message)),{once:!0}),t.postMessage({kind:"initialize",memory:e})}),new fi(t)}createChannel(){const e=new MessageChannel,t=new SharedArrayBuffer(yh*Int32Array.BYTES_PER_ELEMENT);return this.worker.postMessage({kind:"attach",port:e.port2,control:t},[e.port2]),{port:e.port1,control:t}}terminate(){this.worker.terminate()}}const Hs=1,Vs=2,Gs=4,Xo=8,Ah=16,_h=32,Ca=1024,Nh=Ca*8;function Ih(s,e,t){return(r,n,i,o,a)=>{const c=Number(r);if(!Number.isInteger(c)||c<0||c>Ca)return-22n;const f=[Number(n),Number(i),Number(o)],d=[Hs,Gs,Vs],y=Math.ceil(c/8);let p=new Uint8Array(s().buffer);for(const j of f)if(j!==0&&(j<0||j+y>p.byteLength))return-14n;const A=Number(a);let k=-1;if(A!==0){if(A<0||A+16>p.byteLength)return-14n;const j=new DataView(s().buffer),v=j.getBigInt64(A,!0),T=j.getBigInt64(A+8,!0);if(v<0n||T<0n)return-22n;k=Number(v*1000n+(T+999n)/1000n)}const _=new Map;f.forEach((j,v)=>{if(j!==0)for(let T=0;T<c;T+=1)p[j+(T>>3)]&1<<(T&7)&&_.set(T,(_.get(T)??0)|d[v])});const E=t();if(E<=0)return-12n;let L=new DataView(s().buffer),x=0;for(const[j,v]of _){const T=E+x*8;L.setInt32(T,j,!0),L.setInt16(T+4,v,!0),L.setInt16(T+6,0,!0),x+=1}const D=e(E,x,k),z=Number(typeof D=="bigint"?D:D??0);if(z<0)return BigInt(z);p=new Uint8Array(s().buffer),L=new DataView(s().buffer);for(const j of f)j!==0&&p.fill(0,j,j+y);let oe=0,fe=0;for(const[j,v]of _){const T=L.getInt16(E+fe*8+6,!0);if(fe+=1,T&_h)return-9n;[(v&Hs)!==0&&(T&(Hs|Ah|Xo))!==0,(v&Gs)!==0&&(T&(Gs|Xo))!==0,(v&Vs)!==0&&(T&Vs)!==0].forEach((ae,Ae)=>{if(!ae)return;const Me=f[Ae]+(j>>3);p[Me]=(p[Me]??0)|1<<(j&7),oe+=1})}return BigInt(oe)}}var $t;(function(s){s[s.Inspect=1]="Inspect",s[s.Read=2]="Read",s[s.WriteStart=3]="WriteStart",s[s.WriteChunk=4]="WriteChunk",s[s.WriteFinish=5]="WriteFinish",s[s.Remove=6]="Remove"})($t||($t={}));const Fn=512*1024,Jo=256*1024*1024,Qo=5,kh=new TextEncoder,Mh=new TextDecoder("utf-8",{fatal:!0});class xh{channel;control;payload;nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload)}pull(e){const t=this.call($t.Inspect,{path:e});if(!t.exists)return;const r=si(t.length,0,Jo),n=new Uint8Array(r);for(let i=0;i<r;i+=Fn){const o=Math.min(Fn,r-i),a=this.call($t.Read,{path:e,offset:i,length:o}),c=sr(a.content);if(c.byteLength!==o)throw new Error("Invalid coherent file response.");n.set(c,i)}return{bytes:n,...t.mode===void 0?{}:{mode:t.mode},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs},parents:Ua(e,t.parents)}}push(e,t){if(!t){this.call($t.Remove,{path:e});return}if(t.bytes.byteLength>Jo)throw new Error("Coherent file exceeds 256 MiB.");this.call($t.WriteStart,{path:e,length:t.bytes.byteLength,...t.mode===void 0?{}:{mode:t.mode},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs},...t.parents===void 0?{}:{parents:t.parents}});for(let r=0;r<t.bytes.byteLength;r+=Fn){const n=t.bytes.subarray(r,r+Fn);this.call($t.WriteChunk,{offset:r,content:dt(n)})}this.call($t.WriteFinish)}call(e,t={}){const r=()=>{if(Atomics.load(this.control,Qo))throw Object.assign(new Error("Browser file coherence was cancelled."),{errno:125})};r();const n=kh.encode(JSON.stringify(t));if(n.byteLength>this.payload.byteLength)throw new Error("File-coherence request is too large.");if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent file-coherence RPC on one channel.");const i=this.nextRequestId;this.nextRequestId=i>=1073741821?1:i+2,this.control.fill(0,0,Qo),this.payload.set(n),Atomics.store(this.control,1,e),Atomics.store(this.control,3,n.byteLength),Atomics.store(this.control,0,i);try{for(this.channel.port.postMessage(i);Atomics.load(this.control,0)!==i+1;){r();const f=Atomics.load(this.control,0);f!==i+1&&Atomics.wait(this.control,0,f)}const o=Atomics.load(this.control,2),a=si(Atomics.load(this.control,4),0,this.payload.byteLength),c=a===0?void 0:JSON.parse(Mh.decode(this.payload.slice(0,a)));if(o<0)throw Object.assign(new Error(`Browser file coherence failed with ${o}.`),{errno:-o});return c}finally{Atomics.store(this.control,0,0)}}}function Zo(s){const e=s.replace(/-(?:journal|shm|wal)$/u,"");return[e,`${e}-journal`,`${e}-wal`,`${e}-shm`]}function Lh(s,e){return hi(e).flatMap(t=>{if(!s.existsSync(t))return[];const r=s.statSync(t);if(!r.isDirectory())throw Lt("A coherent file parent must be a directory.");return[{path:t,...Wa({mode:r.mode,mtimeMs:r.mtimeMs})}]})}function Ph(s,e,t){const r=new Map(Ua(e,t).map(n=>[n.path,n]));for(const n of hi(e)){if(s.existsSync(n)){if(!s.statSync(n).isDirectory())throw Lt("A coherent file parent must be a directory.");continue}s.mkdirSync(n);const i=r.get(n);i?.mode!==void 0&&s.chmodSync?.(n,i.mode),i?.mtimeMs!==void 0&&s.utimesSync?.(n,new Date(i.mtimeMs),new Date(i.mtimeMs))}}function Ua(s,e){if(e===void 0)return[];const t=new Set(hi(s));if(!Array.isArray(e)||e.length>t.size)throw Lt("Invalid coherent file parents.");return e.map(r=>{if(typeof r!="object"||r===null)throw Lt("Invalid coherent file parent.");const n=r,i=$a(n.path);if(!t.delete(i))throw Lt("Coherent metadata must name distinct ancestors of its file.");return{path:i,...Wa(n)}})}function hi(s){const e=[];for(const t of $a(s).split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return e.slice(0,-1).map((t,r)=>`/${e.slice(0,r+1).join("/")}`)}function Wa(s){const e=s.mode===void 0?void 0:si(s.mode,0,65535),t=s.mtimeMs===void 0?void 0:vh(s.mtimeMs);return{...e===void 0?{}:{mode:e},...t===void 0?{}:{mtimeMs:t}}}function $a(s){const e=Rh(s);if(!e.startsWith("/")||e.length>4096||e.includes("\0"))throw Lt("Invalid coherent file path.");return e}function Rh(s){if(typeof s!="string")throw Lt("Expected a string.");return s}function si(s,e,t){if(!Number.isSafeInteger(s)||s<e||s>t)throw Lt("Expected a bounded integer.");return s}function vh(s){if(typeof s!="number"||!Number.isFinite(s))throw Lt("Expected a finite number.");return s}function Lt(s){return Object.assign(new Error(s),{errno:22})}class Th{locks;coherence;filesystem;held=[];locallyCreated=new Set;constructor(e,t,r){this.locks=e,this.coherence=t,this.filesystem=r}created(e){this.locallyCreated.add(e)}request(e){if(e.operation==="query")return this.locks.request(e);if(e.operation==="set"){const i=!this.held.some(a=>a.path===e.path),o=this.locks.request(e);if(o.result<0)return o;if(i)try{this.refresh(e.path)}catch(a){throw this.locks.request({operation:"unlock",owner:e.owner,namespace:e.namespace,path:e.path,range:e.range}),a}return this.install(e.owner,e.namespace,e.path,e.range),o}if(e.operation==="unlock"){const i=this.without(e.owner,e.namespace,e.path,e.range);this.held.some(a=>a.path===e.path)&&!i.some(a=>a.path===e.path)&&this.publish(e.path);const o=this.locks.request(e);return o.result>=0&&this.replaceHeld(i),o}const t=this.held.filter(i=>i.owner!==e.owner),r=new Set(this.held.filter(i=>i.owner===e.owner).map(i=>i.path));for(const i of r)t.some(o=>o.path===i)||this.publish(i);const n=this.locks.request(e);return n.result>=0&&this.replaceHeld(t),n}refresh(e){const t=performance.now();try{this.refreshNow(e)}finally{qe.waited.ms+=performance.now()-t}}publish(e){const t=performance.now();try{this.publishNow(e)}finally{qe.waited.ms+=performance.now()-t}}refreshNow(e){for(const t of Zo(e)){const r=this.coherence.pull(t);if(!r&&this.locallyCreated.delete(t)){this.coherence.push(t,this.readLocal(t)),this.filesystem.dropChangedPaths?.([t]);continue}this.locallyCreated.delete(t),this.writeLocal(t,r),this.filesystem.dropChangedPaths?.([t])}}publishNow(e){for(const t of Zo(e))this.coherence.push(t,this.readLocal(t)),this.filesystem.dropChangedPaths?.([t])}readLocal(e){if(!this.filesystem.existsSync(e))return;const t=this.filesystem.statSync(e);if(!t.isDirectory())return{bytes:this.filesystem.readFileSync(e),...t.mode===void 0?{}:{mode:t.mode},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs},parents:Lh(this.filesystem,e)}}writeLocal(e,t){if(!t){this.filesystem.existsSync(e)&&!this.filesystem.statSync(e).isDirectory()&&this.filesystem.unlinkSync(e);return}Ph(this.filesystem,e,t.parents),this.filesystem.writeFileSync(e,t.bytes),t.mode!==void 0&&this.filesystem.chmodSync?.(e,t.mode),t.mtimeMs!==void 0&&this.filesystem.utimesSync?.(e,new Date(t.mtimeMs),new Date(t.mtimeMs))}install(e,t,r,n){const i=this.without(e,t,r,n);i.push({owner:e,namespace:t,path:r,...n}),this.replaceHeld(i)}without(e,t,r,n){return this.held.flatMap(i=>i.owner===e&&i.namespace===t&&i.path===r&&Fh(i,n)?Bh(i,n):[i])}replaceHeld(e){this.held.splice(0,this.held.length,...e)}}function Fh(s,e){return s.start<(e.end??Number.POSITIVE_INFINITY)&&e.start<(s.end??Number.POSITIVE_INFINITY)}function Bh(s,e){const t=[];s.start<e.start&&t.push({...s,end:e.start});const r=s.end??Number.POSITIVE_INFINITY,n=e.end??Number.POSITIVE_INFINITY;return n<r&&t.push({...s,start:n,...s.end===void 0?{}:{end:s.end}}),t}const Oh=9n,Dh=22n,qo=new TextEncoder,Kr=new TextDecoder;class za extends Error{imports;constructor(e){super(`Unsupported WALI imports: ${e.join(", ")}`),this.imports=e,this.name="UnsupportedWaliImportError"}}function Yh(s,e){if(Zc(s))return()=>{throw new za([s])};let t=!1;return()=>{if(!t){t=!0;const r=`[WALI] ${s} is not implemented; answering -ENOSYS (38) as a kernel would.`;console.error(r),e?.(r)}return Qc}}class ea extends Error{}class ta extends Error{code;constructor(e){super(`WALI process exited with status ${e}`),this.code=e}}class Ch{async run(e,t={}){const r=t.filesystemPolicy===void 0?void 0:nr(t.filesystemPolicy),n=r,i=await Gc(e),o=jc(i);Kc(o);const a=o.filter(g=>g.module==="wali"),c=[],f=[],d=typeof t.stdin=="object"&&t.stdin!==null&&"read"in t.stdin?t.stdin:new da(typeof t.stdin=="string"?qo.encode(t.stdin):t.stdin??new Uint8Array),y=t.argv?.length?[...t.argv]:["wali-program"],p=y.map(g=>qo.encode(`${g}\0`)),A=zh(t.pid),k=performance.now(),_={...qe.waited};let E=k;const L=new Map,x=t.signalState??Yc();let D,z,oe,fe,j,v,T=!1;const Q=wf(e,t.memory),ae=Ll(),Ae=new Int32Array(new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT));Atomics.store(Ae,1,-1);const Me=new on(new ii),F=t.descriptorTable?.sharedPipes??lh(Me),W=()=>{if(Q)return Q;const g=D?.exports.memory;if(!(g instanceof WebAssembly.Memory))throw new Error("WALI module does not export linear memory.");return g},ue=()=>new DataView(W().buffer),re=()=>new Uint8Array(W().buffer),mt=(g,N)=>(br(W(),g,N),re().slice(g,g+N)),$=(g,N)=>{br(W(),g,N.byteLength),re().set(N,g)},V=(g,N)=>{if(g===1)c.push(N),t.onStdout?.(N.slice());else if(g===2)f.push(N),t.onStderr?.(N.slice());else return-Oh;return BigInt(N.byteLength)},me=(g,N="SYS_exit_group")=>{const P=`[WALI] ${N}(${g&255}) on the MAIN thread -- the process is ending here, not in a pthread. If the program did not ask to exit, this is the caller to find.`;throw console.error(P),t.onDiagnostic?.(P),new ta(g&255)},tt=g=>g<0||g>64?-22n:g===0?0n:g!==9&&(Re.mask&1n<<BigInt(g-1))!==0n?(new us(x).raise(g),0n):((g===9||g===19?"default":new us(x).raise(g))==="default"&&Dc(g)&&me(128+g,`signal ${g}`),0n),Oe=t.executablePath??(y[0].startsWith("/")?y[0]:`/usr/bin/${y[0]}`),Se=a.some(g=>g.name==="__wasm_thread_spawn"),xe=a.some(g=>Uh.has(g.name))?t.browserProcess:void 0,Pt=t.forkState?.allocator??Ea(),Rt=Kl(),He=t.descriptorTable?new ei(t.descriptorTable):void 0;if(He&&Q&&He.attachMemory(Q),!He&&(Se||xe)&&t.filesystem?.toSnapshot&&t.filesystem.replaceSnapshot){if(!Q)throw new Error("A threaded WALI module must import its shared process memory.");const g=t.store||t.layers?t.filesystem.toStoreOverlaySnapshot?.():void 0;T=!(!!xe?.fork&&WebAssembly.Module.exports(i).some(P=>P.name==="asyncify_start_unwind")||a.some(P=>P.name==="SYS_browser_spawn"||P.name==="SYS_browser_spawn_confined_v1")),v=await(T?sn.createInThread:sn.create)(g??t.filesystem.toSnapshot(),{...t.store?{store:t.store}:{},...t.layers?{layers:t.layers}:{},...t.privateRoots?{privateRoots:t.privateRoots}:{},memory:Q,sharedPipes:F,...n?{filesystemPolicy:n}:{},cwd:t.cwd??"/",executablePath:Oe,pid:A,...t.filesystemUpdatePort?{updatePort:t.filesystemUpdatePort}:{},...t.fileLocks?{fileLocks:t.fileLocks}:{},...t.fileCoherence?{fileCoherence:t.fileCoherence}:{}})}if(n&&Se&&!v&&!He)throw new Error("Confined WALI threads require the shared filesystem owner.");const _e=He??v?.filesystem()??t.filesystem,se=()=>{v&&t.filesystem?.replaceSnapshot&&t.filesystem.replaceSnapshot(v.snapshot())},ce=new Jn({...He||v?{descriptorState:F}:{descriptors:Me},...n?{filesystemPolicy:n}:{},..._e?{filesystem:_e}:{},cwd:t.cwd??"/",stdin:d,executablePath:Oe,memory:W,emit:V,stdioAliasRegistry:ae,pid:A,...!v&&t.fileLocks?{fileLocks:t.fileCoherence?new Th(new qe(t.fileLocks.channel),new xh(t.fileCoherence),_e):new qe(t.fileLocks.channel),lockOwner:t.fileLocks.owner}:{},...v?{specialDescriptorMinimum:1e4,descriptorMaximum:19999}:{},...!v&&!He&&t.privateRoots?{privateRoots:t.privateRoots.map(g=>`/${g.split("/").filter(Boolean).join("/")}`)}:{},...t.onDiagnostic?{onDiagnostic:t.onDiagnostic}:{}}),ye=ce.imports(),Le=ce.writeEnvironmentFile(t.env??{},A),K=He??v?.filesystem(),Ve=K?new qf(K,ae,F,W):void 0,Pe=new Xl(W,(g,N,P)=>Ve?.readForMapping(g,N,P)??ce.readForMapping(g,N,P),Pt,g=>Ve?.mappingPath(g)??ce.mappingPath(g),(g,N,P)=>Ve?.writeForMapping(g,N,P)??ce.writeForMapping(g,N,P),Rt,t.onDiagnostic),Re=new Cc(new us(x),W,()=>D?.exports.__indirect_function_table,()=>Number(Pe.imports().SYS_mmap(0,4096,3,34,-1,0)),Uc(()=>D?.exports,W)),yt=t.threadPoolSize??18,xr=new cf(W,A,d,Ae,t.terminal,yt,()=>Pe.growAhead()),be=T?v?.doorbell():void 0;Hi(be?{pump:()=>v.pump(!0),doorbell:be}:void 0);let an=!1;(t.network||xe)&&(oe=await li.create(t.network,F,d instanceof Qs?d.buffer:void 0,ae.buffer,x));const Ne=oe?new jf(W,oe.createChannel(),Re):void 0,or=new dh(W,F,K?void 0:Me,K),Lr=new yf(W,ce,(g,N)=>or.pollDescriptor(g,N)??(Ne?.isNetworkFd(g)?Ne.pollFd(g,N):void 0)),es=new Wf(W,ce),cn=ce.imports(),ts=Ve?.imports(cn)??cn,ln=or.imports({...es.imports(),...ts}),Ht=Lr.imports(),rt=xr.imports(),fn=t.forkState?.parentPid??t.parentPid??1,wt=new Int32Array(t.childPidAllocator??new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));t.childPidAllocator||Atomics.store(wt,0,Math.max(A+1,1e4));const pt=g=>{if(!Number.isSafeInteger(g)||g<=0||g>=re().byteLength)throw new WebAssembly.RuntimeError("WALI process string pointer is out of bounds.");const N=re().indexOf(0,g);if(N<0||N-g>1024*1024)throw new WebAssembly.RuntimeError("WALI process string is not terminated.");return Kr.decode(re().slice(g,N))},gt=g=>{if(g===0)return[];const N=[];for(let P=0;P<65536;P+=1){br(W(),g+P*4,4);const U=ue().getUint32(g+P*4,!0);if(U===0)return N;N.push(pt(U))}throw new WebAssembly.RuntimeError("WALI process string array is not terminated.")},vt=(g,N)=>{const P=or.exportBrowserProcessPipe(g)??ce.exportBrowserProcessPipe(g);if(!(!P||P.role!==N))return va(P)},rs=(g,N,P)=>{if(!Ne)return-10n;if(N!==0&&(N<0||N+4>re().byteLength))return-14n;const{result:U,process:X}=Ne.waitChild(g,P,Re.mask);if(U<=0)return BigInt(U);const le=vf(X);if(le){v&&v.filesystem().importPeerPatch(le),t.filesystem&&_f(t.filesystem,le);const J=t.filesystem?.toSnapshot?.();J&&t.browserProcess?.restore?.(J)}return N!==0&&ue().setInt32(N,(Atomics.load(new Int32Array(X.control),1)&255)<<8,!0),BigInt(U)},Pr=(g,N)=>{const[P,U,X,le,J,he,Te]=g;if(!t.browserProcess)return-38;const Ye=bt(1,[J,he,Te]);if(Ye!==void 0)return Ye;N&&(N=nr(N));const At=r;if(At){if(t.browserProcess.filesystemPolicyVersion!==1)return-95;N=Wc(At,N)}const _t=pt(Number(P)),st=gt(Number(U));st.length===0&&st.push(_t);const hn={};for(const ot of gt(Number(X))){const jt=ot.indexOf("=");jt>0&&(hn[ot.slice(0,jt)]=ot.slice(jt+1))}const Ce=Atomics.add(wt,0,1),Vt={control:new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),response:new SharedArrayBuffer(qs),snapshotApplied:!1},fr=vt(Number(J),"reader"),Gt=vt(Number(he),"writer"),Fe=vt(Number(Te),"writer");let it;try{const ot=Ne.registerChild(Ce,Vt);if(ot<0)throw new Error(`Child registration failed: ${ot}`);return K?.prepareSpawn(),se(),it=K?.copyForExecChannel([Number(J),Number(he),Number(Te)]),t.browserProcess.spawn({pid:Ce,parentPid:A,childPidAllocator:wt.buffer,...it?{descriptorTable:it}:{},...N?{filesystemPolicy:N}:{},executablePath:_t,argv:st,env:hn,...Number(X)===0?{inheritEnvironment:!0}:{},cwd:Number(le)===0?ce.currentWorkingDirectory():pt(Number(le)),control:Vt.control,response:Vt.response,...fr?{stdin:fr}:{},...Gt?{stdout:Gt}:{},...Fe?{stderr:Fe}:{}}),Ce}catch{return it?.releasePort?.postMessage(!0),Ne.forgetChild(Ce),fr&&en(fr),Gt&&en(Gt),Fe&&en(Fe),-5}};let ve=t.forkState?.asyncifyData??0,Rr=!1,we=!!t.forkState,Ge=0,St=!1;const nt=(g,...N)=>{const P=D?.exports[g];if(typeof P!="function")throw new Error(`Missing ${g}; build the module with the Binaryen Asyncify stage.`);P(...N)},ar=()=>K?.currentWorkingDirectory()??ce.currentWorkingDirectory(),bt=(g,N=[])=>{const P=D?.exports.__wali_private_tree_release;if(typeof P!="function")return;const U=Number(P(g,Number(N[0]??-1),Number(N[1]??-1),Number(N[2]??-1)));return U<0?U:void 0},vr=()=>{if(typeof D?.exports.asyncify_start_unwind!="function")return St||t.onDiagnostic?.("[WALI] SYS_fork answers -ENOSYS: module lacks the Binaryen Asyncify build stage (--asyncify --pass-arg=asyncify-imports@wali.SYS_fork)."),St=!0,-38n;if(we)return nt("asyncify_stop_rewind"),we=!1,BigInt(Ge);if(!t.browserProcess?.fork||!K||!Ne)return-38n;const g=bt(0);return g!==void 0?BigInt(g):(Rr=!0,ue().setUint32(ve,ve+8,!0),nt("asyncify_start_unwind",ve),0n)},ns=(g,N,P)=>{if(!t.forkState||!t.browserProcess||!K)return-38n;const U=bt(0);if(U!==void 0)return BigInt(U);const X=pt(g),le=X.startsWith("/")?X:`${ar()}/${X}`;if(!_e?.existsSync(le))return-2n;if(!_e.statSync(le).isFile())return-13n;const J=P===0?{...t.env}:{};for(const _t of gt(P)){const st=_t.indexOf("=");st>0&&(J[_t.slice(0,st)]=_t.slice(st+1))}K.prepareSpawn();const he=K.copyForExecChannel([0,1,2]),Te=vt(0,"reader"),Ye=vt(1,"writer"),At=vt(2,"writer");throw t.browserProcess.spawn({pid:A,parentPid:fn,childPidAllocator:wt.buffer,executablePath:le,argv:gt(N),env:J,cwd:ar(),descriptorTable:he,control:t.forkState.control,response:t.forkState.response,...n?{filesystemPolicy:n}:{},...Te?{stdin:Te}:{},...Ye?{stdout:Ye}:{},...At?{stderr:At}:{}}),new ea},Tt={...{__init:()=>0,__deinit:()=>0,__proc_exit:g=>me(Number(g)),__cl_get_argc:()=>p.length,__cl_get_argv_len:g=>p[Number(g)]?.byteLength??0,__cl_copy_argv:(g,N)=>{const P=p[Number(N)];return P?($(Number(g),P),0):-1},__get_init_envfile:(g,N)=>Le?ce.copyCString(Number(g),Le,Number(N)):0,SYS_write:(g,N,P)=>V(Number(g),mt(Number(N),Number(P))),SYS_writev:(g,N,P)=>{let U=0n;for(let X=0;X<Number(P);X+=1){const le=Number(N)+X*8;br(W(),le,8);const J=ue().getUint32(le,!0),he=ue().getUint32(le+4,!0),Te=V(Number(g),mt(J,he));if(Te<0n)return Te;U+=Te}return U},SYS_exit:g=>me(Number(g),"SYS_exit"),SYS_exit_group:g=>me(Number(g),"SYS_exit_group"),SYS_getpid:()=>BigInt(A),SYS_getppid:()=>BigInt(fn),SYS_gettid:()=>BigInt(A),SYS_getuid:()=>1000n,SYS_geteuid:()=>1000n,SYS_getgid:()=>1000n,SYS_getegid:()=>1000n,SYS_set_tid_address:()=>BigInt(A),SYS_sched_yield:()=>0n,SYS_sched_setscheduler:()=>0n,SYS_tkill:(g,N)=>tt(Number(N)),...Eh(W,()=>t.codec?.version===1,()=>j),SYS_browser_spawn:(...g)=>Pr(g),SYS_browser_spawn_confined_v1:zc(W,()=>t.browserProcess?.filesystemPolicyVersion===1,Pr),SYS_fork:vr,SYS_execve:(g,N,P)=>ns(Number(g),Number(N),Number(P)),SYS_wait4:(g,N,P)=>{for(;;){const U=rs(Number(g),Number(N),Number(P));if(U!==-4n||!Re.deliver(!0))return U}},SYS_pidfd_open:()=>-38n,SYS_kill:(g,N)=>{if(Number(g)===A||Number(g)===0)return tt(Number(N));const P=Math.abs(Number(g));return Ne?.hasChild(P)?(t.browserProcess?.kill?.(P,Number(N)),0n):-3n},SYS_setpgid:()=>0n,SYS_getpgid:g=>BigInt(Number(g)===0?A:Math.abs(Number(g))),__wasm_thread_spawn:(g,N)=>{const P=z?.spawn(Number(g),Number(N),Re.mask)??-11;if(P===-11&&!an){an=!0;const U=`[WALI] pthread_create answered -EAGAIN: all ${yt} worker slots are in use. The pool is the process's whole thread budget and does not grow, so this is a QUOTA, not a cpu count -- sysconf(_SC_NPROCESSORS_ONLN) answers ${xr.reportedCpuCount()} here and a library that opens more than one pool from that number wants a multiple of it. Raise the program's requirements.workers, or state the library's concurrency.`;console.error(U),t.onDiagnostic?.(U)}return P},SYS_clock_gettime:(g,N)=>{const P=Hh(Number(g));return P===void 0?-Dh:(Vh(ue(),Number(N),P),0n)},SYS_gettimeofday:g=>{if(Number(g)!==0){const N=BigInt(Math.floor(ge()*1e3));br(W(),Number(g),16),ue().setBigInt64(Number(g),N/1000000n,!0),ue().setBigInt64(Number(g)+8,N%1000000n,!0)}return 0n},SYS_getrandom:(g,N)=>{const P=re().subarray(Number(g),Number(g)+Number(N));return br(W(),Number(g),Number(N)),Gh(P),BigInt(P.byteLength)},...Pe.imports(),...rt,...Re.imports(),...ln,...Ne?Ne.imports({...ln,...Ht}):Ht,SYS_ioctl:(g,N,P)=>or.ioctl(Number(g),Number(N))??ce.ioctl(Number(g),Number(N))??rt.SYS_ioctl(g,N,P),SYS_prctl:(g,...N)=>Number(g)!==wa?0n:K?K.syscall("SYS_prctl",[g,...N]):ye.SYS_prctl(g,...N)},...t.imports};let Et=0;if(Tt.SYS_select??=Ih(W,(g,N,P)=>Tt.SYS_poll(g,N,P),()=>Et||=Number(Pe.imports().SYS_mmap(0,Nh,3,34,-1,0))),T&&Ve)for(const[g,N]of Object.entries(Ve.ownedFileImports(Tt)))t.imports?.[g]||(Tt[g]=N);const De={};for(const g of a){const N=Tt[g.name]??Yh(g.name,t.onDiagnostic),P=(!K||T)&&$h.has(g.name),U={calls:0,ms:0,sampled:P};L.set(g.name,U),De[g.name]=(...X)=>{t.onSyscall?.(g.name,X),T&&v.pump();const le=!P||(U.calls&ra-1)===0,J=le?performance.now():0;try{const he=N(...X);return t.onSyscallResult?.(g.name,he),Re.deliver(he===-4n),he}finally{U.calls+=1,le&&(U.ms+=(performance.now()-J)*(P?ra:1))}}}const Tr={...Q?{memory:Q}:{},_Unwind_Backtrace:()=>5,_Unwind_FindEnclosingFunction:g=>g,_Unwind_GetCFA:()=>0};if(D=await WebAssembly.instantiate(i,{wali:De,env:Tr}),t.forkState){re().set(new Uint8Array(t.forkState.memory));for(const[g,N]of Object.entries(t.forkState.globals)){const P=D.exports[g];if(!(P instanceof WebAssembly.Global))throw new Error(`Fork snapshot global ${g} is not exported.`);P.value=N}Pe.restoreFork(t.forkState.mappings),rt.SYS_umask(t.forkState.umask)}else if(typeof D.exports.asyncify_start_unwind=="function"){const g=D.exports.__stack_pointer;if(!(g instanceof WebAssembly.Global))throw new Error("Asyncify fork requires --export=__stack_pointer at link.");const N=Number(g.value);if(N<=0)throw new Error("Asyncify fork requires a nonempty module stack.");ve=W().buffer.byteLength,W().grow(Math.ceil((N+8)/65536)),ue().setUint32(ve+4,ve+8+N,!0)}if(t.codec?.version===1)try{fe=await fi.create(W()),j=new bh(fe.createChannel())}catch(g){console.warn("[WALI] the codec bridge is unavailable:",g),fe=void 0,j=void 0}if(Se){if(!Q)throw new Error("A threaded WALI module must be linked with --import-memory so browser workers can share its process memory.");const g=t.memoryLayout??(e instanceof WebAssembly.Module?void 0:Qn(e instanceof Uint8Array?e:new Uint8Array(e)));z=new Ef({module:i,memory:Q,onDemand:g?.passiveData===!0,mmapCursor:Pe.allocatorControl(),sharedMmapRegistry:Rt,fatalState:Ae.buffer,imports:o,size:yt,pid:A,executablePath:Oe,argv:y,cwd:ce.currentWorkingDirectory(),stdioAliasRegistry:ae.buffer,sharedPipes:F,signals:x,childPidAllocator:wt.buffer,...r?{inheritedFilesystemPolicy:r}:{},...t.browserProcessPorts?{browserProcessPorts:t.browserProcessPorts}:{},...t.browserProcess?.filesystemPolicyVersion===1?{childFilesystemPolicyVersion:1}:{},...t.threadOutputPorts?{outputPorts:t.threadOutputPorts}:{},...d instanceof Qs?{stdin:d.buffer}:{},terminal:t.terminal===!0,onStdout:N=>{V(1,N)},onStderr:N=>{V(2,N)},...oe?{network:oe}:{},...K?{filesystem:K}:{},...fe?{codec:fe}:{}}),await z.initialize()}const cr=D.exports._start;if(typeof cr!="function")throw new Error("WALI module does not export _start.");T&&v?.closePort(),E=performance.now();let je=0,Fr=!1;try{try{for(we&&nt("asyncify_start_rewind",ve);cr(),!!Rr;){nt("asyncify_stop_unwind"),Rr=!1;const g=t.memoryLayout??(e instanceof WebAssembly.Module?void 0:Qn(e instanceof Uint8Array?e:new Uint8Array(e)));if(!g)throw new Error("Fork requires the module's imported memory layout.");const N={};for(const[J,he]of Object.entries(D.exports))if(he instanceof WebAssembly.Global)try{he.value=he.value,N[J]=he.value}catch{}const P=new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),U=new SharedArrayBuffer(qs);Ge=Atomics.add(wt,0,1);const X=Ne.registerChild(Ge,{control:P,response:U});if(X<0)throw new Error(`Fork child registration failed: ${X}`);const le=Number(rt.SYS_umask(0));rt.SYS_umask(le),t.onDiagnostic?.(`[WALI] fork snapshot: ${W().buffer.byteLength} bytes, Asyncify stack ${ue().getUint32(ve,!0)-ve-8} bytes.`),t.browserProcess.fork({module:i,memoryLayout:g,pid:Ge,control:P,response:U,descriptorTable:K.copyForForkChannel(),childPidAllocator:wt.buffer,argv:y,env:{...t.env},cwd:ar(),executablePath:Oe,...n?{filesystemPolicy:n}:{},forkState:{control:P,response:U,memory:re().slice().buffer,globals:N,allocator:Pe.allocatorControl().slice(0),mappings:Pe.forkSnapshot(),asyncifyData:ve,umask:le,parentPid:A}}),we=!0,nt("asyncify_start_rewind",ve)}}catch(g){if(g instanceof ea)Fr=!0;else if(g instanceof ta||g instanceof _a)je=g.code;else{if(g instanceof za)throw g;{const N=g instanceof Error?g.stack??g.message:String(g),P=Atomics.load(Ae,1),U=z?.diagnostics(P>=0?P:void 0)??[];throw new Error(`${N}
12
+ WALI stdout:
13
+ ${Kr.decode(Bn(c))}
14
+ WALI stderr:
15
+ ${Kr.decode(Bn(f))}`+(U.length>0?`
16
+ WALI pthread diagnostics:
17
+ ${U.join(`
18
+ `)}`:""),{cause:g})}}}}finally{hh(),z?.terminate(),oe?.terminate(),fe?.terminate(),Le&&_e?.existsSync(Le)&&_e.unlinkSync(Le),v&&t.filesystemUpdatePort&&t.filesystem?.replaceSnapshot?(t.filesystem.replaceSnapshot(v.finalSnapshot()),t.onFilesystemFinalized?.()):se(),K?.closeProcess(),K||ce.descriptors.exit(),v?.terminate(),Hi(void 0)}const lr=performance.now()-k;if(lr>Wh){const g=[...L].filter(([,U])=>U.calls>0),N=g.reduce((U,[,X])=>U+X.ms,0),P=g.sort((U,X)=>X[1].ms-U[1].ms).slice(0,8).map(([U,X])=>`${U.replace(/^SYS_/u,"")} ${X.calls}x ${X.sampled?"~":""}${Math.round(X.ms)}ms`);console.log("[wali-profile]",JSON.stringify({argv:y.slice(0,3),wallMs:Math.round(lr),setupMs:Math.round(E-k),guestMs:Math.round(performance.now()-E),syscallMs:Math.round(N),top:P,locks:`${qe.waited.calls-_.calls}x ${Math.round(qe.waited.ms-_.ms)}ms`}))}return{exitCode:je,...Fr?{replaced:Fr}:{},stdout:Kr.decode(Bn(c)),stderr:Kr.decode(Bn(f)),imports:o}}}const Uh=new Set(["SYS_fork","SYS_execve","SYS_browser_spawn","SYS_browser_spawn_confined_v1","SYS_wait4"]),Wh=2e3,$h=new Set(["SYS_open","SYS_openat","SYS_stat","SYS_lstat","SYS_fstat","SYS_newfstatat","SYS_statx","SYS_lseek","SYS_access","SYS_faccessat","SYS_faccessat2","SYS_readlink","SYS_readlinkat","SYS_getcwd","SYS_getdents64","SYS_mkdir","SYS_mkdirat","SYS_unlink","SYS_unlinkat","SYS_rename","SYS_renameat","SYS_rmdir","SYS_chmod","SYS_fchmod","SYS_utimensat","SYS_ftruncate","SYS_truncate","SYS_mmap","SYS_munmap","SYS_mprotect","SYS_madvise","SYS_mremap","SYS_brk","SYS_getpid","SYS_gettid","SYS_getppid","SYS_getuid","SYS_geteuid","SYS_getgid","SYS_getegid","SYS_clock_gettime","SYS_clock_getres","SYS_gettimeofday","SYS_rt_sigprocmask","SYS_rt_sigaction","SYS_uname","SYS_umask","SYS_dup","SYS_dup2","SYS_dup3","SYS_close","SYS_fcntl"]),ra=16;function zh(s){if(s===void 0)return 2;if(!Number.isSafeInteger(s)||s<=1||s>2147483647)throw new Error("WALI pid must be an integer between 2 and 2147483647.");return s}function br(s,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e+t>s.buffer.byteLength)throw new WebAssembly.RuntimeError(`WALI memory access is out of bounds: ${e}+${t}.`)}function Bn(s){const e=new Uint8Array(s.reduce((r,n)=>r+n.byteLength,0));let t=0;for(const r of s)e.set(r,t),t+=r.byteLength;return e}function Hh(s){if(s===0){const e=typeof performance>"u"?Date.now():performance.timeOrigin+performance.now();return BigInt(Math.floor(e*1e6))}if(s===1||s===4)return BigInt(Math.floor(jn()*1e6))}function Vh(s,e,t){if(e<0||e+16>s.byteLength)throw new WebAssembly.RuntimeError("WALI timespec pointer is out of bounds.");s.setBigInt64(e,t/1000000000n,!0),s.setBigInt64(e+8,t%1000000000n,!0)}function Gh(s){if(!globalThis.crypto?.getRandomValues)throw new Error("Web Crypto is required for SYS_getrandom.");for(let e=0;e<s.byteLength;e+=65536){const t=new Uint8Array(Math.min(65536,s.byteLength-e));globalThis.crypto.getRandomValues(t),s.set(t,e)}}class qn extends Map{names=new Map;static rooted(){const e=new qn;return e.set("/",Qh()),e}set(e,t){if(!this.has(e)&&e!=="/"){const r=zt(e);let n=this.names.get(r);n||(n=new Set,this.names.set(r,n)),n.add(e.slice(r==="/"?1:r.length+1))}return super.set(e,t)}delete(e){if(!super.delete(e))return!1;const t=zt(e),r=this.names.get(t);return r?.delete(e.slice(t==="/"?1:t.length+1)),r?.size===0&&this.names.delete(t),!0}clear(){super.clear(),this.names.clear()}namesIn(e){return[...this.names.get(e)??[]]}subtree(e){const t=[],r=[e];for(;r.length>0;){const n=r.shift(),i=this.get(n);if(i){t.push([n,i]);for(const o of this.names.get(n)??[])r.push(n==="/"?`/${o}`:`${n}/${o}`)}}return t}}class Ar{nodes=qn.rooted();lower;rangeBlocks=new Map;rangeBlockBytes=0;hidden=new Set;nextInode=2;mutationDepth=0;mutated=!1;mutationHandler;changedPaths;static fromSnapshot(e){const t=new Ar;return t.replaceSnapshot(e),t}static fromStore(e,t){const r=new Ar;return r.lower=e,r.mutate(()=>{const n=t.files.filter(i=>{const o=i,a=te(o.path);if(a==="/")return!1;if(o.content!==void 0)return!0;const c=e.entries.get(a);return!c||o.type==="directory"!=(c.type==="directory")?!0:o.mode!==void 0&&o.mode!==(c.mode&4095)||o.mtimeMs!==void 0&&o.mtimeMs!==c.mtimeMs});for(const i of n.sort((o,a)=>On(o.path)-On(a.path))){const o=i,a=te(o.path);if(o.type==="directory")r.node(a)||r.mkdirSync(a,{recursive:!0});else if(o.content!==void 0)r.writeFileSync(a,sr(o.content));else if(!r.node(a))continue;const c=r.node(a);c&&(o.mode!==void 0&&(c.mode=o.mode),o.mtimeMs!==void 0&&(c.atimeMs=c.mtimeMs=o.mtimeMs))}r.mutated=!1}),r}node(e){const t=this.nodes.get(e);if(t||!this.lower||e==="/")return t;if(this.isHidden(e))return;const r=this.lower.entries.get(e);if(!r)return;const n=this.lowerNode(e,r);return this.nodes.set(e,n),n}lowerNode(e,t){const r=this.lower;return t.type==="directory"?{type:"directory",fromStore:!0,mode:t.mode&4095,atimeMs:t.mtimeMs,mtimeMs:t.mtimeMs,ino:this.nextInode++}:{type:"file",fromStore:!0,load:()=>r.view?r.view(e):r.read(e),...r.readRange&&t.length>=jh&&r.readsByRange?.(e)?{range:(n,i)=>this.readBlocks(e,t.length,n,i,(o,a)=>r.readRange(e,o,a))}:{},size:t.length,mode:t.mode&4095,atimeMs:t.mtimeMs,mtimeMs:t.mtimeMs,ino:this.nextInode++}}readBlocks(e,t,r,n,i){const o=Math.min(Math.max(0,r),t),a=Math.min(t,o+Math.max(0,n));if(a<=o)return new Uint8Array(0);if(a-o>Xh)return i(o,a-o);const c=Math.floor(o/Xr),f=Math.floor((a-1)/Xr),d=new Uint8Array(a-o);for(let y=c;y<=f;y+=1){const p=`${y}:${e}`;let A=this.rangeBlocks.get(p);if(A)this.rangeBlocks.delete(p);else for(A=i(y*Xr,Xr),this.rangeBlockBytes+=A.byteLength;this.rangeBlockBytes>Kh&&this.rangeBlocks.size>0;){const[L,x]=this.rangeBlocks.entries().next().value;this.rangeBlocks.delete(L),this.rangeBlockBytes-=x.byteLength}this.rangeBlocks.set(p,A);const k=y*Xr,_=Math.max(o,k),E=Math.min(a,k+A.byteLength);E>_&&d.set(A.subarray(_-k,E-k),_-o)}return d}toStoreOverlaySnapshot(){if(!this.lower||this.hidden.size>0)return this.toSnapshot();const e=this.lower;return{files:[...this.nodes.entries()].filter(([r,n])=>{if(r==="/")return!1;const i=e.entries.get(r);return!(n.fromStore&&!n.dirty&&i&&n.mode===(i.mode&4095)&&n.mtimeMs===i.mtimeMs)}).map(([r,n])=>n.type==="directory"?{path:r,type:"directory",mode:n.mode,mtimeMs:n.mtimeMs}:n.load&&!n.dirty?this.sized(r,n):{path:r,type:"file",content:dt(n.content??new Uint8Array),mode:n.mode,mtimeMs:n.mtimeMs})}}isHidden(e){if(this.hidden.size===0)return!1;for(let t=e;t!=="/";t=zt(t))if(this.hidden.has(t))return!0;return!1}hide(e){this.lower?.entries.has(e)&&this.hidden.add(e)}unhide(e){if(!(!this.lower||!this.isHidden(e))){this.hidden.delete(e);for(const t of this.lower.childrenOf(e))this.hidden.add(e==="/"?`/${t}`:`${e}/${t}`)}}everyNode(){const e=[...this.nodes.entries()];if(!this.lower)return e;for(const[t,r]of this.lower.entries)t==="/"||this.nodes.has(t)||this.isHidden(t)||e.push([t,this.lowerNode(t,r)]);return e}setMutationHandler(e){this.mutationHandler=e,this.changedPaths=e?new Set:void 0}takeChangedPaths(){const e=this.changedPaths??new Set;return this.changedPaths=this.changedPaths?new Set:void 0,e}dropChangedPaths(e){if(this.changedPaths)for(const t of e)this.changedPaths.delete(te(t))}writtenEntry(e,t=!1){const r=te(e),n=this.node(r);if(!n)return;const i={mode:n.mode,mtimeMs:n.mtimeMs};return n.type==="directory"?{path:r,type:"directory",...i}:t?{path:r,type:"file",bytes:this.bytesOf(n).slice(),...i}:{path:r,type:"file",content:dt(this.bytesOf(n)),...i}}replaceSnapshot(e){this.mutate(()=>{const t=new Map(this.everyNode());this.lower=void 0,this.hidden.clear(),this.nodes=qn.rooted();for(const n of t.keys())this.markMutation(n);this.markMutation("/");const r=e.files.slice().sort((n,i)=>On(n.path)-On(i.path));for(const n of r){const i=n,o=te(i.path);if(o!=="/")if(i.type==="directory")this.mkdirSync(o,{recursive:!0});else if(i.content!==void 0){this.writeFileSync(o,sr(i.content));const c=this.nodes.get(o);c&&(c.dirty=!1)}else{const c=t.get(o);this.mkdirSync(zt(o),{recursive:!0}),c?.type==="file"&&this.nodes.set(o,c)}const a=this.node(o);a&&(i.mode!==void 0&&(a.mode=i.mode),i.mtimeMs!==void 0&&(a.atimeMs=a.mtimeMs=i.mtimeMs),this.markMutation(o))}})}toSnapshot(){return{files:[...this.nodes.entries()].map(([e,t])=>t.type==="directory"?{path:e,type:"directory",mode:t.mode,mtimeMs:t.mtimeMs}:t.load&&!t.dirty?this.sized(e,t):{path:e,type:"file",content:dt(t.content??new Uint8Array),mode:t.mode,mtimeMs:t.mtimeMs}).concat(this.untouchedStoreEntries())}}untouchedStoreEntries(){const e=[];if(!this.lower)return e;for(const[t,r]of this.lower.entries)t==="/"||this.nodes.has(t)||this.isHidden(t)||e.push(r.type==="directory"?{path:t,type:"directory",mode:r.mode&4095,mtimeMs:r.mtimeMs}:{path:t,type:"file",size:r.length,mode:r.mode&4095,mtimeMs:r.mtimeMs});return e}toWrittenSnapshot(){return{files:[...this.nodes.entries()].map(([e,t])=>t.type==="directory"?{path:e,type:"directory",mode:t.mode,mtimeMs:t.mtimeMs}:t.dirty?{path:e,type:"file",content:dt(t.content??new Uint8Array),mode:t.mode,mtimeMs:t.mtimeMs}:this.sized(e,t)).concat(this.untouchedStoreEntries())}}sized(e,t){return{path:e,type:"file",size:t.content?.byteLength??t.size??0,mode:t.mode,mtimeMs:t.mtimeMs}}existsSync(e){return this.node(te(e))!==void 0}statSync(e){const t=te(e),r=this.node(t);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);const n=r.content?.byteLength??r.size??0;return{isFile:()=>r.type==="file",isDirectory:()=>r.type==="directory",size:n,mode:r.mode,mtimeMs:r.mtimeMs,atimeMs:r.atimeMs,ctimeMs:r.mtimeMs,nlink:1,uid:1e3,gid:1e3,dev:1,ino:r.ino,rdev:0,blksize:4096,blocks:Math.ceil(n/512)}}lstatSync(e){return this.statSync(e)}async readFile(e){return this.readFileSync(e)}readFileSync(e){const t=te(e),r=this.node(t);if(!r)throw new Error(`ENOENT: no such file, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return this.bytesOf(r).slice()}linkTargetSync(e,t,r,n,i=!1){const o=this.node(i?e:te(e));if(o?.type==="file"){if(o.link===void 0){const a=o.content?.byteLength??o.size??0;o.link=a<t||a>r?null:n(this.bytesOf(o))??null}return o.link??void 0}}bytesOf(e){return e.content===void 0&&e.load&&(e.content=e.load(),e.size=e.content.byteLength),e.content??new Uint8Array}viewRangeSync(e,t,r){const n=this.node(te(e));if(!n)throw new Error(`ENOENT: no such file, open '${te(e)}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${te(e)}'`);return n.range&&n.content===void 0?n.range(t,r):this.bytesOf(n).subarray(t,t+r)}readRangeSync(e,t,r){const n=te(e),i=this.node(n);if(!i)throw new Error(`ENOENT: no such file, open '${n}'`);if(i.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${n}'`);return i.range&&i.content===void 0?i.range(t,r):this.bytesOf(i).slice(t,t+r)}writeRangeSync(e,t,r){this.mutate(()=>{const n=te(e);this.mkdirSync(zt(n),{recursive:!0});const i=this.isHidden(n);this.unhide(n);const o=i?this.nodes.get(n):this.node(n);if(o?.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${n}'`);const a=o?this.bytesOf(o):new Uint8Array,c=t+r.byteLength;let f;if(c<=a.byteLength)f=o?.dirty?a:a.slice();else if(c<=a.buffer.byteLength-a.byteOffset&&o?.dirty)f=new Uint8Array(a.buffer,a.byteOffset,c),f.fill(0,a.byteLength,t);else{const d=this.takeSpare(c);f=new Uint8Array(d??new ArrayBuffer(Math.max(c,a.byteLength*2,4096)),0,c),f.set(a),d&&f.fill(0,a.byteLength,t),o?.dirty&&this.release(a)}f.set(r,t),this.nodes.set(n,{type:"file",content:f,dirty:!0,mode:o?.type==="file"?o.mode:420,atimeMs:ge(),mtimeMs:ge(),ino:o?.type==="file"?o.ino:this.nextInode++}),this.markMutation(n)})}truncateSync(e,t){this.mutate(()=>{const r=te(e),n=this.node(r);if(!n)throw new Error(`ENOENT: no such file, truncate '${r}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, truncate '${r}'`);let i;if(t===0&&n.content===void 0)i=new Uint8Array;else{const o=this.bytesOf(n),a=o.buffer.byteLength-o.byteOffset;n.dirty&&t<=a&&(a<=js||t*4>=a)?(i=new Uint8Array(o.buffer,o.byteOffset,t),i.fill(0,o.byteLength)):(i=new Uint8Array(t),i.set(o.subarray(0,t)),n.dirty&&this.release(o))}this.nodes.set(r,{type:"file",content:i,dirty:!0,mode:n.mode,atimeMs:ge(),mtimeMs:ge(),ino:n.ino}),this.markMutation(r)})}spares=[];release(e){const t=e.buffer;if(!(t instanceof ArrayBuffer)||t.byteLength<js||t.byteLength>na)return;this.spares.push(t);let r=this.spares.reduce((n,i)=>n+i.byteLength,0);for(;this.spares.length>Jh||r>na;)r-=this.spares.shift().byteLength}takeSpare(e){const t=Math.max(e*4,js*4);let r=-1;return this.spares.forEach((n,i)=>{n.byteLength>=e&&n.byteLength<=t&&(r<0||n.byteLength<this.spares[r].byteLength)&&(r=i)}),r<0?void 0:this.spares.splice(r,1)[0]}writeFileSync(e,t){this.mutate(()=>{const r=te(e);this.mkdirSync(zt(r),{recursive:!0});const n=this.isHidden(r);this.unhide(r);const i=n?this.nodes.get(r):this.node(r);i?.type==="file"&&i.dirty&&i.content&&this.release(i.content),this.nodes.set(r,{type:"file",content:typeof t=="string"?new TextEncoder().encode(t):t.slice(),dirty:!0,mode:i?.type==="file"?i.mode:420,atimeMs:ge(),mtimeMs:ge(),ino:i?.type==="file"?i.ino:this.nextInode++}),this.markMutation(r)})}mkdirSync(e,t){this.mutate(()=>{const r=te(e);if(r==="/")return;if(!this.node(r)&&this.node(zt(r))?.type==="directory"){this.unhide(r);const a=ge();this.nodes.set(r,{type:"directory",mode:493,atimeMs:a,mtimeMs:a,ino:this.nextInode++}),this.markMutation(r);return}const n=r.slice(1).split("/");let i="";for(let o=0;o<n.length;o+=1){i+=`/${n[o]}`;const a=this.node(i);if(a?.type==="file")throw new Error(`ENOTDIR: not a directory, mkdir '${i}'`);if(a)continue;if(!t?.recursive&&o!==n.length-1)throw new Error(`ENOENT: no such directory, mkdir '${i}'`);this.unhide(i);const c=ge();this.nodes.set(i,{type:"directory",mode:493,atimeMs:c,mtimeMs:c,ino:this.nextInode++}),this.markMutation(i)}})}readdirSync(e){const t=te(e),r=this.node(t);if(!r)throw new Error(`ENOENT: no such directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);const n=new Set(this.nodes.namesIn(t));if(this.lower&&!this.isHidden(t)){const i=t==="/"?[...new Set([...this.lower.childrenOf("/"),...ca.filter(o=>this.lower.entries.has(o)).map(o=>o.slice(1))])]:this.lower.childrenOf(t);for(const o of i)this.isHidden(t==="/"?`/${o}`:`${t}/${o}`)||n.add(o)}return[...n]}unlinkSync(e){this.mutate(()=>{const t=te(e),r=this.node(t);if(!r)throw new Error(`ENOENT: no such file, unlink '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, unlink '${t}'`);r.dirty&&r.content&&this.release(r.content),this.nodes.delete(t),this.hide(t),this.markMutation(t)})}rmdirSync(e){this.mutate(()=>{const t=te(e);if(t==="/")throw new Error("EPERM: cannot remove root directory");const r=this.node(t);if(!r)throw new Error(`ENOENT: no such directory, rmdir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, rmdir '${t}'`);if(this.readdirSync(t).length>0)throw new Error(`ENOTEMPTY: directory not empty, rmdir '${t}'`);this.nodes.delete(t),this.hide(t),this.markMutation(t)})}renameSync(e,t){this.mutate(()=>{const r=te(e),n=te(t);if(!this.node(r))throw new Error(`ENOENT: no such file or directory, rename '${r}'`);if(this.mkdirSync(zt(n),{recursive:!0}),this.lower&&!this.isHidden(r))for(const[a]of this.lower.descendants(r))this.node(a);const o=this.nodes.subtree(r);for(const[a]of o)this.nodes.delete(a);this.hide(r),this.unhide(n);for(const[a,c]of o){if(c.type==="file"){const y=this.bytesOf(c);c.dirty||(c.content=y.slice()),c.dirty=!0}const f=`${n}${a.slice(r.length)}`,d=this.nodes.get(f);d?.type==="file"&&d.dirty&&d.content&&d!==c&&this.release(d.content),this.nodes.set(f,c),this.markMutation(a),this.markMutation(f)}})}reserveInodes(e){const t=this.nextInode;return this.nextInode+=e,t}restoreNodeSync(e,t){this.mutate(()=>{const r=te(e);this.unhide(r);const n=this.nodes.get(r);n?.type==="file"&&n.dirty&&n.content&&this.release(n.content),this.nodes.set(r,t.directory?{type:"directory",mode:t.mode&4095,atimeMs:t.atimeMs,mtimeMs:t.mtimeMs,ino:t.ino}:{type:"file",content:t.content??new Uint8Array,dirty:!0,mode:t.mode&4095,atimeMs:t.atimeMs,mtimeMs:t.mtimeMs,ino:t.ino}),this.markMutation(r)})}chmodSync(e,t){this.mutate(()=>{const r=te(e),n=this.node(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${r}'`);n.mode=t&4095,this.markMutation(r)})}utimesSync(e,t,r){this.mutate(()=>{const n=te(e),i=this.node(n);if(!i)throw new Error(`ENOENT: no such file or directory, utimes '${n}'`);i.atimeMs=typeof t=="number"?t:Number(t),i.mtimeMs=typeof r=="number"?r:Number(r),this.markMutation(n)})}mutate(e){this.mutationDepth+=1;try{return e()}finally{this.mutationDepth-=1,this.mutationDepth===0&&this.mutated&&(this.mutated=!1,this.mutationHandler?.())}}markMutation(e){this.mutated=!0,this.changedPaths?.add(te(e))}}const jh=1<<20,Xr=64*1024,Kh=8*1024*1024,Xh=1<<20,js=64*1024,Jh=2,na=32*1024*1024;function Qh(){const s=ge();return{type:"directory",mode:493,atimeMs:s,mtimeMs:s,ino:1}}function te(s){if(Zh(s))return s;const e=[];for(const t of`/${s}`.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}function Zh(s){if(s.charCodeAt(0)!==47)return!1;if(s.length===1)return!0;let e=1;for(let t=1;t<=s.length;t+=1){if(t<s.length&&s.charCodeAt(t)!==47)continue;const r=t-e;if(r===0||s.charCodeAt(e)===46&&(r===1||r===2&&s.charCodeAt(e+1)===46))return!1;e=t+1}return!0}function zt(s){return s.slice(0,s.lastIndexOf("/"))||"/"}function On(s){let e=1;for(let t=0;t<s.length;t+=1)s.charCodeAt(t)===47&&(e+=1);return e}const qh=`${yc}/.volter-tree-complete`;async function ed(s,e){const t=Js(s);try{if((await t.initialize(e,{readOnly:!0})||t.opened())&&t.entries.has(qh))return t}catch(r){throw t.close(),r}t.close()}const sa=new WeakMap;async function td(s,e){const t=[...new Set((s??[]).flatMap(o=>o.store===void 0?[]:[o.store]))];if(t.length===0)return;e??={navigator:globalThis.navigator};const r=e;let n=sa.get(r.navigator);n||sa.set(r.navigator,n=new Map);const i=new Map;for(const o of t){let a=n.get(o);a||(a=pc(o,r.navigator.locks).then(()=>ed(r,o)),n.set(o,a));let c;try{c=await a}catch(f){throw n.delete(o),new Error(`The installed tree ${o} would not open: ${f instanceof Error?f.message:String(f)}`,{cause:f})}if(!c)throw n.delete(o),new Error(`The installed tree ${o} is not on this origin's disk to read.`);i.set(o,c)}return i}const Dn=new Map,Yn=new Map;async function rd(s){const e=Yn.get(s);if(e){const n=await e.catch(()=>{});if(n)try{return await n.refresh(),n}catch{n.close()}Yn.delete(s)}const t=xc({navigator:globalThis.navigator},s);Yn.set(s,t);const r=await t.catch(()=>{});return r||Yn.delete(s),r}self.onmessage=s=>{nd(s.data)};async function nd(s){const e=performance.now();let t,r,n;try{n=await td(s.layers)}catch(f){Je({type:"result",id:s.id,filesystem:s.filesystem,error:f instanceof Error?f.message:String(f)});return}if(s.store){if(t=await rd(s.store.projectId),!t){Je({type:"result",id:s.id,filesystem:s.filesystem,error:"The project's store is not there to read."});return}r=Ar.fromStore(Fi(t,s.layers,n),s.filesystem)}else s.layers?r=Ar.fromStore(Fi(void 0,s.layers,n),s.filesystem):r=Ar.fromSnapshot(s.filesystem);const i=r.toSnapshot();r.mkdirSync("/tmp",{recursive:!0}),r.mkdirSync("/home/user",{recursive:!0}),r.mkdirSync(s.cwd,{recursive:!0});const o=Po(i,r.toSnapshot(),{written:!0});s.filesystemUpdatePort&&(o.files.length>0||o.removed.length>0)&&s.filesystemUpdatePort.postMessage({type:"filesystem",patch:o});let a=!1;const c=performance.now()-e;try{const f=performance.now(),d=await id(s.url,s.integrity,s.compiled,x=>Je({type:"compiled",id:s.id,compiled:x})),y=performance.now()-f,p=d.layout,A=p?Na(p):void 0,k=await new Ch().run(d.module,{argv:s.argv,...s.pid!==void 0?{pid:s.pid}:{},...s.parentPid!==void 0?{parentPid:s.parentPid}:{},...s.childPidAllocator?{childPidAllocator:s.childPidAllocator}:{},...p?{memoryLayout:p}:{},...s.descriptorTable?{descriptorTable:s.descriptorTable}:{},...s.executablePath?{executablePath:s.executablePath}:{},cwd:s.cwd,env:s.env,stdin:new Qs(s.stdin),terminal:s.terminal,filesystem:r,...s.filesystemPolicy?{filesystemPolicy:s.filesystemPolicy}:{},...s.store?{store:s.store}:{},...s.layers?{layers:s.layers}:{},...s.privateRoots?{privateRoots:s.privateRoots}:{},...A?{memory:A}:{},threadPoolSize:s.threadPoolSize,...s.codec?{codec:s.codec}:{},...s.network?{network:{...s.network,...s.loopbackPort?{loopbackPort:s.loopbackPort}:{}}}:{},...s.browserProcessPorts?{browserProcessPorts:s.browserProcessPorts}:{},...s.threadOutputPorts?{threadOutputPorts:s.threadOutputPorts}:{},...s.filesystemUpdatePort?{filesystemUpdatePort:s.filesystemUpdatePort}:{},...s.fileLocks?{fileLocks:s.fileLocks}:{},fileCoherence:s.fileCoherence,signalState:s.signalState,browserProcess:{fork:x=>Je({type:"fork",id:s.id,...x,stdin:s.stdin,threadPoolSize:s.threadPoolSize,...s.network&&s.network.allowedHosts.length>0?{network:s.network}:{}}),...s.childFilesystemPolicyVersion===1?{filesystemPolicyVersion:1}:{},spawn:x=>Je({type:"spawn",id:s.id,...x,filesystemPatch:Po(i,r.toSnapshot(),{written:!0})}),kill:(x,D)=>Je({type:"kill",id:s.id,pid:x,signal:D}),restore:x=>r.replaceSnapshot(x)},onStdout:x=>Je({type:"stdout",id:s.id,chunk:x}),onStderr:x=>Je({type:"stderr",id:s.id,chunk:new TextDecoder().decode(x)}),onDiagnostic:x=>Je({type:"diagnostic",id:s.id,message:x}),onFilesystemFinalized:()=>{a=!0}}),_=performance.now(),E=r.toSnapshot(),L=performance.now()-e;L>2e3&&console.log("[wali-profile]",JSON.stringify({argv:s.argv.slice(0,3),worker:{filesystemMs:Math.round(c),moduleMs:Math.round(y),snapshotMs:Math.round(performance.now()-_),totalMs:Math.round(L)}})),Je({type:"result",id:s.id,filesystem:E,filesystemFinalized:a,result:{stdout:k.stdout,stderr:k.stderr,exitCode:k.exitCode}})}catch(f){Je({type:"result",id:s.id,filesystem:r.toSnapshot(),filesystemFinalized:a,error:sd(f)})}}const ia=48*1024;function sd(s){const e=s instanceof Error?s.stack??s.message:String(s),t=e.split(`
19
+ `).slice(0,8).join(`
20
+ `).slice(0,4*1024);if(e.length<=ia)return`${e}
21
+ WALI error summary:
22
+ ${t}`;const r=Math.floor((ia-96)/2);return`${e.slice(0,r)}
23
+ … ${e.length-r*2} error characters truncated …
24
+ ${e.slice(-r)}
25
+ WALI error summary:
26
+ ${t}`}function id(s,e,t,r){if(new URL(s,globalThis.location.href).protocol!=="blob:"&&!e)return Promise.reject(new Error("Remote WALI programs require pinned SHA-256 integrity metadata."));const i=`${s}
27
+ ${e??"local-unverified"}`;let o=Dn.get(i);if(!o&&t&&(o=Promise.resolve(t),Dn.set(i,o)),!o){if(e&&!/^sha256-[A-Za-z0-9+/]{43}=$/u.test(e))return Promise.reject(new Error("Invalid artifact integrity metadata."));o=fetch(s,e?{integrity:e}:{}).then(async a=>{if(!a.ok)throw new Error(`Unable to load WALI program: HTTP ${a.status}.`);const c=WebAssembly.compileStreaming(a.clone()).catch(()=>{}),f=await a.arrayBuffer(),d=Qn(new Uint8Array(f)),p={module:await c??await WebAssembly.compile(f),...d?{layout:d}:{}};return r(p),p}),Dn.set(i,o),o.catch(()=>Dn.delete(i))}return o}function Je(s){postMessage(s,(s.type==="spawn"||s.type==="fork")&&s.descriptorTable?[s.descriptorTable.port,...s.descriptorTable.releasePort?[s.descriptorTable.releasePort]:[]]:[])}export{qe as B,G as F,Ar as S,Jn as W,xc as a,Th as b,on as c,xh as d,ii as e,dt as f,sr as g,ke as h,dh as i,_f as j,Mf as k,Fi as l,td as o};