@volter/browser-substrate 0.1.111 → 0.1.112
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-TLQsaODy.js +3 -0
- package/dist/shell/assets/{browser-sandbox-bridge-hBxWLqQk.js → browser-sandbox-bridge-CmMlTDpO.js} +1 -1
- package/dist/shell/assets/{filesystem-host-9LBfR1Rt.js → filesystem-host-D98WfBoD.js} +1 -1
- package/dist/shell/assets/{filesystem-host-DxNGFCTZ.js → filesystem-host-EfkgP9Jh.js} +1 -1
- package/dist/shell/assets/{filesystem-worker-BVj1pBBE.js → filesystem-worker-51BLqPs5.js} +1 -1
- package/dist/shell/assets/{fork-worker-BqCN8ifL.js → fork-worker-hBikLg_q.js} +1 -1
- package/dist/shell/assets/{node-execution-worker-f4687130227370e7.js → node-execution-worker-5e417bedc3429b5c.js} +1 -1
- package/dist/shell/assets/{sandbox-BpNms5kO.js → sandbox-qgjYY5Gr.js} +1 -1
- package/dist/shell/assets/{shell-C-vckSqy.js → shell-C0qfPTpQ.js} +4 -4
- package/dist/shell/assets/{worker-USPIYmiu.js → worker-BZ-Txq9L.js} +1 -1
- package/dist/shell/assets/{worker-program-worker-qGFOwXwD.js → worker-program-worker-B_u8gbzh.js} +2 -2
- 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
- package/dist/shell/assets/browser-opfs-filesystem-worker-BcQkS5Ea.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const Fn="EINSTALLREFUSED",Ks="[install-trap-record]";class Qs extends Error{request;code=Fn;constructor(e){super(to(e)),this.request=e,this.name="InstallRefusedError"}}const Xs=Symbol.for("browser-substrate.install-recorder"),Zs=Symbol.for("browser-substrate.install-trapped");function Ln(n){const e=globalThis;throw(e[Zs]??=[]).push(n),e[Xs]?.(n),console.error(`[install-trap] ${n.door}: ${n.subject}`),console.info(`${Ks} ${JSON.stringify(n)}`),new Qs(n)}function eo(n){return typeof n!="object"||n===null?!1:n.code===Fn?!0:/^REFUSED \([^)]+\): /u.test(String(n.message??""))}function to(n){return[`REFUSED (${n.door}): ${n.subject}`,"","The tab never installs, downloads, extracts or builds a dependency, and never runs a setup step. Everything a","project uses reaches it prepared, with the image or from the catalog, and this was not. Nothing was attempted.","",...n.fix?[`To fix it: ${n.fix}`]:["To fix it, prepare the image again on a machine, from the project's folder:",""," npx @volter/browser-substrate dev"]].join(`
|
|
2
|
-
`)}const $n=2019846480,Vt=6,oe=6,rt=3,Jt=0,ut=1,Pe=2,Rn=3,Bn=4,Dn=5,Cn=0,zn=1,Un=2,Ht=1,jn=2,qn=4,Gt=32,br=3,Er=["file","directory","symlink"],ro=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,no=new TextEncoder,so=new TextDecoder;function Wn(n){let e=2166136261;for(let t=0;t<n.length;t+=1)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function on(n,e){const t=[...n.keys()];for(const A of t)if(ro.test(A))throw new Error("A path in the store is not well-formed UTF-16.");const s=new Map;for(let A=0;A<t.length;A+=1)s.set(t[A],A);for(const A of e.keys())s.has(A)||(s.set(A,t.length),t.push(A));const a=t.length,d=new Map,f=new Uint32Array(a);let h=0;for(let A=0;A<a;A+=1){const x=t[A];let D=!0;for(let H=0;H<x.length;H+=1)if(x.charCodeAt(H)>=128){D=!1;break}D||d.set(A,no.encode(x)),f[A]=D?x.length:d.get(A).length,h+=f[A]}let m=0;for(const A of e.values())m+=A.size;let w=1;for(;w<a*2;)w<<=1;const b=Vt*4,E=kr(b+a*oe*4,8),S=E+a*rt*8,T=S+w*4,g=T+m*4,U=new SharedArrayBuffer(kr(g+h,8));new Uint32Array(U,0,Vt).set([$n,a,w,m,h,n.size]);const J=new Uint32Array(U,b,a*oe),q=new Float64Array(U,E,a*rt),_e=new Uint32Array(U,S,w),N=new Uint32Array(U,T,m),R=new Uint8Array(U,g,h);let L=0,P=0;for(let A=0;A<a;A+=1){const x=t[A],D=A*oe,H=d.get(A);if(H)R.set(H,L);else for(let M=0;M<x.length;M+=1)R[L+M]=x.charCodeAt(M);const v=f[A];J[D+Jt]=L,J[D+ut]=v,L+=v;let K=H?0:Gt;const te=n.get(x);if(te){K|=Ht|Er.indexOf(te.type)<<br,te.pack&&(K|=qn),J[D+Rn]=te.mode;const M=A*rt;q[M+Cn]=te.mtimeMs,q[M+zn]=te.offset,q[M+Un]=te.length}const ve=e.get(x);if(ve){K|=jn,J[D+Bn]=P,J[D+Dn]=ve.size;for(const M of ve){const B=s.get(`${x}/${M}`);if(B===void 0)throw new Error(`The store's children name ${x}/${M}, which its index does not hold.`);N[P++]=B}}J[D+Pe]=K;let ge=Wn(x)&w-1;for(;_e[ge]!==0;)ge=ge+1&w-1;_e[ge]=A+1}if(P!==m)throw new Error("The shared index's children did not add up.");return U}function kr(n,e){return Math.ceil(n/e)*e}class Re{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,Vt);if(t[0]!==$n)throw new Error("Not a shared store index.");const[,s,a,d,f,h]=t;this.buffer=e,this.count=s,this.entryCount=h;const m=Vt*4,w=kr(m+s*oe*4,8),b=w+s*rt*8,E=b+a*4,S=E+d*4;this.records=new Uint32Array(e,m,s*oe),this.numbers=new Float64Array(e,w,s*rt),this.table=new Uint32Array(e,b,a),this.childList=new Uint32Array(e,E,d),this.strings=new Uint8Array(e,S,f),this.mask=a-1}find(e){let t=Wn(e)&this.mask;for(;;){const s=this.table[t];if(s===0)return-1;if(this.pathIs(s-1,e))return s-1;t=t+1&this.mask}}entry(e){const t=e*oe,s=this.records[t+Pe];if(!(s&Ht))return;const a=e*rt,d={type:Er[s>>>br&3],mode:this.records[t+Rn],mtimeMs:this.numbers[a+Cn],offset:this.numbers[a+zn],length:this.numbers[a+Un]};return s&qn&&(d.pack="packages"),d}typeAt(e){const t=this.records[e*oe+Pe];return t&Ht?Er[t>>>br&3]:void 0}hasEntry(e){return(this.records[e*oe+Pe]&Ht)!==0}childNames(e){const t=e*oe;if(!(this.records[t+Pe]&jn))return;const s=this.records[t+Bn],a=this.records[t+ut]+1,d=[];for(let f=0;f<this.records[t+Dn];f+=1){const h=this.childList[s+f]*oe;d.push(this.decode(this.records[h+Jt]+a,this.records[h+ut]-a,(this.records[h+Pe]&Gt)!==0))}return d}path(e){const t=e*oe;return this.decode(this.records[t+Jt],this.records[t+ut],(this.records[t+Pe]&Gt)!==0)}decode(e,t,s){if(!s)return so.decode(this.strings.slice(e,e+t));let a="";for(let d=e,f=e+t;d<f;d+=4096)a+=String.fromCharCode.apply(null,this.strings.subarray(d,Math.min(f,d+4096)));return a}pathIs(e,t){const s=e*oe,a=this.records[s+Jt],d=this.records[s+ut];if(!(this.records[s+Pe]&Gt))return this.path(e)===t;if(d!==t.length)return!1;for(let f=0;f<d;f+=1)if(this.strings[a+f]!==t.charCodeAt(f))return!1;return!0}}const le=Symbol("deleted");function Jn(n,e){return n===e||!!n&&!!e&&n.type===e.type&&n.offset===e.offset&&n.length===e.length&&n.pack===e.pack&&n.mode===e.mode&&n.mtimeMs===e.mtimeMs&&n.capacity===e.capacity}class Ke{base;overlay=new Map;delta=0;constructor(e){this.base=e}get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const s=this.base.find(e);return s<0?void 0:this.base.entry(s)}typeOf(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t.type;const s=this.base.find(e);return s<0?void 0:this.base.typeAt(s)}has(e){const t=this.overlay.get(e);if(t!==void 0)return t!==le;const s=this.base.find(e);return s>=0&&this.base.hasEntry(s)}set(e,t){this.has(e)||(this.delta+=1);const s=this.base.find(e);return s>=0&&Jn(this.base.entry(s),t)?this.overlay.delete(e):this.overlay.set(e,t),this}delete(e){if(!this.has(e))return!1;const t=this.base.find(e);return t>=0&&this.base.hasEntry(t)?this.overlay.set(e,le):this.overlay.delete(e),this.delta-=1,!0}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t]);for(let e=0;e<this.base.count;e+=1){if(!this.base.hasEntry(e))continue;const t=this.base.path(e);this.overlay.has(t)||(yield[t,this.base.entry(e)])}}*keys(){for(const[e]of this.entries())yield e}*values(){for(const[,e]of this.entries())yield e}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[s,a]of this.entries())e.call(t,a,s,this)}*changed(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t])}*changes(){for(const[e,t]of this.overlay)yield[e,t===le?null:t]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const e=[];let t=0;for(const[s,a]of this.changes()){if(t+=s.length*2+128,t>8*1024*1024)return;e.push([s,a])}return e}}class $t{base;overlay=new Map;constructor(e){this.base=e}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const s=this.base.find(e),a=s<0?void 0:this.base.childNames(s);return a?new Set(a):void 0}mutable(e){const t=this.overlay.get(e);if(t!==void 0&&t!==le)return t;const s=new Set(t===le?[]:this.get(e)??[]);return this.overlay.set(e,s),s}delete(e){this.overlay.set(e,le)}}const oo="supercode-browser-filesystems",Ae="packages",io="state.json",an="/image-range-worker.js",cn="image-ranges.json",ao=2;function ur(n){const e=n;if(!e||e.version!==1||!Number.isSafeInteger(e.bytes)||e.bytes<0||!Array.isArray(e.parts)||e.image!==void 0&&(typeof e.image!="string"||!/^[a-f0-9]{16,64}$/u.test(e.image))||e.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let t=0;for(const s of e.parts){if(!s||s.offset!==t||!Number.isSafeInteger(s.raw)||s.raw<0||!Number.isSafeInteger(s.bytes)||s.bytes<0||s.bytes>1024*1024*1024||s.raw>1024*1024*1024||typeof s.sha256!="string"||!/^[a-f0-9]{64}$/u.test(s.sha256)||typeof s.url!="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(s.url)||s.url.split("/").some(a=>a==="."||a===".."))throw new Error("Invalid immutable image part.");if(t+=s.raw,!Number.isSafeInteger(t))throw new Error("Immutable image ranges exceed the offset limit.")}if(t!==e.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return e}const ln=new Map;class co{ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=!1;ready=!1;startup;cancelStartup;sharedCompletion;constructor(e,t,s,a,d,f){if(this.ranges=e,this.directory=t,this.identity=s,this.receiptKey=d,this.client=f,typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("This browser cannot materialize an immutable image during a synchronous read.");if(this.state=new Int32Array(f?.state??new SharedArrayBuffer(e.parts.length*Int32Array.BYTES_PER_ELEMENT)),this.state.length!==e.parts.length)throw new Error("The image reader's line has the wrong range count.");const h=e.parts.length,m=a??new SharedArrayBuffer((2*h+1)*Int32Array.BYTES_PER_ELEMENT);if(m.byteLength!==h*Int32Array.BYTES_PER_ELEMENT&&m.byteLength!==(2*h+1)*Int32Array.BYTES_PER_ELEMENT)throw new Error("The image completion seed has the wrong range count.");this.completed=new Int32Array(m,0,h),this.firstRead=m.byteLength>h*Int32Array.BYTES_PER_ELEMENT?new Int32Array(m,h*Int32Array.BYTES_PER_ELEMENT,h+1):void 0,this.sharedCompletion=a!==void 0;for(const w of e.parts)Object.freeze(w);Object.freeze(e.parts),Object.freeze(e)}get completionBuffer(){return this.completed.buffer}get verifiedRanges(){return this.ranges}async initialize(){if(this.closed)throw new Error("This immutable image reader is closed.");if(this.ready)return;if(this.startup)return this.startup;let e=!1;for(let t=0;t<this.completed.length;t+=1)if(Atomics.load(this.completed,t)!==2){e=!0;break}if(!e){this.ready=!0,this.client?.port.close();return}if(this.client){const t=this.port=this.client.port;t.onmessage=s=>{s.data?.type!=="closing"||this.port!==t||(t.close(),this.port=void 0,this.closed||this.startMaterializer().catch(a=>console.warn("This process's image reader could not start its own materializer after its line closed.",a)))},t.start(),this.ready=!0;return}return this.startMaterializer()}startMaterializer(){const e=Date.now(),t=new Worker(an,{type:"module",name:"immutable-image-materializer"}),s=this.ready;return s||(this.worker=t),t.addEventListener("error",()=>this.fail()),t.addEventListener("messageerror",()=>this.fail()),this.startup=new Promise((a,d)=>{const f=()=>{clearTimeout(b),t.removeEventListener("message",w),t.removeEventListener("error",h),t.removeEventListener("messageerror",h),this.cancelStartup=void 0},h=()=>m(new Error("The immutable image materializer could not initialize; reload to retry.")),m=E=>{f(),t.terminate(),s||(this.closed=!0,this.fail()),d(E)},w=E=>{if(E.data?.identity===this.identity){if(E.data.type==="init-error"){m(new Error(`The immutable image materializer could not initialize: ${String(E.data.error)}`));return}E.data.type==="ready"&&(console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-e})}`),f(),this.ready=!0,this.worker=t,a())}},b=setTimeout(()=>m(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=m,t.addEventListener("message",w),t.addEventListener("error",h),t.addEventListener("messageerror",h);try{t.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:this.state.buffer,completed:this.completed.buffer,sharedCompletion:this.sharedCompletion,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}catch(E){m(E instanceof Error?E:new Error(String(E)))}}),this.startup}readDigests(){const e=this.firstRead;if(!e)return;const t=this.ranges.parts.length,s=[];for(let a=0;a<t;a+=1){const d=Atomics.load(e,a),f=this.ranges.parts[a];d>0&&f.raw>0&&s.push([d,f.sha256])}return s.sort((a,d)=>a[0]-d[0]).map(([,a])=>a)}completedDigests(){const e=[];for(let t=0;t<this.completed.length;t+=1){const s=this.ranges.parts[t];s.raw>0&&Atomics.load(this.completed,t)===2&&e.push(s.sha256)}return e}prefetch(e,t=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const s=new Map;for(let h=0;h<this.ranges.parts.length;h+=1){const m=this.ranges.parts[h];if(m.raw===0)continue;const w=s.get(m.sha256);w?w.push(h):s.set(m.sha256,[h])}const a=[];for(const h of new Set(e))for(const m of s.get(h)??[])Atomics.load(this.completed,m)!==2&&a.push(m);const d=t.length>0&&a.length>0?Math.min(t.length,8):Math.min(ao,Math.ceil(a.length/32)),f=[];for(let h=0;h<d;h+=1){const m=a.filter((S,T)=>T%d===h),w=new Worker(an,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(w);let b;f.push(new Promise(S=>{b=S}));const E=()=>{w.terminate(),this.prefetchers=this.prefetchers.filter(S=>S!==w),b()};w.addEventListener("error",E),w.addEventListener("messageerror",E),w.addEventListener("message",S=>{S.data?.identity===this.identity&&(S.data.type==="ready"?w.postMessage(t.length>0?{type:"prefetch-stream",url:t[h]}:{type:"prefetch",indices:m}):(S.data.type==="prefetched"||S.data.type==="init-error")&&E())}),w.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:new SharedArrayBuffer(this.state.byteLength),completed:this.completed.buffer,sharedCompletion:!0,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}return{queued:a.length,done:Promise.all(f).then(()=>{})}}ensure(e,t){if(this.closed)throw new Error("This immutable image reader is closed.");if(!this.ready)throw new Error("This immutable image reader has not finished asynchronous initialization.");if(t===0||e>=this.ranges.bytes)return;const s=Math.min(e+t,this.ranges.bytes);let a=0,d=this.ranges.parts.length;for(;a<d;){const f=a+d>>>1,h=this.ranges.parts[f];h.offset+h.raw<=e?a=f+1:d=f}for(let f=a;f<this.ranges.parts.length;f+=1){const h=this.ranges.parts[f];if(h.offset>=s)break;const m=this.firstRead;if(m&&Atomics.load(m,f)===0&&Atomics.compareExchange(m,f,0,Atomics.add(m,this.ranges.parts.length,1)+1),Atomics.load(this.completed,f)===2)continue;const w=this.worker??this.port;if(!w)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");w.postMessage({type:"read",index:f});const b=performance.now(),E=b+3e4;for(;Atomics.load(this.state,f)===0;){const g=E-performance.now();if(g<=0||Atomics.wait(this.state,f,0,g)==="timed-out")throw this.close(),new Error(`The image's immutable part ${h.url} did not arrive within 30 seconds; reload to retry.`)}const S=performance.now()-b,T=ln.get(this.identity)??{ranges:0,ms:0};if(T.ranges+=1,T.ms+=S,ln.set(this.identity,T),console.log(`[boot-trace] ${JSON.stringify({event:"image-blocked",at:Date.now(),reader:this.identity,index:f,range:h.sha256.slice(0,16),ms:Math.round(S)})}`),Atomics.load(this.state,f)!==2)throw new Error(`The image's immutable part ${h.url} could not be verified or stored; see the worker error and reload to retry.`)}}lineForReader(){const e=this.worker??this.port;if(this.closed||!this.ready||!e)return;const t=new MessageChannel,s=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);return e.postMessage({type:"client",port:t.port1,state:s},[t.port1]),{port:t.port2,state:s}}fail(){for(let e=0;e<this.state.length;e+=1)Atomics.compareExchange(this.state,e,0,-1)===0&&Atomics.notify(this.state,e)}close(){if(this.closed)return;if(this.closed=!0,this.cancelStartup){this.cancelStartup(new Error("This immutable image reader closed during initialization."));return}this.fail(),this.port?.close();const e=this.worker;e&&(e.postMessage({type:"closing"}),setTimeout(()=>e.terminate(),250));for(const t of this.prefetchers)t.dispatchEvent(new Event("error"));this.prefetchers=[]}}const pr="/packages",Rt="supercode-browser-packages",Be=new TextEncoder,Qe=new TextDecoder("utf-8",{fatal:!0}),lo=oo,Bt="generations",dn="atomic-staging",Xe=io,de="index.json",hr="index-log.bin",Ze="pack.bin",Dt=8,fn=64*1024*1024,se=1024*1024*1024,un=4*1024*1024*1024,fo=16*1024*1024*1024,uo=["/workspace","/home","/opt"],De=0,pn=1,wr=1e6,hn=8*1024*1024,wn=250,po=64*1024*1024,ho=256*1024*1024,mn=4*1024*1024,et=493,Ct=420;function yn(n,e={}){const t=e.limits?.maxBytes??un,s=e.limits?.maxEntries??wr;if(!Number.isSafeInteger(t)||t<1||t>un||!Number.isSafeInteger(s)||s<1||s>wr)throw new Error("Invalid OPFS workspace limits.");let a,d=!1,f=!1,h=!1,m,w=0,b=0,E,S,T,g=new Map,U=new zt,$,J,q,_e,N,R,L=0,P,A=0;const x=new Map,D=256*1024,H=32;let v=0,K,te=-1/0,ve=0,ge=0,M=0,B=0,Q=0,Ie=0,Oe=0,ae,mt,fe,qe=!1,st,Nr=Promise.resolve(),We=0,Y=!1,Je=!1,V,Ne=0,ue=!1;function yt(){if(!(!V||ue)){if(M>2147483647){_t();return}Atomics.store(V,pn,M)}}function _t(){!V||ue||(ue=!0,(Atomics.load(V,De)&1)===0&&Atomics.add(V,De,1))}function ot(){Ne+=1,Ne===1&&V&&!ue&&Atomics.add(V,De,1)}function it(){Ne-=1,!(Ne>0||!V||ue)&&(yt(),ue||Atomics.add(V,De,1))}function Tr(){if(f)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");return V||(V=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT)),V[De]=Ne>0||ue?1:0,yt()),V.buffer}let re;const ls=8*1024*1024;let Mr=!1;function ds(r){if(f||!V||!T||qe||Ne>0||ue||Y)return;const o=Atomics.load(V,De);if(o&1)return;if(r?.overlays&&g instanceof Ke){const l=g.boundedChanges();if(l)return Zt({generation:T,index:g.base.buffer,changes:l,packBytes:v,logBytes:M,epoch:o,liveBytes:B,linked:w,linkedBytes:b})}if(re&&re.generation===T&&re.epoch===o&&M>=re.logBytes&&M-re.logBytes<=(r?.current?0:ls))return Zt(re);let i;try{i=on(g,ps())}catch(l){console.warn(`[pack-store] no reader seed: ${l instanceof Error?l.message:String(l)}`);return}return re={generation:T,index:i,packBytes:v,logBytes:M,epoch:o,liveBytes:B,linked:w,linkedBytes:b},us(i),Zt(re)}function Zt(r){const o=e.packages?.imageCompletionSeed();return o?{...r,packagesImage:o}:r}function fs(){if(!(!q||!J||!T||qe||Ne>0||Y))return{generation:T,rangesDigest:J,completed:q.completionBuffer,...q.receiptKey?{metadata:{ranges:q.verifiedRanges,receiptKey:q.receiptKey}}:{}}}function us(r){const o=[];if(g instanceof Ke)for(const[l,c]of g.changed())c.capacity!==void 0&&o.push([l,c]);else for(const[l,c]of g)c.capacity!==void 0&&o.push([l,c]);const i=new Re(r);g=new Ke(i),U=new $t(i);for(const[l,c]of o)g.set(l,c)}function ps(){if(U instanceof zt)return U.map;const r=new Map;for(const o of g.keys()){const i=Le(o);if(i===o)continue;let l=r.get(i);l||(l=new Set,r.set(i,l)),l.add(o.slice(i.length+1))}return r}function hs(){!f||h||Y||!P||St(M)}async function gt(r){if(Y)throw new Error("This OPFS workspace is closing.");We+=1;let o,i=!1;try{return await r()}catch(l){throw i=!0,o=l,l}finally{if(We-=1,Y&&We===0)try{rn()}catch(l){throw i?new AggregateError([o,l],"OPFS operation and deferred close both failed."):l}}}async function bt(r){return be(),We!==0?Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation.")):(Je=!0,gt(async()=>{try{return await r()}finally{Je=!1}}))}function ws(r){if(Y)throw new Error("This OPFS workspace is closing.");const o=g.get(r);if(!o||o.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);return Et(o)}function ms(r,o,i){if(Y)throw new Error("This OPFS workspace is closing.");const l=g.get(r);if(!l||l.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);const c=Math.min(Math.max(0,o),l.length),u=Math.min(Math.max(0,i),l.length-c);if(l.pack){const p=e.packages;if(!p)throw new Error("This store has no shared package store to read from.");return p.readExtent(l.offset+c,u)}return kt(l.offset+c,u)}function Et(r){if(r.pack){const o=e.packages;if(!o)throw new Error("This store has no shared package store to read from.");return o.readExtent(r.offset,r.length)}return kt(r.offset,r.length)}function kt(r,o){if(Y)throw new Error("This OPFS workspace is closing.");const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=new Uint8Array(o);if(o>0&&o<=D&&r>=0&&r+o<=A){let c=0;for(;c<o;){const u=r+c,p=Math.floor(u/D)*D;let y=x.get(p);if(!y&&(y=new Uint8Array(Math.min(D,A-p)),q?.ensure(p,y.byteLength),i.read(y,{at:p})!==y.byteLength))throw new Error("An OPFS package range could not be read completely.");x.delete(p),x.set(p,y),x.size>H&&x.delete(x.keys().next().value);const _=u-p,k=Math.min(o-c,y.byteLength-_);l.set(y.subarray(_,_+k),c),c+=k}return l}if(q?.ensure(r,o),o>0&&i.read(l,{at:r})!==o)throw new Error("An OPFS workspace file could not be read completely.");return l}async function ys(r,o={}){if(Y&&a||!a&&We!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(qe)throw new Error("This OPFS store is already opening a workspace.");if(a){if(S!==$r(r))throw new Error("Close this OPFS store before opening another workspace.");return g.size>0}qe=!0,Y=!1;const i=new AbortController;st=i;try{g=new Map,U=new zt,T=void 0,J=void 0,m=void 0,ae=void 0,fe=void 0,v=M=B=Q=w=b=0,he=void 0,Ie=Oe=ve=ge=0,te=-1/0,S=$r(r),f=o.readOnly===!0,N=f?o.imageCompletion:void 0,R=f?o.imageLine:void 0,h=f&&o.extentsOnly===!0,d=o.shared===!0||f,d||await ks(i.signal),i.signal.throwIfAborted();const l=await gs();i.signal.throwIfAborted();try{const p=await l.getDirectoryHandle(lo,{create:!f});i.signal.throwIfAborted(),a=await p.getDirectoryHandle(S,{create:!f})}catch(p){if(i.signal.throwIfAborted(),f&&Ve(p))return!1;throw p}i.signal.throwIfAborted();let c=Ft(await Fe(a,Xe));if(i.signal.throwIfAborted(),!c&&f)return await tr(),!1;if(!c&&d&&(await n.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{i.signal.throwIfAborted(),c=Ft(await Fe(a,Xe)),i.signal.throwIfAborted(),c||(await tr(),await qr({files:[],pack:new ArrayBuffer(0)}),await yo(a))}),i.signal.throwIfAborted(),!c))return m=await pe(T,!1),i.signal.throwIfAborted(),!1;if(!c)return await tr(),i.signal.throwIfAborted(),!1;const u=async p=>{let y;try{y=await pe(p.generation,!1)}catch(O){throw i.signal.throwIfAborted(),Ve(O)?new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause:O}):O}if(i.signal.throwIfAborted(),T=p.generation,L=p.initializedAt,J=p.imageRanges,m=y,h)return S===Ae&&n.navigator.locks?await n.navigator.locks.request(Rt,{mode:"shared",signal:i.signal},async()=>{await He(y),A=$.getSize()}):await He(y),i.signal.throwIfAborted(),!0;const _=f?o.seed:void 0;if(_&&_.generation===p.generation){const O=new Re(_.index);return g=new Ke(O),U=new $t(O),v=_.packBytes,_.changes&&Lr({packBytes:_.packBytes,changes:_.changes}),await He(y),i.signal.throwIfAborted(),M=_.logBytes,{liveBytes:B,linked:w,linkedBytes:b}=_,Q=Math.max(0,v-B),Mr=!0,g.size>0}const k=f?void 0:await js(y);if(i.signal.throwIfAborted(),k){const O=new Re(k.index);g=new Ke(O),U=new $t(O),{packBytes:v,liveBytes:B,linked:w,linkedBytes:b}=k;const I=Atomics.load(new Int32Array(Tr()),De);re={generation:T,index:k.index,packBytes:v,liveBytes:B,linked:w,linkedBytes:b,logBytes:0,epoch:I}}else g=lr(await Fe(y,de)),i.signal.throwIfAborted(),Ye(),v=er(g);await He(y),i.signal.throwIfAborted();const F=k?await qs(k):0;return i.signal.throwIfAborted(),F&&(he={generation:T,bytes:F},re&&(re.logBytes=F)),St(F,!!k),k?Q=Math.max(0,v-B):at(),Ur(),d&&!f&&!k&&g.size>=1e4&&(ke(),await dt(y,g,{access:P,bytes:M,packBytes:v})),d||($.truncate(v),await Gr(a,dn,!0),await rr(T),i.signal.throwIfAborted(),Q>po&&Q>B&&await Ms()),i.signal.throwIfAborted(),g.size>0};return d&&!f?await n.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{if(c=Ft(await Fe(a,Xe)),!c)throw new Error("The committed package store state is missing. Stored data was retained.");return u(c)}):await u(c)}catch(l){const c=[l];try{Ge()}catch(u){c.push(u)}try{E?.()}catch(u){c.push(u)}throw E=void 0,a=void 0,c.length>1?new AggregateError(c,"OPFS workspace open and cleanup failed."):l}finally{qe=!1,st=void 0}}function _s(r){return gt(()=>Fr(r?.whole===!0))}async function Fr(r=!1){if(h)throw new Error("A store opened for its extents alone has no index to follow.");if(f&&a){const u=Ft(await Fe(a,Xe));if(!u)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(u.generation!==T||r){const p=await pe(u.generation,!1),y=lr(await Fe(p,de));v=er(y),u.generation!==T&&(T=u.generation,L=u.initializedAt,J=u.imageRanges,await He(p)),T=u.generation,m=p,g=y,Ye(),St(),at();return}}const o=P;if(!o||!m)return;const i=o.getSize();let l=!1;i<M&&(g=lr(await Fe(m,de)),Ye(),v=er(g),M=0,l=!0);const c=M;St(M),(l||M!==c)&&at()}async function gs(){let r;for(let o=0;o<10;o+=1){st?.signal.throwIfAborted();try{return await n.navigator.storage.getDirectory()}catch(i){r=i,await new Promise(l=>setTimeout(l,200))}}throw r instanceof Error?r:new Error("This browser workspace's storage is unavailable.")}const bs=1e4;async function Z(r,o){let i;const l=st?.signal;for(let u=0;u<2;u+=1){l?.throwIfAborted();const p=r.createSyncAccessHandle({mode:"readwrite-unsafe"});let y,_,k=!1;try{const F=new Promise((I,j)=>{_=()=>j(l?.reason??new DOMException("Workspace open was cancelled.","AbortError")),l?.addEventListener("abort",_,{once:!0}),l?.aborted&&_()}),O=await Promise.race([p.then(I=>({access:I})).catch(I=>{i=I}),new Promise(I=>{y=setTimeout(()=>I(void 0),bs)}),F]);if(l?.throwIfAborted(),O)return k=!0,O.access}finally{y!==void 0&&clearTimeout(y),_&&l?.removeEventListener("abort",_),k||p.then(F=>F.close(),()=>{}).catch(F=>console.error("Late workspace handle cleanup failed.",F))}if(i instanceof TypeError)throw new Error(`This browser cannot share a workspace's files between pages: its file access handles have no readwrite-unsafe mode (Chrome 121 or newer has one). ${i.message}`);await new Promise(F=>setTimeout(F,500))}const c=i instanceof Error?` (${i.message})`:"";throw new Error(`This browser workspace's ${o} is held by another page${c}.`)}async function He(r){Ge();const o=await r.getFileHandle(Ze);$=await Z(o,"store");try{if($.getSize()<v)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const i=await r.getFileHandle(hr);if(P=await Z(i,"record of changes"),M=P.getSize(),J){const l=N,c=l&&l.generation===T&&l.rangesDigest===J?l:void 0;let u,p;if(c?.metadata){if(u=ur(c.metadata.ranges),p=c.metadata.receiptKey,!/^[a-f0-9]{64}$/u.test(p))throw new Error("The owner's immutable receipt key is invalid.")}else{const _=await(await r.getFileHandle(cn)).getFile(),k=new Uint8Array(await _.arrayBuffer());if(await me(k)!==J)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");u=ur(JSON.parse(Qe.decode(k))),p=await me(Be.encode(JSON.stringify(u)))}if(u.bytes>$.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const y=c?R:void 0;y||R?.port.close(),R=void 0,q=new co(u,r,`${S}.${T}`,c?.completed,p,y),console.log(`[boot-trace] ${JSON.stringify({event:"image-reader-open",at:Date.now(),reader:`${S}.${T}`,offered:l!==void 0,shared:c!==void 0,...l&&!c?{offeredGeneration:l.generation,generation:T,rangesMatch:l.rangesDigest===J}:{}})}`),await q.initialize(),_e=u.image}}catch(i){throw Ge(),i}}function Ge(){q?.close(),q=void 0,_e=void 0;const r=$,o=P;$=void 0,P=void 0,M=0,A=0,x.clear();try{r?.close()}finally{o?.close()}}function St(r=0,o=!1){const i=P;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=i.getSize();if(l<=r){M=l;return}const c=new Uint8Array(l-r);if(i.read(c,{at:r})!==c.byteLength)throw new Error("The OPFS workspace index log could not be read.");const u=$?.getSize()??1/0,p=new DataView(c.buffer);let y=0;const _=c.byteLength;for(;y+Dt<=_;){const k=p.getUint32(y,!0),F=p.getUint32(y+4,!0),O=y+Dt;if(k===0||k>fn||O+k>_)break;const I=c.subarray(O,O+k);if(Zr(I)!==F)break;let j;try{j=Hs(JSON.parse(Qe.decode(I)))}catch{break}if(j.packBytes>u)break;Lr(j,o),y=O+k}y!==_&&!d&&i.truncate(r+y),M=r+y}function Lr(r,o=!1){for(const[i,l]of r.changes){const c=g.get(i);if(l&&Jn(c,l)){At(i);continue}o&&(c?.pack?(w-=1,b-=c.length):c&&(B-=c.length),l?.pack?(w+=1,b+=l.length):l&&(B+=l.length)),l===null?(g.delete(i),Br(i)):(g.set(i,l),At(i))}v=Math.max(v,r.packBytes)}function at(){B=0,w=0,b=0;for(const r of g.values())r.pack?(w+=1,b+=r.length):B+=r.length;Q=Math.max(0,v-B)}function er(r){let o=0;for(const i of r.values())i.pack||(o=Math.max(o,i.offset+i.length));return o}const Es=5e3;async function ks(r){if(!n.navigator.locks)return;if(!S)throw new Error("OPFS filesystem project is not initialized.");const o=new AbortController,i=setTimeout(()=>o.abort(),Es);try{await new Promise((l,c)=>{n.navigator.locks.request(`supercode-browser-filesystem-${S}`,{mode:"exclusive",signal:r?AbortSignal.any([r,o.signal]):o.signal},async()=>{clearTimeout(i),l(),await new Promise(u=>{E=u})}).catch(()=>c(r?.aborted?r.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(i)}}function $r(r){if(typeof r!="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(r))throw new Error("OPFS filesystem projectId is invalid.");return r}async function Te(){if(!a)throw new Error("OPFS filesystem worker is not initialized.");return a}async function pe(r,o){return(await(await Te()).getDirectoryHandle(Bt,{create:o})).getDirectoryHandle(r,{create:o})}async function tr(){let r;try{r=await(await Te()).getDirectoryHandle(Bt)}catch(o){if(Ve(o))return;throw o}for await(const o of r.entries())throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}async function rr(r){const o=await Te();let i;try{i=await o.getDirectoryHandle(Bt)}catch(l){if(Ve(l))return;throw l}for await(const[l]of i.entries())l!==r&&await Yr(i,l)}function be(){if(Y)throw new Error("This OPFS workspace is closing.");if(Je)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(f)throw new Error("This store is open for reading; its owner writes it.");if(fe)throw fe}async function Ss(r){en(r)}let nr=!1,Pt=0,he,sr=!1;function Rr(){if(Pt>0)return;const r=he&&he.generation===T&&he.bytes<=M?he.bytes:0;M-r>hn&&!nr&&(nr=!0,(d?n.navigator.locks.request(Rt,{mode:"exclusive"},async()=>{if(!a||Y)return;await Fr();const i=he,l=i&&i.generation===T&&i.bytes<=M?i.bytes:0;M-l>hn&&await Ot()}):Ot()).catch(i=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",i)).finally(()=>{nr=!1})),!d&&!sr&&Q>ho&&Q>B&&(sr=!0,gt(Fs).catch(o=>console.error("The workspace could not be compacted; it keeps its generation.",o)).finally(()=>{sr=!1}))}async function Ps(r){be(),Pt+=1;try{return await r()}finally{Pt-=1,Pt===0&&!Y&&a&&Rr()}}function As(r,o){const i=ye(r.path);if(r.operation==="write"){if(g.get(i)?.type==="directory")throw new Error(`OPFS write target is a directory: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const c=r.content;if(c.byteLength>se)throw new Error(`${i} is ${c.byteLength} bytes; an OPFS workspace file holds at most ${se}.`);xt(i,c.byteLength),Me(i,o);const u=It(c);ee(i,{type:r.symlink?"symlink":"file",mode:r.mode??g.get(i)?.mode??Ct,mtimeMs:r.mtimeMs??Date.now(),offset:u,length:c.byteLength},o);return}if(r.operation==="append"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS append target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const u=r.content,p=(c?.length??0)+u.byteLength;if(p>se)throw new Error(`${i} is ${p} bytes; an OPFS workspace file holds at most ${se}.`);xt(i,p),Me(i,o);const y=r.mode??c?.mode??Ct,_=r.mtimeMs??Date.now(),k=c&&!c.pack?c.capacity??c.length:0;if(S!==Ae&&c&&!c.pack&&c.length>0&&(p<=k||c.offset+k===v)){vt(c.offset+c.length,u),ee(i,{...c,mode:y,mtimeMs:_,length:p,capacity:Math.max(k,p)},o),Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length;return}const F=new Uint8Array(p);c&&c.length>0&&F.set(Et(c),0),F.set(u,p-u.byteLength);const O=It(F),I=Math.min(se,Math.max(p,p*2,64*1024));I>p&&jr(O+I),ee(i,{type:"file",mode:y,mtimeMs:_,offset:O,length:p,capacity:I},o);return}if(r.operation==="write-at"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS write target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const u=r.content,p=r.position,y=c?.length??0;if(u.byteLength===0&&c)return;const _=u.byteLength===0?y:Math.max(y,p+u.byteLength);if(_>se)throw new Error(`${i} is ${_} bytes; an OPFS workspace file holds at most ${se}.`);xt(i,_),Me(i,o);const k=r.mode??c?.mode??Ct,F=r.mtimeMs??Date.now(),O=c&&!c.pack?c.capacity??c.length:0;if(S!==Ae&&c&&!c.pack&&y>0&&(_<=O||c.offset+O===v)){if(p>y&&vt(c.offset+y,new Uint8Array(p-y)),mt&&p<y){const ne=Math.min(y,p+u.byteLength);mt.push([c.offset+p,kt(c.offset+p,ne-p)])}vt(c.offset+p,u),ee(i,{...c,mode:k,mtimeMs:F,length:_,capacity:Math.max(O,_)},o),_!==y&&(Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length);return}const I=new Uint8Array(_);c&&y>0&&I.set(Et(c),0),u.byteLength>0&&I.set(u,p);const j=It(I),W=Math.min(se,Math.max(_,_*2,64*1024));W>_&&jr(j+W),ee(i,{type:"file",mode:k,mtimeMs:F,offset:j,length:_,capacity:W},o);return}if(r.operation==="mkdir"){Me(i,o);const c=g.get(i);if(c&&c.type!=="directory")throw new Error(`OPFS path is a file: ${i}`);ee(i,{type:"directory",mode:r.mode??c?.mode??et,mtimeMs:r.mtimeMs??c?.mtimeMs??Date.now(),offset:0,length:0},o);return}if(r.operation==="remove"){ir(i,o),Ee().includes(i)&&ee(i,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0},o);return}if(r.operation==="link"){xs(i,zr(r.source),o);return}if(r.operation==="rename"){vs(i,ye(r.destination),o);return}const l=g.get(i);if(!l)throw new Error(`OPFS metadata target does not exist: ${i}`);ee(i,{...l,mode:r.mode??l.mode,mtimeMs:r.mtimeMs??l.mtimeMs},o)}function ee(r,o,i){const l=g.get(r);ae&&!ae.has(r)&&ae.set(r,l);const c=l!==void 0&&l.type===o.type&&l.offset===o.offset&&l.length===o.length&&l.pack===o.pack;l&&!c&&(Dr(l),l.type!=="directory"&&o.type!=="directory"&&l.length>0&&!l.pack&&(Ie+=1,Oe+=l.length)),g.set(r,o),At(r),c||(o.pack?(w+=1,b+=o.length):B+=o.length),i.push([r,o])}function At(r){const o=Le(r);o!==r&&U.mutable(o).add(r.slice(o.length+1))}function Br(r){const o=Le(r);U.get(o)?.has(r.slice(o.length+1))&&U.mutable(o).delete(r.slice(o.length+1)),U.delete(r)}function Ye(){U=new zt;for(const r of g.keys())At(r)}function or(r){const o=[],i=l=>{const c=g.get(l);if(!c)return;o.push([l,c]);const u=U.get(l);if(u)for(const p of u)i(`${l}/${p}`)};return i(r),o}function Dr(r,o){if(r.pack){w-=1,b-=r.length;return}B-=r.length,Q+=Math.max(r.length,r.capacity??0)}function Cr(r,o){const i=g.get(r);i&&(ae&&!ae.has(r)&&ae.set(r,i),g.delete(r),Br(r),Dr(i),o.push([r,null]))}function xs(r,o,i){const l=e.packages;if(!l)throw new Error("This store has no shared package store to link from.");const c=zr(o),u=l.descendants(c);if(u.length===0)throw new Error(`The shared package store does not hold ${o}.`);Me(r,i),ir(r,i),we(g.size+u.length);for(const[p,y]of u){const _=p===c?r:`${r}${p.slice(c.length)}`;ee(_,y.type==="directory"?{type:"directory",mode:y.mode,mtimeMs:y.mtimeMs,offset:0,length:0}:{type:y.type,mode:y.mode,mtimeMs:y.mtimeMs,offset:y.offset,length:y.length,pack:Ae},i)}}function Me(r,o){const i=Le(r);if(i!==r&&g.get(i)?.type==="directory"){we(g.size+(g.has(r)?0:1));return}const l=[];let c=ct(r)??Ee()[0];if(g.has(c)||l.push(c),r!==c)for(const p of dr(Qr(Le(r)))){c=`${c}/${p}`;const y=g.get(c);if(y&&y.type!=="directory")throw new Error(`OPFS path parent is a file: ${c}`);y||l.push(c)}we(g.size+l.length+(g.has(r)?0:1));const u=Date.now();for(const p of l)ee(p,{type:"directory",mode:et,mtimeMs:u,offset:0,length:0},o)}function ir(r,o){for(const[i]of or(r))Cr(i,o)}function vs(r,o,i){if(r===o)return;if(o.startsWith(`${r}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const l=or(r);if(l.length===0){if(g.has(o))return;throw new Error(`OPFS rename source does not exist: ${r}`)}Me(o,i),ir(o,i);for(const[c]of l)Cr(c,i);for(const[c,u]of l)ee(`${o}${c.slice(r.length)}`,u,i);we(g.size)}function zr(r){if(typeof r!="string"||!r.startsWith(`${pr}/`)||r.includes("\0")||r.length>4096)throw new Error("Invalid shared store path.");return dr(r.slice(pr.length+1)),r}function Ee(){return S===Ae?[pr]:uo}function ct(r){return Ee().find(o=>r===o||r.startsWith(`${o}/`))}function xt(r,o){const i=g.get(r),l=i&&!i.pack?i.length:0,c=d?fo:t;if(B-l+o>c){const u=d?"the origin's shared packages":"the project's own files";throw new Error(`OPFS workspace exceeds its byte limit: writing ${r} (${o} bytes) would take ${u} past ${c} bytes (${B} bytes held, ${l} replaced).`)}}function we(r){if(r>s)throw new Error("OPFS workspace exceeds its entry limit.")}function Ur(){if(we(g.size),B>t)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${B} bytes, past ${t}.`)}function vt(r,o){const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");let l=0;for(;l<o.byteLength;){const c=i.write(o.subarray(l),{at:r+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}v=Math.max(v,r+o.byteLength)}function jr(r){const o=$;if(!o)throw new Error("OPFS filesystem worker is not initialized.");r<=v||(o.truncate(r),v=r)}function It(r){const o=$;if(!o)throw new Error("OPFS filesystem worker is not initialized.");const i=v;let l=0;for(;l<r.byteLength;){const c=o.write(r.subarray(l),{at:i+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}return v=i+r.byteLength,i}function Is(r){const o=$;if(o.getSize()>=v&&r.getSize()>=M)return;o.flush(),r.flush();const i=o.getSize(),l=r.getSize();if(!(i>=v&&l>=M))throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${i} of ${v} bytes, its log ${l} of ${M}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function Os(r,o={}){const i=P;if(!i||!$)throw new Error("OPFS filesystem worker is not initialized.");if(r.length===0)return;const l=Be.encode(JSON.stringify({packBytes:v,changes:r}));if(l.byteLength>fn)throw new Error("An OPFS workspace index record exceeds its size limit.");const c=new Uint8Array(Dt+l.byteLength),u=new DataView(c.buffer);u.setUint32(0,l.byteLength,!0),u.setUint32(4,Zr(l),!0),c.set(l,Dt);let p=0;for(;p<c.byteLength;){const y=i.write(c.subarray(p),{at:M+p});if(y<=0)throw new Error("The OPFS workspace index log could not be written completely.");p+=y}M+=c.byteLength,Is(i),o.publish!==!1&&yt(),performance.now()-te>=wn?ke():K===void 0&&(K=setTimeout(ke,wn))}function ke(){if(K!==void 0&&(clearTimeout(K),K=void 0),fe)throw fe;const r=performance.now();$?.flush(),P?.flush(),te=performance.now(),ve+=1,ge+=te-r}function Ot(){const r=Nr,o=gt(()=>r.catch(()=>{}).then(Ns));return Nr=o,o}async function Ns(){if(be(),!T)return;const r=T,o=P,i=await pe(r,!1);if(!o||o!==P||r!==T)throw new Error("OPFS workspace changed generations before its checkpoint could start.");ke();const l=M;if(await dt(i,g,{access:o,bytes:l,packBytes:v}),r===T&&(he={generation:r,bytes:l}),o===P&&r===T&&l===M){ot();try{o.truncate(0),o.flush(),M=0,he={generation:r,bytes:0}}finally{it()}}}function qr(r){return bt(()=>Ts(ar(r)))}async function Ts(r){const o=crypto.randomUUID(),i=await pe(o,!0),l=await i.getFileHandle(Ze,{create:!0}),c=await Z(l,"store"),u=new Map;let p=0;try{for(const _ of r.files){let k=0,F=0;if(_.type!=="directory"){const O=new Uint8Array(r.pack,_.offset??0,_.length??0);k=p,F=O.byteLength;let I=0;for(;I<F;){const j=c.write(O.subarray(I),{at:k+I});if(j<=0)throw new Error("An OPFS workspace file could not be written completely.");I+=j}p+=F}u.set(_.path,{type:_.type,mode:_.mode??(_.type==="directory"?et:Ct),mtimeMs:_.mtimeMs??Date.now(),offset:k,length:F})}for(const _ of Ee())u.has(_)||u.set(_,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0});we(u.size),c.truncate(p),c.flush()}finally{c.close()}const y=await dt(i,u);await Nt(o,i,u,p,y)}async function Ms(){await Wr(()=>!0)}async function Fs(){let r=!1,o=!1,i=!1;try{await Ls(()=>{r=!0},()=>{o=!0},()=>{i=!0})}finally{r&&(o||i)?it():r&&_t()}}async function Ls(r,o,i){const l=crypto.randomUUID(),c=await pe(l,!0),u=await Z(await c.getFileHandle(Ze,{create:!0}),"store");let p,y=!1;try{p=await Z(await c.getFileHandle(hr,{create:!0}),"record of changes"),p.truncate(0);const _=new Uint8Array(mn);let k=0;const F=z=>{if(z.pack)return{...z};if(z.type==="directory"||z.length===0)return{...z,offset:0,length:0};const X=$;if(!X)throw new Error("OPFS filesystem worker is not initialized.");const $e=k;let ce=0;for(;ce<z.length;){const ft=Math.min(_.byteLength,z.length-ce),nn=_.subarray(0,ft);if(q?.ensure(z.offset+ce,ft),X.read(nn,{at:z.offset+ce})!==ft)throw new Error("An OPFS workspace file could not be read completely.");let Lt=0;for(;Lt<ft;){const sn=u.write(nn.subarray(Lt),{at:$e+ce+Lt});if(sn<=0)throw new Error("An OPFS workspace file could not be written completely.");Lt+=sn}ce+=ft}k+=z.length;const{capacity:fr,...Vs}=z;return{...Vs,offset:$e}},O=new Map;let I=performance.now();for(const[z,X]of[...g]){if(Y||Je)return;g.get(z)===X&&(O.set(X,F(X)),performance.now()-I>8&&(await new Promise($e=>setTimeout($e,0)),I=performance.now()))}if(Y||Je||!$||!P)return;ot(),r();const j=new Map;for(const[z,X]of g)j.set(z,O.get(X)??F(X));u.truncate(k),u.flush(),p.flush(),ke();const W={pack:$,log:P};$=u,P=p,M=0,g=j,Ye(),v=k,T=l,m=c,at(),y=!0;const ne=new Map(j);try{W.pack.close()}finally{W.log.close()}try{await dt(c,ne);const z={storageVersion:4,generation:l,initializedAt:Date.now()};await lt(await Te(),Xe,z)}catch(z){throw fe=new Error("The workspace moved to a compacted generation it could not record; it takes no more writes, which its next open would discard.",{cause:z}),fe}o(),await rr(l)}finally{if(!y){i();try{u.close()}finally{p?.close()}await Yr(await(await Te()).getDirectoryHandle(Bt),l)}}}async function $s(r){be(),ot();try{await Rs(r)}finally{it()}}async function Rs(r){let o=!1;for(const[i,l]of g){if(!l.pack||l.length===0)continue;const c=r.get(l.offset);if(c===void 0)throw new Error(`The shared store no longer holds the bytes of ${i}.`);c!==l.offset&&(g.set(i,{...l,offset:c}),o=!0)}o&&await Ot()}function Wr(r){return bt(()=>Bs(r))}async function Bs(r){const o=$;if(!o)throw new Error("OPFS filesystem worker is not initialized.");const i=new Map,l=crypto.randomUUID(),c=await pe(l,!0),u=await c.getFileHandle(Ze,{create:!0}),p=await Z(u,"store"),y=new Map,_=new Uint8Array(mn);let k=0;try{for(const[O,I]of g){if(!r(O,I))continue;if(I.pack){y.set(O,{...I});continue}if(I.type==="directory"||I.length===0){y.set(O,{...I,offset:0,length:0});continue}const j=k;i.set(I.offset,j);let W=0;for(;W<I.length;){const X=Math.min(_.byteLength,I.length-W),$e=_.subarray(0,X);if(q?.ensure(I.offset+W,X),o.read($e,{at:I.offset+W})!==X)throw new Error("An OPFS workspace file could not be read completely.");let ce=0;for(;ce<X;){const fr=p.write($e.subarray(ce),{at:j+W+ce});if(fr<=0)throw new Error("An OPFS workspace file could not be written completely.");ce+=fr}W+=X}k+=I.length;const{capacity:ne,...z}=I;y.set(O,{...z,offset:j,length:I.length})}p.truncate(k),p.flush()}finally{p.close()}const F=await dt(c,y);return await Nt(l,c,y,k,F),i}async function Nt(r,o,i,l,c,u){ot();try{await Ds(r,o,i,l,c,u)}finally{it()}}async function Ds(r,o,i,l,c,u){const p=await o.getFileHandle(hr,{create:!0}),y=await Z(p,"record of changes");try{y.truncate(0),y.flush()}finally{y.close()}const _={storageVersion:u?5:4,generation:r,initializedAt:Date.now(),...u?{imageRanges:u}:{}};if(await lt(await Te(),Xe,_),Ge(),T=r,L=_.initializedAt,J=u,c){const k=new Re(c.index);g=new Ke(k),U=new $t(k),re=void 0}else g=i,Ye();v=l,m=o,await He(o),c?({liveBytes:B,linked:w,linkedBytes:b}=c,Q=Math.max(0,v-B)):at(),d||await rr(r)}async function Cs(r,o,i,l,c=!1){if(be(),!d||S!==Ae)throw new Error("Only the shared package store can reserve immutable image extents.");if(v!==0||[...g.values()].some(O=>O.type!=="directory"))return!1;const u=ur(l);if(u.bytes!==r.packBytes||r.entries>wr||r.liveBytes>r.packBytes||o.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(o,r.json.sha256,c)||!await Mt(i,r.binary.sha256,c))throw new Error("The image's prepared metadata does not match its document.");const p=o.subarray(0,4096).indexOf(10);if(p<0)throw new Error("The prepared index has no bounded retained header.");const y=JSON.parse(`${Qe.decode(o.subarray(0,p-1))}}`),_={packBytes:r.packBytes,liveBytes:r.liveBytes,linked:0,linkedBytes:0},k=y.retainedIndex;if(k.version!==1||k.digest!==await Jr(r.binary.sha256,_)||k.packBytes!==_.packBytes||k.liveBytes!==_.liveBytes||k.linked!==0||k.linkedBytes!==0)throw new Error("The prepared index's retained measures are inconsistent.");const F=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(F).set(i),new Re(F).entryCount!==r.entries)throw new Error("The prepared index has the wrong number of entries.");return bt(async()=>{const O=crypto.randomUUID(),I=await pe(O,!0),j=await I.getFileHandle(Ze,{create:!0}),W=await Z(j,"immutable image reservation");try{W.truncate(r.packBytes),W.flush()}finally{W.close()}const ne=Be.encode(JSON.stringify(u));return await Se(I,cn,ne),await Se(I,Tt,i),await Se(I,de,o),await Nt(O,I,new Map,r.packBytes,{index:F,..._},await me(ne)),!0})}async function zs(r,o,i,l=!1,c){if(be(),d||!e.packages||!c&&!e.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(v!==0||[...g.values()].some(k=>k.type!=="directory"))return!1;if(o.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(o,r.json.sha256,l)||!await Mt(i,r.binary.sha256,l))throw new Error("The image's prepared project does not match its descriptor.");const u=o.subarray(0,4096).indexOf(10);if(u<0)throw new Error("The prepared project has no bounded retained header.");const p=JSON.parse(`${Qe.decode(o.subarray(0,u-1))}}`).retainedIndex,y={packBytes:0,liveBytes:0,linked:r.linked,linkedBytes:r.linkedBytes};if(p.version!==1||p.digest!==await Jr(r.binary.sha256,y)||p.packBytes!==0||p.liveBytes!==0||p.linked!==r.linked||p.linkedBytes!==r.linkedBytes)throw new Error("The prepared project's retained measures are inconsistent.");const _=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(_).set(i),new Re(_).entryCount!==r.entries||r.entries>s)throw new Error("The prepared project has invalid entry bounds.");return bt(async()=>{const k=crypto.randomUUID(),F=await pe(k,!0),O=await F.getFileHandle(Ze,{create:!0}),I=await Z(O,"prepared project");try{I.truncate(0),I.flush()}finally{I.close()}if(await Se(F,Tt,i),await Se(F,de,o),c&&!await c)return!1;if(!e.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");return await Nt(k,F,new Map,0,{index:_,...y}),!0})}async function Us(){if(Y)throw new Error("This OPFS workspace is closing.");if(!$)throw new Error("OPFS filesystem worker is not initialized.");const r=[],o=[...g.keys()].sort((p,y)=>Xr(p)-Xr(y)||(p<y?-1:1));let i=0;for(const p of g.values())p.type!=="directory"&&(i+=p.length);const l=new ArrayBuffer(i),c=new Uint8Array(l);let u=0;for(const p of o){const y=g.get(p);if(y.type==="directory"){r.push({path:p,type:"directory",mode:y.mode,mtimeMs:y.mtimeMs});continue}y.length>0&&c.set(Et(y),u),r.push({path:p,type:y.type,offset:u,length:y.length,mode:y.mode,mtimeMs:y.mtimeMs}),u+=y.length}for(const p of[...Ee()].reverse())g.has(p)||r.unshift({path:p,type:"directory",mode:et,mtimeMs:Date.now()});return ar({files:r,pack:l})}async function lt(r,o,i){await Se(r,o,Be.encode(JSON.stringify(i)))}async function Se(r,o,i){const l=await(await Te()).getDirectoryHandle(dn,{create:!0}),c=crypto.randomUUID(),u=await l.getFileHandle(c,{create:!0}),p=await Z(u,"index");try{let y=0;for(;y<i.byteLength;){const _=p.write(i.subarray(y),{at:y});if(_<=0)throw new Error("An OPFS workspace file could not be written completely.");y+=_}p.truncate(i.byteLength),p.flush()}finally{p.close()}try{await u.move(r,o)}finally{await Gr(l,c,!1)}}const Tt="index.shared";async function me(r){const o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join("")}async function Mt(r,o,i){return i||await me(r)===o}function Jr(r,o){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:p}=o;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:u,...p?{journalPrefix:p}:{}})}:${r}`))}async function Hr(r,o){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:p}=o;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:u,...p?{journalPrefix:p}:{}})}:${await me(r)}`))}async function dt(r,o,i){const l=Js(o);if(typeof SharedArrayBuffer>"u"||o.size<1e4){await lt(r,de,l);return}const c=new Map(l.entries),u=new Map,p={packBytes:i?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[j,W]of c){const ne=Le(j);if(ne!==j){let z=u.get(ne);z||(z=new Set,u.set(ne,z)),z.add(j.slice(ne.length+1))}W.pack?(p.linked+=1,p.linkedBytes+=W.length):(p.liveBytes+=W.length,p.packBytes=Math.max(p.packBytes,W.offset+W.length))}let y;try{y=on(c,u)}catch{await lt(r,de,l);return}const _=JSON.stringify(l.entries),k=i?new Uint8Array(i.bytes):void 0;if(k&&i.access.read(k,{at:0})!==k.byteLength)throw new Error("The checkpoint's journal prefix could not be read completely.");const F=k?{bytes:k.byteLength,digest:await me(k)}:void 0,O=new Uint8Array(y).slice(),I={version:F?2:1,digest:await Hr(O,{...p,...F?{journalPrefix:F}:{}}),...p,...F?{journalPrefix:F}:{}};try{await Se(r,Tt,O)}catch{await lt(r,de,{entries:JSON.parse(_)});return}return await Se(r,de,Be.encode(`{"retainedIndex":${JSON.stringify(I)},
|
|
2
|
+
`)}const $n=2019846480,Vt=6,oe=6,rt=3,Jt=0,ut=1,Pe=2,Rn=3,Bn=4,Dn=5,Cn=0,zn=1,Un=2,Ht=1,jn=2,qn=4,Gt=32,br=3,Er=["file","directory","symlink"],ro=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,no=new TextEncoder,so=new TextDecoder;function Wn(n){let e=2166136261;for(let t=0;t<n.length;t+=1)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function on(n,e){const t=[...n.keys()];for(const A of t)if(ro.test(A))throw new Error("A path in the store is not well-formed UTF-16.");const s=new Map;for(let A=0;A<t.length;A+=1)s.set(t[A],A);for(const A of e.keys())s.has(A)||(s.set(A,t.length),t.push(A));const a=t.length,d=new Map,f=new Uint32Array(a);let h=0;for(let A=0;A<a;A+=1){const x=t[A];let D=!0;for(let H=0;H<x.length;H+=1)if(x.charCodeAt(H)>=128){D=!1;break}D||d.set(A,no.encode(x)),f[A]=D?x.length:d.get(A).length,h+=f[A]}let m=0;for(const A of e.values())m+=A.size;let w=1;for(;w<a*2;)w<<=1;const b=Vt*4,E=kr(b+a*oe*4,8),S=E+a*rt*8,T=S+w*4,g=T+m*4,U=new SharedArrayBuffer(kr(g+h,8));new Uint32Array(U,0,Vt).set([$n,a,w,m,h,n.size]);const J=new Uint32Array(U,b,a*oe),q=new Float64Array(U,E,a*rt),_e=new Uint32Array(U,S,w),N=new Uint32Array(U,T,m),R=new Uint8Array(U,g,h);let L=0,P=0;for(let A=0;A<a;A+=1){const x=t[A],D=A*oe,H=d.get(A);if(H)R.set(H,L);else for(let M=0;M<x.length;M+=1)R[L+M]=x.charCodeAt(M);const v=f[A];J[D+Jt]=L,J[D+ut]=v,L+=v;let K=H?0:Gt;const te=n.get(x);if(te){K|=Ht|Er.indexOf(te.type)<<br,te.pack&&(K|=qn),J[D+Rn]=te.mode;const M=A*rt;q[M+Cn]=te.mtimeMs,q[M+zn]=te.offset,q[M+Un]=te.length}const ve=e.get(x);if(ve){K|=jn,J[D+Bn]=P,J[D+Dn]=ve.size;for(const M of ve){const B=s.get(`${x}/${M}`);if(B===void 0)throw new Error(`The store's children name ${x}/${M}, which its index does not hold.`);N[P++]=B}}J[D+Pe]=K;let ge=Wn(x)&w-1;for(;_e[ge]!==0;)ge=ge+1&w-1;_e[ge]=A+1}if(P!==m)throw new Error("The shared index's children did not add up.");return U}function kr(n,e){return Math.ceil(n/e)*e}class Re{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,Vt);if(t[0]!==$n)throw new Error("Not a shared store index.");const[,s,a,d,f,h]=t;this.buffer=e,this.count=s,this.entryCount=h;const m=Vt*4,w=kr(m+s*oe*4,8),b=w+s*rt*8,E=b+a*4,S=E+d*4;this.records=new Uint32Array(e,m,s*oe),this.numbers=new Float64Array(e,w,s*rt),this.table=new Uint32Array(e,b,a),this.childList=new Uint32Array(e,E,d),this.strings=new Uint8Array(e,S,f),this.mask=a-1}find(e){let t=Wn(e)&this.mask;for(;;){const s=this.table[t];if(s===0)return-1;if(this.pathIs(s-1,e))return s-1;t=t+1&this.mask}}entry(e){const t=e*oe,s=this.records[t+Pe];if(!(s&Ht))return;const a=e*rt,d={type:Er[s>>>br&3],mode:this.records[t+Rn],mtimeMs:this.numbers[a+Cn],offset:this.numbers[a+zn],length:this.numbers[a+Un]};return s&qn&&(d.pack="packages"),d}typeAt(e){const t=this.records[e*oe+Pe];return t&Ht?Er[t>>>br&3]:void 0}hasEntry(e){return(this.records[e*oe+Pe]&Ht)!==0}childNames(e){const t=e*oe;if(!(this.records[t+Pe]&jn))return;const s=this.records[t+Bn],a=this.records[t+ut]+1,d=[];for(let f=0;f<this.records[t+Dn];f+=1){const h=this.childList[s+f]*oe;d.push(this.decode(this.records[h+Jt]+a,this.records[h+ut]-a,(this.records[h+Pe]&Gt)!==0))}return d}path(e){const t=e*oe;return this.decode(this.records[t+Jt],this.records[t+ut],(this.records[t+Pe]&Gt)!==0)}decode(e,t,s){if(!s)return so.decode(this.strings.slice(e,e+t));let a="";for(let d=e,f=e+t;d<f;d+=4096)a+=String.fromCharCode.apply(null,this.strings.subarray(d,Math.min(f,d+4096)));return a}pathIs(e,t){const s=e*oe,a=this.records[s+Jt],d=this.records[s+ut];if(!(this.records[s+Pe]&Gt))return this.path(e)===t;if(d!==t.length)return!1;for(let f=0;f<d;f+=1)if(this.strings[a+f]!==t.charCodeAt(f))return!1;return!0}}const le=Symbol("deleted");function Jn(n,e){return n===e||!!n&&!!e&&n.type===e.type&&n.offset===e.offset&&n.length===e.length&&n.pack===e.pack&&n.mode===e.mode&&n.mtimeMs===e.mtimeMs&&n.capacity===e.capacity}class Ke{base;overlay=new Map;delta=0;constructor(e){this.base=e}get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const s=this.base.find(e);return s<0?void 0:this.base.entry(s)}typeOf(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t.type;const s=this.base.find(e);return s<0?void 0:this.base.typeAt(s)}has(e){const t=this.overlay.get(e);if(t!==void 0)return t!==le;const s=this.base.find(e);return s>=0&&this.base.hasEntry(s)}set(e,t){this.has(e)||(this.delta+=1);const s=this.base.find(e);return s>=0&&Jn(this.base.entry(s),t)?this.overlay.delete(e):this.overlay.set(e,t),this}delete(e){if(!this.has(e))return!1;const t=this.base.find(e);return t>=0&&this.base.hasEntry(t)?this.overlay.set(e,le):this.overlay.delete(e),this.delta-=1,!0}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t]);for(let e=0;e<this.base.count;e+=1){if(!this.base.hasEntry(e))continue;const t=this.base.path(e);this.overlay.has(t)||(yield[t,this.base.entry(e)])}}*keys(){for(const[e]of this.entries())yield e}*values(){for(const[,e]of this.entries())yield e}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[s,a]of this.entries())e.call(t,a,s,this)}*changed(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t])}*changes(){for(const[e,t]of this.overlay)yield[e,t===le?null:t]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const e=[];let t=0;for(const[s,a]of this.changes()){if(t+=s.length*2+128,t>8*1024*1024)return;e.push([s,a])}return e}}class $t{base;overlay=new Map;constructor(e){this.base=e}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const s=this.base.find(e),a=s<0?void 0:this.base.childNames(s);return a?new Set(a):void 0}mutable(e){const t=this.overlay.get(e);if(t!==void 0&&t!==le)return t;const s=new Set(t===le?[]:this.get(e)??[]);return this.overlay.set(e,s),s}delete(e){this.overlay.set(e,le)}}const oo="supercode-browser-filesystems",Ae="packages",io="state.json",an="/image-range-worker.js",cn="image-ranges.json",ao=2;function ur(n){const e=n;if(!e||e.version!==1||!Number.isSafeInteger(e.bytes)||e.bytes<0||!Array.isArray(e.parts)||e.image!==void 0&&(typeof e.image!="string"||!/^[a-f0-9]{16,64}$/u.test(e.image))||e.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let t=0;for(const s of e.parts){if(!s||s.offset!==t||!Number.isSafeInteger(s.raw)||s.raw<0||!Number.isSafeInteger(s.bytes)||s.bytes<0||s.bytes>1024*1024*1024||s.raw>1024*1024*1024||typeof s.sha256!="string"||!/^[a-f0-9]{64}$/u.test(s.sha256)||typeof s.url!="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(s.url)||s.url.split("/").some(a=>a==="."||a===".."))throw new Error("Invalid immutable image part.");if(t+=s.raw,!Number.isSafeInteger(t))throw new Error("Immutable image ranges exceed the offset limit.")}if(t!==e.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return e}const ln=new Map;class co{ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=!1;ready=!1;startup;cancelStartup;sharedCompletion;constructor(e,t,s,a,d,f){if(this.ranges=e,this.directory=t,this.identity=s,this.receiptKey=d,this.client=f,typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("This browser cannot materialize an immutable image during a synchronous read.");if(this.state=new Int32Array(f?.state??new SharedArrayBuffer(e.parts.length*Int32Array.BYTES_PER_ELEMENT)),this.state.length!==e.parts.length)throw new Error("The image reader's line has the wrong range count.");const h=e.parts.length,m=a??new SharedArrayBuffer((2*h+1)*Int32Array.BYTES_PER_ELEMENT);if(m.byteLength!==h*Int32Array.BYTES_PER_ELEMENT&&m.byteLength!==(2*h+1)*Int32Array.BYTES_PER_ELEMENT)throw new Error("The image completion seed has the wrong range count.");this.completed=new Int32Array(m,0,h),this.firstRead=m.byteLength>h*Int32Array.BYTES_PER_ELEMENT?new Int32Array(m,h*Int32Array.BYTES_PER_ELEMENT,h+1):void 0,this.sharedCompletion=a!==void 0;for(const w of e.parts)Object.freeze(w);Object.freeze(e.parts),Object.freeze(e)}get completionBuffer(){return this.completed.buffer}get verifiedRanges(){return this.ranges}async initialize(){if(this.closed)throw new Error("This immutable image reader is closed.");if(this.ready)return;if(this.startup)return this.startup;let e=!1;for(let t=0;t<this.completed.length;t+=1)if(Atomics.load(this.completed,t)!==2){e=!0;break}if(!e){this.ready=!0,this.client?.port.close();return}if(this.client){const t=this.port=this.client.port;t.onmessage=s=>{s.data?.type!=="closing"||this.port!==t||(t.close(),this.port=void 0,this.closed||this.startMaterializer().catch(a=>console.warn("This process's image reader could not start its own materializer after its line closed.",a)))},t.start(),this.ready=!0;return}return this.startMaterializer()}startMaterializer(){const e=Date.now(),t=new Worker(an,{type:"module",name:"immutable-image-materializer"}),s=this.ready;return s||(this.worker=t),t.addEventListener("error",()=>this.fail()),t.addEventListener("messageerror",()=>this.fail()),this.startup=new Promise((a,d)=>{const f=()=>{clearTimeout(b),t.removeEventListener("message",w),t.removeEventListener("error",h),t.removeEventListener("messageerror",h),this.cancelStartup=void 0},h=()=>m(new Error("The immutable image materializer could not initialize; reload to retry.")),m=E=>{f(),t.terminate(),s||(this.closed=!0,this.fail()),d(E)},w=E=>{if(E.data?.identity===this.identity){if(E.data.type==="init-error"){m(new Error(`The immutable image materializer could not initialize: ${String(E.data.error)}`));return}E.data.type==="ready"&&(console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-e})}`),f(),this.ready=!0,this.worker=t,a())}},b=setTimeout(()=>m(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=m,t.addEventListener("message",w),t.addEventListener("error",h),t.addEventListener("messageerror",h);try{t.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:this.state.buffer,completed:this.completed.buffer,sharedCompletion:this.sharedCompletion,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}catch(E){m(E instanceof Error?E:new Error(String(E)))}}),this.startup}readDigests(){const e=this.firstRead;if(!e)return;const t=this.ranges.parts.length,s=[];for(let a=0;a<t;a+=1){const d=Atomics.load(e,a),f=this.ranges.parts[a];d>0&&f.raw>0&&s.push([d,f.sha256])}return s.sort((a,d)=>a[0]-d[0]).map(([,a])=>a)}completedDigests(){const e=[];for(let t=0;t<this.completed.length;t+=1){const s=this.ranges.parts[t];s.raw>0&&Atomics.load(this.completed,t)===2&&e.push(s.sha256)}return e}prefetch(e,t=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const s=new Map;for(let h=0;h<this.ranges.parts.length;h+=1){const m=this.ranges.parts[h];if(m.raw===0)continue;const w=s.get(m.sha256);w?w.push(h):s.set(m.sha256,[h])}const a=[];for(const h of new Set(e))for(const m of s.get(h)??[])Atomics.load(this.completed,m)!==2&&a.push(m);const d=t.length>0&&a.length>0?Math.min(t.length,8):Math.min(ao,Math.ceil(a.length/32)),f=[];for(let h=0;h<d;h+=1){const m=a.filter((S,T)=>T%d===h),w=new Worker(an,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(w);let b;f.push(new Promise(S=>{b=S}));const E=()=>{w.terminate(),this.prefetchers=this.prefetchers.filter(S=>S!==w),b()};w.addEventListener("error",E),w.addEventListener("messageerror",E),w.addEventListener("message",S=>{S.data?.identity===this.identity&&(S.data.type==="ready"?w.postMessage(t.length>0?{type:"prefetch-stream",url:t[h]}:{type:"prefetch",indices:m}):(S.data.type==="prefetched"||S.data.type==="init-error")&&E())}),w.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:new SharedArrayBuffer(this.state.byteLength),completed:this.completed.buffer,sharedCompletion:!0,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}return{queued:a.length,done:Promise.all(f).then(()=>{})}}ensure(e,t){if(this.closed)throw new Error("This immutable image reader is closed.");if(!this.ready)throw new Error("This immutable image reader has not finished asynchronous initialization.");if(t===0||e>=this.ranges.bytes)return;const s=Math.min(e+t,this.ranges.bytes);let a=0,d=this.ranges.parts.length;for(;a<d;){const f=a+d>>>1,h=this.ranges.parts[f];h.offset+h.raw<=e?a=f+1:d=f}for(let f=a;f<this.ranges.parts.length;f+=1){const h=this.ranges.parts[f];if(h.offset>=s)break;const m=this.firstRead;if(m&&Atomics.load(m,f)===0&&Atomics.compareExchange(m,f,0,Atomics.add(m,this.ranges.parts.length,1)+1),Atomics.load(this.completed,f)===2)continue;const w=this.worker??this.port;if(!w)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");w.postMessage({type:"read",index:f});const b=performance.now(),E=b+3e4;for(;Atomics.load(this.state,f)===0;){const g=E-performance.now();if(g<=0||Atomics.wait(this.state,f,0,g)==="timed-out")throw this.close(),new Error(`The image's immutable part ${h.url} did not arrive within 30 seconds; reload to retry.`)}const S=performance.now()-b,T=ln.get(this.identity)??{ranges:0,ms:0};if(T.ranges+=1,T.ms+=S,ln.set(this.identity,T),console.log(`[boot-trace] ${JSON.stringify({event:"image-blocked",at:Date.now(),reader:this.identity,index:f,range:h.sha256.slice(0,16),ms:Math.round(S)})}`),Atomics.load(this.state,f)!==2)throw new Error(`The image's immutable part ${h.url} could not be verified or stored; see the worker error and reload to retry.`)}}lineForReader(){const e=this.worker??this.port;if(this.closed||!this.ready||!e)return;const t=new MessageChannel,s=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);return e.postMessage({type:"client",port:t.port1,state:s},[t.port1]),{port:t.port2,state:s}}fail(){for(let e=0;e<this.state.length;e+=1)Atomics.compareExchange(this.state,e,0,-1)===0&&Atomics.notify(this.state,e)}close(){if(this.closed)return;if(this.closed=!0,this.cancelStartup){this.cancelStartup(new Error("This immutable image reader closed during initialization."));return}this.fail(),this.port?.close();const e=this.worker;e&&(e.postMessage({type:"closing"}),setTimeout(()=>e.terminate(),250));for(const t of this.prefetchers)t.dispatchEvent(new Event("error"));this.prefetchers=[]}}const pr="/packages",Rt="supercode-browser-packages",Be=new TextEncoder,Qe=new TextDecoder("utf-8",{fatal:!0}),lo=oo,Bt="generations",dn="atomic-staging",Xe=io,de="index.json",hr="index-log.bin",Ze="pack.bin",Dt=8,fn=64*1024*1024,se=1024*1024*1024,un=10*1024*1024*1024,fo=16*1024*1024*1024,uo=["/workspace","/home","/opt"],De=0,pn=1,wr=1e6,hn=8*1024*1024,wn=250,po=64*1024*1024,ho=256*1024*1024,mn=4*1024*1024,et=493,Ct=420;function yn(n,e={}){const t=e.limits?.maxBytes??un,s=e.limits?.maxEntries??wr;if(!Number.isSafeInteger(t)||t<1||t>un||!Number.isSafeInteger(s)||s<1||s>wr)throw new Error("Invalid OPFS workspace limits.");let a,d=!1,f=!1,h=!1,m,w=0,b=0,E,S,T,g=new Map,U=new zt,$,J,q,_e,N,R,L=0,P,A=0;const x=new Map,D=256*1024,H=32;let v=0,K,te=-1/0,ve=0,ge=0,M=0,B=0,Q=0,Ie=0,Oe=0,ae,mt,fe,qe=!1,st,Nr=Promise.resolve(),We=0,Y=!1,Je=!1,V,Ne=0,ue=!1;function yt(){if(!(!V||ue)){if(M>2147483647){_t();return}Atomics.store(V,pn,M)}}function _t(){!V||ue||(ue=!0,(Atomics.load(V,De)&1)===0&&Atomics.add(V,De,1))}function ot(){Ne+=1,Ne===1&&V&&!ue&&Atomics.add(V,De,1)}function it(){Ne-=1,!(Ne>0||!V||ue)&&(yt(),ue||Atomics.add(V,De,1))}function Tr(){if(f)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");return V||(V=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT)),V[De]=Ne>0||ue?1:0,yt()),V.buffer}let re;const ls=8*1024*1024;let Mr=!1;function ds(r){if(f||!V||!T||qe||Ne>0||ue||Y)return;const o=Atomics.load(V,De);if(o&1)return;if(r?.overlays&&g instanceof Ke){const l=g.boundedChanges();if(l)return Zt({generation:T,index:g.base.buffer,changes:l,packBytes:v,logBytes:M,epoch:o,liveBytes:B,linked:w,linkedBytes:b})}if(re&&re.generation===T&&re.epoch===o&&M>=re.logBytes&&M-re.logBytes<=(r?.current?0:ls))return Zt(re);let i;try{i=on(g,ps())}catch(l){console.warn(`[pack-store] no reader seed: ${l instanceof Error?l.message:String(l)}`);return}return re={generation:T,index:i,packBytes:v,logBytes:M,epoch:o,liveBytes:B,linked:w,linkedBytes:b},us(i),Zt(re)}function Zt(r){const o=e.packages?.imageCompletionSeed();return o?{...r,packagesImage:o}:r}function fs(){if(!(!q||!J||!T||qe||Ne>0||Y))return{generation:T,rangesDigest:J,completed:q.completionBuffer,...q.receiptKey?{metadata:{ranges:q.verifiedRanges,receiptKey:q.receiptKey}}:{}}}function us(r){const o=[];if(g instanceof Ke)for(const[l,c]of g.changed())c.capacity!==void 0&&o.push([l,c]);else for(const[l,c]of g)c.capacity!==void 0&&o.push([l,c]);const i=new Re(r);g=new Ke(i),U=new $t(i);for(const[l,c]of o)g.set(l,c)}function ps(){if(U instanceof zt)return U.map;const r=new Map;for(const o of g.keys()){const i=Le(o);if(i===o)continue;let l=r.get(i);l||(l=new Set,r.set(i,l)),l.add(o.slice(i.length+1))}return r}function hs(){!f||h||Y||!P||St(M)}async function gt(r){if(Y)throw new Error("This OPFS workspace is closing.");We+=1;let o,i=!1;try{return await r()}catch(l){throw i=!0,o=l,l}finally{if(We-=1,Y&&We===0)try{rn()}catch(l){throw i?new AggregateError([o,l],"OPFS operation and deferred close both failed."):l}}}async function bt(r){return be(),We!==0?Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation.")):(Je=!0,gt(async()=>{try{return await r()}finally{Je=!1}}))}function ws(r){if(Y)throw new Error("This OPFS workspace is closing.");const o=g.get(r);if(!o||o.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);return Et(o)}function ms(r,o,i){if(Y)throw new Error("This OPFS workspace is closing.");const l=g.get(r);if(!l||l.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);const c=Math.min(Math.max(0,o),l.length),u=Math.min(Math.max(0,i),l.length-c);if(l.pack){const p=e.packages;if(!p)throw new Error("This store has no shared package store to read from.");return p.readExtent(l.offset+c,u)}return kt(l.offset+c,u)}function Et(r){if(r.pack){const o=e.packages;if(!o)throw new Error("This store has no shared package store to read from.");return o.readExtent(r.offset,r.length)}return kt(r.offset,r.length)}function kt(r,o){if(Y)throw new Error("This OPFS workspace is closing.");const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=new Uint8Array(o);if(o>0&&o<=D&&r>=0&&r+o<=A){let c=0;for(;c<o;){const u=r+c,p=Math.floor(u/D)*D;let y=x.get(p);if(!y&&(y=new Uint8Array(Math.min(D,A-p)),q?.ensure(p,y.byteLength),i.read(y,{at:p})!==y.byteLength))throw new Error("An OPFS package range could not be read completely.");x.delete(p),x.set(p,y),x.size>H&&x.delete(x.keys().next().value);const _=u-p,k=Math.min(o-c,y.byteLength-_);l.set(y.subarray(_,_+k),c),c+=k}return l}if(q?.ensure(r,o),o>0&&i.read(l,{at:r})!==o)throw new Error("An OPFS workspace file could not be read completely.");return l}async function ys(r,o={}){if(Y&&a||!a&&We!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(qe)throw new Error("This OPFS store is already opening a workspace.");if(a){if(S!==$r(r))throw new Error("Close this OPFS store before opening another workspace.");return g.size>0}qe=!0,Y=!1;const i=new AbortController;st=i;try{g=new Map,U=new zt,T=void 0,J=void 0,m=void 0,ae=void 0,fe=void 0,v=M=B=Q=w=b=0,he=void 0,Ie=Oe=ve=ge=0,te=-1/0,S=$r(r),f=o.readOnly===!0,N=f?o.imageCompletion:void 0,R=f?o.imageLine:void 0,h=f&&o.extentsOnly===!0,d=o.shared===!0||f,d||await ks(i.signal),i.signal.throwIfAborted();const l=await gs();i.signal.throwIfAborted();try{const p=await l.getDirectoryHandle(lo,{create:!f});i.signal.throwIfAborted(),a=await p.getDirectoryHandle(S,{create:!f})}catch(p){if(i.signal.throwIfAborted(),f&&Ve(p))return!1;throw p}i.signal.throwIfAborted();let c=Ft(await Fe(a,Xe));if(i.signal.throwIfAborted(),!c&&f)return await tr(),!1;if(!c&&d&&(await n.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{i.signal.throwIfAborted(),c=Ft(await Fe(a,Xe)),i.signal.throwIfAborted(),c||(await tr(),await qr({files:[],pack:new ArrayBuffer(0)}),await yo(a))}),i.signal.throwIfAborted(),!c))return m=await pe(T,!1),i.signal.throwIfAborted(),!1;if(!c)return await tr(),i.signal.throwIfAborted(),!1;const u=async p=>{let y;try{y=await pe(p.generation,!1)}catch(O){throw i.signal.throwIfAborted(),Ve(O)?new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause:O}):O}if(i.signal.throwIfAborted(),T=p.generation,L=p.initializedAt,J=p.imageRanges,m=y,h)return S===Ae&&n.navigator.locks?await n.navigator.locks.request(Rt,{mode:"shared",signal:i.signal},async()=>{await He(y),A=$.getSize()}):await He(y),i.signal.throwIfAborted(),!0;const _=f?o.seed:void 0;if(_&&_.generation===p.generation){const O=new Re(_.index);return g=new Ke(O),U=new $t(O),v=_.packBytes,_.changes&&Lr({packBytes:_.packBytes,changes:_.changes}),await He(y),i.signal.throwIfAborted(),M=_.logBytes,{liveBytes:B,linked:w,linkedBytes:b}=_,Q=Math.max(0,v-B),Mr=!0,g.size>0}const k=f?void 0:await js(y);if(i.signal.throwIfAborted(),k){const O=new Re(k.index);g=new Ke(O),U=new $t(O),{packBytes:v,liveBytes:B,linked:w,linkedBytes:b}=k;const I=Atomics.load(new Int32Array(Tr()),De);re={generation:T,index:k.index,packBytes:v,liveBytes:B,linked:w,linkedBytes:b,logBytes:0,epoch:I}}else g=lr(await Fe(y,de)),i.signal.throwIfAborted(),Ye(),v=er(g);await He(y),i.signal.throwIfAborted();const F=k?await qs(k):0;return i.signal.throwIfAborted(),F&&(he={generation:T,bytes:F},re&&(re.logBytes=F)),St(F,!!k),k?Q=Math.max(0,v-B):at(),Ur(),d&&!f&&!k&&g.size>=1e4&&(ke(),await dt(y,g,{access:P,bytes:M,packBytes:v})),d||($.truncate(v),await Gr(a,dn,!0),await rr(T),i.signal.throwIfAborted(),Q>po&&Q>B&&await Ms()),i.signal.throwIfAborted(),g.size>0};return d&&!f?await n.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{if(c=Ft(await Fe(a,Xe)),!c)throw new Error("The committed package store state is missing. Stored data was retained.");return u(c)}):await u(c)}catch(l){const c=[l];try{Ge()}catch(u){c.push(u)}try{E?.()}catch(u){c.push(u)}throw E=void 0,a=void 0,c.length>1?new AggregateError(c,"OPFS workspace open and cleanup failed."):l}finally{qe=!1,st=void 0}}function _s(r){return gt(()=>Fr(r?.whole===!0))}async function Fr(r=!1){if(h)throw new Error("A store opened for its extents alone has no index to follow.");if(f&&a){const u=Ft(await Fe(a,Xe));if(!u)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(u.generation!==T||r){const p=await pe(u.generation,!1),y=lr(await Fe(p,de));v=er(y),u.generation!==T&&(T=u.generation,L=u.initializedAt,J=u.imageRanges,await He(p)),T=u.generation,m=p,g=y,Ye(),St(),at();return}}const o=P;if(!o||!m)return;const i=o.getSize();let l=!1;i<M&&(g=lr(await Fe(m,de)),Ye(),v=er(g),M=0,l=!0);const c=M;St(M),(l||M!==c)&&at()}async function gs(){let r;for(let o=0;o<10;o+=1){st?.signal.throwIfAborted();try{return await n.navigator.storage.getDirectory()}catch(i){r=i,await new Promise(l=>setTimeout(l,200))}}throw r instanceof Error?r:new Error("This browser workspace's storage is unavailable.")}const bs=1e4;async function Z(r,o){let i;const l=st?.signal;for(let u=0;u<2;u+=1){l?.throwIfAborted();const p=r.createSyncAccessHandle({mode:"readwrite-unsafe"});let y,_,k=!1;try{const F=new Promise((I,j)=>{_=()=>j(l?.reason??new DOMException("Workspace open was cancelled.","AbortError")),l?.addEventListener("abort",_,{once:!0}),l?.aborted&&_()}),O=await Promise.race([p.then(I=>({access:I})).catch(I=>{i=I}),new Promise(I=>{y=setTimeout(()=>I(void 0),bs)}),F]);if(l?.throwIfAborted(),O)return k=!0,O.access}finally{y!==void 0&&clearTimeout(y),_&&l?.removeEventListener("abort",_),k||p.then(F=>F.close(),()=>{}).catch(F=>console.error("Late workspace handle cleanup failed.",F))}if(i instanceof TypeError)throw new Error(`This browser cannot share a workspace's files between pages: its file access handles have no readwrite-unsafe mode (Chrome 121 or newer has one). ${i.message}`);await new Promise(F=>setTimeout(F,500))}const c=i instanceof Error?` (${i.message})`:"";throw new Error(`This browser workspace's ${o} is held by another page${c}.`)}async function He(r){Ge();const o=await r.getFileHandle(Ze);$=await Z(o,"store");try{if($.getSize()<v)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const i=await r.getFileHandle(hr);if(P=await Z(i,"record of changes"),M=P.getSize(),J){const l=N,c=l&&l.generation===T&&l.rangesDigest===J?l:void 0;let u,p;if(c?.metadata){if(u=ur(c.metadata.ranges),p=c.metadata.receiptKey,!/^[a-f0-9]{64}$/u.test(p))throw new Error("The owner's immutable receipt key is invalid.")}else{const _=await(await r.getFileHandle(cn)).getFile(),k=new Uint8Array(await _.arrayBuffer());if(await me(k)!==J)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");u=ur(JSON.parse(Qe.decode(k))),p=await me(Be.encode(JSON.stringify(u)))}if(u.bytes>$.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const y=c?R:void 0;y||R?.port.close(),R=void 0,q=new co(u,r,`${S}.${T}`,c?.completed,p,y),console.log(`[boot-trace] ${JSON.stringify({event:"image-reader-open",at:Date.now(),reader:`${S}.${T}`,offered:l!==void 0,shared:c!==void 0,...l&&!c?{offeredGeneration:l.generation,generation:T,rangesMatch:l.rangesDigest===J}:{}})}`),await q.initialize(),_e=u.image}}catch(i){throw Ge(),i}}function Ge(){q?.close(),q=void 0,_e=void 0;const r=$,o=P;$=void 0,P=void 0,M=0,A=0,x.clear();try{r?.close()}finally{o?.close()}}function St(r=0,o=!1){const i=P;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=i.getSize();if(l<=r){M=l;return}const c=new Uint8Array(l-r);if(i.read(c,{at:r})!==c.byteLength)throw new Error("The OPFS workspace index log could not be read.");const u=$?.getSize()??1/0,p=new DataView(c.buffer);let y=0;const _=c.byteLength;for(;y+Dt<=_;){const k=p.getUint32(y,!0),F=p.getUint32(y+4,!0),O=y+Dt;if(k===0||k>fn||O+k>_)break;const I=c.subarray(O,O+k);if(Zr(I)!==F)break;let j;try{j=Hs(JSON.parse(Qe.decode(I)))}catch{break}if(j.packBytes>u)break;Lr(j,o),y=O+k}y!==_&&!d&&i.truncate(r+y),M=r+y}function Lr(r,o=!1){for(const[i,l]of r.changes){const c=g.get(i);if(l&&Jn(c,l)){At(i);continue}o&&(c?.pack?(w-=1,b-=c.length):c&&(B-=c.length),l?.pack?(w+=1,b+=l.length):l&&(B+=l.length)),l===null?(g.delete(i),Br(i)):(g.set(i,l),At(i))}v=Math.max(v,r.packBytes)}function at(){B=0,w=0,b=0;for(const r of g.values())r.pack?(w+=1,b+=r.length):B+=r.length;Q=Math.max(0,v-B)}function er(r){let o=0;for(const i of r.values())i.pack||(o=Math.max(o,i.offset+i.length));return o}const Es=5e3;async function ks(r){if(!n.navigator.locks)return;if(!S)throw new Error("OPFS filesystem project is not initialized.");const o=new AbortController,i=setTimeout(()=>o.abort(),Es);try{await new Promise((l,c)=>{n.navigator.locks.request(`supercode-browser-filesystem-${S}`,{mode:"exclusive",signal:r?AbortSignal.any([r,o.signal]):o.signal},async()=>{clearTimeout(i),l(),await new Promise(u=>{E=u})}).catch(()=>c(r?.aborted?r.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(i)}}function $r(r){if(typeof r!="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(r))throw new Error("OPFS filesystem projectId is invalid.");return r}async function Te(){if(!a)throw new Error("OPFS filesystem worker is not initialized.");return a}async function pe(r,o){return(await(await Te()).getDirectoryHandle(Bt,{create:o})).getDirectoryHandle(r,{create:o})}async function tr(){let r;try{r=await(await Te()).getDirectoryHandle(Bt)}catch(o){if(Ve(o))return;throw o}for await(const o of r.entries())throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}async function rr(r){const o=await Te();let i;try{i=await o.getDirectoryHandle(Bt)}catch(l){if(Ve(l))return;throw l}for await(const[l]of i.entries())l!==r&&await Yr(i,l)}function be(){if(Y)throw new Error("This OPFS workspace is closing.");if(Je)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(f)throw new Error("This store is open for reading; its owner writes it.");if(fe)throw fe}async function Ss(r){en(r)}let nr=!1,Pt=0,he,sr=!1;function Rr(){if(Pt>0)return;const r=he&&he.generation===T&&he.bytes<=M?he.bytes:0;M-r>hn&&!nr&&(nr=!0,(d?n.navigator.locks.request(Rt,{mode:"exclusive"},async()=>{if(!a||Y)return;await Fr();const i=he,l=i&&i.generation===T&&i.bytes<=M?i.bytes:0;M-l>hn&&await Ot()}):Ot()).catch(i=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",i)).finally(()=>{nr=!1})),!d&&!sr&&Q>ho&&Q>B&&(sr=!0,gt(Fs).catch(o=>console.error("The workspace could not be compacted; it keeps its generation.",o)).finally(()=>{sr=!1}))}async function Ps(r){be(),Pt+=1;try{return await r()}finally{Pt-=1,Pt===0&&!Y&&a&&Rr()}}function As(r,o){const i=ye(r.path);if(r.operation==="write"){if(g.get(i)?.type==="directory")throw new Error(`OPFS write target is a directory: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const c=r.content;if(c.byteLength>se)throw new Error(`${i} is ${c.byteLength} bytes; an OPFS workspace file holds at most ${se}.`);xt(i,c.byteLength),Me(i,o);const u=It(c);ee(i,{type:r.symlink?"symlink":"file",mode:r.mode??g.get(i)?.mode??Ct,mtimeMs:r.mtimeMs??Date.now(),offset:u,length:c.byteLength},o);return}if(r.operation==="append"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS append target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const u=r.content,p=(c?.length??0)+u.byteLength;if(p>se)throw new Error(`${i} is ${p} bytes; an OPFS workspace file holds at most ${se}.`);xt(i,p),Me(i,o);const y=r.mode??c?.mode??Ct,_=r.mtimeMs??Date.now(),k=c&&!c.pack?c.capacity??c.length:0;if(S!==Ae&&c&&!c.pack&&c.length>0&&(p<=k||c.offset+k===v)){vt(c.offset+c.length,u),ee(i,{...c,mode:y,mtimeMs:_,length:p,capacity:Math.max(k,p)},o),Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length;return}const F=new Uint8Array(p);c&&c.length>0&&F.set(Et(c),0),F.set(u,p-u.byteLength);const O=It(F),I=Math.min(se,Math.max(p,p*2,64*1024));I>p&&jr(O+I),ee(i,{type:"file",mode:y,mtimeMs:_,offset:O,length:p,capacity:I},o);return}if(r.operation==="write-at"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS write target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const u=r.content,p=r.position,y=c?.length??0;if(u.byteLength===0&&c)return;const _=u.byteLength===0?y:Math.max(y,p+u.byteLength);if(_>se)throw new Error(`${i} is ${_} bytes; an OPFS workspace file holds at most ${se}.`);xt(i,_),Me(i,o);const k=r.mode??c?.mode??Ct,F=r.mtimeMs??Date.now(),O=c&&!c.pack?c.capacity??c.length:0;if(S!==Ae&&c&&!c.pack&&y>0&&(_<=O||c.offset+O===v)){if(p>y&&vt(c.offset+y,new Uint8Array(p-y)),mt&&p<y){const ne=Math.min(y,p+u.byteLength);mt.push([c.offset+p,kt(c.offset+p,ne-p)])}vt(c.offset+p,u),ee(i,{...c,mode:k,mtimeMs:F,length:_,capacity:Math.max(O,_)},o),_!==y&&(Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length);return}const I=new Uint8Array(_);c&&y>0&&I.set(Et(c),0),u.byteLength>0&&I.set(u,p);const j=It(I),W=Math.min(se,Math.max(_,_*2,64*1024));W>_&&jr(j+W),ee(i,{type:"file",mode:k,mtimeMs:F,offset:j,length:_,capacity:W},o);return}if(r.operation==="mkdir"){Me(i,o);const c=g.get(i);if(c&&c.type!=="directory")throw new Error(`OPFS path is a file: ${i}`);ee(i,{type:"directory",mode:r.mode??c?.mode??et,mtimeMs:r.mtimeMs??c?.mtimeMs??Date.now(),offset:0,length:0},o);return}if(r.operation==="remove"){ir(i,o),Ee().includes(i)&&ee(i,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0},o);return}if(r.operation==="link"){xs(i,zr(r.source),o);return}if(r.operation==="rename"){vs(i,ye(r.destination),o);return}const l=g.get(i);if(!l)throw new Error(`OPFS metadata target does not exist: ${i}`);ee(i,{...l,mode:r.mode??l.mode,mtimeMs:r.mtimeMs??l.mtimeMs},o)}function ee(r,o,i){const l=g.get(r);ae&&!ae.has(r)&&ae.set(r,l);const c=l!==void 0&&l.type===o.type&&l.offset===o.offset&&l.length===o.length&&l.pack===o.pack;l&&!c&&(Dr(l),l.type!=="directory"&&o.type!=="directory"&&l.length>0&&!l.pack&&(Ie+=1,Oe+=l.length)),g.set(r,o),At(r),c||(o.pack?(w+=1,b+=o.length):B+=o.length),i.push([r,o])}function At(r){const o=Le(r);o!==r&&U.mutable(o).add(r.slice(o.length+1))}function Br(r){const o=Le(r);U.get(o)?.has(r.slice(o.length+1))&&U.mutable(o).delete(r.slice(o.length+1)),U.delete(r)}function Ye(){U=new zt;for(const r of g.keys())At(r)}function or(r){const o=[],i=l=>{const c=g.get(l);if(!c)return;o.push([l,c]);const u=U.get(l);if(u)for(const p of u)i(`${l}/${p}`)};return i(r),o}function Dr(r,o){if(r.pack){w-=1,b-=r.length;return}B-=r.length,Q+=Math.max(r.length,r.capacity??0)}function Cr(r,o){const i=g.get(r);i&&(ae&&!ae.has(r)&&ae.set(r,i),g.delete(r),Br(r),Dr(i),o.push([r,null]))}function xs(r,o,i){const l=e.packages;if(!l)throw new Error("This store has no shared package store to link from.");const c=zr(o),u=l.descendants(c);if(u.length===0)throw new Error(`The shared package store does not hold ${o}.`);Me(r,i),ir(r,i),we(g.size+u.length);for(const[p,y]of u){const _=p===c?r:`${r}${p.slice(c.length)}`;ee(_,y.type==="directory"?{type:"directory",mode:y.mode,mtimeMs:y.mtimeMs,offset:0,length:0}:{type:y.type,mode:y.mode,mtimeMs:y.mtimeMs,offset:y.offset,length:y.length,pack:Ae},i)}}function Me(r,o){const i=Le(r);if(i!==r&&g.get(i)?.type==="directory"){we(g.size+(g.has(r)?0:1));return}const l=[];let c=ct(r)??Ee()[0];if(g.has(c)||l.push(c),r!==c)for(const p of dr(Qr(Le(r)))){c=`${c}/${p}`;const y=g.get(c);if(y&&y.type!=="directory")throw new Error(`OPFS path parent is a file: ${c}`);y||l.push(c)}we(g.size+l.length+(g.has(r)?0:1));const u=Date.now();for(const p of l)ee(p,{type:"directory",mode:et,mtimeMs:u,offset:0,length:0},o)}function ir(r,o){for(const[i]of or(r))Cr(i,o)}function vs(r,o,i){if(r===o)return;if(o.startsWith(`${r}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const l=or(r);if(l.length===0){if(g.has(o))return;throw new Error(`OPFS rename source does not exist: ${r}`)}Me(o,i),ir(o,i);for(const[c]of l)Cr(c,i);for(const[c,u]of l)ee(`${o}${c.slice(r.length)}`,u,i);we(g.size)}function zr(r){if(typeof r!="string"||!r.startsWith(`${pr}/`)||r.includes("\0")||r.length>4096)throw new Error("Invalid shared store path.");return dr(r.slice(pr.length+1)),r}function Ee(){return S===Ae?[pr]:uo}function ct(r){return Ee().find(o=>r===o||r.startsWith(`${o}/`))}function xt(r,o){const i=g.get(r),l=i&&!i.pack?i.length:0,c=d?fo:t;if(B-l+o>c){const u=d?"the origin's shared packages":"the project's own files";throw new Error(`OPFS workspace exceeds its byte limit: writing ${r} (${o} bytes) would take ${u} past ${c} bytes (${B} bytes held, ${l} replaced).`)}}function we(r){if(r>s)throw new Error("OPFS workspace exceeds its entry limit.")}function Ur(){if(we(g.size),B>t)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${B} bytes, past ${t}.`)}function vt(r,o){const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");let l=0;for(;l<o.byteLength;){const c=i.write(o.subarray(l),{at:r+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}v=Math.max(v,r+o.byteLength)}function jr(r){const o=$;if(!o)throw new Error("OPFS filesystem worker is not initialized.");r<=v||(o.truncate(r),v=r)}function It(r){const o=$;if(!o)throw new Error("OPFS filesystem worker is not initialized.");const i=v;let l=0;for(;l<r.byteLength;){const c=o.write(r.subarray(l),{at:i+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}return v=i+r.byteLength,i}function Is(r){const o=$;if(o.getSize()>=v&&r.getSize()>=M)return;o.flush(),r.flush();const i=o.getSize(),l=r.getSize();if(!(i>=v&&l>=M))throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${i} of ${v} bytes, its log ${l} of ${M}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function Os(r,o={}){const i=P;if(!i||!$)throw new Error("OPFS filesystem worker is not initialized.");if(r.length===0)return;const l=Be.encode(JSON.stringify({packBytes:v,changes:r}));if(l.byteLength>fn)throw new Error("An OPFS workspace index record exceeds its size limit.");const c=new Uint8Array(Dt+l.byteLength),u=new DataView(c.buffer);u.setUint32(0,l.byteLength,!0),u.setUint32(4,Zr(l),!0),c.set(l,Dt);let p=0;for(;p<c.byteLength;){const y=i.write(c.subarray(p),{at:M+p});if(y<=0)throw new Error("The OPFS workspace index log could not be written completely.");p+=y}M+=c.byteLength,Is(i),o.publish!==!1&&yt(),performance.now()-te>=wn?ke():K===void 0&&(K=setTimeout(ke,wn))}function ke(){if(K!==void 0&&(clearTimeout(K),K=void 0),fe)throw fe;const r=performance.now();$?.flush(),P?.flush(),te=performance.now(),ve+=1,ge+=te-r}function Ot(){const r=Nr,o=gt(()=>r.catch(()=>{}).then(Ns));return Nr=o,o}async function Ns(){if(be(),!T)return;const r=T,o=P,i=await pe(r,!1);if(!o||o!==P||r!==T)throw new Error("OPFS workspace changed generations before its checkpoint could start.");ke();const l=M;if(await dt(i,g,{access:o,bytes:l,packBytes:v}),r===T&&(he={generation:r,bytes:l}),o===P&&r===T&&l===M){ot();try{o.truncate(0),o.flush(),M=0,he={generation:r,bytes:0}}finally{it()}}}function qr(r){return bt(()=>Ts(ar(r)))}async function Ts(r){const o=crypto.randomUUID(),i=await pe(o,!0),l=await i.getFileHandle(Ze,{create:!0}),c=await Z(l,"store"),u=new Map;let p=0;try{for(const _ of r.files){let k=0,F=0;if(_.type!=="directory"){const O=new Uint8Array(r.pack,_.offset??0,_.length??0);k=p,F=O.byteLength;let I=0;for(;I<F;){const j=c.write(O.subarray(I),{at:k+I});if(j<=0)throw new Error("An OPFS workspace file could not be written completely.");I+=j}p+=F}u.set(_.path,{type:_.type,mode:_.mode??(_.type==="directory"?et:Ct),mtimeMs:_.mtimeMs??Date.now(),offset:k,length:F})}for(const _ of Ee())u.has(_)||u.set(_,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0});we(u.size),c.truncate(p),c.flush()}finally{c.close()}const y=await dt(i,u);await Nt(o,i,u,p,y)}async function Ms(){await Wr(()=>!0)}async function Fs(){let r=!1,o=!1,i=!1;try{await Ls(()=>{r=!0},()=>{o=!0},()=>{i=!0})}finally{r&&(o||i)?it():r&&_t()}}async function Ls(r,o,i){const l=crypto.randomUUID(),c=await pe(l,!0),u=await Z(await c.getFileHandle(Ze,{create:!0}),"store");let p,y=!1;try{p=await Z(await c.getFileHandle(hr,{create:!0}),"record of changes"),p.truncate(0);const _=new Uint8Array(mn);let k=0;const F=z=>{if(z.pack)return{...z};if(z.type==="directory"||z.length===0)return{...z,offset:0,length:0};const X=$;if(!X)throw new Error("OPFS filesystem worker is not initialized.");const $e=k;let ce=0;for(;ce<z.length;){const ft=Math.min(_.byteLength,z.length-ce),nn=_.subarray(0,ft);if(q?.ensure(z.offset+ce,ft),X.read(nn,{at:z.offset+ce})!==ft)throw new Error("An OPFS workspace file could not be read completely.");let Lt=0;for(;Lt<ft;){const sn=u.write(nn.subarray(Lt),{at:$e+ce+Lt});if(sn<=0)throw new Error("An OPFS workspace file could not be written completely.");Lt+=sn}ce+=ft}k+=z.length;const{capacity:fr,...Vs}=z;return{...Vs,offset:$e}},O=new Map;let I=performance.now();for(const[z,X]of[...g]){if(Y||Je)return;g.get(z)===X&&(O.set(X,F(X)),performance.now()-I>8&&(await new Promise($e=>setTimeout($e,0)),I=performance.now()))}if(Y||Je||!$||!P)return;ot(),r();const j=new Map;for(const[z,X]of g)j.set(z,O.get(X)??F(X));u.truncate(k),u.flush(),p.flush(),ke();const W={pack:$,log:P};$=u,P=p,M=0,g=j,Ye(),v=k,T=l,m=c,at(),y=!0;const ne=new Map(j);try{W.pack.close()}finally{W.log.close()}try{await dt(c,ne);const z={storageVersion:4,generation:l,initializedAt:Date.now()};await lt(await Te(),Xe,z)}catch(z){throw fe=new Error("The workspace moved to a compacted generation it could not record; it takes no more writes, which its next open would discard.",{cause:z}),fe}o(),await rr(l)}finally{if(!y){i();try{u.close()}finally{p?.close()}await Yr(await(await Te()).getDirectoryHandle(Bt),l)}}}async function $s(r){be(),ot();try{await Rs(r)}finally{it()}}async function Rs(r){let o=!1;for(const[i,l]of g){if(!l.pack||l.length===0)continue;const c=r.get(l.offset);if(c===void 0)throw new Error(`The shared store no longer holds the bytes of ${i}.`);c!==l.offset&&(g.set(i,{...l,offset:c}),o=!0)}o&&await Ot()}function Wr(r){return bt(()=>Bs(r))}async function Bs(r){const o=$;if(!o)throw new Error("OPFS filesystem worker is not initialized.");const i=new Map,l=crypto.randomUUID(),c=await pe(l,!0),u=await c.getFileHandle(Ze,{create:!0}),p=await Z(u,"store"),y=new Map,_=new Uint8Array(mn);let k=0;try{for(const[O,I]of g){if(!r(O,I))continue;if(I.pack){y.set(O,{...I});continue}if(I.type==="directory"||I.length===0){y.set(O,{...I,offset:0,length:0});continue}const j=k;i.set(I.offset,j);let W=0;for(;W<I.length;){const X=Math.min(_.byteLength,I.length-W),$e=_.subarray(0,X);if(q?.ensure(I.offset+W,X),o.read($e,{at:I.offset+W})!==X)throw new Error("An OPFS workspace file could not be read completely.");let ce=0;for(;ce<X;){const fr=p.write($e.subarray(ce),{at:j+W+ce});if(fr<=0)throw new Error("An OPFS workspace file could not be written completely.");ce+=fr}W+=X}k+=I.length;const{capacity:ne,...z}=I;y.set(O,{...z,offset:j,length:I.length})}p.truncate(k),p.flush()}finally{p.close()}const F=await dt(c,y);return await Nt(l,c,y,k,F),i}async function Nt(r,o,i,l,c,u){ot();try{await Ds(r,o,i,l,c,u)}finally{it()}}async function Ds(r,o,i,l,c,u){const p=await o.getFileHandle(hr,{create:!0}),y=await Z(p,"record of changes");try{y.truncate(0),y.flush()}finally{y.close()}const _={storageVersion:u?5:4,generation:r,initializedAt:Date.now(),...u?{imageRanges:u}:{}};if(await lt(await Te(),Xe,_),Ge(),T=r,L=_.initializedAt,J=u,c){const k=new Re(c.index);g=new Ke(k),U=new $t(k),re=void 0}else g=i,Ye();v=l,m=o,await He(o),c?({liveBytes:B,linked:w,linkedBytes:b}=c,Q=Math.max(0,v-B)):at(),d||await rr(r)}async function Cs(r,o,i,l,c=!1){if(be(),!d||S!==Ae)throw new Error("Only the shared package store can reserve immutable image extents.");if(v!==0||[...g.values()].some(O=>O.type!=="directory"))return!1;const u=ur(l);if(u.bytes!==r.packBytes||r.entries>wr||r.liveBytes>r.packBytes||o.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(o,r.json.sha256,c)||!await Mt(i,r.binary.sha256,c))throw new Error("The image's prepared metadata does not match its document.");const p=o.subarray(0,4096).indexOf(10);if(p<0)throw new Error("The prepared index has no bounded retained header.");const y=JSON.parse(`${Qe.decode(o.subarray(0,p-1))}}`),_={packBytes:r.packBytes,liveBytes:r.liveBytes,linked:0,linkedBytes:0},k=y.retainedIndex;if(k.version!==1||k.digest!==await Jr(r.binary.sha256,_)||k.packBytes!==_.packBytes||k.liveBytes!==_.liveBytes||k.linked!==0||k.linkedBytes!==0)throw new Error("The prepared index's retained measures are inconsistent.");const F=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(F).set(i),new Re(F).entryCount!==r.entries)throw new Error("The prepared index has the wrong number of entries.");return bt(async()=>{const O=crypto.randomUUID(),I=await pe(O,!0),j=await I.getFileHandle(Ze,{create:!0}),W=await Z(j,"immutable image reservation");try{W.truncate(r.packBytes),W.flush()}finally{W.close()}const ne=Be.encode(JSON.stringify(u));return await Se(I,cn,ne),await Se(I,Tt,i),await Se(I,de,o),await Nt(O,I,new Map,r.packBytes,{index:F,..._},await me(ne)),!0})}async function zs(r,o,i,l=!1,c){if(be(),d||!e.packages||!c&&!e.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(v!==0||[...g.values()].some(k=>k.type!=="directory"))return!1;if(o.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(o,r.json.sha256,l)||!await Mt(i,r.binary.sha256,l))throw new Error("The image's prepared project does not match its descriptor.");const u=o.subarray(0,4096).indexOf(10);if(u<0)throw new Error("The prepared project has no bounded retained header.");const p=JSON.parse(`${Qe.decode(o.subarray(0,u-1))}}`).retainedIndex,y={packBytes:0,liveBytes:0,linked:r.linked,linkedBytes:r.linkedBytes};if(p.version!==1||p.digest!==await Jr(r.binary.sha256,y)||p.packBytes!==0||p.liveBytes!==0||p.linked!==r.linked||p.linkedBytes!==r.linkedBytes)throw new Error("The prepared project's retained measures are inconsistent.");const _=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(_).set(i),new Re(_).entryCount!==r.entries||r.entries>s)throw new Error("The prepared project has invalid entry bounds.");return bt(async()=>{const k=crypto.randomUUID(),F=await pe(k,!0),O=await F.getFileHandle(Ze,{create:!0}),I=await Z(O,"prepared project");try{I.truncate(0),I.flush()}finally{I.close()}if(await Se(F,Tt,i),await Se(F,de,o),c&&!await c)return!1;if(!e.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");return await Nt(k,F,new Map,0,{index:_,...y}),!0})}async function Us(){if(Y)throw new Error("This OPFS workspace is closing.");if(!$)throw new Error("OPFS filesystem worker is not initialized.");const r=[],o=[...g.keys()].sort((p,y)=>Xr(p)-Xr(y)||(p<y?-1:1));let i=0;for(const p of g.values())p.type!=="directory"&&(i+=p.length);const l=new ArrayBuffer(i),c=new Uint8Array(l);let u=0;for(const p of o){const y=g.get(p);if(y.type==="directory"){r.push({path:p,type:"directory",mode:y.mode,mtimeMs:y.mtimeMs});continue}y.length>0&&c.set(Et(y),u),r.push({path:p,type:y.type,offset:u,length:y.length,mode:y.mode,mtimeMs:y.mtimeMs}),u+=y.length}for(const p of[...Ee()].reverse())g.has(p)||r.unshift({path:p,type:"directory",mode:et,mtimeMs:Date.now()});return ar({files:r,pack:l})}async function lt(r,o,i){await Se(r,o,Be.encode(JSON.stringify(i)))}async function Se(r,o,i){const l=await(await Te()).getDirectoryHandle(dn,{create:!0}),c=crypto.randomUUID(),u=await l.getFileHandle(c,{create:!0}),p=await Z(u,"index");try{let y=0;for(;y<i.byteLength;){const _=p.write(i.subarray(y),{at:y});if(_<=0)throw new Error("An OPFS workspace file could not be written completely.");y+=_}p.truncate(i.byteLength),p.flush()}finally{p.close()}try{await u.move(r,o)}finally{await Gr(l,c,!1)}}const Tt="index.shared";async function me(r){const o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join("")}async function Mt(r,o,i){return i||await me(r)===o}function Jr(r,o){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:p}=o;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:u,...p?{journalPrefix:p}:{}})}:${r}`))}async function Hr(r,o){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:p}=o;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:u,...p?{journalPrefix:p}:{}})}:${await me(r)}`))}async function dt(r,o,i){const l=Js(o);if(typeof SharedArrayBuffer>"u"||o.size<1e4){await lt(r,de,l);return}const c=new Map(l.entries),u=new Map,p={packBytes:i?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[j,W]of c){const ne=Le(j);if(ne!==j){let z=u.get(ne);z||(z=new Set,u.set(ne,z)),z.add(j.slice(ne.length+1))}W.pack?(p.linked+=1,p.linkedBytes+=W.length):(p.liveBytes+=W.length,p.packBytes=Math.max(p.packBytes,W.offset+W.length))}let y;try{y=on(c,u)}catch{await lt(r,de,l);return}const _=JSON.stringify(l.entries),k=i?new Uint8Array(i.bytes):void 0;if(k&&i.access.read(k,{at:0})!==k.byteLength)throw new Error("The checkpoint's journal prefix could not be read completely.");const F=k?{bytes:k.byteLength,digest:await me(k)}:void 0,O=new Uint8Array(y).slice(),I={version:F?2:1,digest:await Hr(O,{...p,...F?{journalPrefix:F}:{}}),...p,...F?{journalPrefix:F}:{}};try{await Se(r,Tt,O)}catch{await lt(r,de,{entries:JSON.parse(_)});return}return await Se(r,de,Be.encode(`{"retainedIndex":${JSON.stringify(I)},
|
|
3
3
|
"entries":${_}}`)),{index:y,...p}}async function js(r){if(!(typeof SharedArrayBuffer>"u"))try{const o=await r.getFileHandle(de),i=await Z(o,"index");let l;try{const O=new Uint8Array(Math.min(512,i.getSize())),I=i.read(O,{at:0});l=Qe.decode(O.subarray(0,I))}finally{i.close()}const c=l.split(`
|
|
4
4
|
`,1)[0];if(!c.startsWith('{"retainedIndex":')||!c.endsWith(","))return;const u=JSON.parse(c.slice(0,-1)+"}").retainedIndex;if(u.version!==1&&u.version!==2||!/^[a-f0-9]{64}$/u.test(u.digest)||![u.packBytes,u.liveBytes,u.linked,u.linkedBytes].every(O=>Number.isSafeInteger(O)&&O>=0)||u.version===1&&u.journalPrefix!==void 0||u.version===2&&(!u.journalPrefix||!Number.isSafeInteger(u.journalPrefix.bytes)||u.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(u.journalPrefix.digest)))return;const p=await r.getFileHandle(Tt),y=await Z(p,"index");let _;try{const O=y.getSize();if(O>256*1024*1024||(_=new Uint8Array(O),y.read(_,{at:0})!==O))return}finally{y.close()}if(await Hr(_,u)!==u.digest)return;const k=new SharedArrayBuffer(_.byteLength);new Uint8Array(k).set(_);const F=new Re(k);return we(F.entryCount),{...u,index:k}}catch{return}}async function qs(r){const o=r.journalPrefix;if(!o||!P||!$||o.bytes>P.getSize()||r.packBytes>$.getSize())return 0;const i=new Uint8Array(o.bytes);return P.read(i,{at:0})!==i.byteLength?0:await me(i)===o.digest?o.bytes:0}async function Fe(r,o){let i;try{i=await r.getFileHandle(o)}catch(u){if(Ve(u))return;throw u}let l;if(f){l=await(await i.getFile()).text();try{return JSON.parse(l)}catch(u){throw new Error(`Invalid OPFS workspace metadata (${o}). Stored data was retained.`,{cause:u})}}const c=await Z(i,"index");try{const u=c.getSize(),p=new Uint8Array(u);if(u>0&&c.read(p,{at:0})!==u)throw new Error("An OPFS workspace file could not be read completely.");l=Qe.decode(p)}finally{c.close()}try{return JSON.parse(l)}catch(u){throw new Error(`Invalid OPFS workspace metadata (${o}). Stored data was retained.`,{cause:u})}}async function Gr(r,o,i){try{await r.removeEntry(o,{recursive:i})}catch(l){if(!Ve(l))throw l}}async function Yr(r,o){try{await r.removeEntry(o,{recursive:!0})}catch{}}function Vr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS filesystem mutation.");if(r.operation!=="write"&&r.operation!=="append"&&r.operation!=="write-at"&&r.operation!=="mkdir"&&r.operation!=="remove"&&r.operation!=="rename"&&r.operation!=="metadata"&&r.operation!=="link")throw new Error("Invalid OPFS filesystem mutation.");if(ye(r.path),r.operation==="rename"&&ye(r.destination),(r.operation==="write"||r.operation==="append"||r.operation==="write-at")&&!(r.content instanceof Uint8Array))throw new Error("Invalid OPFS file content.");if(r.operation==="write-at"&&(!Number.isSafeInteger(r.position)||r.position<0))throw new Error("Invalid OPFS write position.");return cr(r),r}function Ws(r){if(!Array.isArray(r)||r.length===0||r.length>128)throw new Error("Invalid OPFS filesystem mutation batch.");return r.map(o=>Vr(o))}function ar(r){if(!r||!Array.isArray(r.files)||r.files.length>s||!(r.pack instanceof ArrayBuffer))throw new Error("Invalid OPFS workspace snapshot.");const o=new Set,i=new Map(Ee().map(c=>[c,"directory"]));let l=0;for(const c of r.files){if(!c||typeof c!="object")throw new Error("Invalid OPFS workspace snapshot entry.");if(ye(c.path),c.type!=="file"&&c.type!=="directory"&&c.type!=="symlink"||o.has(c.path))throw new Error("Invalid or duplicate OPFS workspace entry.");if(o.add(c.path),i.set(c.path,c.type),Ee().includes(c.path)&&c.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(c.type!=="directory"){const u=c.offset??0,p=c.length??0;if(!Number.isSafeInteger(u)||!Number.isSafeInteger(p)||u<0||p<0||p>se||u+p>r.pack.byteLength)throw new Error("Invalid OPFS workspace file.");if(l+=p,l>t)throw new Error("OPFS workspace exceeds its byte limit.")}else if((c.offset??0)!==0||(c.length??0)!==0)throw new Error("An OPFS workspace directory cannot contain file bytes.");cr(c)}we(i.size);for(const c of r.files)if(!Ee().includes(c.path)&&i.get(Le(c.path))!=="directory")throw new Error(`An OPFS workspace snapshot has no directory parent for ${c.path}.`);return r}function cr(r){if(r.mode!==void 0&&(!Number.isSafeInteger(r.mode)||r.mode<0||r.mode>4095))throw new Error("Invalid OPFS file mode.");if(r.mtimeMs!==void 0&&(typeof r.mtimeMs!="number"||!Number.isFinite(r.mtimeMs)||r.mtimeMs<0))throw new Error("Invalid OPFS modification time.")}function Js(r){return{entries:[...r]}}function lr(r){const o=new Map;if(r===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!r||typeof r!="object"||!Array.isArray(r.entries))throw new Error("Invalid OPFS workspace index.");const i=r.entries;we(i.length);for(const l of i){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index entry.");const c=ye(l[0]);if(o.has(c))throw new Error("Duplicate OPFS workspace index entry.");o.set(c,Kr(l[1]))}return o}function Kr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index entry.");const o=r;if(o.type!=="file"&&o.type!=="directory"&&o.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");if(cr(o),o.mode===void 0||o.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(o.offset)||o.offset<0||!Number.isSafeInteger(o.length)||o.length<0||o.length>se)throw new Error("Invalid OPFS workspace index extent.");if(o.pack!==void 0&&o.pack!==Ae)throw new Error("Invalid OPFS workspace index entry.");return{type:o.type,mode:o.mode,mtimeMs:o.mtimeMs,offset:o.offset,length:o.length,...o.pack?{pack:o.pack}:{}}}function Hs(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index record.");const o=r;if(!Number.isSafeInteger(o.packBytes)||o.packBytes<0||!Array.isArray(o.changes))throw new Error("Invalid OPFS workspace index record.");const i=[];for(const l of o.changes){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index record.");i.push([ye(l[0]),l[1]===null?null:Kr(l[1])])}return{packBytes:o.packBytes,changes:i}}function Ft(r){if(r===void 0)return;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const o=r;if(o.storageVersion!==4&&o.storageVersion!==5||o.storageVersion===5&&(typeof o.imageRanges!="string"||!/^[a-f0-9]{64}$/u.test(o.imageRanges))||o.storageVersion===4&&o.imageRanges!==void 0||typeof o.generation!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(o.generation)||typeof o.initializedAt!="number"||!Number.isFinite(o.initializedAt))throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.");return o}function ye(r){if(typeof r!="string"||ct(r)===void 0||r.includes("\0")||r.length>4096)throw new Error("Invalid OPFS workspace path.");return Qr(r),r}function Qr(r){const o=ct(r);if(o===void 0)throw new Error("Invalid OPFS workspace path.");const i=r===o?"":r.slice(o.length+1);return dr(i),i}function dr(r){const o=r===""?[]:r.split("/");if(o.some(i=>!i||i==="."||i===".."||i.includes("\0")))throw new Error("Invalid OPFS workspace path segment.");return o}function Le(r){const o=r.slice(0,r.lastIndexOf("/"));return o===""||ct(o)===void 0?ct(r)??r:o}function Xr(r){let o=1;for(let i=0;i<r.length;i+=1)r.charCodeAt(i)===47&&(o+=1);return o}function Ve(r){return r instanceof DOMException&&r.name==="NotFoundError"}function Zr(r){let o=2166136261;for(let i=0;i<r.byteLength;i+=1)o^=r[i],o=Math.imul(o,16777619);return o>>>0}typeof addEventListener=="function"&&addEventListener("close",()=>{$?.flush(),P?.flush(),Ge(),E?.()});function en(r,o={}){if(be(),ae)throw new Error("An OPFS mutation batch cannot be nested.");for(const i of r)Vr(i);return r.length?tn(i=>{for(const l of r)As(l,i)},o):[]}function Gs(r,o,i={}){if(be(),ae)throw new Error("An OPFS mutation batch cannot be nested.");for(const l of o){if(ye(l.path),l.type!=="file"&&l.type!=="directory"&&l.type!=="symlink")throw new Error(`OPFS extent ${l.path} has no valid type.`);if(l.type==="directory")continue;const{offset:c,length:u}=l;if(c===void 0||u===void 0||!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||c<0||u<0||c+u>r.byteLength)throw new Error(`OPFS extent ${l.path} lies outside its bytes.`);if(u>se)throw new Error(`${l.path} is ${u} bytes; an OPFS workspace file holds at most ${se}.`)}return o.length?tn(l=>{const c=r.byteLength>0?It(r):v;for(const u of o){const p=ye(u.path);Me(p,l);const y=g.get(p);if(u.type==="directory"){if(y&&y.type!=="directory")throw new Error(`OPFS path is a file: ${p}`);ee(p,{type:"directory",mode:u.mode,mtimeMs:u.mtimeMs,offset:0,length:0},l);continue}if(y?.type==="directory")throw new Error(`OPFS write target is a directory: ${p}`);xt(p,u.length),ee(p,{type:u.type,mode:u.mode,mtimeMs:u.mtimeMs,offset:c+u.offset,length:u.length},l)}},i):[]}function tn(r,o){if(!$||!P)throw new Error("OPFS filesystem worker is not initialized.");const i={packBytes:v,logBytes:M,liveBytes:B,deadBytes:Q,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b},l=new Map;ae=l;const c=[];mt=c;const u=[];try{return r(u),Ur(),Os(u,{publish:!o.durable}),o.durable&&(ke(),yt()),Rr(),u}catch(p){const y=V!==void 0&&!ue&&Atomics.load(V,pn)!==i.logBytes;y&&ot();for(const[_,k]of l)k===void 0?g.delete(_):g.set(_,k);Ye();try{for(let _=c.length-1;_>=0;_-=1)vt(c[_][0],c[_][1])}catch(_){p=new AggregateError([p,_],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes:v,logBytes:M,liveBytes:B,deadBytes:Q,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b}=i),K!==void 0&&(clearTimeout(K),K=void 0);try{P.truncate(M),P.flush(),$.truncate(v),$.flush()}catch(_){throw _t(),fe=new AggregateError([p,_],"OPFS could not roll back a failed batch; reopen this workspace before writing again."),fe}throw y&&it(),p}finally{ae=void 0,mt=void 0}}function Ys(){if(qe){st?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}Y||(Y=!0,We===0&&rn())}function rn(){_t();try{ke()}finally{try{Ge()}finally{const r=E;E=void 0,a=void 0;try{r?.()}finally{e.ownsPackages&&e.packages?.close()}}}}return{initialize:ys,opened:()=>a!==void 0&&!Y,stats:()=>({entries:g.size,liveBytes:B,deadBytes:Q,packBytes:v,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b,flushes:ve,flushMs:ge}),applyNow:en,applyExtentsNow:Gs,close:Ys,readExtent:kt,descendants:or,retain:Wr,remapLinks:$s,childrenOf:r=>[...U.get(r)??[]].sort(),refresh:_s,follow:hs,clock:Tr,readerSeed:ds,imageCompletionSeed:fs,imageLine:()=>q?.lineForReader()??e.packages?.imageLine(),imageStartupSet:()=>q?.readDigests()??q?.completedDigests()??[],prefetchImage:(r,o)=>q?.prefetch(r,o)??{queued:0,done:Promise.resolve()},seeded:()=>Mr,get logBytes(){return M},checkpoint:Ot,deferMaintenance:Ps,installPreparedImage:Cs,installPreparedProject:zs,get deferredImage(){return _e},get imagePlacedAt(){return a&&J?L:void 0},get entries(){return g},get packBytes(){return v},read:ws,readRange:ms,snapshot:Us,replace:qr,apply:Ss,flush:()=>{if(Y||!a)throw new Error("This OPFS workspace is not open.");if(Je)throw new Error("Wait for the OPFS generation replacement before flushing it.");ke()},validateSnapshot:ar,validateMutationBatch:Ws}}async function wo(n,e,t,s){const a=yn(n);await a.initialize(Ae,{readOnly:!0,extentsOnly:!0});const d=yn(n,{packages:a,ownsPackages:!0});let f;try{f=await d.initialize(e,{readOnly:!0,...t?{seed:t}:{}})}catch(h){throw d.close(),a.close(),h}if(!f&&!d.opened()){a.close();return}return d}const mo="sweep.json";async function yo(n){const t=await(await n.getFileHandle(mo,{create:!0})).createWritable();await t.write(JSON.stringify({at:Date.now()})),await t.close()}class zt{map=new Map;get(e){return this.map.get(e)}mutable(e){let t=this.map.get(e);return t||(t=new Set,this.map.set(e,t)),t}delete(e){this.map.delete(e)}}function _o(n){const e=n.toBase64;if(typeof e=="function")return e.call(n);let t="";for(let s=0;s<n.byteLength;s+=32768)t+=String.fromCharCode(...n.subarray(s,s+32768));return btoa(t)}function Hn(n){const e=Uint8Array.fromBase64;if(typeof e=="function")return e(n);const t=atob(n),s=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)s[a]=t.charCodeAt(a);return s}function go(n,e,t){const{appended:s,superseded:a}=t?bo(n,e,t):{appended:new Map,superseded:new Set},d=[...e.removed].sort((h,m)=>Ut(m)-Ut(h));for(const h of d)n.existsSync(h)&&(n.statSync(h).isDirectory()?n.rmdirSync(h):n.unlinkSync(h));const f=[...e.files].filter(h=>!a.has(h.path)).sort((h,m)=>Ut(h.path)-Ut(m.path));for(const h of f){if(h.type==="directory")n.existsSync(h.path)&&!n.statSync(h.path).isDirectory()&&n.unlinkSync(h.path),n.mkdirSync(h.path,{recursive:!0});else if(Ue(h)){n.existsSync(h.path)&&n.statSync(h.path).isDirectory()&&n.rmdirSync(h.path);const m=h.path.slice(0,h.path.lastIndexOf("/"))||"/";m!=="/"&&!n.existsSync(m)&&n.mkdirSync(m,{recursive:!0});const w=n.existsSync(h.path)?n.statSync(h.path).mode:void 0,b=w!==void 0&&(w&128)===0;b&&n.chmodSync?.(h.path,w&4095|128),n.writeFileSync(h.path,s.get(h.path)??pt(h)),b&&h.mode===void 0&&n.chmodSync?.(h.path,w&4095)}else if(!n.existsSync(h.path)||n.statSync(h.path).isDirectory())continue;h.mode!==void 0&&n.chmodSync?.(h.path,h.mode),h.mtimeMs!==void 0&&n.utimesSync?.(h.path,new Date(h.mtimeMs),new Date(h.mtimeMs))}}function bo(n,e,t){const s=new Map,a=new Set,d=t.byPath,f=d instanceof Map?d:new Map(t.files.map(w=>[w.path,w])),h=new Map(e.files.map(w=>[w.path,w])),m=new Set([...e.files.map(w=>w.path),...e.removed]);for(const w of m){const b=f.get(w),E=Ao(n,w);if(b!==void 0&&yr(b,h.get(w))||E===void 0&&h.get(w)!==void 0)continue;const S=h.get(w);if(!(E!==void 0&&S!==void 0&&S.type===E.type&&(C(S).mtimeMs??0)>(C(E).mtimeMs??0))&&!(b!==void 0&&E!==void 0&&b.type===E.type&&(C(E).mtimeMs??0)<(C(b).mtimeMs??0))&&!yr(b,E)&&!yr(h.get(w),E)){if(ko(b,E,h.get(w)))continue;const T=Eo(n,w,b,E,h.get(w),t.bytesOf?.bind(t));if(T){s.set(w,T);continue}const g=h.get(w);if(b!==void 0&&E!==void 0&&g!==void 0&&g.type===E.type&&(C(g).mtimeMs??0)>=(C(b).mtimeMs??0)&&(C(E).mtimeMs??0)>(C(g).mtimeMs??0)&&(C(E).mtimeMs??0)>(C(b).mtimeMs??0)){a.add(w);continue}throw new Error(`Browser filesystem write conflict at ${w}. ${JSON.stringify({base:mr(b),current:mr(E),proposed:mr(h.get(w))})}`)}}return{appended:s,superseded:a}}function Eo(n,e,t,s,a,d){if(t?.type!=="file"||s?.type!=="file"||a?.type!=="file"||!Ue(a)||!n.readFileSync||C(s).mode!==C(a).mode)return;const f=Ue(t)?pt(t):d?.(e);if(!f||f.length===0)return;const h=pt(a),m=n.readFileSync(e),w=typeof m=="string"?new TextEncoder().encode(m):m,b=S=>S.length>=f.length&&Yn(S.subarray(0,f.length),f);if(h.length<=f.length||!b(h)||!b(w))return;const E=new Uint8Array(w.length+h.length-f.length);return E.set(w,0),E.set(h.subarray(f.length),w.length),E}function mr(n){return n?{type:n.type,...C(n)}:null}function ko(n,e,t){return e?.type!=="directory"||t?.type!=="directory"?!1:n===void 0?C(e).mode===C(t).mode:C(e).mode===C(t).mode&&n.type==="directory"&&C(n).mode===C(e).mode}function So(n,e){const t=new Set(e.removed),s=new Map(e.files.map(d=>[d.path,d])),a=[];for(const d of n.files){if(t.has(d.path))continue;const f=s.get(d.path);if(f){a.push(f),s.delete(d.path);continue}a.push(d)}for(const d of s.values())a.push(d);return{files:a}}function Po(n,e,t={}){const s=new Map(n.files.map(d=>[d.path,d])),a=new Map(e.files.map(d=>[d.path,d]));return{files:e.files.filter(d=>{const f=s.get(d.path);return d.path==="/"&&!f?!1:!f||f.type!==d.type||!Gn(f,d)||t.written===!0&&d.type==="file"&&!Ue(f)&&Ue(d)||C(f).mode!==C(d).mode||C(f).mtimeMs!==C(d).mtimeMs}),removed:n.files.flatMap(d=>a.has(d.path)?[]:[d.path])}}function Ut(n){let e=1;for(let t=0;t<n.length;t+=1)n.charCodeAt(t)===47&&(e+=1);return e}function Ao(n,e){if(!n.existsSync(e))return;const t=n.statSync(e),s={...t.mode!==void 0?{mode:t.mode}:{},...t.mtimeMs!==void 0?{mtimeMs:t.mtimeMs}:{}};return t.isDirectory()?{path:e,type:"directory",...s}:{path:e,type:"file",...t.size!==void 0?{size:t.size}:{},...s}}function yr(n,e){return n===void 0?e===void 0:e!==void 0&&n.type===e.type&&Gn(n,e)&&C(n).mode===C(e).mode&&C(n).mtimeMs===C(e).mtimeMs}function C(n){const e=n;return{...e.mode===void 0?{}:{mode:e.mode&4095},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs}}}function Gn(n,e){return n.type!=="file"||e.type!=="file"?!0:n.content!==void 0&&e.content!==void 0?n.content===e.content:Ue(n)&&Ue(e)?Yn(pt(n),pt(e)):_n(n)===_n(e)}function _n(n){if(n.size!==void 0)return n.size;if(n.bytes!==void 0)return n.bytes.byteLength;if(n.content===void 0)return;const e=n.content.endsWith("==")?2:n.content.endsWith("=")?1:0;return Math.floor(n.content.length*3/4)-e}function Ue(n){return n!==void 0&&(n.bytes!==void 0||n.content!==void 0)}function pt(n){return n.bytes??(n.content===void 0?void 0:Hn(n.content))}function Yn(n,e){if(n===e)return!0;if(n.byteLength!==e.byteLength)return!1;let t=0;if(n.byteOffset%4===0&&e.byteOffset%4===0){const s=n.byteLength>>>2,a=new Uint32Array(n.buffer,n.byteOffset,s),d=new Uint32Array(e.buffer,e.byteOffset,s);for(let f=0;f<s;f+=1)if(a[f]!==d[f])return!1;t=s<<2}for(;t<n.byteLength;t+=1)if(n[t]!==e[t])return!1;return!0}const Or="314.0.6",xo=`https://cdn.jsdelivr.net/pyodide/v${Or}/full/`,vo=[{file:"pyodide.mjs",integrity:"sha256-aeP2zOw+FLRl32C+V3ymL1NiUUBrmgDM4BnqxSUqJJU=",bytes:17931},{file:"pyodide.asm.mjs",integrity:"sha256-KsXro2XsEoOcdcA7ObO+HdY7eYhSzEYLAUtSI4vgQvc=",bytes:1250344},{file:"pyodide.asm.wasm",integrity:"sha256-OgoA3+qjSKwg+e8JkEIz0y0z9kQzlmLUrzaPiiAQ83o=",bytes:9598218},{file:"python_stdlib.zip",integrity:"sha256-gMW+a6v+AylwaXA0EMPClATc8lJdKxKHRrrlU2+Ugx8=",bytes:2545564},{file:"pyodide-lock.json",integrity:"sha256-P9rvCenjZcheACc3cg+NCrjyeMHCRKLd5qN2Y89IitQ=",bytes:114440}];function Io(n){const e=vo.find(t=>t.file===n);if(!e)throw new Error(`Pyodide ${Or} publishes no pinned ${n}.`);return e}async function Oo(n){const e=new Uint8Array(await crypto.subtle.digest("SHA-256",n));let t="";for(const s of e)t+=String.fromCharCode(s);return`sha256-${btoa(t)}`}async function gn(n,e){const t=Io(n),s=await Oo(e);if(s!==t.integrity)throw new Error(`Pyodide ${Or} ${n} is ${s}, not the pinned ${t.integrity}.`)}const G="/workspace";let bn,Yt="program";function No(){return Yt}async function To(n,e){const t=Yt;Yt=n;try{return await e()}finally{Yt=t}}async function Mo(n){return new Uint8Array(await new Response(new Blob([n]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer())}function Vn(n=xo,e){return bn??=(async()=>{const t=e?await Mo(e).catch(()=>{}):void 0,s=async(a,d)=>{if(t)try{const f=await a.loadPyodide({...d,_loadSnapshot:t});return await f.runPythonAsync(`import random
|
|
5
5
|
random.seed()`),delete f._api?.config?._loadSnapshot,f}catch(f){console.warn(`[python] the interpreter snapshot did not restore; starting Python: ${f instanceof Error?f.message:String(f)}`)}return await a.loadPyodide(d)};return To("runtime",async()=>{if(n.startsWith("/")){const b=await import(`file://${n}pyodide.mjs`),E=await import(`file://${n}pyodide.asm.mjs`);return await s(b,{indexURL:n,createPyodideModule:E.default})}const[a,d]=await Promise.all([fetch(`${n}pyodide.mjs`),fetch(`${n}pyodide.asm.mjs`)]);if(!a.ok)throw new Error(`Could not load Pyodide (${a.status}).`);if(!d.ok)throw new Error(`Could not load the Pyodide runtime module (${d.status}).`);const[f,h]=await Promise.all([a.bytes(),d.bytes()]);await gn("pyodide.mjs",f),await gn("pyodide.asm.mjs",h);const m=URL.createObjectURL(new Blob([f],{type:"text/javascript"})),w=URL.createObjectURL(new Blob([h],{type:"text/javascript"}));try{const b=await import(m),E=await import(w);return await s(b,{indexURL:n,createPyodideModule:E.default})}finally{URL.revokeObjectURL(m),URL.revokeObjectURL(w)}})})(),bn}const Fo=16384;function Lo(n){return{existsSync:e=>n.analyzePath(e).exists,statSync:e=>{const t=n.stat(e),s=(t.mode&61440)===Fo;return{isDirectory:()=>s,...typeof t.size=="number"?{size:t.size}:{},...Sr(t)}},readFile:e=>Promise.resolve(n.readFile(e)),writeFileSync:(e,t)=>n.writeFile(e,typeof t=="string"?new TextEncoder().encode(t):t),mkdirSync:e=>n.mkdirTree(e),unlinkSync:e=>n.unlink(e),rmdirSync:e=>n.rmdir(e),chmodSync:(e,t)=>n.chmod(e,t),utimesSync:(e,t,s)=>n.utime(e,En(t),En(s))}}function $o(n,e,t){go(Lo(n),e,t)}function En(n){return typeof n=="number"?n:Number(n)}function Ro(n,e){Zn(n,G),n.mkdirTree(G);const t=e.files.slice().sort((s,a)=>kn(s.path)-kn(a.path));for(const s of t)s.path!==G&&!s.path.startsWith(`${G}/`)||(s.type==="directory"?n.mkdirTree(s.path):(n.mkdirTree(s.path.slice(0,s.path.lastIndexOf("/"))||"/"),n.writeFile(s.path,Bo(s.content??""))));for(const s of t){const a=s;a.path!==G&&!a.path.startsWith(`${G}/`)||(a.mode!==void 0&&n.chmod(a.path,a.mode),a.mtimeMs!==void 0&&n.utime(a.path,a.mtimeMs,a.mtimeMs))}}function Kn(n,e){const s=[...e.files.filter(a=>a.path!==G&&!a.path.startsWith(`${G}/`))];return Xn(n,G,s),{files:s}}function Kt(n,e){const t=n.startsWith("/")?n:`${e}/${n}`,s=[];for(const a of t.split("/"))!a||a==="."||(a===".."?s.pop():s.push(a));return`/${s.join("/")}`}function je(n){return n.slice(n.lastIndexOf("/")+1)}function Qn(n){let e="";for(let t=0;t<n.byteLength;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function Bo(n){const e=atob(n);return Uint8Array.from(e,t=>t.charCodeAt(0))}function Xn(n,e,t){const s=n.stat(e),a=Sr(s);t.push({path:e,type:"directory",...a});for(const d of n.readdir(e)){if(d==="."||d==="..")continue;const f=`${e}/${d}`,h=n.stat(f);(h.mode&61440)===16384?Xn(n,f,t):t.push({path:f,type:"file",content:Qn(n.readFile(f)),...Sr(h)})}}function Zn(n,e){if(n.analyzePath(e).exists)for(const t of n.readdir(e)){if(t==="."||t==="..")continue;const s=`${e}/${t}`;(n.stat(s).mode&61440)===16384?(Zn(n,s),n.rmdir(s)):n.unlink(s)}}function kn(n){let e=1;for(let t=0;t<n.length;t+=1)n.charCodeAt(t)===47&&(e+=1);return e}function Sr(n){const e=typeof n.mtime=="number"?n.mtime:Number(n.mtime);return{mode:n.mode&4095,...typeof e=="number"&&Number.isFinite(e)?{mtimeMs:e}:{}}}const Pr=16384,Do=32768,Sn=44;function Co(n,e){const t=n,s=t.filesystems?.MEMFS;if(!s||typeof t.mount!="function"||typeof s.createNode!="function")return;const a={dirty:new Set,removed:new Set},d=()=>t.genericErrors?.[Sn]??new t.ErrnoError(Sn),f=N=>N.packPath??G;function h(N,R,L){const P=e.entries.get(L);if(!P)throw d();const A=P.mode&4095|(P.type==="directory"?Pr:Do),x=s.createNode(N,R,A,0);return x.packPath=L,x.timestamp=P.mtimeMs,x.atime=x.mtime=x.ctime=P.mtimeMs,P.type==="directory"?(x.packListed=!1,x.node_ops=S(x.node_ops)):(x.packLoaded=!1,x.usedBytes=P.length,x.node_ops=g(x.node_ops),x.stream_ops=$(x.stream_ops)),x}function m(N){if(N.packLoaded!==!1||!N.packPath)return;const R=e.read(N.packPath);N.contents=R,N.usedBytes=R.byteLength,N.packLoaded=!0}function w(N){t.isDir(N.mode)||a.dirty.add(b(N))}function b(N){const R=[];let L=N;for(;L&&L.parent!==L;)R.unshift(L.name),L=L.parent;return`${G}/${R.join("/")}`.replace(/\/+$/u,"")||G}const E=new WeakMap;function S(N){const R=E.get(N);if(R)return R;const L={...N,lookup:(P,A)=>{const x=`${f(P)}/${A}`;if(!a.removed.has(x)&&e.entries.has(x))return h(P,A,x);throw d()},readdir:P=>{const A=N.readdir(P),x=new Set(A),D=f(P);for(const H of e.childrenOf(D))a.removed.has(`${D}/${H}`)||x.add(H);return[...x]},mknod:(P,A,x,D)=>{const H=`${f(P)}/${A}`;a.removed.delete(H);const v=N.mknod(P,A,x,D);return v.packPath=H,t.isDir(x)?(v.packListed=!0,v.node_ops=S(v.node_ops)):(v.packLoaded=!0,a.dirty.add(H),v.node_ops=g(v.node_ops),v.stream_ops=$(v.stream_ops)),v},unlink:(P,A)=>{const x=`${f(P)}/${A}`;N.unlink(P,A),a.dirty.delete(x),a.removed.add(x)},rmdir:(P,A)=>{const x=`${f(P)}/${A}`;for(const D of e.childrenOf(x))if(!a.removed.has(`${x}/${D}`))throw new t.ErrnoError(55);N.rmdir(P,A),a.removed.add(x)},rename:(P,A,x)=>{const D=b(P);t.isFile(P.mode)?m(P):J(P),N.rename(P,A,x);const H=`${f(A)}/${x}`;q(P,D,H),a.removed.add(D),a.removed.delete(H)}};return E.set(N,L),L}const T=new WeakMap;function g(N){const R=T.get(N);if(R)return R;const L={...N,setattr:(P,A)=>{A.size!==void 0&&m(P),N.setattr(P,A),(A.size!==void 0||A.mode!==void 0||A.timestamp!==void 0)&&w(P)}};return T.set(N,L),L}const U=new WeakMap;function $(N){const R=U.get(N);if(R)return R;const L={...N,open:P=>{m(P.node),N.open?.(P)},write:(P,A,x,D,H,v)=>{m(P.node);const K=N.write(P,A,x,D,H,v);return w(P.node),K}};return U.set(N,L),L}function J(N){const R=f(N);for(const L of e.childrenOf(R)){if(a.removed.has(`${R}/${L}`))continue;const A=N.contents[L]??h(N,L,`${R}/${L}`);t.isDir(A.mode)?J(A):m(A)}N.packListed=!0}function q(N,R,L){if(N.packPath=L,t.isFile(N.mode)){a.dirty.delete(R),a.dirty.add(L);return}for(const[P,A]of Object.entries(N.contents))q(A,`${R}/${P}`,`${L}/${P}`)}const _e={mount:()=>{const N=s.createNode(null,"/",Pr|493,0);return N.packPath=G,N.node_ops=S(N.node_ops),N}};if(t.analyzePath(G).exists){try{t.unmount(G)}catch{}try{t.rmdir(G)}catch{}}return t.mkdirTree(G),t.mount(_e,{},G),a}function zo(n,e,t){const s=t.files.filter(d=>d.path!==G&&!d.path.startsWith(`${G}/`)),a=d=>{const f=n.stat(d),h=typeof f.mtime=="number"?f.mtime:Number(f.mtime),m={mode:f.mode&4095,...typeof h=="number"&&Number.isFinite(h)?{mtimeMs:h}:{}};if((f.mode&61440)===Pr){s.push({path:d,type:"directory",...m});for(const w of n.readdir(d))w==="."||w===".."||a(`${d}/${w}`);return}e.dirty.has(d)?s.push({path:d,type:"file",content:Qn(n.readFile(d)),...m}):s.push({path:d,type:"file",...typeof f.size=="number"?{size:f.size}:{},...m})};return a(G),{files:s}}const Ce="/workspace/.supercode/python-requirements.txt",Pn=64,Uo=256;async function jo(n){const e=Go(n.FS);e.length!==0&&(Ln({door:"pip install",subject:`${e.join(" ")}, recorded in ${Ce} by an earlier session`,fix:`a Python project's packages cannot yet be carried as packs; remove ${Ce} to run Python without them.`}),await es(n,e),rs(n.FS,await ts(n)))}async function qo(n,e){e.requirements.length!==0&&(await es(n,e.requirements),rs(n.FS,await ts(n)))}function Wo(n){const e=new Map;let t;for(const s of n.split(`
|