@volter/browser-substrate 0.1.109 → 0.1.110
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/shell/assets/{browser-opfs-filesystem-worker-CmF6UKMW.js → browser-opfs-filesystem-worker-DF78_MSS.js} +2 -2
- package/dist/shell/assets/{browser-sandbox-bridge-C8nlSsT2.js → browser-sandbox-bridge-D83LgnQx.js} +1 -1
- package/dist/shell/assets/{filesystem-host-BzPlXSri.js → filesystem-host-Bz80KA3H.js} +1 -1
- package/dist/shell/assets/{filesystem-host-Pq9IHKRx.js → filesystem-host-DiM0ruXt.js} +1 -1
- package/dist/shell/assets/{filesystem-worker-CC3pSXUP.js → filesystem-worker-B_zvdiVO.js} +1 -1
- package/dist/shell/assets/{fork-worker-4YKQ4KTo.js → fork-worker-BcogGro3.js} +1 -1
- package/dist/shell/assets/{node-execution-worker-67ab1cab4177b67d.js → node-execution-worker-aad84e7ccac38d49.js} +1 -1
- package/dist/shell/assets/{sandbox-mhFzIWaQ.js → sandbox-eUWD4AMK.js} +1 -1
- package/dist/shell/assets/{shell-BZbhxnju.js → shell-17SQHc7q.js} +4 -4
- package/dist/shell/assets/{worker-BmHEnCyv.js → worker-BjKdS6e6.js} +1 -1
- package/dist/shell/assets/{worker-program-worker-DueMwljE.js → worker-program-worker-DfQzwSkL.js} +5 -5
- package/dist/shell/index.html +2 -2
- package/dist/shell/node-execution-worker.js +2 -2
- package/dist/shell/python-execution-worker.js +1 -1
- package/dist/shell/python-runtime-snapshot.bin +0 -0
- package/dist/shell/python-runtime-snapshot.json +1 -1
- package/dist/shell/sandbox.html +2 -2
- package/package.json +1 -1
|
@@ -6,7 +6,7 @@ let G;function xn(s){G=s}const ki=5,Mi=20;function Vt(s,t,e,r,n){if(!G)return At
|
|
|
6
6
|
WALI pthread ${t.tid??"unknown"} error summary:
|
|
7
7
|
${e}
|
|
8
8
|
`))}}spawn(t,e,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:t,argumentPointer:e,tid:i,signalMask:r};return n.worker?n.worker.postMessage(o):this.coordinator.postMessage({...o,slotIndex:n.index}),i}diagnostics(t){const e=new TextDecoder,r=32,n=480;return this.slots.filter(i=>t===void 0||i.index===t).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 l=Math.max(0,o-r);l<o;l+=1){const u=l%r*n,f=Math.min(a[u]|a[u+1]<<8,n-2);c.push(e.decode(Uint8Array.from(a.subarray(u+2,u+2+f))))}return[`slot ${i.index+1}: ${c.join(`
|
|
9
|
-
`)}`]})}terminate(){this.coordinator?.terminate(),this.coordinator=void 0;for(const t of this.slots)t.worker?.terminate();this.slots.length=0}}function wa(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 Ot(s){const t=s.toBase64;if(typeof t=="function")return t.call(s);let e="";for(let r=0;r<s.byteLength;r+=32768)e+=String.fromCharCode(...s.subarray(r,r+32768));return btoa(e)}function me(s){const t=Uint8Array.fromBase64;if(typeof t=="function")return t(s);const e=atob(s),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r}function _a(s,t,e){const{appended:r,superseded:n}=e?Aa(s,t,e):{appended:new Map,superseded:new Set},i=[...t.removed].sort((a,c)=>We(c)-We(a));for(const a of i)s.existsSync(a)&&(s.statSync(a).isDirectory()?s.rmdirSync(a):s.unlinkSync(a));const o=[...t.files].filter(a=>!n.has(a.path)).sort((a,c)=>We(a.path)-We(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(be(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 l=s.existsSync(a.path)?s.statSync(a.path).mode:void 0,u=l!==void 0&&(l&128)===0;u&&s.chmodSync?.(a.path,l&4095|128),s.writeFileSync(a.path,r.get(a.path)??ge(a)),u&&a.mode===void 0&&s.chmodSync?.(a.path,l&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 Aa(s,t,e){const r=new Map,n=new Set,i=e.byPath,o=i instanceof Map?i:new Map(e.files.map(l=>[l.path,l])),a=new Map(t.files.map(l=>[l.path,l])),c=new Set([...t.files.map(l=>l.path),...t.removed]);for(const l of c){const u=o.get(l),f=Ia(s,l);if(u!==void 0&&Tr(u,a.get(l))||f===void 0&&a.get(l)!==void 0)continue;const d=a.get(l);if(!(f!==void 0&&d!==void 0&&d.type===f.type&&(Y(d).mtimeMs??0)>(Y(f).mtimeMs??0))&&!(u!==void 0&&f!==void 0&&u.type===f.type&&(Y(f).mtimeMs??0)<(Y(u).mtimeMs??0))&&!Tr(u,f)&&!Tr(a.get(l),f)){if(Na(u,f,a.get(l)))continue;const m=Ea(s,l,u,f,a.get(l),e.bytesOf?.bind(e));if(m){r.set(l,m);continue}const p=a.get(l);if(u!==void 0&&f!==void 0&&p!==void 0&&p.type===f.type&&(Y(p).mtimeMs??0)>=(Y(u).mtimeMs??0)&&(Y(f).mtimeMs??0)>(Y(p).mtimeMs??0)&&(Y(f).mtimeMs??0)>(Y(u).mtimeMs??0)){n.add(l);continue}throw new Error(`Browser filesystem write conflict at ${l}. ${JSON.stringify({base:Br(u),current:Br(f),proposed:Br(a.get(l))})}`)}}return{appended:r,superseded:n}}function Ea(s,t,e,r,n,i){if(e?.type!=="file"||r?.type!=="file"||n?.type!=="file"||!be(n)||!s.readFileSync||Y(r).mode!==Y(n).mode)return;const o=be(e)?ge(e):i?.(t);if(!o||o.length===0)return;const a=ge(n),c=s.readFileSync(t),l=typeof c=="string"?new TextEncoder().encode(c):c,u=d=>d.length>=o.length&&ri(d.subarray(0,o.length),o);if(a.length<=o.length||!u(a)||!u(l))return;const f=new Uint8Array(l.length+a.length-o.length);return f.set(l,0),f.set(a.subarray(o.length),l.length),f}function Br(s){return s?{type:s.type,...Y(s)}:null}function Na(s,t,e){return t?.type!=="directory"||e?.type!=="directory"?!1:s===void 0?Y(t).mode===Y(e).mode:Y(t).mode===Y(e).mode&&s.type==="directory"&&Y(s).mode===Y(t).mode}function We(s){let t=1;for(let e=0;e<s.length;e+=1)s.charCodeAt(e)===47&&(t+=1);return t}function Ia(s,t){if(!s.existsSync(t))return;const e=s.statSync(t),r={...e.mode!==void 0?{mode:e.mode}:{},...e.mtimeMs!==void 0?{mtimeMs:e.mtimeMs}:{}};return e.isDirectory()?{path:t,type:"directory",...r}:{path:t,type:"file",...e.size!==void 0?{size:e.size}:{},...r}}function Tr(s,t){return s===void 0?t===void 0:t!==void 0&&s.type===t.type&&La(s,t)&&Y(s).mode===Y(t).mode&&Y(s).mtimeMs===Y(t).mtimeMs}function Y(s){const t=s;return{...t.mode===void 0?{}:{mode:t.mode&4095},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs}}}function La(s,t){return s.type!=="file"||t.type!=="file"?!0:s.content!==void 0&&t.content!==void 0?s.content===t.content:be(s)&&be(t)?ri(ge(s),ge(t)):fs(s)===fs(t)}function fs(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 t=s.content.endsWith("==")?2:s.content.endsWith("=")?1:0;return Math.floor(s.content.length*3/4)-t}function be(s){return s!==void 0&&(s.bytes!==void 0||s.content!==void 0)}function ge(s){return s.bytes??(s.content===void 0?void 0:me(s.content))}function ri(s,t){if(s===t)return!0;if(s.byteLength!==t.byteLength)return!1;let e=0;if(s.byteOffset%4===0&&t.byteOffset%4===0){const r=s.byteLength>>>2,n=new Uint32Array(s.buffer,s.byteOffset,r),i=new Uint32Array(t.buffer,t.byteOffset,r);for(let o=0;o<r;o+=1)if(n[o]!==i[o])return!1;e=r<<2}for(;e<s.byteLength;e+=1)if(s[e]!==t[e])return!1;return!0}const ds=0,ms=1,ct=2,zt=3,Ht=4,ni=5,si=6,jr=16*1024*1024,xa=1024*1024;function ka(){const s=new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),t=new SharedArrayBuffer(xa),e=new Int32Array(s);return Atomics.store(e,zt,1),Atomics.store(e,Ht,1),{reader:{control:s,payload:t,role:"reader"},writer:{control:s,payload:t,role:"writer"}}}function ii(s){const t=Gt(s);return Atomics.add(t,s.role==="reader"?zt:Ht,1),s}function Se(s){const t=Gt(s),e=s.role==="reader"?zt:Ht;Atomics.sub(t,e,1)<=1&&Atomics.store(t,e,0),Atomics.add(t,s.role==="reader"?si:ni,1),Atomics.notify(t,ct)}function oi(s,t){const e=Gt(s),r=Atomics.load(e,ct);let n=0;return s.role==="reader"?(t&1&&(r>0||Atomics.load(e,Ht)===0)&&(n|=1),Atomics.load(e,Ht)===0&&(n|=16)):(t&4&&Atomics.load(e,zt)>0&&r<Ra(s)&&(n|=4),Atomics.load(e,zt)===0&&(n|=16)),n}function sn(s,t){if(s.role!=="reader")return-9n;if(t===0)return new Uint8Array;const e=Gt(s),r=ci(s),n=Atomics.load(e,ct);if(n===0)return Atomics.load(e,Ht)===0?new Uint8Array:-11n;const i=Math.min(Math.max(0,t),n),o=Atomics.load(e,ds),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(e,ds,(o+i)%r.byteLength),Atomics.sub(e,ct,i),i>0&&Atomics.add(e,si,1),Atomics.notify(e,ct),c}function Ma(s,t){const e=Gt(s);for(;;){const r=sn(s,t);if(r!==-11n)return r;Vt(e,ct,0,50)}}function ai(s,t){if(s.role!=="writer")return-9n;const e=Gt(s),r=ci(s);let n=0;for(;n<t.byteLength;){if(Atomics.load(e,zt)===0)return n>0?BigInt(n):-32n;const i=Atomics.load(e,ct),o=r.byteLength-i;if(o===0){Vt(e,ct,i,50);continue}const a=Atomics.load(e,ms),c=Math.min(t.byteLength-n,o,r.byteLength-a);r.set(t.subarray(n,n+c),a),Atomics.store(e,ms,(a+c)%r.byteLength),Atomics.add(e,ct,c),Atomics.add(e,ni,1),Atomics.notify(e,ct),n+=c}return BigInt(n)}const Ss=new WeakMap;function Gt(s){const t=s.controlOffset??0;let e=Ss.get(s.control);e||(e=new Map,Ss.set(s.control,e));let r=e.get(t);return r||(r=new Int32Array(s.control,t,8),e.set(t,r)),r}function Ra(s){return s.payloadLength??s.payload.byteLength-(s.payloadOffset??0)}function ci(s){const t=s.payloadOffset??0,e=s.payloadLength??s.payload.byteLength-t;return new Uint8Array(s.payload,t,e)}function va(s){const t=Atomics.load(new Int32Array(s.control),2);if(t<=0||t>s.response.byteLength)return;const e=Uint8Array.from(new Uint8Array(s.response,0,t));return JSON.parse(new TextDecoder().decode(e))}const Ya=1,Pa=15,Ba=1,Ta=97n,Fa=93n,Ca=11n,Da=32n,ys=1,ps=4,Ua=16;class Wa{memory;descriptors;constructor(t,e){this.memory=t,this.descriptors=e}imports(){return{SYS_socketpair:(t,e,r,n)=>this.socketpair(Number(t),Number(e),Number(r),Number(n)),SYS_pipe:t=>this.pipe(Number(t),0),SYS_pipe2:(t,e)=>this.pipe(Number(t),Number(e))}}pipe(t,e){if((e&-526337)!==0)return-22n;if(!Number.isSafeInteger(t)||t<0||t+8>this.memory().buffer.byteLength)return-14n;const r=ka(),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(t,n,!0),o.setInt32(t+4,i,!0),0n}pipeEndpoint(t){return{browserProcessPipe:t,read:e=>sn(t,e),write:e=>ai(t,e),poll:e=>oi(t,e),fcntl:e=>e===3?0x800n:[1,2,4].includes(e)?0n:-22n,duplicate:e=>(ii(t),BigInt(this.descriptors.allocateSpecial(this.pipeEndpoint(t),e))),close:()=>Se(t)}}socketpair(t,e,r,n){if(t!==Ya)return-Ta;if((e&Pa)!==Ba||r!==0)return-Fa;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)),l=new DataView(this.memory().buffer);return l.setInt32(n,a,!0),l.setInt32(n+4,c,!0),0n}endpoint(t){return{read:e=>Oa(t,e),write:e=>$a(t,e),poll:e=>Va(t,e),fcntl:e=>e===3?0x802n:[1,2,4].includes(e)?0n:-22n,duplicate:e=>{const r=this.descriptors.allocateSpecial(this.endpoint(t),e);return t.references+=1,BigInt(r)},close:()=>{t.references-=1,!(t.references>0||t.closed)&&(t.closed=!0,t.peer&&(t.peer.peerClosed=!0))}}}}function Oa(s,t){if(s.closed)return-9n;if(t<0)return-22n;if(s.byteLength===0)return s.peerClosed?new Uint8Array:-Ca;const e=new Uint8Array(Math.min(t,s.byteLength));let r=0;for(;r<e.byteLength;){const n=s.chunks[0],i=Math.min(n.byteLength,e.byteLength-r);e.set(n.subarray(0,i),r),r+=i,s.byteLength-=i,i===n.byteLength?s.chunks.shift():s.chunks[0]=n.subarray(i)}return e}function $a(s,t){if(s.closed)return-9n;const e=s.peer;if(!e||e.closed)return-Da;const r=t.slice();return e.chunks.push(r),e.byteLength+=r.byteLength,BigInt(r.byteLength)}function Va(s,t){let e=s.peerClosed?Ua:0;return t&ys&&(s.byteLength>0||s.peerClosed)&&(e|=ys),t&ps&&!s.peerClosed&&(e|=ps),e}const za=2e4,li=256*1024;var I;(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"})(I||(I={}));const Fr=new Map;function ui(s,t){const e=Fr.get(s);Fr.delete(s);const r=e??t();return Fr.set(s,t()),r}const yt=9n,C=22n,bs=16,ut=38n;class on{worker;constructor(t){this.worker=t}static async create(t,e,r,n,i){if(typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("WALI networking requires Web Workers and SharedArrayBuffer.");const o=[...new Set(t?.allowedHosts.map(l=>l.toLowerCase())??[])];if(t&&(!t.loopbackPort&&o.length===0||o.some(l=>!/^[a-z0-9.-]+$/u.test(l))))throw new Error("WALI networking requires a loopback attachment or at least one valid hostname.");if(t&&(!Number.isSafeInteger(t.maxConnections)||t.maxConnections<1||t.maxConnections>1024||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1024||t.maxBytes>1024*1024*1024))throw new Error("WALI networking requires bounded connection and byte quotas.");const a=ui("network",()=>pe(new Worker(new URL("/assets/network-worker-DuuxEt8T.js",import.meta.url),{type:"module",name:"wali-network"}))),c=new on(a);return await new Promise((l,u)=>{const f=d=>{d.data.kind==="ready"&&(a.removeEventListener("message",f),l()),d.data.kind==="error"&&(a.removeEventListener("message",f),u(new Error(d.data.message)))};a.addEventListener("message",f),a.addEventListener("error",d=>u(d.error??new Error(d.message)),{once:!0}),a.postMessage({kind:"initialize",allowedHosts:o,relayUrl:t?.relayUrl??"/api/wali/tcp",maxConnections:t?.maxConnections??0,maxBytes:t?.maxBytes??0,...e?{sharedPipes:e}:{},...r?{stdin:r}:{},...n?{stdioAliasRegistry:n}:{},...i?{signals:i}:{},...t?.loopbackPort?{loopbackPort:t.loopbackPort}:{}},t?.loopbackPort?[t.loopbackPort]:[])}).catch(l=>{throw a.terminate(),l}),c}createChannel(){const t=new MessageChannel,e={port:t.port1,control:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*16),payload:new SharedArrayBuffer(li)};return this.worker.postMessage({kind:"attach",port:t.port2,control:e.control,payload:e.payload},[t.port2]),e.port.start(),e}terminate(){this.worker.terminate()}}class Ha{channel;control;payload;nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload)}call(t,e=[],r,n){if((r?.byteLength??0)>this.payload.byteLength)return{result:-Number(C),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,t),Atomics.store(this.control,3,r?.byteLength??0),e.slice(0,10).forEach((u,f)=>Atomics.store(this.control,5+f,u|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 u=Atomics.load(this.control,0);if(u===i+1)break;if(u!==i&&u!==-i)throw new Error(`Invalid WALI network RPC state ${u} for request ${i}.`);const f=Math.max(0,o-Date.now());if(f===0&&u===i&&Atomics.compareExchange(this.control,0,i,0)===i)return{result:-110,output:new Uint8Array};try{Vt(this.control,0,u,u===-i?void 0:f)}catch{if(Atomics.compareExchange(this.control,0,i,0)===i)return{result:-Number(ut),output:new Uint8Array}}}const a=Atomics.load(this.control,2),c=Atomics.load(this.control,4),l=this.payload.slice(0,Math.max(0,c));return Atomics.store(this.control,0,0),{result:a,output:l}}}class Ga{memory;signals;client;waitBuffer;constructor(t,e,r){this.memory=t,this.signals=r,this.client=new Ha(e)}isNetworkFd(t){return t>=za&&!K(t)}registerChild(t,e){return this.client.call(I.ChildRegister,[t],void 0,e).result}forgetChild(t){this.client.call(I.ChildForget,[t])}hasChild(t){return this.client.call(I.ChildExists,[t]).result===1}waitChild(t,e,r=0n){const n=this.waitBuffer??={control:new SharedArrayBuffer(32),response:new SharedArrayBuffer(jr)};return{result:this.client.call(I.ChildWait,[t,e,Number(r&0xffffffffn),Number(r>>32n)],void 0,n).result,process:n}}imports(t={}){const e=(r,n)=>t[r]?.(...n)??-ut;return{SYS_pidfd_open:(r,n)=>BigInt(this.client.call(I.PidFdOpen,[Number(r),Number(n)]).result),SYS_dup:r=>this.isNetworkFd(Number(r))?BigInt(this.client.call(I.Duplicate,[Number(r)]).result):t.SYS_dup?.(r)??-ut,SYS_socket:(r,n,i)=>BigInt(this.client.call(I.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),()=>e("SYS_bind",[r,n,i])),SYS_listen:(r,n)=>this.networkOr(Number(r),()=>this.client.call(I.Listen,[Number(r),Number(n)]).result,()=>e("SYS_listen",[r,n])),SYS_accept:(r,n,i)=>this.accept(Number(r),Number(n),Number(i),0,()=>e("SYS_accept",[r,n,i])),SYS_accept4:(r,n,i,o)=>this.accept(Number(r),Number(n),Number(i),Number(o),()=>e("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(I.Shutdown,[Number(r),Number(n)]).result,()=>e("SYS_shutdown",[r,n])),SYS_setsockopt:(r,n,i,o,a)=>this.isNetworkFd(Number(r))?0n:e("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(I.Close,[Number(r)]).result):t.SYS_close?.(r)??-ut,SYS_read:(r,n,i)=>this.isNetworkFd(Number(r))?this.receive(Number(r),Number(n),Number(i),0):t.SYS_read?.(r,n,i)??-ut,SYS_write:(r,n,i)=>this.isNetworkFd(Number(r))?this.send(Number(r),Number(n),Number(i),0):t.SYS_write?.(r,n,i)??-ut,SYS_readv:(r,n,i)=>this.isNetworkFd(Number(r))?this.readv(Number(r),Number(n),Number(i)):t.SYS_readv?.(r,n,i)??-ut,SYS_writev:(r,n,i)=>this.isNetworkFd(Number(r))?this.writev(Number(r),Number(n),Number(i)):t.SYS_writev?.(r,n,i)??-ut,SYS_fcntl:(r,n,i)=>this.isNetworkFd(Number(r))?BigInt(this.client.call(I.Fcntl,[Number(r),Number(n),Xa(i)]).result):t.SYS_fcntl?.(r,n,i)??-ut,SYS_poll:(r,n,i)=>this.poll(Number(r),Number(n),Number(i),()=>e("SYS_poll",[r,n,0])),SYS_epoll_create:r=>Number(r)>0?BigInt(this.client.call(I.EpollCreate).result):-C,SYS_epoll_create1:()=>BigInt(this.client.call(I.EpollCreate).result),SYS_eventfd:r=>BigInt(this.client.call(I.EventFd,[Number(r),0]).result),SYS_eventfd2:(r,n)=>BigInt(this.client.call(I.EventFd,[Number(r),Number(n)]).result),SYS_timerfd_create:(r,n)=>BigInt(this.client.call(I.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),()=>e("SYS_epoll_ctl",[r,n,i,o])),SYS_epoll_wait:(r,n,i,o)=>this.epollWait(Number(r),Number(n),Number(i),Number(o),()=>e("SYS_epoll_wait",[r,n,i,o])),SYS_epoll_pwait:(r,n,i,o,a,c)=>{const l=()=>this.epollWait(Number(r),Number(n),Number(i),Number(o),()=>e("SYS_epoll_pwait",[r,n,i,o,a,c]));if(!a)return l();if(!this.signals)return-38n;const u=this.signals.mask,f=this.signals.imports().SYS_rt_sigprocmask(2,a,0,c);if(f!==0n)return f;try{const d=l();return this.signals.deliver(d===-4n),d}finally{this.signals.mask=u}}}}pollFd(t,e){return this.isNetworkFd(t)?this.client.call(I.Poll,[t,e]).result:32}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}copy(t,e){if(t<0||e<0||t+e>this.bytes().byteLength)throw new WebAssembly.RuntimeError("WALI network memory access is out of bounds.");return this.bytes().slice(t,t+e)}networkOr(t,e,r){return this.isNetworkFd(t)?BigInt(e()):r()}withAddress(t,e,r){return this.isNetworkFd(t)?BigInt(this.client.call(I.Connect,[t],this.copy(e,r)).result):-yt}bind(t,e,r,n){return this.isNetworkFd(t)?BigInt(this.client.call(I.Bind,[t],this.copy(e,r)).result):n()}accept(t,e,r,n,i){if(!this.isNetworkFd(t))return i();if(e!==0&&(r<=0||r+4>this.bytes().byteLength))return-C;const o=e===0?0:this.view().getUint32(r,!0);if(e!==0&&(e<0||e+o>this.bytes().byteLength))return-C;const{result:a,output:c}=this.client.call(I.Accept,[t,n]);return a<0||e===0||(this.bytes().set(c.subarray(0,o),e),this.view().setUint32(r,c.byteLength,!0)),BigInt(a)}socketPair(t,e,r,n){const{result:i,output:o}=this.client.call(I.SocketPair,[t,e,r]);if(i===0){if(n<0||n+8>this.bytes().byteLength)return-C;this.bytes().set(o,n)}return BigInt(i)}setTimerFd(t,e,r,n){if(!this.isNetworkFd(t)||r<0||r+32>this.bytes().byteLength)return-yt;const{result:i,output:o}=this.client.call(I.TimerFdSetTime,[t,e],this.copy(r,32));if(i===0&&n!==0){if(n<0||n+32>this.bytes().byteLength||o.byteLength!==32)return-C;this.bytes().set(o,n)}return BigInt(i)}send(t,e,r,n){return this.isNetworkFd(t)?BigInt(this.client.call(I.Send,[t,n],this.copy(e,r)).result):-yt}receive(t,e,r,n){if(!this.isNetworkFd(t))return-yt;const{result:i,output:o}=this.client.call(I.Receive,[t,r,n]);return i>0&&this.bytes().set(o.subarray(0,i),e),BigInt(i)}receiveFrom(t,e,r,n,i,o){const a=this.receive(t,e,r,n);if(a<0n||i===0||o===0)return a;if(o<0||o+4>this.bytes().byteLength)return-C;const c=this.view().getUint32(o,!0);return this.writeDnsPeer(i,c)?(this.view().setUint32(o,16,!0),a):-C}sendMessage(t,e,r){if(!this.isNetworkFd(t)||e<0||e+28>this.bytes().byteLength)return-yt;const n=this.view().getUint32(e+8,!0),i=this.view().getUint32(e+12,!0);if(i>1024)return-C;const o=[];let a=0;for(let u=0;u<i;u+=1){const f=n+u*8,d=this.copy(this.view().getUint32(f,!0),this.view().getUint32(f+4,!0));o.push(d),a+=d.byteLength}const c=new Uint8Array(a);let l=0;for(const u of o)c.set(u,l),l+=u.byteLength;return BigInt(this.client.call(I.Send,[t,r],c).result)}receiveMessage(t,e,r){if(!this.isNetworkFd(t)||e<0||e+28>this.bytes().byteLength)return-yt;const n=this.view().getUint32(e+8,!0),i=this.view().getUint32(e+12,!0);if(i>1024)return-C;let o=0;for(let d=0;d<i;d+=1)o+=this.view().getUint32(n+d*8+4,!0);const{result:a,output:c}=this.client.call(I.Receive,[t,o,r]);if(a<=0)return BigInt(a);let l=0;for(let d=0;d<i&&l<a;d+=1){const m=n+d*8,p=this.view().getUint32(m,!0),y=Math.min(this.view().getUint32(m+4,!0),a-l);this.bytes().set(c.subarray(l,l+y),p),l+=y}const u=this.view().getUint32(e,!0),f=this.view().getUint32(e+4,!0);return u!==0&&this.writeDnsPeer(u,f)&&this.view().setUint32(e+4,16,!0),this.view().setUint32(e+20,0,!0),this.view().setInt32(e+24,0,!0),BigInt(a)}writeDnsPeer(t,e){return e<16||t<0||t+16>this.bytes().byteLength?!1:(this.bytes().fill(0,t,t+16),this.view().setUint16(t,2,!0),this.view().setUint16(t+2,53,!1),this.bytes().set([127,0,0,1],t+4),!0)}getSocketOption(t,e,r){return this.isNetworkFd(t)?r<=0||r+4>this.bytes().byteLength||this.view().getUint32(r,!0)<4||e<0||e+4>this.bytes().byteLength?-C:(this.view().setInt32(e,0,!0),this.view().setUint32(r,4,!0),0n):-yt}getSocketName(t,e,r){if(!this.isNetworkFd(t))return-yt;if(r<0||r+4>this.bytes().byteLength)return-C;const n=this.view().getUint32(r,!0),{result:i,output:o}=this.client.call(I.SocketName,[t]);return i<0?BigInt(i):n<o.byteLength||e<0||e+o.byteLength>this.bytes().byteLength?-C:(this.bytes().set(o,e),this.view().setUint32(r,o.byteLength,!0),0n)}writev(t,e,r){if(r<0||r>1024)return-C;const n=[];let i=0;for(let c=0;c<r;c+=1){const l=e+c*8,u=this.copy(this.view().getUint32(l,!0),this.view().getUint32(l+4,!0));n.push(u),i+=u.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(I.Send,[t,0],o).result)}readv(t,e,r){if(r<0||r>1024)return-C;let n=0;for(let c=0;c<r;c+=1)n+=this.view().getUint32(e+c*8+4,!0);const{result:i,output:o}=this.client.call(I.Receive,[t,n,0]);if(i<=0)return BigInt(i);let a=0;for(let c=0;c<r&&a<i;c+=1){const l=e+c*8,u=this.view().getUint32(l,!0),f=Math.min(this.view().getUint32(l+4,!0),i-a);this.bytes().set(o.subarray(a,a+f),u),a+=f}return BigInt(i)}poll(t,e,r,n){if(e<0||e>li/8)return-C;this.copy(t,e*8),n();const i=this.signals?.mask??0n,{result:o,output:a}=this.client.call(I.PollMany,[r,Number(i&0xffffffffn),Number(i>>32n)],this.copy(t,e*8));return o>=0&&this.bytes().set(a,t),BigInt(o)}epollControl(t,e,r,n,i){if(!this.isNetworkFd(t)&&!this.isNetworkFd(r))return i();const o=e===2?void 0:this.copy(n,bs);return BigInt(this.client.call(I.EpollControl,[t,e,r],o).result)}epollWait(t,e,r,n,i){if(r<=0)return-C;const o=this.signals?.mask??0n,{result:a,output:c}=this.client.call(I.EpollWait,[t,r,n,Number(o&0xffffffffn),Number(o>>32n)]);return a===-9?i():(a>0&&this.bytes().set(c.subarray(0,a*bs),e),BigInt(a))}}function Xa(s){return typeof s=="bigint"?Number(BigInt.asIntN(32,s)):s|0}const gs=-4,Cr=3;class tt{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder("utf-8",{fatal:!0});nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload)}static waited={calls:0,ms:0};request(t){const e=performance.now();try{return this.requestNow(t)}finally{tt.waited.calls+=1,tt.waited.ms+=performance.now()-e}}requestNow(t){if(Atomics.load(this.control,Cr))return{result:gs};const e=this.encoder.encode(JSON.stringify(t));if(e.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,Cr),this.payload.set(e),Atomics.store(this.control,1,e.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,Cr))return{result:gs};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 Jr{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder;nextRequestId=1;bell;wakeMemory;directSyscall(t){const e=this.channel.local;if(!(!e||t==="SYS_flock"||t==="SYS_fcntl"))return r=>{const{imports:n,errno:i}=e.handlers(),o=n[t];if(!o)throw at(-38);let a;try{a=o(...r)}catch(c){throw at(i(c))}return typeof a=="bigint"?a:BigInt(a??0)}}ownsLocalFile(t){const e=this.channel.local;return e!==void 0&&e.handlers().owns(t)}localHandlers(){const t=this.channel.local;return t?()=>t.handlers():void 0}wakeThrough(t){this.wakeMemory=t}constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload),this.bell=t.doorbell?new Int32Array(t.doorbell):void 0}attachMemory(t){this.channel.port.postMessage({memory:t})}copyForExec(t){return this.call(L.CopyForExec,{stdio:t}).process}currentWorkingDirectory(){return this.call(L.GetCwd)}copyForForkChannel(){return this.createChannel(de,this.call(L.CopyForFork).process)}createChannel(t,e){const r=je(t),n=this.channel.sharedPipes&&{...this.channel.sharedPipes,table:e===void 0?this.channel.sharedPipes.table:new SharedArrayBuffer(65536*4)},i=e===void 0?void 0:new MessageChannel,o={...r.server,...e===void 0?{}:{process:e},...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(t){return this.createChannel(de,this.copyForExec(t))}closeProcess(){this.call(L.CloseProcess)}existsSync(t){return this.call(L.Exists,{path:t})}statSync(t){return _s(this.call(L.Stat,{path:t}))}lstatSync(t){return _s(this.call(L.Lstat,{path:t}))}readFileSync(t){const e=this.statSync(t).size;if(e<=z)return me(this.call(L.ReadFile,{path:t}).content);const r=new Uint8Array(e);for(let n=0;n<e;n+=z){const i=this.readRangeSync(t,n,Math.min(z,e-n));if(r.set(i,n),i.byteLength<Math.min(z,e-n))return r.subarray(0,n+i.byteLength)}return r}async readFile(t){return this.readFileSync(t)}readRangeSync(t,e,r){const n=new Uint8Array(r);let i=0;for(;i<r;){const o=Math.min(z,r-i),a=me(this.call(L.ReadRange,{path:t,offset:e+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(t,e,r){for(let n=0;(n<r.byteLength||n===0&&r.byteLength===0)&&(this.call(L.WriteRange,{path:t,offset:e+n,content:Ot(r.subarray(n,n+z))}),r.byteLength!==0);n+=z);}writeFileSync(t,e){const r=typeof e=="string"?this.encoder.encode(e):e;if(r.byteLength<=z){this.call(L.WriteFile,{path:t,content:Ot(r)});return}this.call(L.WriteFile,{path:t,content:""}),this.writeRangeSync(t,0,r)}mkdirSync(t,e){this.call(L.Mkdir,{path:t,recursive:e?.recursive===!0})}readdirSync(t){return this.call(L.Readdir,{path:t})}unlinkSync(t){this.call(L.Unlink,{path:t})}rmdirSync(t){this.call(L.Rmdir,{path:t})}renameSync(t,e){this.call(L.Rename,{from:t,to:e})}toSnapshot(){return JSON.parse(this.decoder.decode(this.readChunked(L.SnapshotSize)))}finalSnapshot(){return JSON.parse(this.decoder.decode(this.readChunked(L.FinalSnapshotSize)))}readChunked(t){const{length:e}=this.call(t);if(!Number.isSafeInteger(e)||e<0)throw at(-5);const r=new Uint8Array(e);for(let n=0;n<e;n+=z){const i=Math.min(z,e-n),{content:o}=this.call(L.SnapshotChunk,{offset:n,length:i}),a=me(o);if(a.byteLength!==i)throw at(-5);r.set(a,n)}return r}prepareSpawn(){this.call(L.PrepareSpawn)}importPeerPatch(t){const e=this.encoder.encode(JSON.stringify(t));this.call(L.ImportPeerPatchStart,{length:e.byteLength});for(let r=0;r<e.byteLength;r+=z)this.call(L.ImportPeerPatchChunk,{offset:r,content:Ot(e.subarray(r,r+z))})}replaceSnapshot(t){const e=this.encoder.encode(JSON.stringify(t));this.call(L.ReplaceSnapshotStart,{length:e.byteLength});for(let r=0;r<e.byteLength;r+=z){const n=e.subarray(r,r+z);this.call(L.ReplaceSnapshotChunk,{offset:r,content:Ot(n)})}}syscall(t,e){const r=this.channel.local;if(r)for(;;){const o=r.syscall(t,e);if(typeof o=="bigint")return o;if(o!==void 0)throw at(o.failed);const a=performance.now();r.idle(),tt.waited.ms+=performance.now()-a}let n=this.names.get(t);n||(n=this.encoder.encode(t),this.names.set(t,n));const i=this.view??=new DataView(this.payload.buffer,this.payload.byteOffset,this.payload.byteLength);this.payload[0]=e.length,this.payload[1]=n.byteLength;for(let o=0;o<e.length;o+=1)i.setBigInt64(8+o*8,BigInt(e[o]),!0);return this.payload.set(n,8+e.length*8),this.exchange(L.SyscallBinary,8+e.length*8+n.byteLength,Ka(t,e)||this.bell?null:3e4),i.getBigInt64(0,!0)}names=new Map;lastResult=0;view;readForMapping(t,e,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,t,!0),i.setFloat64(8,e+o,!0),i.setInt32(16,a,!0);const c=this.exchange(L.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(t){return this.call(L.MappingPath,{fd:t}).path}writeForMapping(t,e,r){const n=this.encoder.encode(t);if(16+n.byteLength+r.byteLength>this.payload.byteLength)return this.call(L.WriteForMapping,{path:t,offset:e,content:Ot(r)}).written;const i=this.view??=new DataView(this.payload.buffer,this.payload.byteOffset,this.payload.byteLength);return i.setFloat64(0,e,!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(L.WriteForMappingBinary,16+n.byteLength+r.byteLength,3e4),this.payload[0]===1}call(t,e={},r=3e4){const n=this.encoder.encode(JSON.stringify(e));if(n.byteLength>this.payload.byteLength)throw at(-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(t,n.byteLength,r);return i>0?JSON.parse(this.decoder.decode(this.payload.slice(0,i))):void 0}exchange(t,e,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,t),Atomics.store(this.control,3,e),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 l=Atomics.load(this.bell,1);l!==0&&this.wakeMemory&&Atomics.notify(new Int32Array(this.wakeMemory.buffer),l-1)}else this.channel.port.postMessage(n);const o=r===null?void 0:Date.now()+r;for(;;){const l=Atomics.load(this.control,0);if(l===n+1)break;if(l!==n&&l!==-n)throw new Error(`Invalid WALI filesystem RPC state ${l} for request ${n}.`);const u=o===void 0?void 0:Math.max(0,o-Date.now());if(u===0&&l===n&&Atomics.compareExchange(this.control,0,n,0)===n)throw at(-110);Atomics.wait(this.control,0,l,l===-n?void 0:u)}const a=Atomics.load(this.control,2),c=Atomics.load(this.control,4);if(Atomics.store(this.control,0,0),a<0)throw at(a);return this.lastResult=a,c}}function Ka(s,t){if(s==="SYS_flock"){const r=Number(t[1]??0);return(r&4)===0&&(r&8)===0}if(s!=="SYS_fcntl")return!1;const e=Number(t[1]??0);return e===7||e===38}const ja=5;class we{sink;root;sharedPipes;constructor(t,e,r){this.sink=t,this.root=e,this.sharedPipes=r}static async createInThread(t,e){const r=await import("./filesystem-host-Pq9IHKRx.js"),n=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),i=new Int32Array(n);r.hostInThread(n),await r.initializeHost({kind:"initialize",snapshot:t,...e});const o=je(de),a=r.attachChannel({...o.server,...e.sharedPipes?{sharedPipes:e.sharedPipes}:{}}),c=new Jr({...o.client,...e.sharedPipes?{sharedPipes:e.sharedPipes}:{},local:{doorbell:n,serveNow:()=>r.serveNow(a),attach:u=>{r.attachChannel(u)},syscall:(u,f)=>r.syscallNow(a,u,f),handlers:()=>r.handlersNow(a),idle:()=>{r.pumpHost(!0),Atomics.wait(i,0,Atomics.load(i,0),ja)}}}),l={attach:u=>{r.attachChannel(u)},terminate:()=>r.resetHost(),doorbell:n,host:r};return new we(l,c,e.sharedPipes)}closePort(){this.sink.host?.closeHostPort()}pump(t=!1){(this.sink.host?.hostWaiting()||t)&&this.sink.host?.pumpHost(t)}doorbell(){return this.sink.doorbell?new Int32Array(this.sink.doorbell):void 0}static async create(t,e){const r=ui("filesystem",()=>pe(new Worker(new URL("/assets/filesystem-worker-CC3pSXUP.js",import.meta.url),{type:"module",name:"wali-filesystem"})));await new Promise((o,a)=>{const c=u=>{u.data.kind==="ready"&&(r.removeEventListener("message",c),o()),u.data.kind==="error"&&(r.removeEventListener("message",c),a(new Error(u.data.message)))};r.addEventListener("message",c),r.addEventListener("error",u=>a(u.error??new Error(u.message)),{once:!0});const l=[...e.updatePort?[e.updatePort]:[],...e.fileLocks?[e.fileLocks.channel.port]:[],...e.fileCoherence?[e.fileCoherence.port]:[]];r.postMessage({kind:"initialize",snapshot:t,...e},l)});const n=je(de);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 we(i,new Jr({...n.client,...e.sharedPipes?{sharedPipes:e.sharedPipes}:{}}),e.sharedPipes)}createChannel(t,e=0){const r=je(t),n=this.sharedPipes&&{...this.sharedPipes,table:e===0?this.sharedPipes.table:new SharedArrayBuffer(65536*4)};return this.sink.attach({process:e,...r.server,...n?{sharedPipes:n}:{}},[r.server.port]),{...r.client,...n?{sharedPipes:n}:{},...this.sink.doorbell?{doorbell:this.sink.doorbell}:{}}}copyForExec(){return this.createChannel(de,this.root.copyForExec())}filesystem(){return this.root}snapshot(){return this.root.toSnapshot()}finalSnapshot(){return this.root.finalSnapshot()}replaceSnapshot(t){this.root.replaceSnapshot(t)}terminate(){this.sink.terminate()}}const le=1e4,Ja=new Set([5,6,7,36,37,38]),Za=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"]),ws=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 Qa{client;stdioAliasRegistry;descriptorState;memory;constructor(t,e,r,n){this.client=t,this.stdioAliasRegistry=e,this.descriptorState=r,this.memory=n}poll(t,e,r,n){const i=this.memory?.();if(!i||!Number.isSafeInteger(r)||r<=0||e<0||e+r*8>i.buffer.byteLength)return t(e,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(),l=new Map;let u=new DataView(i.buffer);for(let g=0;g<r;g+=1){const w=u.getInt32(e+g*8,!0);if(w<3||w>=le&&!K(w))continue;const E=this.stdioAliasRegistry&&w<this.stdioAliasRegistry.length?Atomics.load(this.stdioAliasRegistry,w):-1;if(E===0||E===1||E===2||o&&a&&Atomics.load(a,Atomics.load(o,w)*3+2))continue;const N=c?c().owns(w):Number(this.client.syscall("SYS_fcntl",[w,1,0]))>=0;l.set(g,N?u.getInt16(e+g*8+4,!0)&4:32)}if(l.size===0)return t(e,r,n);const f=[...l.values()].filter(g=>g!==0).length,d=new Uint8Array(i.buffer,e,r*8).slice(),m=[];for(let g=0;g<r;g+=1)l.has(g)||m.push(g);const p=new Uint8Array(i.buffer);m.forEach((g,w)=>p.set(d.subarray(g*8,g*8+8),e+w*8));let y;try{y=t(e,m.length,f?0:n)}finally{const g=new Uint8Array(i.buffer,e,m.length*8).slice();new Uint8Array(i.buffer).set(d,e),u=new DataView(i.buffer),m.forEach((w,E)=>u.setInt16(e+w*8+6,g[E*8+6]|g[E*8+7]<<8,!0));for(const[w,E]of l)u.setInt16(e+w*8+6,E,!0)}return typeof y!="bigint"&&typeof y!="number"||Number(y)<0?y:BigInt(Number(y)+f)}ownedFileImports(t){const e={};for(const r of ws){const n=r==="SYS_fcntl",i=n?void 0:this.client.directSyscall(r),o=t[r];if(!i&&!n||!o||r==="SYS_flock")continue;const a=this.client.localHandlers();a&&(e[r]=(...c)=>{const l=Number(c[0]);if(l<3||l>=le&&!K(l)||n&&Ja.has(Number(c[1])))return o(...c);const{imports:u,errno:f,owns:d}=a();if(!d(l))return o(...c);const m=u[r];if(!m)throw at(-38);let p;try{p=m(...c)}catch(y){throw at(f(y))}return typeof p=="bigint"?p:BigInt(p??0)})}return e}imports(t){const e={};for(const o of Za){const a=this.client.directSyscall(o);e[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 ws){const a=this.client.directSyscall(o),c=o==="SYS_read"||o==="SYS_readv"||o==="SYS_write"||o==="SYS_writev"||o==="SYS_fstat",l=o==="SYS_write"||o==="SYS_writev",u=o==="SYS_pread64"||o==="SYS_pwrite64"||o==="SYS_preadv"||o==="SYS_pwritev";e[o]=(...f)=>{const d=Number(f[0]);if(r&&n&&d>=0&&(d<2e4||K(d))){const p=Atomics.load(r,d),y=Atomics.load(n,p*3+2);return y&&u?-29n:y&&c?(l&&this.client.prepareSpawn(),t[o]?.(...f)??-9n):a?a(f):this.client.syscall(o,f)}const m=this.stdioAliasRegistry&&d>=0&&d<this.stdioAliasRegistry.length?Atomics.load(this.stdioAliasRegistry,d):-1;return d<3||d>=le&&!K(d)||m===0||m===1||m===2?((o==="SYS_write"||o==="SYS_writev")&&this.client.prepareSpawn(),t[o]?.(...f)??-9n):a?a(f):this.client.syscall(o,f)}}const i=t.SYS_poll;return this.memory&&i&&(e.SYS_poll=(o,a,c)=>this.poll(i,Number(o),Number(a),Number(c))),{...t,...e}}readForMapping(t,e,r){if(!(t<3||t>=le&&!K(t)))return this.client.readForMapping(t,e,r)}mappingPath(t){if(!(t<3||t>=le&&!K(t)))return this.client.mappingPath(t)}writeForMapping(t,e,r){return this.client.writeForMapping(t,e,r)}}function je(s){const t=new MessageChannel,e=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*8),r=new SharedArrayBuffer(s);return t.port1.start(),{client:{port:t.port1,control:e,payload:r},server:{port:t.port2,control:e,payload:r}}}function _s(s){return{isFile:()=>s.file,isDirectory:()=>s.directory,isSymbolicLink:()=>s.symbolicLink===!0,size:s.size,...qa(s,"mode","mtimeMs","atimeMs","ctimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks")}}function qa(s,...t){return Object.fromEntries(t.flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}function at(s){const t={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(t),{code:t})}const As=1e4,tc=19999,Dr=64,Zr=64*1024,Je=8,Es=3,Ns=4,Ur=2048,Wr=524288,ec=0,rc=1,nc=2,sc=3,ic=4,Is=1030,oc=1,ac=4096;function cc(s=new _e(new en)){const t={table:s.sharedEntries.buffer,descriptions:s.registry.pipeMetadata.buffer,slots:new SharedArrayBuffer(Dr*Int32Array.BYTES_PER_ELEMENT),controls:new SharedArrayBuffer(Dr*Je*Int32Array.BYTES_PER_ELEMENT),payloads:new SharedArrayBuffer(Dr*Zr)};return hi.set(t.table,s),t}const hi=new WeakMap,Ls=new WeakMap;let Qr,qr;function lc(s,t){if(!Number.isSafeInteger(t)||t<0||t>=65536)return 0;let e=s===Qr?qr:Ls.get(s);e||(e={table:new Int32Array(s.table),descriptions:new Int32Array(s.descriptions)},Ls.set(s,e)),Qr=s,qr=e;const r=Atomics.load(e.table,t);return Atomics.load(e.descriptions,r*3)}function uc(){Qr=void 0,qr=void 0}class hc{memory;state;remote;table;slots;constructor(t,e,r,n){this.memory=t,this.state=e,this.remote=n,this.table=r??hi.get(e.table),this.slots=new Int32Array(e.slots)}isPipeFd(t){return this.entry(t)!==0}exportBrowserProcessPipe(t){const e=this.entry(t);return e===0?void 0:this.handle(e)}pollDescriptor(t,e){const r=this.entry(t);return r===0?void 0:oi(this.handle(r),e)}ioctl(t,e){if(this.isPipeFd(t))return e===21537||e===21585||e===21584?0n:-25n}imports(t={}){const e=(n,i)=>t[n]?.(...i)??-38n,r={...t,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)):t.SYS_close?.(n)??-38n,SYS_read:(n,i,o)=>this.isPipeFd(Number(n))?this.read(Number(n),Number(i),Number(o)):t.SYS_read?.(n,i,o)??-38n,SYS_pread64:(n,i,o,a)=>this.isPipeFd(Number(n))?-29n:t.SYS_pread64?.(n,i,o,a)??-38n,SYS_write:(n,i,o)=>this.isPipeFd(Number(n))?this.write(Number(n),Number(i),Number(o)):t.SYS_write?.(n,i,o)??-38n,SYS_pwrite64:(n,i,o,a)=>this.isPipeFd(Number(n))?-29n:t.SYS_pwrite64?.(n,i,o,a)??-38n,SYS_preadv:(n,i,o,a,c)=>this.isPipeFd(Number(n))?-29n:t.SYS_preadv?.(n,i,o,a,c)??-38n,SYS_pwritev:(n,i,o,a,c)=>this.isPipeFd(Number(n))?-29n:t.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)):t.SYS_readv?.(n,i,o)??-38n,SYS_writev:(n,i,o)=>this.isPipeFd(Number(n))?this.writev(Number(n),Number(i),Number(o)):t.SYS_writev?.(n,i,o)??-38n,SYS_lseek:(n,i,o)=>this.isPipeFd(Number(n))?-29n:t.SYS_lseek?.(n,i,o)??-38n,SYS_fstat:(n,i)=>this.isPipeFd(Number(n))?this.fstat(Number(i)):t.SYS_fstat?.(n,i)??-38n,SYS_dup:n=>this.isPipeFd(Number(n))?this.duplicate(Number(n)):t.SYS_dup?.(n)??-38n,SYS_dup2:(n,i)=>this.isPipeFd(Number(n))?this.duplicate(Number(n),Number(i),3,!1,t):t.SYS_dup2?.(n,i)??-38n,SYS_dup3:(n,i,o)=>this.isPipeFd(Number(n))?Number(n)===Number(i)||(Number(o)&~Wr)!==0?-22n:this.duplicate(Number(n),Number(i),3,!!(Number(o)&Wr),t):t.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))),t):t.SYS_fcntl?.(n,i,o)??-38n,SYS_poll:(n,i,o)=>this.poll(Number(n),Number(i),Number(o),()=>e("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(t,e){if((e&-526337)!==0)return-22n;if(!this.validRange(t,8))return-14n;const r=this.allocateSlot();if(r<0)return-24n;const n=this.control(r);n.fill(0),Atomics.store(n,Es,1),Atomics.store(n,Ns,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=e&Wr?1:0,Atomics.store(new Int32Array(this.state.descriptions),this.table.entries[c].description*3+1,e&Ur);const a=this.view();return a.setInt32(t,i,!0),a.setInt32(t+4,o,!0),0n}read(t,e,r){if(!Number.isSafeInteger(r)||r<0||!this.validRange(e,r))return-22n;const i=(this.statusFlags(t)&Ur?sn:Ma)(this.handle(this.entry(t)),r);return typeof i=="bigint"?i:(this.bytes().set(i,e),BigInt(i.byteLength))}write(t,e,r){return!Number.isSafeInteger(r)||r<0||!this.validRange(e,r)?-22n:ai(this.handle(this.entry(t)),this.bytes().slice(e,e+r))}readv(t,e,r){if(!Number.isSafeInteger(r)||r<0||r>1024||!this.validRange(e,r*8))return-22n;let n=0n;for(let i=0;i<r;i+=1){const o=e+i*8,a=this.read(t,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(t,e,r){if(!Number.isSafeInteger(r)||r<0||r>1024||!this.validRange(e,r*8))return-22n;let n=0n;for(let i=0;i<r;i+=1){const o=e+i*8,a=this.write(t,this.view().getUint32(o,!0),this.view().getUint32(o+4,!0));if(a<0n)return n>0n?n:a;n+=a}return n}fstat(t){if(!this.validRange(t,144))return-14n;const e=this.view();for(let r=0;r<144;r+=4)e.setUint32(t+r,0,!0);return e.setBigUint64(t+16,1n,!0),e.setUint32(t+24,ac|438,!0),e.setUint32(t+28,1e3,!0),e.setUint32(t+32,1e3,!0),e.setBigInt64(t+56,4096n,!0),0n}statusFlags(t){const e=Atomics.load(new Int32Array(this.state.table),t);return Atomics.load(new Int32Array(this.state.descriptions),e*3+1)}fcntl(t,e,r,n){if(e===ec||e===Is)return this.duplicate(t,void 0,Math.max(3,r),e===Is,n);const i=this.table.entries[t];return e===rc?BigInt(i.flags):e===nc?(i.flags=r&oc,0n):e===sc?BigInt(this.statusFlags(t)|(this.entry(t)<0?1:0)):e===ic?(Atomics.store(new Int32Array(this.state.descriptions),i.description*3+1,r&Ur),0n):-22n}duplicate(t,e,r=As,n=!1,i={}){const o=this.table.get(t);if(!o)return-9n;if(e===t)return BigInt(t);const a=e===void 0?this.freeDescriptor(r):e;return a<0||a>=65536?-9n:(this.table.set(a,o,n?1:0),BigInt(a))}close(t){return this.table.close(t)?0n:-9n}poll(t,e,r,n){if(!Number.isSafeInteger(e)||e<0||e>65536||!this.validRange(t,e*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<e;a+=1){const c=t+a*8,l=this.view().getInt32(c,!0),u=this.pollDescriptor(l,this.view().getInt16(c+4,!0));u!==void 0&&(this.view().getInt16(c+6,!0)!==0&&(o-=1),this.view().setInt16(c+6,u,!0),u!==0&&(o+=1))}return BigInt(o)}allocateSlot(){for(let t=0;t<this.slots.length;t+=1)if(Atomics.compareExchange(this.slots,t,0,1)===0)return t;return-1}freeDescriptor(t){for(let e=Math.max(3,t);e<=tc;e++)if(!this.table.get(e))return e;return-1}allocateDescriptor(t,e=As){const r=this.freeDescriptor(e);if(r<0)return r;const n=Math.abs(t)-1,i=this.table.registry.create("pipe",{pipe:n,side:t>0?"reader":"writer"},()=>{Se(this.handle(t));const o=this.control(n);Atomics.load(o,Es)===0&&Atomics.load(o,Ns)===0&&Atomics.store(this.slots,n,0)});return Atomics.store(this.table.registry.pipeMetadata,i.id*3,t),this.table.set(r,i),r}entry(t){return lc(this.state,t)}handle(t){const e=Math.abs(t)-1;return{control:this.state.controls,payload:this.state.payloads,role:t>0?"reader":"writer",controlOffset:e*Je*Int32Array.BYTES_PER_ELEMENT,payloadOffset:e*Zr,payloadLength:Zr}}control(t){return new Int32Array(this.state.controls,t*Je*Int32Array.BYTES_PER_ELEMENT,Je)}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}validRange(t,e){return Number.isSafeInteger(t)&&Number.isSafeInteger(e)&&t>=0&&e>=0&&t+e<=this.memory().buffer.byteLength}}const Or=64*1024,fc=1e4;var bt;(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"})(bt||(bt={}));var xs;(function(s){s[s.VideoDecoder=0]="VideoDecoder",s[s.VideoEncoder=1]="VideoEncoder",s[s.AudioDecoder=2]="AudioDecoder",s[s.AudioEncoder=3]="AudioEncoder"})(xs||(xs={}));const ks=1;var q;(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"})(q||(q={}));const dc=6,mc=9,Sc=-5,$r=-9,yc=-11,Oe=-14,xt=-22,Ut=-95,pc=-110,Ms=3e4,bc=fc+5e3;class gc{channel;control;nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control)}call(t,e,r){if(Atomics.load(this.control,q.State)!==0)return yc;const n=this.nextRequestId;this.nextRequestId=n>=1073741821?1:n+2,this.control.fill(0);for(let a=0;a<dc;a+=1)Atomics.store(this.control,q.Argument0+a,e[a]??0);Atomics.store(this.control,q.Operation,t),Atomics.store(this.control,q.State,n),this.channel.port.postMessage(n);const i=Date.now()+r;for(;;){const a=Atomics.load(this.control,q.State);if(a===n+1)break;if(a!==n&&a!==-n)return Sc;const c=Math.max(0,i-Date.now());if(c===0&&a===n&&Atomics.compareExchange(this.control,q.State,n,0)===n)return pc;Atomics.wait(this.control,q.State,a,a===-n?void 0:c)}const o=Atomics.load(this.control,q.Result);return Atomics.store(this.control,q.State,0),o}}function wc(s,t,e){const r=()=>s().buffer.byteLength,n=(c,l)=>Number.isSafeInteger(c)&&c>0&&l>=0&&c<=r()-l,i=(c,l)=>l===0?Number.isSafeInteger(c)&&c>=0:n(c,l),o=(c,l,u=Ms)=>{const f=e();return BigInt(f?f.call(c,l,u):Ut)},a=c=>(l,u,f)=>{if(!t())return BigInt(Ut);const d=Number(l),m=Number(u),p=Number(f);return!Number.isInteger(d)||d<0||d>3||!Number.isSafeInteger(p)||p<1||p>Or?BigInt(xt):n(m,p)?o(c,[d,m,p]):BigInt(Oe)};return{SYS_browser_codec_query_v1:a(bt.Query),SYS_browser_codec_open_v1:a(bt.Open),SYS_browser_codec_push_v1:(c,l,u,f,d)=>{if(!t())return BigInt(Ut);const m=Number(c),p=Number(l),y=Number(u),g=Number(f),w=Number(d);return!Number.isInteger(m)||m<=0?BigInt($r):!Number.isSafeInteger(y)||y<0||!Number.isSafeInteger(w)||w<1||w>Or?BigInt(xt):y>0&&!n(p,y)||!n(g,w)?BigInt(Oe):o(bt.Push,[m,p,y,g,w])},SYS_browser_codec_pull_v1:(c,l,u,f,d,m)=>{if(!t())return BigInt(Ut);const p=Number(c),y=Number(l),g=Number(u),w=Number(f),E=Number(d),N=Number(m);return!Number.isInteger(p)||p<=0?BigInt($r):!Number.isInteger(y)||(y&~ks)!==0||!Number.isSafeInteger(w)||w<0||!Number.isSafeInteger(N)||N<0||N>Or?BigInt(xt):!i(g,w)||!i(E,N)?BigInt(Oe):o(bt.Pull,[p,y,g,w,E,N],(y&ks)===0?Ms:bc)},SYS_browser_codec_flush_v1:c=>{if(!t())return BigInt(Ut);const l=Number(c);return!Number.isInteger(l)||l<=0?BigInt($r):o(bt.Flush,[l])},SYS_browser_codec_close_v1:c=>{if(!t())return BigInt(Ut);const l=Number(c);return!Number.isInteger(l)||l<=0?0n:o(bt.Close,[l])}}}class an{worker;constructor(t){this.worker=t}static async create(t){const e=pe(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"&&(e.removeEventListener("message",i),r()),o.data.kind==="error"&&(e.removeEventListener("message",i),n(new Error(o.data.message)))};e.addEventListener("message",i),e.addEventListener("error",o=>n(o.error??new Error(o.message)),{once:!0}),e.postMessage({kind:"initialize",memory:t})}),new an(e)}createChannel(){const t=new MessageChannel,e=new SharedArrayBuffer(mc*Int32Array.BYTES_PER_ELEMENT);return this.worker.postMessage({kind:"attach",port:t.port2,control:e},[t.port2]),{port:t.port1,control:e}}terminate(){this.worker.terminate()}}const Vr=1,zr=2,Hr=4,Rs=8,_c=16,Ac=32,fi=1024,Ec=fi*8;function Nc(s,t,e){return(r,n,i,o,a)=>{const c=Number(r);if(!Number.isInteger(c)||c<0||c>fi)return-22n;const l=[Number(n),Number(i),Number(o)],u=[Vr,Hr,zr],f=Math.ceil(c/8);let d=new Uint8Array(s().buffer);for(const P of l)if(P!==0&&(P<0||P+f>d.byteLength))return-14n;const m=Number(a);let p=-1;if(m!==0){if(m<0||m+16>d.byteLength)return-14n;const P=new DataView(s().buffer),x=P.getBigInt64(m,!0),M=P.getBigInt64(m+8,!0);if(x<0n||M<0n)return-22n;p=Number(x*1000n+(M+999n)/1000n)}const y=new Map;l.forEach((P,x)=>{if(P!==0)for(let M=0;M<c;M+=1)d[P+(M>>3)]&1<<(M&7)&&y.set(M,(y.get(M)??0)|u[x])});const g=e();if(g<=0)return-12n;let w=new DataView(s().buffer),E=0;for(const[P,x]of y){const M=g+E*8;w.setInt32(M,P,!0),w.setInt16(M+4,x,!0),w.setInt16(M+6,0,!0),E+=1}const N=t(g,E,p),$=Number(typeof N=="bigint"?N:N??0);if($<0)return BigInt($);d=new Uint8Array(s().buffer),w=new DataView(s().buffer);for(const P of l)P!==0&&d.fill(0,P,P+f);let U=0,H=0;for(const[P,x]of y){const M=w.getInt16(g+H*8+6,!0);if(H+=1,M&Ac)return-9n;[(x&Vr)!==0&&(M&(Vr|_c|Rs))!==0,(x&Hr)!==0&&(M&(Hr|Rs))!==0,(x&zr)!==0&&(M&zr)!==0].forEach((Mt,Rt)=>{if(!Mt)return;const vt=l[Rt]+(P>>3);d[vt]=(d[vt]??0)|1<<(P&7),U+=1})}return BigInt(U)}}var gt;(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"})(gt||(gt={}));const $e=512*1024,vs=256*1024*1024,Ys=5,Ic=new TextEncoder,Lc=new TextDecoder("utf-8",{fatal:!0});class xc{channel;control;payload;nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload)}pull(t){const e=this.call(gt.Inspect,{path:t});if(!e.exists)return;const r=tn(e.length,0,vs),n=new Uint8Array(r);for(let i=0;i<r;i+=$e){const o=Math.min($e,r-i),a=this.call(gt.Read,{path:t,offset:i,length:o}),c=me(a.content);if(c.byteLength!==o)throw new Error("Invalid coherent file response.");n.set(c,i)}return{bytes:n,...e.mode===void 0?{}:{mode:e.mode},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs},parents:di(t,e.parents)}}push(t,e){if(!e){this.call(gt.Remove,{path:t});return}if(e.bytes.byteLength>vs)throw new Error("Coherent file exceeds 256 MiB.");this.call(gt.WriteStart,{path:t,length:e.bytes.byteLength,...e.mode===void 0?{}:{mode:e.mode},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs},...e.parents===void 0?{}:{parents:e.parents}});for(let r=0;r<e.bytes.byteLength;r+=$e){const n=e.bytes.subarray(r,r+$e);this.call(gt.WriteChunk,{offset:r,content:Ot(n)})}this.call(gt.WriteFinish)}call(t,e={}){const r=()=>{if(Atomics.load(this.control,Ys))throw Object.assign(new Error("Browser file coherence was cancelled."),{errno:125})};r();const n=Ic.encode(JSON.stringify(e));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,Ys),this.payload.set(n),Atomics.store(this.control,1,t),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 l=Atomics.load(this.control,0);l!==i+1&&Atomics.wait(this.control,0,l)}const o=Atomics.load(this.control,2),a=tn(Atomics.load(this.control,4),0,this.payload.byteLength),c=a===0?void 0:JSON.parse(Lc.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 Ps(s){const t=s.replace(/-(?:journal|shm|wal)$/u,"");return[t,`${t}-journal`,`${t}-wal`,`${t}-shm`]}function kc(s,t){return cn(t).flatMap(e=>{if(!s.existsSync(e))return[];const r=s.statSync(e);if(!r.isDirectory())throw ft("A coherent file parent must be a directory.");return[{path:e,...mi({mode:r.mode,mtimeMs:r.mtimeMs})}]})}function Mc(s,t,e){const r=new Map(di(t,e).map(n=>[n.path,n]));for(const n of cn(t)){if(s.existsSync(n)){if(!s.statSync(n).isDirectory())throw ft("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 di(s,t){if(t===void 0)return[];const e=new Set(cn(s));if(!Array.isArray(t)||t.length>e.size)throw ft("Invalid coherent file parents.");return t.map(r=>{if(typeof r!="object"||r===null)throw ft("Invalid coherent file parent.");const n=r,i=Si(n.path);if(!e.delete(i))throw ft("Coherent metadata must name distinct ancestors of its file.");return{path:i,...mi(n)}})}function cn(s){const t=[];for(const e of Si(s).split("/"))!e||e==="."||(e===".."?t.pop():t.push(e));return t.slice(0,-1).map((e,r)=>`/${t.slice(0,r+1).join("/")}`)}function mi(s){const t=s.mode===void 0?void 0:tn(s.mode,0,65535),e=s.mtimeMs===void 0?void 0:vc(s.mtimeMs);return{...t===void 0?{}:{mode:t},...e===void 0?{}:{mtimeMs:e}}}function Si(s){const t=Rc(s);if(!t.startsWith("/")||t.length>4096||t.includes("\0"))throw ft("Invalid coherent file path.");return t}function Rc(s){if(typeof s!="string")throw ft("Expected a string.");return s}function tn(s,t,e){if(!Number.isSafeInteger(s)||s<t||s>e)throw ft("Expected a bounded integer.");return s}function vc(s){if(typeof s!="number"||!Number.isFinite(s))throw ft("Expected a finite number.");return s}function ft(s){return Object.assign(new Error(s),{errno:22})}class Yc{locks;coherence;filesystem;held=[];locallyCreated=new Set;constructor(t,e,r){this.locks=t,this.coherence=e,this.filesystem=r}created(t){this.locallyCreated.add(t)}request(t){if(t.operation==="query")return this.locks.request(t);if(t.operation==="set"){const i=!this.held.some(a=>a.path===t.path),o=this.locks.request(t);if(o.result<0)return o;if(i)try{this.refresh(t.path)}catch(a){throw this.locks.request({operation:"unlock",owner:t.owner,namespace:t.namespace,path:t.path,range:t.range}),a}return this.install(t.owner,t.namespace,t.path,t.range),o}if(t.operation==="unlock"){const i=this.without(t.owner,t.namespace,t.path,t.range);this.held.some(a=>a.path===t.path)&&!i.some(a=>a.path===t.path)&&this.publish(t.path);const o=this.locks.request(t);return o.result>=0&&this.replaceHeld(i),o}const e=this.held.filter(i=>i.owner!==t.owner),r=new Set(this.held.filter(i=>i.owner===t.owner).map(i=>i.path));for(const i of r)e.some(o=>o.path===i)||this.publish(i);const n=this.locks.request(t);return n.result>=0&&this.replaceHeld(e),n}refresh(t){const e=performance.now();try{this.refreshNow(t)}finally{tt.waited.ms+=performance.now()-e}}publish(t){const e=performance.now();try{this.publishNow(t)}finally{tt.waited.ms+=performance.now()-e}}refreshNow(t){for(const e of Ps(t)){const r=this.coherence.pull(e);if(!r&&this.locallyCreated.delete(e)){this.coherence.push(e,this.readLocal(e)),this.filesystem.dropChangedPaths?.([e]);continue}this.locallyCreated.delete(e),this.writeLocal(e,r),this.filesystem.dropChangedPaths?.([e])}}publishNow(t){for(const e of Ps(t))this.coherence.push(e,this.readLocal(e)),this.filesystem.dropChangedPaths?.([e])}readLocal(t){if(!this.filesystem.existsSync(t))return;const e=this.filesystem.statSync(t);if(!e.isDirectory())return{bytes:this.filesystem.readFileSync(t),...e.mode===void 0?{}:{mode:e.mode},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs},parents:kc(this.filesystem,t)}}writeLocal(t,e){if(!e){this.filesystem.existsSync(t)&&!this.filesystem.statSync(t).isDirectory()&&this.filesystem.unlinkSync(t);return}Mc(this.filesystem,t,e.parents),this.filesystem.writeFileSync(t,e.bytes),e.mode!==void 0&&this.filesystem.chmodSync?.(t,e.mode),e.mtimeMs!==void 0&&this.filesystem.utimesSync?.(t,new Date(e.mtimeMs),new Date(e.mtimeMs))}install(t,e,r,n){const i=this.without(t,e,r,n);i.push({owner:t,namespace:e,path:r,...n}),this.replaceHeld(i)}without(t,e,r,n){return this.held.flatMap(i=>i.owner===t&&i.namespace===e&&i.path===r&&Pc(i,n)?Bc(i,n):[i])}replaceHeld(t){this.held.splice(0,this.held.length,...t)}}function Pc(s,t){return s.start<(t.end??Number.POSITIVE_INFINITY)&&t.start<(s.end??Number.POSITIVE_INFINITY)}function Bc(s,t){const e=[];s.start<t.start&&e.push({...s,end:t.start});const r=s.end??Number.POSITIVE_INFINITY,n=t.end??Number.POSITIVE_INFINITY;return n<r&&e.push({...s,start:n,...s.end===void 0?{}:{end:s.end}}),e}const Tc=9n,Fc=22n,Bs=new TextEncoder,ue=new TextDecoder;class yi extends Error{imports;constructor(t){super(`Unsupported WALI imports: ${t.join(", ")}`),this.imports=t,this.name="UnsupportedWaliImportError"}}function Cc(s,t){if(ji(s))return()=>{throw new yi([s])};let e=!1;return()=>{if(!e){e=!0;const r=`[WALI] ${s} is not implemented; answering -ENOSYS (38) as a kernel would.`;console.error(r),t?.(r)}return Ki}}class Ts extends Error{}class Fs extends Error{code;constructor(t){super(`WALI process exited with status ${t}`),this.code=t}}class Dc{async run(t,e={}){const r=e.filesystemPolicy===void 0?void 0:kt(e.filesystemPolicy),n=r,i=await Vi(t),o=zi(i);Hi(o);const a=o.filter(h=>h.module==="wali"),c=[],l=[],u=typeof e.stdin=="object"&&e.stdin!==null&&"read"in e.stdin?e.stdin:new Os(typeof e.stdin=="string"?Bs.encode(e.stdin):e.stdin??new Uint8Array),f=e.argv?.length?[...e.argv]:["wali-program"],d=f.map(h=>Bs.encode(`${h}\0`)),m=$c(e.pid),p=performance.now(),y={...tt.waited};let g=p;const w=new Map,E=e.signalState??Ti();let N,$,U,H,P,x,M=!1;const j=da(t,e.memory),Mt=xo(),Rt=new Int32Array(new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT));Atomics.store(Rt,1,-1);const vt=new _e(new en),Yt=e.descriptorTable?.sharedPipes??cc(vt),v=()=>{if(j)return j;const h=N?.exports.memory;if(!(h instanceof WebAssembly.Memory))throw new Error("WALI module does not export linear memory.");return h},rt=()=>new DataView(v().buffer),lt=()=>new Uint8Array(v().buffer),ln=(h,S)=>(Wt(v(),h,S),lt().slice(h,h+S)),pi=(h,S)=>{Wt(v(),h,S.byteLength),lt().set(S,h)},Xt=(h,S)=>{if(h===1)c.push(S),e.onStdout?.(S.slice());else if(h===2)l.push(S),e.onStderr?.(S.slice());else return-Tc;return BigInt(S.byteLength)},Ae=(h,S="SYS_exit_group")=>{const b=`[WALI] ${S}(${h&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(b),e.onDiagnostic?.(b),new Fs(h&255)},un=h=>h<0||h>64?-22n:h===0?0n:h!==9&&(At.mask&1n<<BigInt(h-1))!==0n?(new fr(E).raise(h),0n):((h===9||h===19?"default":new fr(E).raise(h))==="default"&&Bi(h)&&Ae(128+h,`signal ${h}`),0n),Ee=e.executablePath??(f[0].startsWith("/")?f[0]:`/usr/bin/${f[0]}`),nr=a.some(h=>h.name==="__wasm_thread_spawn"),sr=a.some(h=>Uc.has(h.name))?e.browserProcess:void 0,bi=e.forkState?.allocator??Js(),hn=Go(),dt=e.descriptorTable?new Jr(e.descriptorTable):void 0;if(dt&&j&&dt.attachMemory(j),!dt&&(nr||sr)&&e.filesystem?.toSnapshot&&e.filesystem.replaceSnapshot){if(!j)throw new Error("A threaded WALI module must import its shared process memory.");const h=e.store||e.layers?e.filesystem.toStoreOverlaySnapshot?.():void 0;M=!(!!sr?.fork&&WebAssembly.Module.exports(i).some(b=>b.name==="asyncify_start_unwind")||a.some(b=>b.name==="SYS_browser_spawn"||b.name==="SYS_browser_spawn_confined_v1")),x=await(M?we.createInThread:we.create)(h??e.filesystem.toSnapshot(),{...e.store?{store:e.store}:{},...e.layers?{layers:e.layers}:{},...e.privateRoots?{privateRoots:e.privateRoots}:{},memory:j,sharedPipes:Yt,...n?{filesystemPolicy:n}:{},cwd:e.cwd??"/",executablePath:Ee,pid:m,...e.filesystemUpdatePort?{updatePort:e.filesystemUpdatePort}:{},...e.fileLocks?{fileLocks:e.fileLocks}:{},...e.fileCoherence?{fileCoherence:e.fileCoherence}:{}})}if(n&&nr&&!x&&!dt)throw new Error("Confined WALI threads require the shared filesystem owner.");const _t=dt??x?.filesystem()??e.filesystem,fn=()=>{x&&e.filesystem?.replaceSnapshot&&e.filesystem.replaceSnapshot(x.snapshot())},W=new er({...dt||x?{descriptorState:Yt}:{descriptors:vt},...n?{filesystemPolicy:n}:{},..._t?{filesystem:_t}:{},cwd:e.cwd??"/",stdin:u,executablePath:Ee,memory:v,emit:Xt,stdioAliasRegistry:Mt,pid:m,...!x&&e.fileLocks?{fileLocks:e.fileCoherence?new Yc(new tt(e.fileLocks.channel),new xc(e.fileCoherence),_t):new tt(e.fileLocks.channel),lockOwner:e.fileLocks.owner}:{},...x?{specialDescriptorMinimum:1e4,descriptorMaximum:19999}:{},...!x&&!dt&&e.privateRoots?{privateRoots:e.privateRoots.map(h=>`/${h.split("/").filter(Boolean).join("/")}`)}:{},...e.onDiagnostic?{onDiagnostic:e.onDiagnostic}:{}}),gi=W.imports(),Kt=W.writeEnvironmentFile(e.env??{},m),F=dt??x?.filesystem(),Pt=F?new Qa(F,Mt,Yt,v):void 0,mt=new Xo(v,(h,S,b)=>Pt?.readForMapping(h,S,b)??W.readForMapping(h,S,b),bi,h=>Pt?.mappingPath(h)??W.mappingPath(h),(h,S,b)=>Pt?.writeForMapping(h,S,b)??W.writeForMapping(h,S,b),hn,e.onDiagnostic),At=new Fi(new fr(E),v,()=>N?.exports.__indirect_function_table,()=>Number(mt.imports().SYS_mmap(0,4096,3,34,-1,0)),Ci(()=>N?.exports,v)),ir=e.threadPoolSize??18,dn=new ia(v,m,u,Rt,e.terminal,ir,()=>mt.growAhead()),mn=M?x?.doorbell():void 0;xn(mn?{pump:()=>x.pump(!0),doorbell:mn}:void 0);let Sn=!1;(e.network||sr)&&(U=await on.create(e.network,Yt,u instanceof Gr?u.buffer:void 0,Mt.buffer,E));const J=U?new Ga(v,U.createChannel(),At):void 0,Ne=new hc(v,Yt,F?void 0:vt,F),wi=new fa(v,W,(h,S)=>Ne.pollDescriptor(h,S)??(J?.isNetworkFd(h)?J.pollFd(h,S):void 0)),_i=new Wa(v,W),yn=W.imports(),Ai=Pt?.imports(yn)??yn,pn=Ne.imports({..._i.imports(),...Ai}),bn=wi.imports(),jt=dn.imports(),gn=e.forkState?.parentPid??e.parentPid??1,Et=new Int32Array(e.childPidAllocator??new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));e.childPidAllocator||Atomics.store(Et,0,Math.max(m+1,1e4));const Ie=h=>{if(!Number.isSafeInteger(h)||h<=0||h>=lt().byteLength)throw new WebAssembly.RuntimeError("WALI process string pointer is out of bounds.");const S=lt().indexOf(0,h);if(S<0||S-h>1024*1024)throw new WebAssembly.RuntimeError("WALI process string is not terminated.");return ue.decode(lt().slice(h,S))},Le=h=>{if(h===0)return[];const S=[];for(let b=0;b<65536;b+=1){Wt(v(),h+b*4,4);const A=rt().getUint32(h+b*4,!0);if(A===0)return S;S.push(Ie(A))}throw new WebAssembly.RuntimeError("WALI process string array is not terminated.")},Bt=(h,S)=>{const b=Ne.exportBrowserProcessPipe(h)??W.exportBrowserProcessPipe(h);if(!(!b||b.role!==S))return ii(b)},Ei=(h,S,b)=>{if(!J)return-10n;if(S!==0&&(S<0||S+4>lt().byteLength))return-14n;const{result:A,process:k}=J.waitChild(h,b,At.mask);if(A<=0)return BigInt(A);const T=va(k);if(T){x&&x.filesystem().importPeerPatch(T),e.filesystem&&_a(e.filesystem,T);const O=e.filesystem?.toSnapshot?.();O&&e.browserProcess?.restore?.(O)}return S!==0&&rt().setInt32(S,(Atomics.load(new Int32Array(k.control),1)&255)<<8,!0),BigInt(A)},wn=(h,S)=>{const[b,A,k,T,O,D,nt]=h;if(!e.browserProcess)return-38;const Qt=cr(1,[O,D,nt]);if(Qt!==void 0)return Qt;S&&(S=kt(S));const qt=r;if(qt){if(e.browserProcess.filesystemPolicyVersion!==1)return-95;S=Di(qt,S)}const Tt=Ie(Number(b)),Nt=Le(Number(A));Nt.length===0&&Nt.push(Tt);const Ln={};for(const Ft of Le(Number(k))){const hr=Ft.indexOf("=");hr>0&&(Ln[Ft.slice(0,hr)]=Ft.slice(hr+1))}const Me=Atomics.add(Et,0,1),ur={control:new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),response:new SharedArrayBuffer(jr),snapshotApplied:!1},Re=Bt(Number(O),"reader"),ve=Bt(Number(D),"writer"),Ye=Bt(Number(nt),"writer");let Pe;try{const Ft=J.registerChild(Me,ur);if(Ft<0)throw new Error(`Child registration failed: ${Ft}`);return F?.prepareSpawn(),fn(),Pe=F?.copyForExecChannel([Number(O),Number(D),Number(nt)]),e.browserProcess.spawn({pid:Me,parentPid:m,childPidAllocator:Et.buffer,...Pe?{descriptorTable:Pe}:{},...S?{filesystemPolicy:S}:{},executablePath:Tt,argv:Nt,env:Ln,...Number(k)===0?{inheritEnvironment:!0}:{},cwd:Number(T)===0?W.currentWorkingDirectory():Ie(Number(T)),control:ur.control,response:ur.response,...Re?{stdin:Re}:{},...ve?{stdout:ve}:{},...Ye?{stderr:Ye}:{}}),Me}catch{return Pe?.releasePort?.postMessage(!0),J.forgetChild(Me),Re&&Se(Re),ve&&Se(ve),Ye&&Se(Ye),-5}};let Z=e.forkState?.asyncifyData??0,or=!1,xe=!!e.forkState,ke=0,_n=!1;const Jt=(h,...S)=>{const b=N?.exports[h];if(typeof b!="function")throw new Error(`Missing ${h}; build the module with the Binaryen Asyncify stage.`);b(...S)},ar=()=>F?.currentWorkingDirectory()??W.currentWorkingDirectory(),cr=(h,S=[])=>{const b=N?.exports.__wali_private_tree_release;if(typeof b!="function")return;const A=Number(b(h,Number(S[0]??-1),Number(S[1]??-1),Number(S[2]??-1)));return A<0?A:void 0},Ni=()=>{if(typeof N?.exports.asyncify_start_unwind!="function")return _n||e.onDiagnostic?.("[WALI] SYS_fork answers -ENOSYS: module lacks the Binaryen Asyncify build stage (--asyncify --pass-arg=asyncify-imports@wali.SYS_fork)."),_n=!0,-38n;if(xe)return Jt("asyncify_stop_rewind"),xe=!1,BigInt(ke);if(!e.browserProcess?.fork||!F||!J)return-38n;const h=cr(0);return h!==void 0?BigInt(h):(or=!0,rt().setUint32(Z,Z+8,!0),Jt("asyncify_start_unwind",Z),0n)},Ii=(h,S,b)=>{if(!e.forkState||!e.browserProcess||!F)return-38n;const A=cr(0);if(A!==void 0)return BigInt(A);const k=Ie(h),T=k.startsWith("/")?k:`${ar()}/${k}`;if(!_t?.existsSync(T))return-2n;if(!_t.statSync(T).isFile())return-13n;const O=b===0?{...e.env}:{};for(const Tt of Le(b)){const Nt=Tt.indexOf("=");Nt>0&&(O[Tt.slice(0,Nt)]=Tt.slice(Nt+1))}F.prepareSpawn();const D=F.copyForExecChannel([0,1,2]),nt=Bt(0,"reader"),Qt=Bt(1,"writer"),qt=Bt(2,"writer");throw e.browserProcess.spawn({pid:m,parentPid:gn,childPidAllocator:Et.buffer,executablePath:T,argv:Le(S),env:O,cwd:ar(),descriptorTable:D,control:e.forkState.control,response:e.forkState.response,...n?{filesystemPolicy:n}:{},...nt?{stdin:nt}:{},...Qt?{stdout:Qt}:{},...qt?{stderr:qt}:{}}),new Ts},Zt={...{__init:()=>0,__deinit:()=>0,__proc_exit:h=>Ae(Number(h)),__cl_get_argc:()=>d.length,__cl_get_argv_len:h=>d[Number(h)]?.byteLength??0,__cl_copy_argv:(h,S)=>{const b=d[Number(S)];return b?(pi(Number(h),b),0):-1},__get_init_envfile:(h,S)=>Kt?W.copyCString(Number(h),Kt,Number(S)):0,SYS_write:(h,S,b)=>Xt(Number(h),ln(Number(S),Number(b))),SYS_writev:(h,S,b)=>{let A=0n;for(let k=0;k<Number(b);k+=1){const T=Number(S)+k*8;Wt(v(),T,8);const O=rt().getUint32(T,!0),D=rt().getUint32(T+4,!0),nt=Xt(Number(h),ln(O,D));if(nt<0n)return nt;A+=nt}return A},SYS_exit:h=>Ae(Number(h),"SYS_exit"),SYS_exit_group:h=>Ae(Number(h),"SYS_exit_group"),SYS_getpid:()=>BigInt(m),SYS_getppid:()=>BigInt(gn),SYS_gettid:()=>BigInt(m),SYS_getuid:()=>1000n,SYS_geteuid:()=>1000n,SYS_getgid:()=>1000n,SYS_getegid:()=>1000n,SYS_set_tid_address:()=>BigInt(m),SYS_sched_yield:()=>0n,SYS_sched_setscheduler:()=>0n,SYS_tkill:(h,S)=>un(Number(S)),...wc(v,()=>e.codec?.version===1,()=>P),SYS_browser_spawn:(...h)=>wn(h),SYS_browser_spawn_confined_v1:Wi(v,()=>e.browserProcess?.filesystemPolicyVersion===1,wn),SYS_fork:Ni,SYS_execve:(h,S,b)=>Ii(Number(h),Number(S),Number(b)),SYS_wait4:(h,S,b)=>{for(;;){const A=Ei(Number(h),Number(S),Number(b));if(A!==-4n||!At.deliver(!0))return A}},SYS_pidfd_open:()=>-38n,SYS_kill:(h,S)=>{if(Number(h)===m||Number(h)===0)return un(Number(S));const b=Math.abs(Number(h));return J?.hasChild(b)?(e.browserProcess?.kill?.(b,Number(S)),0n):-3n},SYS_setpgid:()=>0n,SYS_getpgid:h=>BigInt(Number(h)===0?m:Math.abs(Number(h))),__wasm_thread_spawn:(h,S)=>{const b=$?.spawn(Number(h),Number(S),At.mask)??-11;if(b===-11&&!Sn){Sn=!0;const A=`[WALI] pthread_create answered -EAGAIN: all ${ir} 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 ${dn.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(A),e.onDiagnostic?.(A)}return b},SYS_clock_gettime:(h,S)=>{const b=Vc(Number(h));return b===void 0?-Fc:(zc(rt(),Number(S),b),0n)},SYS_gettimeofday:h=>{if(Number(h)!==0){const S=BigInt(Math.floor(wt()*1e3));Wt(v(),Number(h),16),rt().setBigInt64(Number(h),S/1000000n,!0),rt().setBigInt64(Number(h)+8,S%1000000n,!0)}return 0n},SYS_getrandom:(h,S)=>{const b=lt().subarray(Number(h),Number(h)+Number(S));return Wt(v(),Number(h),Number(S)),Hc(b),BigInt(b.byteLength)},...mt.imports(),...jt,...At.imports(),...pn,...J?J.imports({...pn,...bn}):bn,SYS_ioctl:(h,S,b)=>Ne.ioctl(Number(h),Number(S))??W.ioctl(Number(h),Number(S))??jt.SYS_ioctl(h,S,b),SYS_prctl:(h,...S)=>Number(h)!==Hs?0n:F?F.syscall("SYS_prctl",[h,...S]):gi.SYS_prctl(h,...S)},...e.imports};let Li=0;if(Zt.SYS_select??=Nc(v,(h,S,b)=>Zt.SYS_poll(h,S,b),()=>Li||=Number(mt.imports().SYS_mmap(0,Ec,3,34,-1,0))),M&&Pt)for(const[h,S]of Object.entries(Pt.ownedFileImports(Zt)))e.imports?.[h]||(Zt[h]=S);const An={};for(const h of a){const S=Zt[h.name]??Cc(h.name,e.onDiagnostic),b=(!F||M)&&Oc.has(h.name),A={calls:0,ms:0,sampled:b};w.set(h.name,A),An[h.name]=(...k)=>{e.onSyscall?.(h.name,k),M&&x.pump();const T=!b||(A.calls&Cs-1)===0,O=T?performance.now():0;try{const D=S(...k);return e.onSyscallResult?.(h.name,D),At.deliver(D===-4n),D}finally{A.calls+=1,T&&(A.ms+=(performance.now()-O)*(b?Cs:1))}}}const xi={...j?{memory:j}:{},_Unwind_Backtrace:()=>5,_Unwind_FindEnclosingFunction:h=>h,_Unwind_GetCFA:()=>0};if(N=await WebAssembly.instantiate(i,{wali:An,env:xi}),e.forkState){lt().set(new Uint8Array(e.forkState.memory));for(const[h,S]of Object.entries(e.forkState.globals)){const b=N.exports[h];if(!(b instanceof WebAssembly.Global))throw new Error(`Fork snapshot global ${h} is not exported.`);b.value=S}mt.restoreFork(e.forkState.mappings),jt.SYS_umask(e.forkState.umask)}else if(typeof N.exports.asyncify_start_unwind=="function"){const h=N.exports.__stack_pointer;if(!(h instanceof WebAssembly.Global))throw new Error("Asyncify fork requires --export=__stack_pointer at link.");const S=Number(h.value);if(S<=0)throw new Error("Asyncify fork requires a nonempty module stack.");Z=v().buffer.byteLength,v().grow(Math.ceil((S+8)/65536)),rt().setUint32(Z+4,Z+8+S,!0)}if(e.codec?.version===1)try{H=await an.create(v()),P=new gc(H.createChannel())}catch(h){console.warn("[WALI] the codec bridge is unavailable:",h),H=void 0,P=void 0}if(nr){if(!j)throw new Error("A threaded WALI module must be linked with --import-memory so browser workers can share its process memory.");const h=e.memoryLayout??(t instanceof WebAssembly.Module?void 0:Kr(t instanceof Uint8Array?t:new Uint8Array(t)));$=new ga({module:i,memory:j,onDemand:h?.passiveData===!0,mmapCursor:mt.allocatorControl(),sharedMmapRegistry:hn,fatalState:Rt.buffer,imports:o,size:ir,pid:m,executablePath:Ee,argv:f,cwd:W.currentWorkingDirectory(),stdioAliasRegistry:Mt.buffer,sharedPipes:Yt,signals:E,childPidAllocator:Et.buffer,...r?{inheritedFilesystemPolicy:r}:{},...e.browserProcessPorts?{browserProcessPorts:e.browserProcessPorts}:{},...e.browserProcess?.filesystemPolicyVersion===1?{childFilesystemPolicyVersion:1}:{},...e.threadOutputPorts?{outputPorts:e.threadOutputPorts}:{},...u instanceof Gr?{stdin:u.buffer}:{},terminal:e.terminal===!0,onStdout:S=>{Xt(1,S)},onStderr:S=>{Xt(2,S)},...U?{network:U}:{},...F?{filesystem:F}:{},...H?{codec:H}:{}}),await $.initialize()}const En=N.exports._start;if(typeof En!="function")throw new Error("WALI module does not export _start.");M&&x?.closePort(),g=performance.now();let Nn=0,lr=!1;try{try{for(xe&&Jt("asyncify_start_rewind",Z);En(),!!or;){Jt("asyncify_stop_unwind"),or=!1;const h=e.memoryLayout??(t instanceof WebAssembly.Module?void 0:Kr(t instanceof Uint8Array?t:new Uint8Array(t)));if(!h)throw new Error("Fork requires the module's imported memory layout.");const S={};for(const[O,D]of Object.entries(N.exports))if(D instanceof WebAssembly.Global)try{D.value=D.value,S[O]=D.value}catch{}const b=new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),A=new SharedArrayBuffer(jr);ke=Atomics.add(Et,0,1);const k=J.registerChild(ke,{control:b,response:A});if(k<0)throw new Error(`Fork child registration failed: ${k}`);const T=Number(jt.SYS_umask(0));jt.SYS_umask(T),e.onDiagnostic?.(`[WALI] fork snapshot: ${v().buffer.byteLength} bytes, Asyncify stack ${rt().getUint32(Z,!0)-Z-8} bytes.`),e.browserProcess.fork({module:i,memoryLayout:h,pid:ke,control:b,response:A,descriptorTable:F.copyForForkChannel(),childPidAllocator:Et.buffer,argv:f,env:{...e.env},cwd:ar(),executablePath:Ee,...n?{filesystemPolicy:n}:{},forkState:{control:b,response:A,memory:lt().slice().buffer,globals:S,allocator:mt.allocatorControl().slice(0),mappings:mt.forkSnapshot(),asyncifyData:Z,umask:T,parentPid:m}}),xe=!0,Jt("asyncify_start_rewind",Z)}}catch(h){if(h instanceof Ts)lr=!0;else if(h instanceof Fs||h instanceof Qs)Nn=h.code;else{if(h instanceof yi)throw h;{const S=h instanceof Error?h.stack??h.message:String(h),b=Atomics.load(Rt,1),A=$?.diagnostics(b>=0?b:void 0)??[];throw new Error(`${S}
|
|
9
|
+
`)}`]})}terminate(){this.coordinator?.terminate(),this.coordinator=void 0;for(const t of this.slots)t.worker?.terminate();this.slots.length=0}}function wa(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 Ot(s){const t=s.toBase64;if(typeof t=="function")return t.call(s);let e="";for(let r=0;r<s.byteLength;r+=32768)e+=String.fromCharCode(...s.subarray(r,r+32768));return btoa(e)}function me(s){const t=Uint8Array.fromBase64;if(typeof t=="function")return t(s);const e=atob(s),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r}function _a(s,t,e){const{appended:r,superseded:n}=e?Aa(s,t,e):{appended:new Map,superseded:new Set},i=[...t.removed].sort((a,c)=>We(c)-We(a));for(const a of i)s.existsSync(a)&&(s.statSync(a).isDirectory()?s.rmdirSync(a):s.unlinkSync(a));const o=[...t.files].filter(a=>!n.has(a.path)).sort((a,c)=>We(a.path)-We(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(be(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 l=s.existsSync(a.path)?s.statSync(a.path).mode:void 0,u=l!==void 0&&(l&128)===0;u&&s.chmodSync?.(a.path,l&4095|128),s.writeFileSync(a.path,r.get(a.path)??ge(a)),u&&a.mode===void 0&&s.chmodSync?.(a.path,l&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 Aa(s,t,e){const r=new Map,n=new Set,i=e.byPath,o=i instanceof Map?i:new Map(e.files.map(l=>[l.path,l])),a=new Map(t.files.map(l=>[l.path,l])),c=new Set([...t.files.map(l=>l.path),...t.removed]);for(const l of c){const u=o.get(l),f=Ia(s,l);if(u!==void 0&&Tr(u,a.get(l))||f===void 0&&a.get(l)!==void 0)continue;const d=a.get(l);if(!(f!==void 0&&d!==void 0&&d.type===f.type&&(Y(d).mtimeMs??0)>(Y(f).mtimeMs??0))&&!(u!==void 0&&f!==void 0&&u.type===f.type&&(Y(f).mtimeMs??0)<(Y(u).mtimeMs??0))&&!Tr(u,f)&&!Tr(a.get(l),f)){if(Na(u,f,a.get(l)))continue;const m=Ea(s,l,u,f,a.get(l),e.bytesOf?.bind(e));if(m){r.set(l,m);continue}const p=a.get(l);if(u!==void 0&&f!==void 0&&p!==void 0&&p.type===f.type&&(Y(p).mtimeMs??0)>=(Y(u).mtimeMs??0)&&(Y(f).mtimeMs??0)>(Y(p).mtimeMs??0)&&(Y(f).mtimeMs??0)>(Y(u).mtimeMs??0)){n.add(l);continue}throw new Error(`Browser filesystem write conflict at ${l}. ${JSON.stringify({base:Br(u),current:Br(f),proposed:Br(a.get(l))})}`)}}return{appended:r,superseded:n}}function Ea(s,t,e,r,n,i){if(e?.type!=="file"||r?.type!=="file"||n?.type!=="file"||!be(n)||!s.readFileSync||Y(r).mode!==Y(n).mode)return;const o=be(e)?ge(e):i?.(t);if(!o||o.length===0)return;const a=ge(n),c=s.readFileSync(t),l=typeof c=="string"?new TextEncoder().encode(c):c,u=d=>d.length>=o.length&&ri(d.subarray(0,o.length),o);if(a.length<=o.length||!u(a)||!u(l))return;const f=new Uint8Array(l.length+a.length-o.length);return f.set(l,0),f.set(a.subarray(o.length),l.length),f}function Br(s){return s?{type:s.type,...Y(s)}:null}function Na(s,t,e){return t?.type!=="directory"||e?.type!=="directory"?!1:s===void 0?Y(t).mode===Y(e).mode:Y(t).mode===Y(e).mode&&s.type==="directory"&&Y(s).mode===Y(t).mode}function We(s){let t=1;for(let e=0;e<s.length;e+=1)s.charCodeAt(e)===47&&(t+=1);return t}function Ia(s,t){if(!s.existsSync(t))return;const e=s.statSync(t),r={...e.mode!==void 0?{mode:e.mode}:{},...e.mtimeMs!==void 0?{mtimeMs:e.mtimeMs}:{}};return e.isDirectory()?{path:t,type:"directory",...r}:{path:t,type:"file",...e.size!==void 0?{size:e.size}:{},...r}}function Tr(s,t){return s===void 0?t===void 0:t!==void 0&&s.type===t.type&&La(s,t)&&Y(s).mode===Y(t).mode&&Y(s).mtimeMs===Y(t).mtimeMs}function Y(s){const t=s;return{...t.mode===void 0?{}:{mode:t.mode&4095},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs}}}function La(s,t){return s.type!=="file"||t.type!=="file"?!0:s.content!==void 0&&t.content!==void 0?s.content===t.content:be(s)&&be(t)?ri(ge(s),ge(t)):fs(s)===fs(t)}function fs(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 t=s.content.endsWith("==")?2:s.content.endsWith("=")?1:0;return Math.floor(s.content.length*3/4)-t}function be(s){return s!==void 0&&(s.bytes!==void 0||s.content!==void 0)}function ge(s){return s.bytes??(s.content===void 0?void 0:me(s.content))}function ri(s,t){if(s===t)return!0;if(s.byteLength!==t.byteLength)return!1;let e=0;if(s.byteOffset%4===0&&t.byteOffset%4===0){const r=s.byteLength>>>2,n=new Uint32Array(s.buffer,s.byteOffset,r),i=new Uint32Array(t.buffer,t.byteOffset,r);for(let o=0;o<r;o+=1)if(n[o]!==i[o])return!1;e=r<<2}for(;e<s.byteLength;e+=1)if(s[e]!==t[e])return!1;return!0}const ds=0,ms=1,ct=2,zt=3,Ht=4,ni=5,si=6,jr=16*1024*1024,xa=1024*1024;function ka(){const s=new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),t=new SharedArrayBuffer(xa),e=new Int32Array(s);return Atomics.store(e,zt,1),Atomics.store(e,Ht,1),{reader:{control:s,payload:t,role:"reader"},writer:{control:s,payload:t,role:"writer"}}}function ii(s){const t=Gt(s);return Atomics.add(t,s.role==="reader"?zt:Ht,1),s}function Se(s){const t=Gt(s),e=s.role==="reader"?zt:Ht;Atomics.sub(t,e,1)<=1&&Atomics.store(t,e,0),Atomics.add(t,s.role==="reader"?si:ni,1),Atomics.notify(t,ct)}function oi(s,t){const e=Gt(s),r=Atomics.load(e,ct);let n=0;return s.role==="reader"?(t&1&&(r>0||Atomics.load(e,Ht)===0)&&(n|=1),Atomics.load(e,Ht)===0&&(n|=16)):(t&4&&Atomics.load(e,zt)>0&&r<Ra(s)&&(n|=4),Atomics.load(e,zt)===0&&(n|=16)),n}function sn(s,t){if(s.role!=="reader")return-9n;if(t===0)return new Uint8Array;const e=Gt(s),r=ci(s),n=Atomics.load(e,ct);if(n===0)return Atomics.load(e,Ht)===0?new Uint8Array:-11n;const i=Math.min(Math.max(0,t),n),o=Atomics.load(e,ds),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(e,ds,(o+i)%r.byteLength),Atomics.sub(e,ct,i),i>0&&Atomics.add(e,si,1),Atomics.notify(e,ct),c}function Ma(s,t){const e=Gt(s);for(;;){const r=sn(s,t);if(r!==-11n)return r;Vt(e,ct,0,50)}}function ai(s,t){if(s.role!=="writer")return-9n;const e=Gt(s),r=ci(s);let n=0;for(;n<t.byteLength;){if(Atomics.load(e,zt)===0)return n>0?BigInt(n):-32n;const i=Atomics.load(e,ct),o=r.byteLength-i;if(o===0){Vt(e,ct,i,50);continue}const a=Atomics.load(e,ms),c=Math.min(t.byteLength-n,o,r.byteLength-a);r.set(t.subarray(n,n+c),a),Atomics.store(e,ms,(a+c)%r.byteLength),Atomics.add(e,ct,c),Atomics.add(e,ni,1),Atomics.notify(e,ct),n+=c}return BigInt(n)}const Ss=new WeakMap;function Gt(s){const t=s.controlOffset??0;let e=Ss.get(s.control);e||(e=new Map,Ss.set(s.control,e));let r=e.get(t);return r||(r=new Int32Array(s.control,t,8),e.set(t,r)),r}function Ra(s){return s.payloadLength??s.payload.byteLength-(s.payloadOffset??0)}function ci(s){const t=s.payloadOffset??0,e=s.payloadLength??s.payload.byteLength-t;return new Uint8Array(s.payload,t,e)}function va(s){const t=Atomics.load(new Int32Array(s.control),2);if(t<=0||t>s.response.byteLength)return;const e=Uint8Array.from(new Uint8Array(s.response,0,t));return JSON.parse(new TextDecoder().decode(e))}const Ya=1,Pa=15,Ba=1,Ta=97n,Fa=93n,Ca=11n,Da=32n,ys=1,ps=4,Ua=16;class Wa{memory;descriptors;constructor(t,e){this.memory=t,this.descriptors=e}imports(){return{SYS_socketpair:(t,e,r,n)=>this.socketpair(Number(t),Number(e),Number(r),Number(n)),SYS_pipe:t=>this.pipe(Number(t),0),SYS_pipe2:(t,e)=>this.pipe(Number(t),Number(e))}}pipe(t,e){if((e&-526337)!==0)return-22n;if(!Number.isSafeInteger(t)||t<0||t+8>this.memory().buffer.byteLength)return-14n;const r=ka(),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(t,n,!0),o.setInt32(t+4,i,!0),0n}pipeEndpoint(t){return{browserProcessPipe:t,read:e=>sn(t,e),write:e=>ai(t,e),poll:e=>oi(t,e),fcntl:e=>e===3?0x800n:[1,2,4].includes(e)?0n:-22n,duplicate:e=>(ii(t),BigInt(this.descriptors.allocateSpecial(this.pipeEndpoint(t),e))),close:()=>Se(t)}}socketpair(t,e,r,n){if(t!==Ya)return-Ta;if((e&Pa)!==Ba||r!==0)return-Fa;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)),l=new DataView(this.memory().buffer);return l.setInt32(n,a,!0),l.setInt32(n+4,c,!0),0n}endpoint(t){return{read:e=>Oa(t,e),write:e=>$a(t,e),poll:e=>Va(t,e),fcntl:e=>e===3?0x802n:[1,2,4].includes(e)?0n:-22n,duplicate:e=>{const r=this.descriptors.allocateSpecial(this.endpoint(t),e);return t.references+=1,BigInt(r)},close:()=>{t.references-=1,!(t.references>0||t.closed)&&(t.closed=!0,t.peer&&(t.peer.peerClosed=!0))}}}}function Oa(s,t){if(s.closed)return-9n;if(t<0)return-22n;if(s.byteLength===0)return s.peerClosed?new Uint8Array:-Ca;const e=new Uint8Array(Math.min(t,s.byteLength));let r=0;for(;r<e.byteLength;){const n=s.chunks[0],i=Math.min(n.byteLength,e.byteLength-r);e.set(n.subarray(0,i),r),r+=i,s.byteLength-=i,i===n.byteLength?s.chunks.shift():s.chunks[0]=n.subarray(i)}return e}function $a(s,t){if(s.closed)return-9n;const e=s.peer;if(!e||e.closed)return-Da;const r=t.slice();return e.chunks.push(r),e.byteLength+=r.byteLength,BigInt(r.byteLength)}function Va(s,t){let e=s.peerClosed?Ua:0;return t&ys&&(s.byteLength>0||s.peerClosed)&&(e|=ys),t&ps&&!s.peerClosed&&(e|=ps),e}const za=2e4,li=256*1024;var I;(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"})(I||(I={}));const Fr=new Map;function ui(s,t){const e=Fr.get(s);Fr.delete(s);const r=e??t();return Fr.set(s,t()),r}const yt=9n,C=22n,bs=16,ut=38n;class on{worker;constructor(t){this.worker=t}static async create(t,e,r,n,i){if(typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("WALI networking requires Web Workers and SharedArrayBuffer.");const o=[...new Set(t?.allowedHosts.map(l=>l.toLowerCase())??[])];if(t&&(!t.loopbackPort&&o.length===0||o.some(l=>!/^[a-z0-9.-]+$/u.test(l))))throw new Error("WALI networking requires a loopback attachment or at least one valid hostname.");if(t&&(!Number.isSafeInteger(t.maxConnections)||t.maxConnections<1||t.maxConnections>1024||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1024||t.maxBytes>1024*1024*1024))throw new Error("WALI networking requires bounded connection and byte quotas.");const a=ui("network",()=>pe(new Worker(new URL("/assets/network-worker-DuuxEt8T.js",import.meta.url),{type:"module",name:"wali-network"}))),c=new on(a);return await new Promise((l,u)=>{const f=d=>{d.data.kind==="ready"&&(a.removeEventListener("message",f),l()),d.data.kind==="error"&&(a.removeEventListener("message",f),u(new Error(d.data.message)))};a.addEventListener("message",f),a.addEventListener("error",d=>u(d.error??new Error(d.message)),{once:!0}),a.postMessage({kind:"initialize",allowedHosts:o,relayUrl:t?.relayUrl??"/api/wali/tcp",maxConnections:t?.maxConnections??0,maxBytes:t?.maxBytes??0,...e?{sharedPipes:e}:{},...r?{stdin:r}:{},...n?{stdioAliasRegistry:n}:{},...i?{signals:i}:{},...t?.loopbackPort?{loopbackPort:t.loopbackPort}:{}},t?.loopbackPort?[t.loopbackPort]:[])}).catch(l=>{throw a.terminate(),l}),c}createChannel(){const t=new MessageChannel,e={port:t.port1,control:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*16),payload:new SharedArrayBuffer(li)};return this.worker.postMessage({kind:"attach",port:t.port2,control:e.control,payload:e.payload},[t.port2]),e.port.start(),e}terminate(){this.worker.terminate()}}class Ha{channel;control;payload;nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload)}call(t,e=[],r,n){if((r?.byteLength??0)>this.payload.byteLength)return{result:-Number(C),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,t),Atomics.store(this.control,3,r?.byteLength??0),e.slice(0,10).forEach((u,f)=>Atomics.store(this.control,5+f,u|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 u=Atomics.load(this.control,0);if(u===i+1)break;if(u!==i&&u!==-i)throw new Error(`Invalid WALI network RPC state ${u} for request ${i}.`);const f=Math.max(0,o-Date.now());if(f===0&&u===i&&Atomics.compareExchange(this.control,0,i,0)===i)return{result:-110,output:new Uint8Array};try{Vt(this.control,0,u,u===-i?void 0:f)}catch{if(Atomics.compareExchange(this.control,0,i,0)===i)return{result:-Number(ut),output:new Uint8Array}}}const a=Atomics.load(this.control,2),c=Atomics.load(this.control,4),l=this.payload.slice(0,Math.max(0,c));return Atomics.store(this.control,0,0),{result:a,output:l}}}class Ga{memory;signals;client;waitBuffer;constructor(t,e,r){this.memory=t,this.signals=r,this.client=new Ha(e)}isNetworkFd(t){return t>=za&&!K(t)}registerChild(t,e){return this.client.call(I.ChildRegister,[t],void 0,e).result}forgetChild(t){this.client.call(I.ChildForget,[t])}hasChild(t){return this.client.call(I.ChildExists,[t]).result===1}waitChild(t,e,r=0n){const n=this.waitBuffer??={control:new SharedArrayBuffer(32),response:new SharedArrayBuffer(jr)};return{result:this.client.call(I.ChildWait,[t,e,Number(r&0xffffffffn),Number(r>>32n)],void 0,n).result,process:n}}imports(t={}){const e=(r,n)=>t[r]?.(...n)??-ut;return{SYS_pidfd_open:(r,n)=>BigInt(this.client.call(I.PidFdOpen,[Number(r),Number(n)]).result),SYS_dup:r=>this.isNetworkFd(Number(r))?BigInt(this.client.call(I.Duplicate,[Number(r)]).result):t.SYS_dup?.(r)??-ut,SYS_socket:(r,n,i)=>BigInt(this.client.call(I.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),()=>e("SYS_bind",[r,n,i])),SYS_listen:(r,n)=>this.networkOr(Number(r),()=>this.client.call(I.Listen,[Number(r),Number(n)]).result,()=>e("SYS_listen",[r,n])),SYS_accept:(r,n,i)=>this.accept(Number(r),Number(n),Number(i),0,()=>e("SYS_accept",[r,n,i])),SYS_accept4:(r,n,i,o)=>this.accept(Number(r),Number(n),Number(i),Number(o),()=>e("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(I.Shutdown,[Number(r),Number(n)]).result,()=>e("SYS_shutdown",[r,n])),SYS_setsockopt:(r,n,i,o,a)=>this.isNetworkFd(Number(r))?0n:e("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(I.Close,[Number(r)]).result):t.SYS_close?.(r)??-ut,SYS_read:(r,n,i)=>this.isNetworkFd(Number(r))?this.receive(Number(r),Number(n),Number(i),0):t.SYS_read?.(r,n,i)??-ut,SYS_write:(r,n,i)=>this.isNetworkFd(Number(r))?this.send(Number(r),Number(n),Number(i),0):t.SYS_write?.(r,n,i)??-ut,SYS_readv:(r,n,i)=>this.isNetworkFd(Number(r))?this.readv(Number(r),Number(n),Number(i)):t.SYS_readv?.(r,n,i)??-ut,SYS_writev:(r,n,i)=>this.isNetworkFd(Number(r))?this.writev(Number(r),Number(n),Number(i)):t.SYS_writev?.(r,n,i)??-ut,SYS_fcntl:(r,n,i)=>this.isNetworkFd(Number(r))?BigInt(this.client.call(I.Fcntl,[Number(r),Number(n),Xa(i)]).result):t.SYS_fcntl?.(r,n,i)??-ut,SYS_poll:(r,n,i)=>this.poll(Number(r),Number(n),Number(i),()=>e("SYS_poll",[r,n,0])),SYS_epoll_create:r=>Number(r)>0?BigInt(this.client.call(I.EpollCreate).result):-C,SYS_epoll_create1:()=>BigInt(this.client.call(I.EpollCreate).result),SYS_eventfd:r=>BigInt(this.client.call(I.EventFd,[Number(r),0]).result),SYS_eventfd2:(r,n)=>BigInt(this.client.call(I.EventFd,[Number(r),Number(n)]).result),SYS_timerfd_create:(r,n)=>BigInt(this.client.call(I.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),()=>e("SYS_epoll_ctl",[r,n,i,o])),SYS_epoll_wait:(r,n,i,o)=>this.epollWait(Number(r),Number(n),Number(i),Number(o),()=>e("SYS_epoll_wait",[r,n,i,o])),SYS_epoll_pwait:(r,n,i,o,a,c)=>{const l=()=>this.epollWait(Number(r),Number(n),Number(i),Number(o),()=>e("SYS_epoll_pwait",[r,n,i,o,a,c]));if(!a)return l();if(!this.signals)return-38n;const u=this.signals.mask,f=this.signals.imports().SYS_rt_sigprocmask(2,a,0,c);if(f!==0n)return f;try{const d=l();return this.signals.deliver(d===-4n),d}finally{this.signals.mask=u}}}}pollFd(t,e){return this.isNetworkFd(t)?this.client.call(I.Poll,[t,e]).result:32}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}copy(t,e){if(t<0||e<0||t+e>this.bytes().byteLength)throw new WebAssembly.RuntimeError("WALI network memory access is out of bounds.");return this.bytes().slice(t,t+e)}networkOr(t,e,r){return this.isNetworkFd(t)?BigInt(e()):r()}withAddress(t,e,r){return this.isNetworkFd(t)?BigInt(this.client.call(I.Connect,[t],this.copy(e,r)).result):-yt}bind(t,e,r,n){return this.isNetworkFd(t)?BigInt(this.client.call(I.Bind,[t],this.copy(e,r)).result):n()}accept(t,e,r,n,i){if(!this.isNetworkFd(t))return i();if(e!==0&&(r<=0||r+4>this.bytes().byteLength))return-C;const o=e===0?0:this.view().getUint32(r,!0);if(e!==0&&(e<0||e+o>this.bytes().byteLength))return-C;const{result:a,output:c}=this.client.call(I.Accept,[t,n]);return a<0||e===0||(this.bytes().set(c.subarray(0,o),e),this.view().setUint32(r,c.byteLength,!0)),BigInt(a)}socketPair(t,e,r,n){const{result:i,output:o}=this.client.call(I.SocketPair,[t,e,r]);if(i===0){if(n<0||n+8>this.bytes().byteLength)return-C;this.bytes().set(o,n)}return BigInt(i)}setTimerFd(t,e,r,n){if(!this.isNetworkFd(t)||r<0||r+32>this.bytes().byteLength)return-yt;const{result:i,output:o}=this.client.call(I.TimerFdSetTime,[t,e],this.copy(r,32));if(i===0&&n!==0){if(n<0||n+32>this.bytes().byteLength||o.byteLength!==32)return-C;this.bytes().set(o,n)}return BigInt(i)}send(t,e,r,n){return this.isNetworkFd(t)?BigInt(this.client.call(I.Send,[t,n],this.copy(e,r)).result):-yt}receive(t,e,r,n){if(!this.isNetworkFd(t))return-yt;const{result:i,output:o}=this.client.call(I.Receive,[t,r,n]);return i>0&&this.bytes().set(o.subarray(0,i),e),BigInt(i)}receiveFrom(t,e,r,n,i,o){const a=this.receive(t,e,r,n);if(a<0n||i===0||o===0)return a;if(o<0||o+4>this.bytes().byteLength)return-C;const c=this.view().getUint32(o,!0);return this.writeDnsPeer(i,c)?(this.view().setUint32(o,16,!0),a):-C}sendMessage(t,e,r){if(!this.isNetworkFd(t)||e<0||e+28>this.bytes().byteLength)return-yt;const n=this.view().getUint32(e+8,!0),i=this.view().getUint32(e+12,!0);if(i>1024)return-C;const o=[];let a=0;for(let u=0;u<i;u+=1){const f=n+u*8,d=this.copy(this.view().getUint32(f,!0),this.view().getUint32(f+4,!0));o.push(d),a+=d.byteLength}const c=new Uint8Array(a);let l=0;for(const u of o)c.set(u,l),l+=u.byteLength;return BigInt(this.client.call(I.Send,[t,r],c).result)}receiveMessage(t,e,r){if(!this.isNetworkFd(t)||e<0||e+28>this.bytes().byteLength)return-yt;const n=this.view().getUint32(e+8,!0),i=this.view().getUint32(e+12,!0);if(i>1024)return-C;let o=0;for(let d=0;d<i;d+=1)o+=this.view().getUint32(n+d*8+4,!0);const{result:a,output:c}=this.client.call(I.Receive,[t,o,r]);if(a<=0)return BigInt(a);let l=0;for(let d=0;d<i&&l<a;d+=1){const m=n+d*8,p=this.view().getUint32(m,!0),y=Math.min(this.view().getUint32(m+4,!0),a-l);this.bytes().set(c.subarray(l,l+y),p),l+=y}const u=this.view().getUint32(e,!0),f=this.view().getUint32(e+4,!0);return u!==0&&this.writeDnsPeer(u,f)&&this.view().setUint32(e+4,16,!0),this.view().setUint32(e+20,0,!0),this.view().setInt32(e+24,0,!0),BigInt(a)}writeDnsPeer(t,e){return e<16||t<0||t+16>this.bytes().byteLength?!1:(this.bytes().fill(0,t,t+16),this.view().setUint16(t,2,!0),this.view().setUint16(t+2,53,!1),this.bytes().set([127,0,0,1],t+4),!0)}getSocketOption(t,e,r){return this.isNetworkFd(t)?r<=0||r+4>this.bytes().byteLength||this.view().getUint32(r,!0)<4||e<0||e+4>this.bytes().byteLength?-C:(this.view().setInt32(e,0,!0),this.view().setUint32(r,4,!0),0n):-yt}getSocketName(t,e,r){if(!this.isNetworkFd(t))return-yt;if(r<0||r+4>this.bytes().byteLength)return-C;const n=this.view().getUint32(r,!0),{result:i,output:o}=this.client.call(I.SocketName,[t]);return i<0?BigInt(i):n<o.byteLength||e<0||e+o.byteLength>this.bytes().byteLength?-C:(this.bytes().set(o,e),this.view().setUint32(r,o.byteLength,!0),0n)}writev(t,e,r){if(r<0||r>1024)return-C;const n=[];let i=0;for(let c=0;c<r;c+=1){const l=e+c*8,u=this.copy(this.view().getUint32(l,!0),this.view().getUint32(l+4,!0));n.push(u),i+=u.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(I.Send,[t,0],o).result)}readv(t,e,r){if(r<0||r>1024)return-C;let n=0;for(let c=0;c<r;c+=1)n+=this.view().getUint32(e+c*8+4,!0);const{result:i,output:o}=this.client.call(I.Receive,[t,n,0]);if(i<=0)return BigInt(i);let a=0;for(let c=0;c<r&&a<i;c+=1){const l=e+c*8,u=this.view().getUint32(l,!0),f=Math.min(this.view().getUint32(l+4,!0),i-a);this.bytes().set(o.subarray(a,a+f),u),a+=f}return BigInt(i)}poll(t,e,r,n){if(e<0||e>li/8)return-C;this.copy(t,e*8),n();const i=this.signals?.mask??0n,{result:o,output:a}=this.client.call(I.PollMany,[r,Number(i&0xffffffffn),Number(i>>32n)],this.copy(t,e*8));return o>=0&&this.bytes().set(a,t),BigInt(o)}epollControl(t,e,r,n,i){if(!this.isNetworkFd(t)&&!this.isNetworkFd(r))return i();const o=e===2?void 0:this.copy(n,bs);return BigInt(this.client.call(I.EpollControl,[t,e,r],o).result)}epollWait(t,e,r,n,i){if(r<=0)return-C;const o=this.signals?.mask??0n,{result:a,output:c}=this.client.call(I.EpollWait,[t,r,n,Number(o&0xffffffffn),Number(o>>32n)]);return a===-9?i():(a>0&&this.bytes().set(c.subarray(0,a*bs),e),BigInt(a))}}function Xa(s){return typeof s=="bigint"?Number(BigInt.asIntN(32,s)):s|0}const gs=-4,Cr=3;class tt{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder("utf-8",{fatal:!0});nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload)}static waited={calls:0,ms:0};request(t){const e=performance.now();try{return this.requestNow(t)}finally{tt.waited.calls+=1,tt.waited.ms+=performance.now()-e}}requestNow(t){if(Atomics.load(this.control,Cr))return{result:gs};const e=this.encoder.encode(JSON.stringify(t));if(e.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,Cr),this.payload.set(e),Atomics.store(this.control,1,e.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,Cr))return{result:gs};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 Jr{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder;nextRequestId=1;bell;wakeMemory;directSyscall(t){const e=this.channel.local;if(!(!e||t==="SYS_flock"||t==="SYS_fcntl"))return r=>{const{imports:n,errno:i}=e.handlers(),o=n[t];if(!o)throw at(-38);let a;try{a=o(...r)}catch(c){throw at(i(c))}return typeof a=="bigint"?a:BigInt(a??0)}}ownsLocalFile(t){const e=this.channel.local;return e!==void 0&&e.handlers().owns(t)}localHandlers(){const t=this.channel.local;return t?()=>t.handlers():void 0}wakeThrough(t){this.wakeMemory=t}constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload),this.bell=t.doorbell?new Int32Array(t.doorbell):void 0}attachMemory(t){this.channel.port.postMessage({memory:t})}copyForExec(t){return this.call(L.CopyForExec,{stdio:t}).process}currentWorkingDirectory(){return this.call(L.GetCwd)}copyForForkChannel(){return this.createChannel(de,this.call(L.CopyForFork).process)}createChannel(t,e){const r=je(t),n=this.channel.sharedPipes&&{...this.channel.sharedPipes,table:e===void 0?this.channel.sharedPipes.table:new SharedArrayBuffer(65536*4)},i=e===void 0?void 0:new MessageChannel,o={...r.server,...e===void 0?{}:{process:e},...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(t){return this.createChannel(de,this.copyForExec(t))}closeProcess(){this.call(L.CloseProcess)}existsSync(t){return this.call(L.Exists,{path:t})}statSync(t){return _s(this.call(L.Stat,{path:t}))}lstatSync(t){return _s(this.call(L.Lstat,{path:t}))}readFileSync(t){const e=this.statSync(t).size;if(e<=z)return me(this.call(L.ReadFile,{path:t}).content);const r=new Uint8Array(e);for(let n=0;n<e;n+=z){const i=this.readRangeSync(t,n,Math.min(z,e-n));if(r.set(i,n),i.byteLength<Math.min(z,e-n))return r.subarray(0,n+i.byteLength)}return r}async readFile(t){return this.readFileSync(t)}readRangeSync(t,e,r){const n=new Uint8Array(r);let i=0;for(;i<r;){const o=Math.min(z,r-i),a=me(this.call(L.ReadRange,{path:t,offset:e+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(t,e,r){for(let n=0;(n<r.byteLength||n===0&&r.byteLength===0)&&(this.call(L.WriteRange,{path:t,offset:e+n,content:Ot(r.subarray(n,n+z))}),r.byteLength!==0);n+=z);}writeFileSync(t,e){const r=typeof e=="string"?this.encoder.encode(e):e;if(r.byteLength<=z){this.call(L.WriteFile,{path:t,content:Ot(r)});return}this.call(L.WriteFile,{path:t,content:""}),this.writeRangeSync(t,0,r)}mkdirSync(t,e){this.call(L.Mkdir,{path:t,recursive:e?.recursive===!0})}readdirSync(t){return this.call(L.Readdir,{path:t})}unlinkSync(t){this.call(L.Unlink,{path:t})}rmdirSync(t){this.call(L.Rmdir,{path:t})}renameSync(t,e){this.call(L.Rename,{from:t,to:e})}toSnapshot(){return JSON.parse(this.decoder.decode(this.readChunked(L.SnapshotSize)))}finalSnapshot(){return JSON.parse(this.decoder.decode(this.readChunked(L.FinalSnapshotSize)))}readChunked(t){const{length:e}=this.call(t);if(!Number.isSafeInteger(e)||e<0)throw at(-5);const r=new Uint8Array(e);for(let n=0;n<e;n+=z){const i=Math.min(z,e-n),{content:o}=this.call(L.SnapshotChunk,{offset:n,length:i}),a=me(o);if(a.byteLength!==i)throw at(-5);r.set(a,n)}return r}prepareSpawn(){this.call(L.PrepareSpawn)}importPeerPatch(t){const e=this.encoder.encode(JSON.stringify(t));this.call(L.ImportPeerPatchStart,{length:e.byteLength});for(let r=0;r<e.byteLength;r+=z)this.call(L.ImportPeerPatchChunk,{offset:r,content:Ot(e.subarray(r,r+z))})}replaceSnapshot(t){const e=this.encoder.encode(JSON.stringify(t));this.call(L.ReplaceSnapshotStart,{length:e.byteLength});for(let r=0;r<e.byteLength;r+=z){const n=e.subarray(r,r+z);this.call(L.ReplaceSnapshotChunk,{offset:r,content:Ot(n)})}}syscall(t,e){const r=this.channel.local;if(r)for(;;){const o=r.syscall(t,e);if(typeof o=="bigint")return o;if(o!==void 0)throw at(o.failed);const a=performance.now();r.idle(),tt.waited.ms+=performance.now()-a}let n=this.names.get(t);n||(n=this.encoder.encode(t),this.names.set(t,n));const i=this.view??=new DataView(this.payload.buffer,this.payload.byteOffset,this.payload.byteLength);this.payload[0]=e.length,this.payload[1]=n.byteLength;for(let o=0;o<e.length;o+=1)i.setBigInt64(8+o*8,BigInt(e[o]),!0);return this.payload.set(n,8+e.length*8),this.exchange(L.SyscallBinary,8+e.length*8+n.byteLength,Ka(t,e)||this.bell?null:3e4),i.getBigInt64(0,!0)}names=new Map;lastResult=0;view;readForMapping(t,e,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,t,!0),i.setFloat64(8,e+o,!0),i.setInt32(16,a,!0);const c=this.exchange(L.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(t){return this.call(L.MappingPath,{fd:t}).path}writeForMapping(t,e,r){const n=this.encoder.encode(t);if(16+n.byteLength+r.byteLength>this.payload.byteLength)return this.call(L.WriteForMapping,{path:t,offset:e,content:Ot(r)}).written;const i=this.view??=new DataView(this.payload.buffer,this.payload.byteOffset,this.payload.byteLength);return i.setFloat64(0,e,!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(L.WriteForMappingBinary,16+n.byteLength+r.byteLength,3e4),this.payload[0]===1}call(t,e={},r=3e4){const n=this.encoder.encode(JSON.stringify(e));if(n.byteLength>this.payload.byteLength)throw at(-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(t,n.byteLength,r);return i>0?JSON.parse(this.decoder.decode(this.payload.slice(0,i))):void 0}exchange(t,e,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,t),Atomics.store(this.control,3,e),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 l=Atomics.load(this.bell,1);l!==0&&this.wakeMemory&&Atomics.notify(new Int32Array(this.wakeMemory.buffer),l-1)}else this.channel.port.postMessage(n);const o=r===null?void 0:Date.now()+r;for(;;){const l=Atomics.load(this.control,0);if(l===n+1)break;if(l!==n&&l!==-n)throw new Error(`Invalid WALI filesystem RPC state ${l} for request ${n}.`);const u=o===void 0?void 0:Math.max(0,o-Date.now());if(u===0&&l===n&&Atomics.compareExchange(this.control,0,n,0)===n)throw at(-110);Atomics.wait(this.control,0,l,l===-n?void 0:u)}const a=Atomics.load(this.control,2),c=Atomics.load(this.control,4);if(Atomics.store(this.control,0,0),a<0)throw at(a);return this.lastResult=a,c}}function Ka(s,t){if(s==="SYS_flock"){const r=Number(t[1]??0);return(r&4)===0&&(r&8)===0}if(s!=="SYS_fcntl")return!1;const e=Number(t[1]??0);return e===7||e===38}const ja=5;class we{sink;root;sharedPipes;constructor(t,e,r){this.sink=t,this.root=e,this.sharedPipes=r}static async createInThread(t,e){const r=await import("./filesystem-host-DiM0ruXt.js"),n=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),i=new Int32Array(n);r.hostInThread(n),await r.initializeHost({kind:"initialize",snapshot:t,...e});const o=je(de),a=r.attachChannel({...o.server,...e.sharedPipes?{sharedPipes:e.sharedPipes}:{}}),c=new Jr({...o.client,...e.sharedPipes?{sharedPipes:e.sharedPipes}:{},local:{doorbell:n,serveNow:()=>r.serveNow(a),attach:u=>{r.attachChannel(u)},syscall:(u,f)=>r.syscallNow(a,u,f),handlers:()=>r.handlersNow(a),idle:()=>{r.pumpHost(!0),Atomics.wait(i,0,Atomics.load(i,0),ja)}}}),l={attach:u=>{r.attachChannel(u)},terminate:()=>r.resetHost(),doorbell:n,host:r};return new we(l,c,e.sharedPipes)}closePort(){this.sink.host?.closeHostPort()}pump(t=!1){(this.sink.host?.hostWaiting()||t)&&this.sink.host?.pumpHost(t)}doorbell(){return this.sink.doorbell?new Int32Array(this.sink.doorbell):void 0}static async create(t,e){const r=ui("filesystem",()=>pe(new Worker(new URL("/assets/filesystem-worker-B_zvdiVO.js",import.meta.url),{type:"module",name:"wali-filesystem"})));await new Promise((o,a)=>{const c=u=>{u.data.kind==="ready"&&(r.removeEventListener("message",c),o()),u.data.kind==="error"&&(r.removeEventListener("message",c),a(new Error(u.data.message)))};r.addEventListener("message",c),r.addEventListener("error",u=>a(u.error??new Error(u.message)),{once:!0});const l=[...e.updatePort?[e.updatePort]:[],...e.fileLocks?[e.fileLocks.channel.port]:[],...e.fileCoherence?[e.fileCoherence.port]:[]];r.postMessage({kind:"initialize",snapshot:t,...e},l)});const n=je(de);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 we(i,new Jr({...n.client,...e.sharedPipes?{sharedPipes:e.sharedPipes}:{}}),e.sharedPipes)}createChannel(t,e=0){const r=je(t),n=this.sharedPipes&&{...this.sharedPipes,table:e===0?this.sharedPipes.table:new SharedArrayBuffer(65536*4)};return this.sink.attach({process:e,...r.server,...n?{sharedPipes:n}:{}},[r.server.port]),{...r.client,...n?{sharedPipes:n}:{},...this.sink.doorbell?{doorbell:this.sink.doorbell}:{}}}copyForExec(){return this.createChannel(de,this.root.copyForExec())}filesystem(){return this.root}snapshot(){return this.root.toSnapshot()}finalSnapshot(){return this.root.finalSnapshot()}replaceSnapshot(t){this.root.replaceSnapshot(t)}terminate(){this.sink.terminate()}}const le=1e4,Ja=new Set([5,6,7,36,37,38]),Za=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"]),ws=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 Qa{client;stdioAliasRegistry;descriptorState;memory;constructor(t,e,r,n){this.client=t,this.stdioAliasRegistry=e,this.descriptorState=r,this.memory=n}poll(t,e,r,n){const i=this.memory?.();if(!i||!Number.isSafeInteger(r)||r<=0||e<0||e+r*8>i.buffer.byteLength)return t(e,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(),l=new Map;let u=new DataView(i.buffer);for(let g=0;g<r;g+=1){const w=u.getInt32(e+g*8,!0);if(w<3||w>=le&&!K(w))continue;const E=this.stdioAliasRegistry&&w<this.stdioAliasRegistry.length?Atomics.load(this.stdioAliasRegistry,w):-1;if(E===0||E===1||E===2||o&&a&&Atomics.load(a,Atomics.load(o,w)*3+2))continue;const N=c?c().owns(w):Number(this.client.syscall("SYS_fcntl",[w,1,0]))>=0;l.set(g,N?u.getInt16(e+g*8+4,!0)&4:32)}if(l.size===0)return t(e,r,n);const f=[...l.values()].filter(g=>g!==0).length,d=new Uint8Array(i.buffer,e,r*8).slice(),m=[];for(let g=0;g<r;g+=1)l.has(g)||m.push(g);const p=new Uint8Array(i.buffer);m.forEach((g,w)=>p.set(d.subarray(g*8,g*8+8),e+w*8));let y;try{y=t(e,m.length,f?0:n)}finally{const g=new Uint8Array(i.buffer,e,m.length*8).slice();new Uint8Array(i.buffer).set(d,e),u=new DataView(i.buffer),m.forEach((w,E)=>u.setInt16(e+w*8+6,g[E*8+6]|g[E*8+7]<<8,!0));for(const[w,E]of l)u.setInt16(e+w*8+6,E,!0)}return typeof y!="bigint"&&typeof y!="number"||Number(y)<0?y:BigInt(Number(y)+f)}ownedFileImports(t){const e={};for(const r of ws){const n=r==="SYS_fcntl",i=n?void 0:this.client.directSyscall(r),o=t[r];if(!i&&!n||!o||r==="SYS_flock")continue;const a=this.client.localHandlers();a&&(e[r]=(...c)=>{const l=Number(c[0]);if(l<3||l>=le&&!K(l)||n&&Ja.has(Number(c[1])))return o(...c);const{imports:u,errno:f,owns:d}=a();if(!d(l))return o(...c);const m=u[r];if(!m)throw at(-38);let p;try{p=m(...c)}catch(y){throw at(f(y))}return typeof p=="bigint"?p:BigInt(p??0)})}return e}imports(t){const e={};for(const o of Za){const a=this.client.directSyscall(o);e[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 ws){const a=this.client.directSyscall(o),c=o==="SYS_read"||o==="SYS_readv"||o==="SYS_write"||o==="SYS_writev"||o==="SYS_fstat",l=o==="SYS_write"||o==="SYS_writev",u=o==="SYS_pread64"||o==="SYS_pwrite64"||o==="SYS_preadv"||o==="SYS_pwritev";e[o]=(...f)=>{const d=Number(f[0]);if(r&&n&&d>=0&&(d<2e4||K(d))){const p=Atomics.load(r,d),y=Atomics.load(n,p*3+2);return y&&u?-29n:y&&c?(l&&this.client.prepareSpawn(),t[o]?.(...f)??-9n):a?a(f):this.client.syscall(o,f)}const m=this.stdioAliasRegistry&&d>=0&&d<this.stdioAliasRegistry.length?Atomics.load(this.stdioAliasRegistry,d):-1;return d<3||d>=le&&!K(d)||m===0||m===1||m===2?((o==="SYS_write"||o==="SYS_writev")&&this.client.prepareSpawn(),t[o]?.(...f)??-9n):a?a(f):this.client.syscall(o,f)}}const i=t.SYS_poll;return this.memory&&i&&(e.SYS_poll=(o,a,c)=>this.poll(i,Number(o),Number(a),Number(c))),{...t,...e}}readForMapping(t,e,r){if(!(t<3||t>=le&&!K(t)))return this.client.readForMapping(t,e,r)}mappingPath(t){if(!(t<3||t>=le&&!K(t)))return this.client.mappingPath(t)}writeForMapping(t,e,r){return this.client.writeForMapping(t,e,r)}}function je(s){const t=new MessageChannel,e=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*8),r=new SharedArrayBuffer(s);return t.port1.start(),{client:{port:t.port1,control:e,payload:r},server:{port:t.port2,control:e,payload:r}}}function _s(s){return{isFile:()=>s.file,isDirectory:()=>s.directory,isSymbolicLink:()=>s.symbolicLink===!0,size:s.size,...qa(s,"mode","mtimeMs","atimeMs","ctimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks")}}function qa(s,...t){return Object.fromEntries(t.flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}function at(s){const t={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(t),{code:t})}const As=1e4,tc=19999,Dr=64,Zr=64*1024,Je=8,Es=3,Ns=4,Ur=2048,Wr=524288,ec=0,rc=1,nc=2,sc=3,ic=4,Is=1030,oc=1,ac=4096;function cc(s=new _e(new en)){const t={table:s.sharedEntries.buffer,descriptions:s.registry.pipeMetadata.buffer,slots:new SharedArrayBuffer(Dr*Int32Array.BYTES_PER_ELEMENT),controls:new SharedArrayBuffer(Dr*Je*Int32Array.BYTES_PER_ELEMENT),payloads:new SharedArrayBuffer(Dr*Zr)};return hi.set(t.table,s),t}const hi=new WeakMap,Ls=new WeakMap;let Qr,qr;function lc(s,t){if(!Number.isSafeInteger(t)||t<0||t>=65536)return 0;let e=s===Qr?qr:Ls.get(s);e||(e={table:new Int32Array(s.table),descriptions:new Int32Array(s.descriptions)},Ls.set(s,e)),Qr=s,qr=e;const r=Atomics.load(e.table,t);return Atomics.load(e.descriptions,r*3)}function uc(){Qr=void 0,qr=void 0}class hc{memory;state;remote;table;slots;constructor(t,e,r,n){this.memory=t,this.state=e,this.remote=n,this.table=r??hi.get(e.table),this.slots=new Int32Array(e.slots)}isPipeFd(t){return this.entry(t)!==0}exportBrowserProcessPipe(t){const e=this.entry(t);return e===0?void 0:this.handle(e)}pollDescriptor(t,e){const r=this.entry(t);return r===0?void 0:oi(this.handle(r),e)}ioctl(t,e){if(this.isPipeFd(t))return e===21537||e===21585||e===21584?0n:-25n}imports(t={}){const e=(n,i)=>t[n]?.(...i)??-38n,r={...t,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)):t.SYS_close?.(n)??-38n,SYS_read:(n,i,o)=>this.isPipeFd(Number(n))?this.read(Number(n),Number(i),Number(o)):t.SYS_read?.(n,i,o)??-38n,SYS_pread64:(n,i,o,a)=>this.isPipeFd(Number(n))?-29n:t.SYS_pread64?.(n,i,o,a)??-38n,SYS_write:(n,i,o)=>this.isPipeFd(Number(n))?this.write(Number(n),Number(i),Number(o)):t.SYS_write?.(n,i,o)??-38n,SYS_pwrite64:(n,i,o,a)=>this.isPipeFd(Number(n))?-29n:t.SYS_pwrite64?.(n,i,o,a)??-38n,SYS_preadv:(n,i,o,a,c)=>this.isPipeFd(Number(n))?-29n:t.SYS_preadv?.(n,i,o,a,c)??-38n,SYS_pwritev:(n,i,o,a,c)=>this.isPipeFd(Number(n))?-29n:t.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)):t.SYS_readv?.(n,i,o)??-38n,SYS_writev:(n,i,o)=>this.isPipeFd(Number(n))?this.writev(Number(n),Number(i),Number(o)):t.SYS_writev?.(n,i,o)??-38n,SYS_lseek:(n,i,o)=>this.isPipeFd(Number(n))?-29n:t.SYS_lseek?.(n,i,o)??-38n,SYS_fstat:(n,i)=>this.isPipeFd(Number(n))?this.fstat(Number(i)):t.SYS_fstat?.(n,i)??-38n,SYS_dup:n=>this.isPipeFd(Number(n))?this.duplicate(Number(n)):t.SYS_dup?.(n)??-38n,SYS_dup2:(n,i)=>this.isPipeFd(Number(n))?this.duplicate(Number(n),Number(i),3,!1,t):t.SYS_dup2?.(n,i)??-38n,SYS_dup3:(n,i,o)=>this.isPipeFd(Number(n))?Number(n)===Number(i)||(Number(o)&~Wr)!==0?-22n:this.duplicate(Number(n),Number(i),3,!!(Number(o)&Wr),t):t.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))),t):t.SYS_fcntl?.(n,i,o)??-38n,SYS_poll:(n,i,o)=>this.poll(Number(n),Number(i),Number(o),()=>e("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(t,e){if((e&-526337)!==0)return-22n;if(!this.validRange(t,8))return-14n;const r=this.allocateSlot();if(r<0)return-24n;const n=this.control(r);n.fill(0),Atomics.store(n,Es,1),Atomics.store(n,Ns,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=e&Wr?1:0,Atomics.store(new Int32Array(this.state.descriptions),this.table.entries[c].description*3+1,e&Ur);const a=this.view();return a.setInt32(t,i,!0),a.setInt32(t+4,o,!0),0n}read(t,e,r){if(!Number.isSafeInteger(r)||r<0||!this.validRange(e,r))return-22n;const i=(this.statusFlags(t)&Ur?sn:Ma)(this.handle(this.entry(t)),r);return typeof i=="bigint"?i:(this.bytes().set(i,e),BigInt(i.byteLength))}write(t,e,r){return!Number.isSafeInteger(r)||r<0||!this.validRange(e,r)?-22n:ai(this.handle(this.entry(t)),this.bytes().slice(e,e+r))}readv(t,e,r){if(!Number.isSafeInteger(r)||r<0||r>1024||!this.validRange(e,r*8))return-22n;let n=0n;for(let i=0;i<r;i+=1){const o=e+i*8,a=this.read(t,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(t,e,r){if(!Number.isSafeInteger(r)||r<0||r>1024||!this.validRange(e,r*8))return-22n;let n=0n;for(let i=0;i<r;i+=1){const o=e+i*8,a=this.write(t,this.view().getUint32(o,!0),this.view().getUint32(o+4,!0));if(a<0n)return n>0n?n:a;n+=a}return n}fstat(t){if(!this.validRange(t,144))return-14n;const e=this.view();for(let r=0;r<144;r+=4)e.setUint32(t+r,0,!0);return e.setBigUint64(t+16,1n,!0),e.setUint32(t+24,ac|438,!0),e.setUint32(t+28,1e3,!0),e.setUint32(t+32,1e3,!0),e.setBigInt64(t+56,4096n,!0),0n}statusFlags(t){const e=Atomics.load(new Int32Array(this.state.table),t);return Atomics.load(new Int32Array(this.state.descriptions),e*3+1)}fcntl(t,e,r,n){if(e===ec||e===Is)return this.duplicate(t,void 0,Math.max(3,r),e===Is,n);const i=this.table.entries[t];return e===rc?BigInt(i.flags):e===nc?(i.flags=r&oc,0n):e===sc?BigInt(this.statusFlags(t)|(this.entry(t)<0?1:0)):e===ic?(Atomics.store(new Int32Array(this.state.descriptions),i.description*3+1,r&Ur),0n):-22n}duplicate(t,e,r=As,n=!1,i={}){const o=this.table.get(t);if(!o)return-9n;if(e===t)return BigInt(t);const a=e===void 0?this.freeDescriptor(r):e;return a<0||a>=65536?-9n:(this.table.set(a,o,n?1:0),BigInt(a))}close(t){return this.table.close(t)?0n:-9n}poll(t,e,r,n){if(!Number.isSafeInteger(e)||e<0||e>65536||!this.validRange(t,e*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<e;a+=1){const c=t+a*8,l=this.view().getInt32(c,!0),u=this.pollDescriptor(l,this.view().getInt16(c+4,!0));u!==void 0&&(this.view().getInt16(c+6,!0)!==0&&(o-=1),this.view().setInt16(c+6,u,!0),u!==0&&(o+=1))}return BigInt(o)}allocateSlot(){for(let t=0;t<this.slots.length;t+=1)if(Atomics.compareExchange(this.slots,t,0,1)===0)return t;return-1}freeDescriptor(t){for(let e=Math.max(3,t);e<=tc;e++)if(!this.table.get(e))return e;return-1}allocateDescriptor(t,e=As){const r=this.freeDescriptor(e);if(r<0)return r;const n=Math.abs(t)-1,i=this.table.registry.create("pipe",{pipe:n,side:t>0?"reader":"writer"},()=>{Se(this.handle(t));const o=this.control(n);Atomics.load(o,Es)===0&&Atomics.load(o,Ns)===0&&Atomics.store(this.slots,n,0)});return Atomics.store(this.table.registry.pipeMetadata,i.id*3,t),this.table.set(r,i),r}entry(t){return lc(this.state,t)}handle(t){const e=Math.abs(t)-1;return{control:this.state.controls,payload:this.state.payloads,role:t>0?"reader":"writer",controlOffset:e*Je*Int32Array.BYTES_PER_ELEMENT,payloadOffset:e*Zr,payloadLength:Zr}}control(t){return new Int32Array(this.state.controls,t*Je*Int32Array.BYTES_PER_ELEMENT,Je)}bytes(){return new Uint8Array(this.memory().buffer)}view(){return new DataView(this.memory().buffer)}validRange(t,e){return Number.isSafeInteger(t)&&Number.isSafeInteger(e)&&t>=0&&e>=0&&t+e<=this.memory().buffer.byteLength}}const Or=64*1024,fc=1e4;var bt;(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"})(bt||(bt={}));var xs;(function(s){s[s.VideoDecoder=0]="VideoDecoder",s[s.VideoEncoder=1]="VideoEncoder",s[s.AudioDecoder=2]="AudioDecoder",s[s.AudioEncoder=3]="AudioEncoder"})(xs||(xs={}));const ks=1;var q;(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"})(q||(q={}));const dc=6,mc=9,Sc=-5,$r=-9,yc=-11,Oe=-14,xt=-22,Ut=-95,pc=-110,Ms=3e4,bc=fc+5e3;class gc{channel;control;nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control)}call(t,e,r){if(Atomics.load(this.control,q.State)!==0)return yc;const n=this.nextRequestId;this.nextRequestId=n>=1073741821?1:n+2,this.control.fill(0);for(let a=0;a<dc;a+=1)Atomics.store(this.control,q.Argument0+a,e[a]??0);Atomics.store(this.control,q.Operation,t),Atomics.store(this.control,q.State,n),this.channel.port.postMessage(n);const i=Date.now()+r;for(;;){const a=Atomics.load(this.control,q.State);if(a===n+1)break;if(a!==n&&a!==-n)return Sc;const c=Math.max(0,i-Date.now());if(c===0&&a===n&&Atomics.compareExchange(this.control,q.State,n,0)===n)return pc;Atomics.wait(this.control,q.State,a,a===-n?void 0:c)}const o=Atomics.load(this.control,q.Result);return Atomics.store(this.control,q.State,0),o}}function wc(s,t,e){const r=()=>s().buffer.byteLength,n=(c,l)=>Number.isSafeInteger(c)&&c>0&&l>=0&&c<=r()-l,i=(c,l)=>l===0?Number.isSafeInteger(c)&&c>=0:n(c,l),o=(c,l,u=Ms)=>{const f=e();return BigInt(f?f.call(c,l,u):Ut)},a=c=>(l,u,f)=>{if(!t())return BigInt(Ut);const d=Number(l),m=Number(u),p=Number(f);return!Number.isInteger(d)||d<0||d>3||!Number.isSafeInteger(p)||p<1||p>Or?BigInt(xt):n(m,p)?o(c,[d,m,p]):BigInt(Oe)};return{SYS_browser_codec_query_v1:a(bt.Query),SYS_browser_codec_open_v1:a(bt.Open),SYS_browser_codec_push_v1:(c,l,u,f,d)=>{if(!t())return BigInt(Ut);const m=Number(c),p=Number(l),y=Number(u),g=Number(f),w=Number(d);return!Number.isInteger(m)||m<=0?BigInt($r):!Number.isSafeInteger(y)||y<0||!Number.isSafeInteger(w)||w<1||w>Or?BigInt(xt):y>0&&!n(p,y)||!n(g,w)?BigInt(Oe):o(bt.Push,[m,p,y,g,w])},SYS_browser_codec_pull_v1:(c,l,u,f,d,m)=>{if(!t())return BigInt(Ut);const p=Number(c),y=Number(l),g=Number(u),w=Number(f),E=Number(d),N=Number(m);return!Number.isInteger(p)||p<=0?BigInt($r):!Number.isInteger(y)||(y&~ks)!==0||!Number.isSafeInteger(w)||w<0||!Number.isSafeInteger(N)||N<0||N>Or?BigInt(xt):!i(g,w)||!i(E,N)?BigInt(Oe):o(bt.Pull,[p,y,g,w,E,N],(y&ks)===0?Ms:bc)},SYS_browser_codec_flush_v1:c=>{if(!t())return BigInt(Ut);const l=Number(c);return!Number.isInteger(l)||l<=0?BigInt($r):o(bt.Flush,[l])},SYS_browser_codec_close_v1:c=>{if(!t())return BigInt(Ut);const l=Number(c);return!Number.isInteger(l)||l<=0?0n:o(bt.Close,[l])}}}class an{worker;constructor(t){this.worker=t}static async create(t){const e=pe(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"&&(e.removeEventListener("message",i),r()),o.data.kind==="error"&&(e.removeEventListener("message",i),n(new Error(o.data.message)))};e.addEventListener("message",i),e.addEventListener("error",o=>n(o.error??new Error(o.message)),{once:!0}),e.postMessage({kind:"initialize",memory:t})}),new an(e)}createChannel(){const t=new MessageChannel,e=new SharedArrayBuffer(mc*Int32Array.BYTES_PER_ELEMENT);return this.worker.postMessage({kind:"attach",port:t.port2,control:e},[t.port2]),{port:t.port1,control:e}}terminate(){this.worker.terminate()}}const Vr=1,zr=2,Hr=4,Rs=8,_c=16,Ac=32,fi=1024,Ec=fi*8;function Nc(s,t,e){return(r,n,i,o,a)=>{const c=Number(r);if(!Number.isInteger(c)||c<0||c>fi)return-22n;const l=[Number(n),Number(i),Number(o)],u=[Vr,Hr,zr],f=Math.ceil(c/8);let d=new Uint8Array(s().buffer);for(const P of l)if(P!==0&&(P<0||P+f>d.byteLength))return-14n;const m=Number(a);let p=-1;if(m!==0){if(m<0||m+16>d.byteLength)return-14n;const P=new DataView(s().buffer),x=P.getBigInt64(m,!0),M=P.getBigInt64(m+8,!0);if(x<0n||M<0n)return-22n;p=Number(x*1000n+(M+999n)/1000n)}const y=new Map;l.forEach((P,x)=>{if(P!==0)for(let M=0;M<c;M+=1)d[P+(M>>3)]&1<<(M&7)&&y.set(M,(y.get(M)??0)|u[x])});const g=e();if(g<=0)return-12n;let w=new DataView(s().buffer),E=0;for(const[P,x]of y){const M=g+E*8;w.setInt32(M,P,!0),w.setInt16(M+4,x,!0),w.setInt16(M+6,0,!0),E+=1}const N=t(g,E,p),$=Number(typeof N=="bigint"?N:N??0);if($<0)return BigInt($);d=new Uint8Array(s().buffer),w=new DataView(s().buffer);for(const P of l)P!==0&&d.fill(0,P,P+f);let U=0,H=0;for(const[P,x]of y){const M=w.getInt16(g+H*8+6,!0);if(H+=1,M&Ac)return-9n;[(x&Vr)!==0&&(M&(Vr|_c|Rs))!==0,(x&Hr)!==0&&(M&(Hr|Rs))!==0,(x&zr)!==0&&(M&zr)!==0].forEach((Mt,Rt)=>{if(!Mt)return;const vt=l[Rt]+(P>>3);d[vt]=(d[vt]??0)|1<<(P&7),U+=1})}return BigInt(U)}}var gt;(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"})(gt||(gt={}));const $e=512*1024,vs=256*1024*1024,Ys=5,Ic=new TextEncoder,Lc=new TextDecoder("utf-8",{fatal:!0});class xc{channel;control;payload;nextRequestId=1;constructor(t){this.channel=t,this.control=new Int32Array(t.control),this.payload=new Uint8Array(t.payload)}pull(t){const e=this.call(gt.Inspect,{path:t});if(!e.exists)return;const r=tn(e.length,0,vs),n=new Uint8Array(r);for(let i=0;i<r;i+=$e){const o=Math.min($e,r-i),a=this.call(gt.Read,{path:t,offset:i,length:o}),c=me(a.content);if(c.byteLength!==o)throw new Error("Invalid coherent file response.");n.set(c,i)}return{bytes:n,...e.mode===void 0?{}:{mode:e.mode},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs},parents:di(t,e.parents)}}push(t,e){if(!e){this.call(gt.Remove,{path:t});return}if(e.bytes.byteLength>vs)throw new Error("Coherent file exceeds 256 MiB.");this.call(gt.WriteStart,{path:t,length:e.bytes.byteLength,...e.mode===void 0?{}:{mode:e.mode},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs},...e.parents===void 0?{}:{parents:e.parents}});for(let r=0;r<e.bytes.byteLength;r+=$e){const n=e.bytes.subarray(r,r+$e);this.call(gt.WriteChunk,{offset:r,content:Ot(n)})}this.call(gt.WriteFinish)}call(t,e={}){const r=()=>{if(Atomics.load(this.control,Ys))throw Object.assign(new Error("Browser file coherence was cancelled."),{errno:125})};r();const n=Ic.encode(JSON.stringify(e));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,Ys),this.payload.set(n),Atomics.store(this.control,1,t),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 l=Atomics.load(this.control,0);l!==i+1&&Atomics.wait(this.control,0,l)}const o=Atomics.load(this.control,2),a=tn(Atomics.load(this.control,4),0,this.payload.byteLength),c=a===0?void 0:JSON.parse(Lc.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 Ps(s){const t=s.replace(/-(?:journal|shm|wal)$/u,"");return[t,`${t}-journal`,`${t}-wal`,`${t}-shm`]}function kc(s,t){return cn(t).flatMap(e=>{if(!s.existsSync(e))return[];const r=s.statSync(e);if(!r.isDirectory())throw ft("A coherent file parent must be a directory.");return[{path:e,...mi({mode:r.mode,mtimeMs:r.mtimeMs})}]})}function Mc(s,t,e){const r=new Map(di(t,e).map(n=>[n.path,n]));for(const n of cn(t)){if(s.existsSync(n)){if(!s.statSync(n).isDirectory())throw ft("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 di(s,t){if(t===void 0)return[];const e=new Set(cn(s));if(!Array.isArray(t)||t.length>e.size)throw ft("Invalid coherent file parents.");return t.map(r=>{if(typeof r!="object"||r===null)throw ft("Invalid coherent file parent.");const n=r,i=Si(n.path);if(!e.delete(i))throw ft("Coherent metadata must name distinct ancestors of its file.");return{path:i,...mi(n)}})}function cn(s){const t=[];for(const e of Si(s).split("/"))!e||e==="."||(e===".."?t.pop():t.push(e));return t.slice(0,-1).map((e,r)=>`/${t.slice(0,r+1).join("/")}`)}function mi(s){const t=s.mode===void 0?void 0:tn(s.mode,0,65535),e=s.mtimeMs===void 0?void 0:vc(s.mtimeMs);return{...t===void 0?{}:{mode:t},...e===void 0?{}:{mtimeMs:e}}}function Si(s){const t=Rc(s);if(!t.startsWith("/")||t.length>4096||t.includes("\0"))throw ft("Invalid coherent file path.");return t}function Rc(s){if(typeof s!="string")throw ft("Expected a string.");return s}function tn(s,t,e){if(!Number.isSafeInteger(s)||s<t||s>e)throw ft("Expected a bounded integer.");return s}function vc(s){if(typeof s!="number"||!Number.isFinite(s))throw ft("Expected a finite number.");return s}function ft(s){return Object.assign(new Error(s),{errno:22})}class Yc{locks;coherence;filesystem;held=[];locallyCreated=new Set;constructor(t,e,r){this.locks=t,this.coherence=e,this.filesystem=r}created(t){this.locallyCreated.add(t)}request(t){if(t.operation==="query")return this.locks.request(t);if(t.operation==="set"){const i=!this.held.some(a=>a.path===t.path),o=this.locks.request(t);if(o.result<0)return o;if(i)try{this.refresh(t.path)}catch(a){throw this.locks.request({operation:"unlock",owner:t.owner,namespace:t.namespace,path:t.path,range:t.range}),a}return this.install(t.owner,t.namespace,t.path,t.range),o}if(t.operation==="unlock"){const i=this.without(t.owner,t.namespace,t.path,t.range);this.held.some(a=>a.path===t.path)&&!i.some(a=>a.path===t.path)&&this.publish(t.path);const o=this.locks.request(t);return o.result>=0&&this.replaceHeld(i),o}const e=this.held.filter(i=>i.owner!==t.owner),r=new Set(this.held.filter(i=>i.owner===t.owner).map(i=>i.path));for(const i of r)e.some(o=>o.path===i)||this.publish(i);const n=this.locks.request(t);return n.result>=0&&this.replaceHeld(e),n}refresh(t){const e=performance.now();try{this.refreshNow(t)}finally{tt.waited.ms+=performance.now()-e}}publish(t){const e=performance.now();try{this.publishNow(t)}finally{tt.waited.ms+=performance.now()-e}}refreshNow(t){for(const e of Ps(t)){const r=this.coherence.pull(e);if(!r&&this.locallyCreated.delete(e)){this.coherence.push(e,this.readLocal(e)),this.filesystem.dropChangedPaths?.([e]);continue}this.locallyCreated.delete(e),this.writeLocal(e,r),this.filesystem.dropChangedPaths?.([e])}}publishNow(t){for(const e of Ps(t))this.coherence.push(e,this.readLocal(e)),this.filesystem.dropChangedPaths?.([e])}readLocal(t){if(!this.filesystem.existsSync(t))return;const e=this.filesystem.statSync(t);if(!e.isDirectory())return{bytes:this.filesystem.readFileSync(t),...e.mode===void 0?{}:{mode:e.mode},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs},parents:kc(this.filesystem,t)}}writeLocal(t,e){if(!e){this.filesystem.existsSync(t)&&!this.filesystem.statSync(t).isDirectory()&&this.filesystem.unlinkSync(t);return}Mc(this.filesystem,t,e.parents),this.filesystem.writeFileSync(t,e.bytes),e.mode!==void 0&&this.filesystem.chmodSync?.(t,e.mode),e.mtimeMs!==void 0&&this.filesystem.utimesSync?.(t,new Date(e.mtimeMs),new Date(e.mtimeMs))}install(t,e,r,n){const i=this.without(t,e,r,n);i.push({owner:t,namespace:e,path:r,...n}),this.replaceHeld(i)}without(t,e,r,n){return this.held.flatMap(i=>i.owner===t&&i.namespace===e&&i.path===r&&Pc(i,n)?Bc(i,n):[i])}replaceHeld(t){this.held.splice(0,this.held.length,...t)}}function Pc(s,t){return s.start<(t.end??Number.POSITIVE_INFINITY)&&t.start<(s.end??Number.POSITIVE_INFINITY)}function Bc(s,t){const e=[];s.start<t.start&&e.push({...s,end:t.start});const r=s.end??Number.POSITIVE_INFINITY,n=t.end??Number.POSITIVE_INFINITY;return n<r&&e.push({...s,start:n,...s.end===void 0?{}:{end:s.end}}),e}const Tc=9n,Fc=22n,Bs=new TextEncoder,ue=new TextDecoder;class yi extends Error{imports;constructor(t){super(`Unsupported WALI imports: ${t.join(", ")}`),this.imports=t,this.name="UnsupportedWaliImportError"}}function Cc(s,t){if(ji(s))return()=>{throw new yi([s])};let e=!1;return()=>{if(!e){e=!0;const r=`[WALI] ${s} is not implemented; answering -ENOSYS (38) as a kernel would.`;console.error(r),t?.(r)}return Ki}}class Ts extends Error{}class Fs extends Error{code;constructor(t){super(`WALI process exited with status ${t}`),this.code=t}}class Dc{async run(t,e={}){const r=e.filesystemPolicy===void 0?void 0:kt(e.filesystemPolicy),n=r,i=await Vi(t),o=zi(i);Hi(o);const a=o.filter(h=>h.module==="wali"),c=[],l=[],u=typeof e.stdin=="object"&&e.stdin!==null&&"read"in e.stdin?e.stdin:new Os(typeof e.stdin=="string"?Bs.encode(e.stdin):e.stdin??new Uint8Array),f=e.argv?.length?[...e.argv]:["wali-program"],d=f.map(h=>Bs.encode(`${h}\0`)),m=$c(e.pid),p=performance.now(),y={...tt.waited};let g=p;const w=new Map,E=e.signalState??Ti();let N,$,U,H,P,x,M=!1;const j=da(t,e.memory),Mt=xo(),Rt=new Int32Array(new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT));Atomics.store(Rt,1,-1);const vt=new _e(new en),Yt=e.descriptorTable?.sharedPipes??cc(vt),v=()=>{if(j)return j;const h=N?.exports.memory;if(!(h instanceof WebAssembly.Memory))throw new Error("WALI module does not export linear memory.");return h},rt=()=>new DataView(v().buffer),lt=()=>new Uint8Array(v().buffer),ln=(h,S)=>(Wt(v(),h,S),lt().slice(h,h+S)),pi=(h,S)=>{Wt(v(),h,S.byteLength),lt().set(S,h)},Xt=(h,S)=>{if(h===1)c.push(S),e.onStdout?.(S.slice());else if(h===2)l.push(S),e.onStderr?.(S.slice());else return-Tc;return BigInt(S.byteLength)},Ae=(h,S="SYS_exit_group")=>{const b=`[WALI] ${S}(${h&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(b),e.onDiagnostic?.(b),new Fs(h&255)},un=h=>h<0||h>64?-22n:h===0?0n:h!==9&&(At.mask&1n<<BigInt(h-1))!==0n?(new fr(E).raise(h),0n):((h===9||h===19?"default":new fr(E).raise(h))==="default"&&Bi(h)&&Ae(128+h,`signal ${h}`),0n),Ee=e.executablePath??(f[0].startsWith("/")?f[0]:`/usr/bin/${f[0]}`),nr=a.some(h=>h.name==="__wasm_thread_spawn"),sr=a.some(h=>Uc.has(h.name))?e.browserProcess:void 0,bi=e.forkState?.allocator??Js(),hn=Go(),dt=e.descriptorTable?new Jr(e.descriptorTable):void 0;if(dt&&j&&dt.attachMemory(j),!dt&&(nr||sr)&&e.filesystem?.toSnapshot&&e.filesystem.replaceSnapshot){if(!j)throw new Error("A threaded WALI module must import its shared process memory.");const h=e.store||e.layers?e.filesystem.toStoreOverlaySnapshot?.():void 0;M=!(!!sr?.fork&&WebAssembly.Module.exports(i).some(b=>b.name==="asyncify_start_unwind")||a.some(b=>b.name==="SYS_browser_spawn"||b.name==="SYS_browser_spawn_confined_v1")),x=await(M?we.createInThread:we.create)(h??e.filesystem.toSnapshot(),{...e.store?{store:e.store}:{},...e.layers?{layers:e.layers}:{},...e.privateRoots?{privateRoots:e.privateRoots}:{},memory:j,sharedPipes:Yt,...n?{filesystemPolicy:n}:{},cwd:e.cwd??"/",executablePath:Ee,pid:m,...e.filesystemUpdatePort?{updatePort:e.filesystemUpdatePort}:{},...e.fileLocks?{fileLocks:e.fileLocks}:{},...e.fileCoherence?{fileCoherence:e.fileCoherence}:{}})}if(n&&nr&&!x&&!dt)throw new Error("Confined WALI threads require the shared filesystem owner.");const _t=dt??x?.filesystem()??e.filesystem,fn=()=>{x&&e.filesystem?.replaceSnapshot&&e.filesystem.replaceSnapshot(x.snapshot())},W=new er({...dt||x?{descriptorState:Yt}:{descriptors:vt},...n?{filesystemPolicy:n}:{},..._t?{filesystem:_t}:{},cwd:e.cwd??"/",stdin:u,executablePath:Ee,memory:v,emit:Xt,stdioAliasRegistry:Mt,pid:m,...!x&&e.fileLocks?{fileLocks:e.fileCoherence?new Yc(new tt(e.fileLocks.channel),new xc(e.fileCoherence),_t):new tt(e.fileLocks.channel),lockOwner:e.fileLocks.owner}:{},...x?{specialDescriptorMinimum:1e4,descriptorMaximum:19999}:{},...!x&&!dt&&e.privateRoots?{privateRoots:e.privateRoots.map(h=>`/${h.split("/").filter(Boolean).join("/")}`)}:{},...e.onDiagnostic?{onDiagnostic:e.onDiagnostic}:{}}),gi=W.imports(),Kt=W.writeEnvironmentFile(e.env??{},m),F=dt??x?.filesystem(),Pt=F?new Qa(F,Mt,Yt,v):void 0,mt=new Xo(v,(h,S,b)=>Pt?.readForMapping(h,S,b)??W.readForMapping(h,S,b),bi,h=>Pt?.mappingPath(h)??W.mappingPath(h),(h,S,b)=>Pt?.writeForMapping(h,S,b)??W.writeForMapping(h,S,b),hn,e.onDiagnostic),At=new Fi(new fr(E),v,()=>N?.exports.__indirect_function_table,()=>Number(mt.imports().SYS_mmap(0,4096,3,34,-1,0)),Ci(()=>N?.exports,v)),ir=e.threadPoolSize??18,dn=new ia(v,m,u,Rt,e.terminal,ir,()=>mt.growAhead()),mn=M?x?.doorbell():void 0;xn(mn?{pump:()=>x.pump(!0),doorbell:mn}:void 0);let Sn=!1;(e.network||sr)&&(U=await on.create(e.network,Yt,u instanceof Gr?u.buffer:void 0,Mt.buffer,E));const J=U?new Ga(v,U.createChannel(),At):void 0,Ne=new hc(v,Yt,F?void 0:vt,F),wi=new fa(v,W,(h,S)=>Ne.pollDescriptor(h,S)??(J?.isNetworkFd(h)?J.pollFd(h,S):void 0)),_i=new Wa(v,W),yn=W.imports(),Ai=Pt?.imports(yn)??yn,pn=Ne.imports({..._i.imports(),...Ai}),bn=wi.imports(),jt=dn.imports(),gn=e.forkState?.parentPid??e.parentPid??1,Et=new Int32Array(e.childPidAllocator??new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));e.childPidAllocator||Atomics.store(Et,0,Math.max(m+1,1e4));const Ie=h=>{if(!Number.isSafeInteger(h)||h<=0||h>=lt().byteLength)throw new WebAssembly.RuntimeError("WALI process string pointer is out of bounds.");const S=lt().indexOf(0,h);if(S<0||S-h>1024*1024)throw new WebAssembly.RuntimeError("WALI process string is not terminated.");return ue.decode(lt().slice(h,S))},Le=h=>{if(h===0)return[];const S=[];for(let b=0;b<65536;b+=1){Wt(v(),h+b*4,4);const A=rt().getUint32(h+b*4,!0);if(A===0)return S;S.push(Ie(A))}throw new WebAssembly.RuntimeError("WALI process string array is not terminated.")},Bt=(h,S)=>{const b=Ne.exportBrowserProcessPipe(h)??W.exportBrowserProcessPipe(h);if(!(!b||b.role!==S))return ii(b)},Ei=(h,S,b)=>{if(!J)return-10n;if(S!==0&&(S<0||S+4>lt().byteLength))return-14n;const{result:A,process:k}=J.waitChild(h,b,At.mask);if(A<=0)return BigInt(A);const T=va(k);if(T){x&&x.filesystem().importPeerPatch(T),e.filesystem&&_a(e.filesystem,T);const O=e.filesystem?.toSnapshot?.();O&&e.browserProcess?.restore?.(O)}return S!==0&&rt().setInt32(S,(Atomics.load(new Int32Array(k.control),1)&255)<<8,!0),BigInt(A)},wn=(h,S)=>{const[b,A,k,T,O,D,nt]=h;if(!e.browserProcess)return-38;const Qt=cr(1,[O,D,nt]);if(Qt!==void 0)return Qt;S&&(S=kt(S));const qt=r;if(qt){if(e.browserProcess.filesystemPolicyVersion!==1)return-95;S=Di(qt,S)}const Tt=Ie(Number(b)),Nt=Le(Number(A));Nt.length===0&&Nt.push(Tt);const Ln={};for(const Ft of Le(Number(k))){const hr=Ft.indexOf("=");hr>0&&(Ln[Ft.slice(0,hr)]=Ft.slice(hr+1))}const Me=Atomics.add(Et,0,1),ur={control:new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),response:new SharedArrayBuffer(jr),snapshotApplied:!1},Re=Bt(Number(O),"reader"),ve=Bt(Number(D),"writer"),Ye=Bt(Number(nt),"writer");let Pe;try{const Ft=J.registerChild(Me,ur);if(Ft<0)throw new Error(`Child registration failed: ${Ft}`);return F?.prepareSpawn(),fn(),Pe=F?.copyForExecChannel([Number(O),Number(D),Number(nt)]),e.browserProcess.spawn({pid:Me,parentPid:m,childPidAllocator:Et.buffer,...Pe?{descriptorTable:Pe}:{},...S?{filesystemPolicy:S}:{},executablePath:Tt,argv:Nt,env:Ln,...Number(k)===0?{inheritEnvironment:!0}:{},cwd:Number(T)===0?W.currentWorkingDirectory():Ie(Number(T)),control:ur.control,response:ur.response,...Re?{stdin:Re}:{},...ve?{stdout:ve}:{},...Ye?{stderr:Ye}:{}}),Me}catch{return Pe?.releasePort?.postMessage(!0),J.forgetChild(Me),Re&&Se(Re),ve&&Se(ve),Ye&&Se(Ye),-5}};let Z=e.forkState?.asyncifyData??0,or=!1,xe=!!e.forkState,ke=0,_n=!1;const Jt=(h,...S)=>{const b=N?.exports[h];if(typeof b!="function")throw new Error(`Missing ${h}; build the module with the Binaryen Asyncify stage.`);b(...S)},ar=()=>F?.currentWorkingDirectory()??W.currentWorkingDirectory(),cr=(h,S=[])=>{const b=N?.exports.__wali_private_tree_release;if(typeof b!="function")return;const A=Number(b(h,Number(S[0]??-1),Number(S[1]??-1),Number(S[2]??-1)));return A<0?A:void 0},Ni=()=>{if(typeof N?.exports.asyncify_start_unwind!="function")return _n||e.onDiagnostic?.("[WALI] SYS_fork answers -ENOSYS: module lacks the Binaryen Asyncify build stage (--asyncify --pass-arg=asyncify-imports@wali.SYS_fork)."),_n=!0,-38n;if(xe)return Jt("asyncify_stop_rewind"),xe=!1,BigInt(ke);if(!e.browserProcess?.fork||!F||!J)return-38n;const h=cr(0);return h!==void 0?BigInt(h):(or=!0,rt().setUint32(Z,Z+8,!0),Jt("asyncify_start_unwind",Z),0n)},Ii=(h,S,b)=>{if(!e.forkState||!e.browserProcess||!F)return-38n;const A=cr(0);if(A!==void 0)return BigInt(A);const k=Ie(h),T=k.startsWith("/")?k:`${ar()}/${k}`;if(!_t?.existsSync(T))return-2n;if(!_t.statSync(T).isFile())return-13n;const O=b===0?{...e.env}:{};for(const Tt of Le(b)){const Nt=Tt.indexOf("=");Nt>0&&(O[Tt.slice(0,Nt)]=Tt.slice(Nt+1))}F.prepareSpawn();const D=F.copyForExecChannel([0,1,2]),nt=Bt(0,"reader"),Qt=Bt(1,"writer"),qt=Bt(2,"writer");throw e.browserProcess.spawn({pid:m,parentPid:gn,childPidAllocator:Et.buffer,executablePath:T,argv:Le(S),env:O,cwd:ar(),descriptorTable:D,control:e.forkState.control,response:e.forkState.response,...n?{filesystemPolicy:n}:{},...nt?{stdin:nt}:{},...Qt?{stdout:Qt}:{},...qt?{stderr:qt}:{}}),new Ts},Zt={...{__init:()=>0,__deinit:()=>0,__proc_exit:h=>Ae(Number(h)),__cl_get_argc:()=>d.length,__cl_get_argv_len:h=>d[Number(h)]?.byteLength??0,__cl_copy_argv:(h,S)=>{const b=d[Number(S)];return b?(pi(Number(h),b),0):-1},__get_init_envfile:(h,S)=>Kt?W.copyCString(Number(h),Kt,Number(S)):0,SYS_write:(h,S,b)=>Xt(Number(h),ln(Number(S),Number(b))),SYS_writev:(h,S,b)=>{let A=0n;for(let k=0;k<Number(b);k+=1){const T=Number(S)+k*8;Wt(v(),T,8);const O=rt().getUint32(T,!0),D=rt().getUint32(T+4,!0),nt=Xt(Number(h),ln(O,D));if(nt<0n)return nt;A+=nt}return A},SYS_exit:h=>Ae(Number(h),"SYS_exit"),SYS_exit_group:h=>Ae(Number(h),"SYS_exit_group"),SYS_getpid:()=>BigInt(m),SYS_getppid:()=>BigInt(gn),SYS_gettid:()=>BigInt(m),SYS_getuid:()=>1000n,SYS_geteuid:()=>1000n,SYS_getgid:()=>1000n,SYS_getegid:()=>1000n,SYS_set_tid_address:()=>BigInt(m),SYS_sched_yield:()=>0n,SYS_sched_setscheduler:()=>0n,SYS_tkill:(h,S)=>un(Number(S)),...wc(v,()=>e.codec?.version===1,()=>P),SYS_browser_spawn:(...h)=>wn(h),SYS_browser_spawn_confined_v1:Wi(v,()=>e.browserProcess?.filesystemPolicyVersion===1,wn),SYS_fork:Ni,SYS_execve:(h,S,b)=>Ii(Number(h),Number(S),Number(b)),SYS_wait4:(h,S,b)=>{for(;;){const A=Ei(Number(h),Number(S),Number(b));if(A!==-4n||!At.deliver(!0))return A}},SYS_pidfd_open:()=>-38n,SYS_kill:(h,S)=>{if(Number(h)===m||Number(h)===0)return un(Number(S));const b=Math.abs(Number(h));return J?.hasChild(b)?(e.browserProcess?.kill?.(b,Number(S)),0n):-3n},SYS_setpgid:()=>0n,SYS_getpgid:h=>BigInt(Number(h)===0?m:Math.abs(Number(h))),__wasm_thread_spawn:(h,S)=>{const b=$?.spawn(Number(h),Number(S),At.mask)??-11;if(b===-11&&!Sn){Sn=!0;const A=`[WALI] pthread_create answered -EAGAIN: all ${ir} 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 ${dn.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(A),e.onDiagnostic?.(A)}return b},SYS_clock_gettime:(h,S)=>{const b=Vc(Number(h));return b===void 0?-Fc:(zc(rt(),Number(S),b),0n)},SYS_gettimeofday:h=>{if(Number(h)!==0){const S=BigInt(Math.floor(wt()*1e3));Wt(v(),Number(h),16),rt().setBigInt64(Number(h),S/1000000n,!0),rt().setBigInt64(Number(h)+8,S%1000000n,!0)}return 0n},SYS_getrandom:(h,S)=>{const b=lt().subarray(Number(h),Number(h)+Number(S));return Wt(v(),Number(h),Number(S)),Hc(b),BigInt(b.byteLength)},...mt.imports(),...jt,...At.imports(),...pn,...J?J.imports({...pn,...bn}):bn,SYS_ioctl:(h,S,b)=>Ne.ioctl(Number(h),Number(S))??W.ioctl(Number(h),Number(S))??jt.SYS_ioctl(h,S,b),SYS_prctl:(h,...S)=>Number(h)!==Hs?0n:F?F.syscall("SYS_prctl",[h,...S]):gi.SYS_prctl(h,...S)},...e.imports};let Li=0;if(Zt.SYS_select??=Nc(v,(h,S,b)=>Zt.SYS_poll(h,S,b),()=>Li||=Number(mt.imports().SYS_mmap(0,Ec,3,34,-1,0))),M&&Pt)for(const[h,S]of Object.entries(Pt.ownedFileImports(Zt)))e.imports?.[h]||(Zt[h]=S);const An={};for(const h of a){const S=Zt[h.name]??Cc(h.name,e.onDiagnostic),b=(!F||M)&&Oc.has(h.name),A={calls:0,ms:0,sampled:b};w.set(h.name,A),An[h.name]=(...k)=>{e.onSyscall?.(h.name,k),M&&x.pump();const T=!b||(A.calls&Cs-1)===0,O=T?performance.now():0;try{const D=S(...k);return e.onSyscallResult?.(h.name,D),At.deliver(D===-4n),D}finally{A.calls+=1,T&&(A.ms+=(performance.now()-O)*(b?Cs:1))}}}const xi={...j?{memory:j}:{},_Unwind_Backtrace:()=>5,_Unwind_FindEnclosingFunction:h=>h,_Unwind_GetCFA:()=>0};if(N=await WebAssembly.instantiate(i,{wali:An,env:xi}),e.forkState){lt().set(new Uint8Array(e.forkState.memory));for(const[h,S]of Object.entries(e.forkState.globals)){const b=N.exports[h];if(!(b instanceof WebAssembly.Global))throw new Error(`Fork snapshot global ${h} is not exported.`);b.value=S}mt.restoreFork(e.forkState.mappings),jt.SYS_umask(e.forkState.umask)}else if(typeof N.exports.asyncify_start_unwind=="function"){const h=N.exports.__stack_pointer;if(!(h instanceof WebAssembly.Global))throw new Error("Asyncify fork requires --export=__stack_pointer at link.");const S=Number(h.value);if(S<=0)throw new Error("Asyncify fork requires a nonempty module stack.");Z=v().buffer.byteLength,v().grow(Math.ceil((S+8)/65536)),rt().setUint32(Z+4,Z+8+S,!0)}if(e.codec?.version===1)try{H=await an.create(v()),P=new gc(H.createChannel())}catch(h){console.warn("[WALI] the codec bridge is unavailable:",h),H=void 0,P=void 0}if(nr){if(!j)throw new Error("A threaded WALI module must be linked with --import-memory so browser workers can share its process memory.");const h=e.memoryLayout??(t instanceof WebAssembly.Module?void 0:Kr(t instanceof Uint8Array?t:new Uint8Array(t)));$=new ga({module:i,memory:j,onDemand:h?.passiveData===!0,mmapCursor:mt.allocatorControl(),sharedMmapRegistry:hn,fatalState:Rt.buffer,imports:o,size:ir,pid:m,executablePath:Ee,argv:f,cwd:W.currentWorkingDirectory(),stdioAliasRegistry:Mt.buffer,sharedPipes:Yt,signals:E,childPidAllocator:Et.buffer,...r?{inheritedFilesystemPolicy:r}:{},...e.browserProcessPorts?{browserProcessPorts:e.browserProcessPorts}:{},...e.browserProcess?.filesystemPolicyVersion===1?{childFilesystemPolicyVersion:1}:{},...e.threadOutputPorts?{outputPorts:e.threadOutputPorts}:{},...u instanceof Gr?{stdin:u.buffer}:{},terminal:e.terminal===!0,onStdout:S=>{Xt(1,S)},onStderr:S=>{Xt(2,S)},...U?{network:U}:{},...F?{filesystem:F}:{},...H?{codec:H}:{}}),await $.initialize()}const En=N.exports._start;if(typeof En!="function")throw new Error("WALI module does not export _start.");M&&x?.closePort(),g=performance.now();let Nn=0,lr=!1;try{try{for(xe&&Jt("asyncify_start_rewind",Z);En(),!!or;){Jt("asyncify_stop_unwind"),or=!1;const h=e.memoryLayout??(t instanceof WebAssembly.Module?void 0:Kr(t instanceof Uint8Array?t:new Uint8Array(t)));if(!h)throw new Error("Fork requires the module's imported memory layout.");const S={};for(const[O,D]of Object.entries(N.exports))if(D instanceof WebAssembly.Global)try{D.value=D.value,S[O]=D.value}catch{}const b=new SharedArrayBuffer(8*Int32Array.BYTES_PER_ELEMENT),A=new SharedArrayBuffer(jr);ke=Atomics.add(Et,0,1);const k=J.registerChild(ke,{control:b,response:A});if(k<0)throw new Error(`Fork child registration failed: ${k}`);const T=Number(jt.SYS_umask(0));jt.SYS_umask(T),e.onDiagnostic?.(`[WALI] fork snapshot: ${v().buffer.byteLength} bytes, Asyncify stack ${rt().getUint32(Z,!0)-Z-8} bytes.`),e.browserProcess.fork({module:i,memoryLayout:h,pid:ke,control:b,response:A,descriptorTable:F.copyForForkChannel(),childPidAllocator:Et.buffer,argv:f,env:{...e.env},cwd:ar(),executablePath:Ee,...n?{filesystemPolicy:n}:{},forkState:{control:b,response:A,memory:lt().slice().buffer,globals:S,allocator:mt.allocatorControl().slice(0),mappings:mt.forkSnapshot(),asyncifyData:Z,umask:T,parentPid:m}}),xe=!0,Jt("asyncify_start_rewind",Z)}}catch(h){if(h instanceof Ts)lr=!0;else if(h instanceof Fs||h instanceof Qs)Nn=h.code;else{if(h instanceof yi)throw h;{const S=h instanceof Error?h.stack??h.message:String(h),b=Atomics.load(Rt,1),A=$?.diagnostics(b>=0?b:void 0)??[];throw new Error(`${S}
|
|
10
10
|
WALI stdout:
|
|
11
11
|
${ue.decode(Ve(c))}
|
|
12
12
|
WALI stderr:
|