@volter/browser-substrate 0.1.99 → 0.1.101

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.
@@ -57,7 +57,7 @@ ${p}`,n.blocking)}const s=e.filesystem,i=[...n.notes],a={},o=[],l=await U$(s,ws(
57
57
  `),E.chmod!==void 0&&g6(s,D,Number.parseInt(E.chmod,8));break}case"run":{r.runsSteps||_c({door:"Dockerfile RUN",subject:`line ${E.line}: ${Y8(E.command)}`}),o.push({kind:"run",stage:m.name});const A={...r.environment??{},...S,...b.env},T=await e.spawn(Bh(E.command,b.root),{cwd:xl(b,b.workdir),env:A,...r.signal?{signal:r.signal}:{},...r.onStdout?{onStdout:r.onStdout}:{},...r.onStderr?{onStderr:r.onStderr}:{}});if(T.exitCode!==0)throw new On(`RUN at line ${E.line} exited with ${T.exitCode}: ${Y8(E.command)}
58
58
  ${T.stderr.trimEnd()}`);break}case"cmd":b.cmd=E.argv,b.cmdForm=E.form;break;case"entrypoint":b.entrypoint=E.argv,b.entrypointForm=E.form;break;case"expose":for(const{port:A}of E.ports)b.exposedPorts.includes(A)||b.exposedPorts.push(A);break;case"volume":for(const A of E.paths)b.volumes.push(A),wc(s,xl(b,Im(b.workdir,A)));break;case"healthcheck":b.healthcheck=E;break}}a[m.name]=b}const d=a[n.target.stage.name];if(!d)throw new On("The target stage was not built.");return{report:n,stages:a,target:d,command:kZ(d),notes:i,steps:o}}async function EZ(e,t,r,n){if(n.length===0)return{rebuild:!1};if(!t.steps||n.some(({path:l})=>l===ws(r,".dockerignore")))return{rebuild:!0};const s=e.filesystem,i=await U$(s,ws(r,".dockerignore")),a=new Map,o=[];for(const l of t.steps){if((a.get(l.stage)??[]).length>0)return{rebuild:!0};if(l.kind!=="copy")continue;const u=l.fromStage?a.get(l.fromStage)??[]:n;if(u.length===0)continue;if(l.patterns?.some(p=>/[*?]/u.test(p))){const p=l.patterns.flatMap(m=>P$(s,m));if(p.length!==l.sources.length||p.some((m,g)=>m!==l.sources[g]?.path)||u.some(({path:m})=>!s.existsSync(m)))return{rebuild:!0}}const d=[];for(const p of l.sources)for(const m of u){if(!(p.directory?m.path.startsWith(`${p.path.replace(/\/$/u,"")}/`):m.path===p.path)||!l.fromStage&&y6(ug(l.sourceRoot,m.path),i))continue;if(!p.directory&&m.removed)return{rebuild:!0};const b=p.directory?ws(l.destination,ug(p.path,m.path)):l.directory?ws(l.destination,L$(p.path)):l.destination;o.push({source:m.path,target:b,removed:m.removed,...l.chmod!==void 0?{chmod:l.chmod}:{}}),d.push({path:b,removed:m.removed})}d.length>0&&a.set(l.stage,d)}for(const l of o)l.removed?s.existsSync(l.target)&&s.unlinkSync(l.target):(wc(s,dv(l.target)),await m6(s,l.source,l.target),l.chmod!==void 0&&g6(s,l.target,l.chmod));return{rebuild:!1}}function kZ(e){const t=e.entrypoint??[],r=e.cmd??[];if(t.length===0&&r.length===0)return;if(e.entrypointForm==="shell"&&t.length>0)return t[0];const n=lp([...t,...e.cmdForm==="shell"&&r.length>0?["sh","-c",r[0]]:r]);return n.length>0?n.map(Bc).join(" "):void 0}function AZ(e,t,r={}){const n=r.command??t.command;if(n===void 0)throw new On("The file has no CMD or ENTRYPOINT.");return e.start(Bh(n,t.target.root),{cwd:xl(t.target,t.target.workdir),env:{...r.environment??{},...t.target.env},...r.signal?{signal:r.signal}:{},...r.onStdout?{onStdout:r.onStdout}:{},...r.onStderr?{onStderr:r.onStderr}:{}})}function CZ(e,t,r,n={}){const s=[...new Set([n.signal,n.process?.signal].filter(a=>a!==void 0))],i=()=>s.find(a=>a.aborted);return i()?Promise.reject(i().reason??new On(`Waiting for port ${t} was cancelled.`)):n.process&&n.process.state!=="running"?Promise.reject(new On(`The process exited before port ${t} was ready.`)):e.ports().includes(t)?Promise.resolve(e.portUrl(t)):new Promise((a,o)=>{let l=!1,c=()=>{},u;const d=m=>{if(!l){l=!0,u!==void 0&&clearTimeout(u),c();for(const g of s)g.removeEventListener("abort",p);if(m!==void 0)o(m);else try{a(e.portUrl(t))}catch(g){o(g)}}},p=()=>d(i()?.reason??new On(`Waiting for port ${t} was cancelled.`));c=e.on("port",m=>{m.port===t&&m.state==="open"&&d()}),u=setTimeout(()=>d(new On(`Port ${t} did not open within ${r} ms.`)),r);for(const m of s)m.addEventListener("abort",p,{once:!0});n.process?.result.then(m=>d(new On(`The process exited with ${m.exitCode} before port ${t} was ready.`)),m=>d(m??new On(`The process failed before port ${t} was ready.`))),i()?p():e.ports().includes(t)&&d()})}const TZ=["/dev/","/proc/","/sys/","/bin/","/sbin/","/usr/bin/","/usr/sbin/","/usr/local/bin/","/usr/lib/","/lib/","/etc/","/tmp/","/var/run/","/dev","/tmp"];function Bh(e,t){const r=t.replace(/\/+$/u,"");return e.replace(/(^|[\s=:"'])(\/(?:[A-Za-z0-9._-]+\/?)+)(?=$|[\s"';&|)>])/gu,(n,s,i)=>TZ.some(a=>i===a.replace(/\/$/u,"")||i.startsWith(a))||i.startsWith(`${r}/`)||i===r?n:`${s}${r}${i}`)}function xl(e,t){return ws(e.root,t)}function ws(...e){const t=e.filter(r=>r!=="").join("/").replace(/\/+/g,"/");return fv(t)}function fv(e){const t=e.startsWith("/"),r=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."){r.pop();continue}r.push(n)}return(t?"/":"")+r.join("/")||(t?"/":".")}function Im(e,t){return t.startsWith("/")?fv(t):fv(`${e}/${t}`)}function dv(e){const t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function L$(e){return e.slice(e.lastIndexOf("/")+1)}function ug(e,t){return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,""):t}function wc(e,t){e.existsSync(t)||e.mkdirSync(t,{recursive:!0})}async function m6(e,t,r){e.writeFileSync(r,await e.readFile(t)),g6(e,r,e.statSync(t).mode&4095)}function g6(e,t,r){const n=e;Number.isInteger(r)&&n.chmodSync&&n.chmodSync(t,r)}async function hv(e,t,r,n){wc(e,r);let s=0;for(const i of e.readdirSync(t)){const a=`${t}/${i}`.replace(/\/+/g,"/");if(n&&y6(ug(n.base,a),n.ignore))continue;const o=`${r}/${i}`.replace(/\/+/g,"/");e.statSync(a).isDirectory()?s+=await hv(e,a,o,n):(await m6(e,a,o),s+=1)}return s}function P$(e,t){if(!/[*?]/.test(t))return e.existsSync(t)?[t]:[];const r=t.split("/").filter(s=>s!=="");let n=["/"];for(const s of r){const i=[];for(const a of n){if(!/[*?]/.test(s)){const l=ws(a,s);e.existsSync(l)&&i.push(l);continue}if(!e.existsSync(a)||!e.statSync(a).isDirectory())continue;const o=new RegExp(`^${s.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]")}$`);for(const l of e.readdirSync(a))o.test(l)&&i.push(ws(a,l))}n=i}return n}async function U$(e,t){if(!e.existsSync(t))return[];const r=[];for(const n of(await e.readFile(t,"utf8")).split(/\r?\n/)){const s=n.trim();if(s===""||s.startsWith("#"))continue;const i=s.startsWith("!"),o=(i?s.slice(1):s).replace(/^\/+/,"").replace(/\/+$/,"").split("/").map(l=>l==="**"?"(?:.+)?":l.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]")).join("/").replace(/\(\?:\.\+\)\?\//g,"(?:.+/)?");r.push({negate:i,matcher:new RegExp(`^${o}(?:/.*)?$`)})}return r}function y6(e,t){let r=!1;for(const n of t)n.matcher.test(e)&&(r=!n.negate);return r}function NZ(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?[-+][^}]*)?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(r,n,s)=>t[n??s??""]??"")}function Y8(e){return e.split(`
59
59
  `)[0]??""}async function $Z(e,t,r){if(t.verdict==="linux")throw new On(`This backend cannot run the stack natively: ${t.blocking.map(g=>`${g.service}: ${g.reason}`).join("; ")}`);const n=r.signal,s=new AbortController;r={...r,signal:s.signal};const i=[],a=new Map,o=new Map;let l;const c=()=>l??=(async()=>{const g=[];n?.removeEventListener("abort",u),s.abort(n?.reason??new Error("Compose stopped."));const b=[...i].reverse();for(const v of b)try{v.handle.kill()}catch(S){g.push(S)}for(const[v,S]of o)try{ov(e.host.ports,v,S)}catch(x){g.push(x)}o.clear();{let v;await Promise.race([Promise.allSettled(b.map(S=>S.handle.result)).then(()=>{}),new Promise(S=>{v=setTimeout(S,2e3)})]),v!==void 0&&clearTimeout(v)}if(i.length=0,g.length)throw new AggregateError(g,"Some Compose services could not be released.")})(),u=()=>{c().catch(g=>console.error("Cancelled Compose cleanup failed.",g))};n?.addEventListener("abort",u,{once:!0}),n?.aborted&&u();const d=g=>{const b=e.ports().filter(v=>g.includes(v));if(b.length)throw new On(`Compose ports are already in use: ${b.join(", ")}.`)},p=async(g,b)=>{for(const v of pv([...b])){const S=await CZ(g.runtime,v,r.portTimeoutMs??3e4,{...r.signal?{signal:r.signal}:{},process:g.handle}),x=d$(g.runtime.host.ports,v);x&&o.set(v,x),g.ports.push({port:v,url:S})}},m=t.file.services.map(g=>g.name);try{s.signal.throwIfAborted();const g=t.order.map(b=>t.file.services.find(v=>v.name===b)).filter(b=>b.build!==void 0);await RZ(g,r.buildConcurrency??(r.buildRuntimeForService?4:1),async b=>{s.signal.throwIfAborted();const v=r.buildRuntimeForService?.(b)??e,S=r.builds[b.name];if(!S)throw new On(`No parsed Dockerfile for service ${b.name}.`);const x={...r.environment??{},...X8(b.environment,m)};a.set(b.name,await p6(v,S,{context:$b(r.context,b.build.context),stagesRoot:$b(r.stagesRoot,b.name),lanes:r.lanes,...r.runsSteps?{runsSteps:!0}:{},buildArgs:b.build.args,...b.build.target!==void 0?{target:b.build.target}:{},environment:x,...r.signal?{signal:r.signal}:{},...r.onStdout?{onStdout:E=>r.onStdout(b.name,E)}:{},...r.onStderr?{onStderr:E=>r.onStderr(b.name,E)}:{}}).catch(E=>{throw s.abort(E),E}))});for(const b of t.order){r.signal?.throwIfAborted();const v=t.file.services.find(D=>D.name===b),S=t.services.find(D=>D.service.name===b),x=e,E={...r.environment??{},...X8(v.environment,m)},A=IZ(v);let T;if(v.build){const D=a.get(b);if(!D)throw new On(`Service ${b} was not built.`);const I=OZ(v,D),U=A.length>0?A:D.target.exposedPorts;d(U);const O=AZ(x,D,{environment:E,...I!==void 0?{command:I}:{},...r.signal?{signal:r.signal}:{},...r.onStdout?{onStdout:_=>r.onStdout(b,_)}:{},...r.onStderr?{onStderr:_=>r.onStderr(b,_)}:{}});T={name:b,runtime:x,handle:O,ports:[],build:D,context:$b(r.context,v.build.context)},i.push(T),await p(T,U)}else{const D=v.image,I=D.registry?`${D.registry}/${D.repository}`:D.repository,U=r.lanes.images[I]??r.lanes.images[D.repository],O=U?r.programs[U.program]:void 0;if(!U||!O)throw new On(`Service ${b} uses image ${D.raw}, which no program provides on this backend (${S.reasons.join("; ")||"no lane"}).`);const _=O(v,{ports:A,env:E}),$=pv(_.ports??A);d($);const F=x.start(_.command,{..._.cwd!==void 0?{cwd:_.cwd}:{},env:{...E,..._.env??{}},...r.signal?{signal:r.signal}:{},...r.onStdout?{onStdout:P=>r.onStdout(b,P)}:{},...r.onStderr?{onStderr:P=>r.onStderr(b,P)}:{}});T={name:b,runtime:x,handle:F,ports:[]},i.push(T),await p(T,$)}}}catch(g){s.abort(g);try{await c()}catch(b){throw new AggregateError([g,b],"Compose startup and cleanup failed.")}throw g}return{services:i,stop:c}}async function RZ(e,t,r){if(!Number.isSafeInteger(t)||t<1||t>64)throw new On("Compose build concurrency must be an integer from 1 through 64.");let n=0,s;const i=async()=>{for(;s===void 0;){const a=n++;if(a>=e.length)return;try{await r(e[a])}catch(o){s=o}}};if(await Promise.all(Array.from({length:Math.min(t,e.length)},i)),s!==void 0)throw s}function OZ(e,t){if(!e.command&&!e.entrypoint)return;const r={...t.target};return e.entrypoint&&(r.entrypoint=e.entrypoint,r.entrypointForm="exec"),e.command&&(r.cmd=e.command,r.cmdForm="exec"),[...r.entrypoint??[],...r.cmd??[]].map(_Z).join(" ")}function _Z(e){return/^[A-Za-z0-9_\/.:=@%+,-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function IZ(e){return pv([...e.ports.map(t=>t.container),...e.expose])}function X8(e,t){const r={};for(const[n,s]of Object.entries(e)){let i=s;for(const a of t)i=i.replace(new RegExp(`(^|[/@\\s=])${MZ(a)}(?=[:/\\s]|$)`,"g"),"$1127.0.0.1");r[n]=i}return r}function MZ(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pv(e){return[...new Set(e)]}function $b(...e){const t=[],r=e[0]?.startsWith("/")??!1;for(const n of e)for(const s of n.split("/"))if(!(s===""||s===".")){if(s===".."){t.pop();continue}t.push(s)}return(r?"/":"")+t.join("/")}const DZ=["awk","base64","basename","cat","chmod","cp","cut","date","diff","dirname","du","echo","env","expr","file","find","grep","gzip","head","jq","ln","ls","md5sum","mkdir","mv","printf","pwd","readlink","rm","rmdir","sed","seq","sleep","sort","split","stat","tac","tail","tar","tee","touch","tr","true","uniq","wc","which","whoami","xargs"];function b6(e,t={}){const r=[...e.programs()],n={};r.includes("node")&&(n.node={name:"node"},n["library/node"]={name:"node"}),r.includes("node")&&r.includes("bun")&&(n.bun={name:"bun"},n["oven/bun"]={name:"bun"}),(r.includes("python")||r.includes("python3"))&&(n.python={name:"python"},n["library/python"]={name:"python"});const s=r.filter(i=>["npm","npx","pnpm","yarn","bun","corepack","pip","pip3","uv"].includes(i));return JV({runtimes:n,packageManagers:s,programs:r,shellUtilities:e.processHost.hasShell||r.includes("sh")||r.includes("bash")?DZ:[],...t})}const LZ="supercode-browser-filesystems",PZ="packages",UZ="state.json";async function F$(e){try{return await(await(await(await e.getDirectory()).getDirectoryHandle(LZ)).getDirectoryHandle(PZ)).getFileHandle(UZ),!0}catch{return!1}}function es(e){if(!e||typeof e!="object"||Object.keys(e).some(r=>r!=="writableRoots")||!Array.isArray(e.writableRoots)||e.writableRoots.length>128)throw new TypeError("Invalid process filesystem policy: expected up to 128 writableRoots.");const t=[...new Set(Array.from(e.writableRoots,w6))].sort();return Object.freeze({writableRoots:Object.freeze(t.filter(r=>!t.some(n=>n!==r&&fg(r,n))))})}function Xg(e,t){const r=es(e);if(t===void 0)return r;const n=es(t);return es({writableRoots:r.writableRoots.flatMap(s=>n.writableRoots.flatMap(i=>fg(s,i)?[s]:fg(i,s)?[i]:[]))})}function Ic(e,t){if(e!==void 0&&t?.filesystemPolicy!==!0)throw Object.assign(new Error("This process backend cannot enforce filesystem confinement."),{code:"ENOTSUP"})}function FZ(e,t){const r=BZ(e,t),n={existsSync:s=>e.existsSync(s),statSync:s=>e.statSync(s),lstatSync:s=>e.lstatSync(s),readFile:e.readFile.bind(e),readdirSync:s=>e.readdirSync(s),toSnapshot:()=>e.toSnapshot(),on:(s,i)=>(e.on(s,i),n),off:(s,i)=>(e.off(s,i),n),writeFileSync:(s,i)=>e.writeFileSync(r(s),i),mkdirSync:(s,i)=>{const a=w6(s);i?.recursive&&e.existsSync(a)&&e.lstatSync(a).isDirectory()&&!e.lstatSync(a).isSymbolicLink()||e.mkdirSync(r(a),i)},unlinkSync:s=>e.unlinkSync(r(s)),rmdirSync:s=>e.rmdirSync(r(s)),renameSync:(s,i)=>{const a=r(s),o=r(i);e.renameSync(a,o)},...e.chmodSync?{chmodSync:(s,i)=>e.chmodSync(r(s),i)}:{},...e.utimesSync?{utimesSync:(s,i,a)=>e.utimesSync(r(s),i,a)}:{}};return Object.freeze(n)}function BZ(e,t){const r=es(t),n=s=>r.writableRoots.some(i=>fg(s,i));return s=>{const i=w6(s);n(i)||Rb(i);let a="";for(const o of i.split("/").filter(Boolean)){a+=`/${o}`;try{e.lstatSync(a).isSymbolicLink()&&Rb(i)}catch(l){if(l.code!=="ENOENT")throw l;n(a)||Rb(a)}}return i}}function w6(e){if(typeof e!="string"||!e.startsWith("/")||e.includes("\0")||e.length>8192)throw new TypeError("Filesystem policy paths must be absolute paths without NUL bytes.");const t=[];for(const r of e.split("/"))r===".."?t.pop():r&&r!=="."&&t.push(r);return`/${t.join("/")}`}function fg(e,t){return t==="/"||e===t||e.startsWith(`${t}/`)}function Rb(e){throw Object.assign(new Error(`EACCES: process filesystem policy denies mutation of '${e}'`),{code:"EACCES",path:e})}const dg=2;function K8(e){return`${e}-lifecycle`}function zZ(e,t=Date.now()){return{version:dg,id:crypto.randomUUID(),projectId:e,createdAt:t,updatedAt:t,processes:[],attachments:{}}}function A1(e,t){if(!e||typeof e!="object")return;const r=e;if(r.version!==1&&r.version!==dg||r.projectId!==t||typeof r.id!="string"||!r.id||!Ob(r.createdAt)||!Ob(r.updatedAt)||!Array.isArray(r.processes)||!r.attachments||typeof r.attachments!="object"||Array.isArray(r.attachments))return;const n=[],s=new Set;for(const i of r.processes){if(!i||typeof i!="object")return;const a=i;if(typeof a.id!="string"||!a.id||s.has(a.id)||typeof a.command!="string"||!a.command.trim()||!Ob(a.startedAt)||(s.add(a.id),a.cwd!==void 0&&(typeof a.cwd!="string"||!a.cwd.startsWith("/")||a.cwd.includes("\0")))||a.env!==void 0&&(!a.env||typeof a.env!="object"||Array.isArray(a.env)||Object.entries(a.env).some(([l,c])=>!l||/[=\0]/u.test(l)||typeof c!="string"||c.includes("\0"))))return;let o;if("filesystemPolicy"in a){if(r.version===1)return;try{o=es(a.filesystemPolicy)}catch{return}}n.push({id:a.id,command:a.command,startedAt:a.startedAt,...typeof a.cwd=="string"?{cwd:a.cwd}:{},...a.env&&typeof a.env=="object"?{env:{...a.env}}:{},...o!==void 0?{filesystemPolicy:o}:{}})}return{version:dg,id:r.id,projectId:t,createdAt:r.createdAt,updatedAt:r.updatedAt,processes:n,attachments:{...r.attachments}}}function Ob(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Mm(e){const{filesystemPolicy:t,...r}=e;return{...r,...e.env!==void 0?{env:{...e.env}}:{},...t!==void 0?{filesystemPolicy:es(t)}:{}}}class v6{store;record;tail=Promise.resolve();constructor(t,r){this.store=r;const n=A1(t,t.projectId);if(!n)throw new TypeError("Invalid browser lifecycle record.");this.record={...n,attachments:structuredClone(n.attachments)}}static async open(t,r=jZ){const n=await r.read(K8(t)),s=A1(n,t);if(n!==void 0&&!s)throw new Error(`The saved lifecycle for ${t} is invalid; its identity and process grants have been preserved for recovery.`);const i=s??zZ(t),a=new v6(i,r);return(!s||n.version!==dg)&&await a.save(),a}get id(){return this.record.id}get projectId(){return this.record.projectId}get createdAt(){return this.record.createdAt}snapshot(){return{...this.record,processes:this.record.processes.map(Mm),attachments:structuredClone(this.record.attachments)}}get processes(){return this.record.processes.map(Mm)}rememberProcess(t){const r=t.id===void 0?void 0:this.record.processes.find(a=>a.id===t.id),n=Mm({...t,id:t.id??crypto.randomUUID(),startedAt:t.startedAt??r?.startedAt??Date.now()}),s=[...this.record.processes.filter(a=>a.id!==n.id),n],i=A1({...this.record,processes:s},this.record.projectId);if(!i)throw new TypeError("Invalid background process record.");return this.record=i,this.save(),Mm(n)}forgetProcess(t){this.record.processes.some(r=>r.id===t)&&(this.record.processes=this.record.processes.filter(r=>r.id!==t),this.save())}attachment(t){return structuredClone(this.record.attachments[t])}attach(t,r){this.record.attachments={...this.record.attachments,[t]:structuredClone(r)},this.save()}detach(t){if(!(t in this.record.attachments))return;const{[t]:r,...n}=this.record.attachments;this.record.attachments=n,this.save()}flush(){return this.tail}async reset(){this.record={...this.record,processes:[],attachments:{},updatedAt:Date.now()},await this.save()}save(){this.record.updatedAt=Date.now();const t=this.snapshot();return this.tail=this.tail.catch(()=>{}).then(()=>this.store.write(K8(this.record.projectId),t)),this.tail.catch(()=>{}),this.tail}}const jZ={read:e=>wj(e),write:(e,t)=>bj(e,t),delete:e=>yj(e)},zh="volter-browser-project",zc=1,B$=22100,xf=5e4,kl=128*1024*1024,jh=192*1024*1024,z$=4096,mv=2048;async function WZ(e,t){const r=gv(t.root??"/"),n=[...t.excludePaths??[]].map(gv);if(n.includes(r))throw new Error("Browser project archive cannot exclude its root.");const s=await qZ(e,r,n),i=s.reduce((l,c)=>l+c.bytes,0);if(t.format==="json"){const l={kind:zh,version:zc,entries:s},c=await jc(Sf(JSON.stringify(l))),u=Sf(JSON.stringify({...l,integrity:c},null,2));return yv(u),{format:"json",mediaType:"application/json",extension:".json",bytes:u,integrity:c,entries:s.length,fileBytes:i}}if(t.format!=="zip")throw new Error("Browser project archive format must be json or zip.");const{bytes:a,integrity:o}=await ZZ(s,nY(t.name,r));return yv(a),{format:"zip",mediaType:"application/zip",extension:".zip",bytes:a,integrity:o,entries:s.length,fileBytes:i}}async function HZ(e,t={}){const r=await aY(e);yv(r);const n=t.format??iY(r);if(n!=="json"&&n!=="zip")throw new Error("Browser project archive format must be json or zip.");const s=n==="json"?await GZ(r):await YZ(r);if(t.integrity!==void 0&&s.integrity!==t.integrity)throw new Error(`Browser project archive integrity mismatch: expected ${t.integrity}, received ${s.integrity}.`);return{format:s.format,integrity:s.integrity,entries:s.entries,fileBytes:s.fileBytes}}async function x6(e,t,r={}){const n=await HZ(t,r),s=gv(r.root??"/");return Q8(e,n.entries,s,r.replace!==!1,r.requireEmpty===!0),e.importTree&&await e.importTree({root:s,replace:r.replace!==!1,requireEmpty:r.requireEmpty===!0,entries:n.entries.map(a=>({path:a.path===""?s:`${s==="/"?"":s}/${a.path}`,mode:a.mode,mtimeMs:a.mtimeMs,...a.type==="directory"?{type:"directory"}:{type:"file",bytes:Xa(a.content)}}))})||(Q8(e,n.entries,s,r.replace!==!1,r.requireEmpty===!0),XZ(e,n.entries,s,r.replace!==!1)),{format:n.format,integrity:n.integrity,entries:n.entries.length,fileBytes:n.fileBytes}}async function qZ(e,t,r){let n=!1;const s=a=>{const o=t==="/"||a===t||a.startsWith(`${t}/`)||t.startsWith(`${a==="/"?"":a}/`),l=r.some(c=>a===c||a.startsWith(`${c}/`));o&&!l&&(n=!0)};e.on("change",s),e.on("delete",s);const i=wf.for(e)?.onChange(s);try{if(!e.existsSync(t)||!e.statSync(t).isDirectory())throw new Error(`Browser project root is not a directory: ${t}`);const o=e.toSnapshot().files.filter(u=>{const d=t==="/"||u.path===t||u.path.startsWith(`${t}/`),p=r.some(m=>u.path===m||u.path.startsWith(`${m}/`));return d&&!p});if(o.length>xf)throw new Error(`Browser project exceeds ${xf} entries.`);if(!o.some(u=>u.path===t)){const u=e.statSync(t);o.push({path:t,type:"directory",mode:u.mode,mtimeMs:u.mtimeMs})}const l=[];let c=0;for(const u of o){const d=sY(t,u.path);E6(d);const p=e.lstatSync(u.path);if(p.isSymbolicLink())throw new Error(`Browser project archives cannot represent symbolic links: ${u.path}`);const m=j$(u.mode)?u.mode:p.mode&4095,g=A6(u.mtimeMs)?u.mtimeMs:p.mtimeMs;if(u.type==="directory"){l.push({path:d,type:"directory",mode:m,mtimeMs:g,bytes:0});continue}const b=u.content!==void 0?Xa(u.content):Uint8Array.from(await e.readFile(u.path));if(c+=b.byteLength,c>kl)throw new Error(`Browser project exceeds ${kl} file bytes.`);l.push({path:d,type:"file",mode:m,mtimeMs:g,bytes:b.byteLength,integrity:await jc(b),content:As(b)})}if(l.sort(k6),S6(l),n)throw new Error("The workspace changed while exporting its archive; retry when those writes finish.");return l}finally{e.off("change",s),e.off("delete",s),i?.()}}async function GZ(e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new Error("Browser project JSON is not valid UTF-8 JSON.")}if(!W$(t)||t.kind!==zh||t.version!==zc||typeof t.integrity!="string"||!Array.isArray(t.entries))throw new Error("Browser project JSON has an unsupported shape or version.");bv(t,["kind","version","entries","integrity"],"Browser project JSON");const r=await VZ(t.entries),s=await jc(Sf(JSON.stringify({kind:zh,version:zc,entries:r})));if(s!==t.integrity)throw new Error("Browser project JSON failed its integrity check.");return{format:"json",entries:r,integrity:s,fileBytes:oY(r)}}async function VZ(e){if(e.length>xf)throw new Error(`Browser project exceeds ${xf} entries.`);const t=[];let r=0;for(const n of e){if(!W$(n)||typeof n.path!="string"||n.type!=="file"&&n.type!=="directory"||!j$(n.mode)||!A6(n.mtimeMs)||!Number.isSafeInteger(n.bytes)||n.bytes<0)throw new Error("Browser project contains an invalid entry.");if(E6(n.path),n.type==="directory"){if(bv(n,["path","type","mode","mtimeMs","bytes"],"Browser project directory"),n.bytes!==0)throw new Error("Browser project directory has a nonzero byte length.");t.push({path:n.path,type:"directory",mode:n.mode,mtimeMs:n.mtimeMs,bytes:0});continue}if(bv(n,["path","type","mode","mtimeMs","bytes","integrity","content"],"Browser project file"),typeof n.integrity!="string"||typeof n.content!="string")throw new Error("Browser project file has no integrity or content value.");const s=Xa(n.content);if(s.byteLength!==n.bytes||await jc(s)!==n.integrity)throw new Error(`Browser project file failed its integrity check: ${n.path}`);if(r+=s.byteLength,r>kl)throw new Error(`Browser project exceeds ${kl} file bytes.`);t.push({path:n.path,type:"file",mode:n.mode,mtimeMs:n.mtimeMs,bytes:n.bytes,integrity:n.integrity,content:n.content})}return S6(t),t}async function ZZ(e,t){const r=[],n=[];let s=0;for(const p of e){const m=p.path===""?`${t}/`:`${t}/${p.path}${p.type==="directory"?"/":""}`,g=Sf(m),b=p.type==="file"?Xa(p.content??""):new Uint8Array,v=KZ(p),S=H$(b),{time:x,date:E}=J8(p.mtimeMs),A=new Uint8Array(30),T=new DataView(A.buffer);T.setUint32(0,67324752,!0),T.setUint16(4,20,!0),T.setUint16(6,mv,!0),T.setUint16(8,0,!0),T.setUint16(10,x,!0),T.setUint16(12,E,!0),T.setUint32(14,S,!0),T.setUint32(18,b.byteLength,!0),T.setUint32(22,b.byteLength,!0),T.setUint16(26,g.byteLength,!0),T.setUint16(28,v.byteLength,!0),r.push({entry:p,name:g,extra:v,data:b,crc:S,localOffset:s}),n.push(A,g,v,b),s+=A.byteLength+g.byteLength+v.byteLength+b.byteLength}const i=[],a=s;for(const p of r){const{time:m,date:g}=J8(p.entry.mtimeMs),b=new Uint8Array(46),v=new DataView(b.buffer);v.setUint32(0,33639248,!0),v.setUint16(4,798,!0),v.setUint16(6,20,!0),v.setUint16(8,mv,!0),v.setUint16(10,0,!0),v.setUint16(12,m,!0),v.setUint16(14,g,!0),v.setUint32(16,p.crc,!0),v.setUint32(20,p.data.byteLength,!0),v.setUint32(24,p.data.byteLength,!0),v.setUint16(28,p.name.byteLength,!0),v.setUint16(30,p.extra.byteLength,!0),v.setUint32(38,rY(p.entry),!0),v.setUint32(42,p.localOffset,!0),i.push(b,p.name,p.extra),s+=b.byteLength+p.name.byteLength+p.extra.byteLength}const o=e7([...n,...i],s),l=await jc(o),c=Sf(`${zh}-v${zc};${l}`),u=new Uint8Array(22+c.byteLength),d=new DataView(u.buffer);return d.setUint32(0,101010256,!0),d.setUint16(8,r.length,!0),d.setUint16(10,r.length,!0),d.setUint32(12,s-a,!0),d.setUint32(16,a,!0),d.setUint16(20,c.byteLength,!0),u.set(c,22),{bytes:e7([o,u]),integrity:l}}async function YZ(e){const t=eY(e),r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(r.getUint16(t+4,!0)!==0||r.getUint16(t+6,!0)!==0)throw new Error("Multi-disk ZIP archives are not supported.");const n=r.getUint16(t+10,!0),s=r.getUint32(t+12,!0),i=r.getUint32(t+16,!0),a=r.getUint16(t+20,!0);if(r.getUint16(t+8,!0)!==n||n>xf||t+22+a!==e.byteLength||i+s!==t)throw new Error("Browser project ZIP directory is invalid.");const o=_b(e.subarray(t+22)),l=`${zh}-v${zc};`;if(!o.startsWith(l))throw new Error("ZIP is not a supported versioned browser project archive.");const c=o.slice(l.length);if(await jc(e.subarray(0,t))!==c)throw new Error("Browser project ZIP failed its archive integrity check.");const u=[];let d=i;for(let b=0;b<n;b+=1){if(Dm(e,d,46),r.getUint32(d,!0)!==33639248)throw new Error("Browser project ZIP central directory is invalid.");const v=r.getUint16(d+8,!0),S=r.getUint16(d+10,!0),x=r.getUint16(d+28,!0),E=r.getUint16(d+30,!0),A=r.getUint16(d+32,!0);Dm(e,d+46,x+E+A),u.push({name:_b(e.subarray(d+46,d+46+x)),method:S,flags:v,crc:r.getUint32(d+16,!0),compressed:r.getUint32(d+20,!0),size:r.getUint32(d+24,!0),extra:e.slice(d+46+x,d+46+x+E),external:r.getUint32(d+38,!0),localOffset:r.getUint32(d+42,!0)}),d+=46+x+E+A}if(d!==t||u.length===0)throw new Error("Browser project ZIP has an invalid entry table.");const p=tY(u.map(b=>b.name)),m=[];let g=0;for(const b of u){if(b.flags!==mv||b.method!==0&&b.method!==8)throw new Error(`Browser project ZIP entry uses unsupported features: ${b.name}`);const v=b.name.endsWith("/"),S=b.name.slice(p.length+1,v?-1:void 0);E6(S);const x=QZ(b.extra,v);if((b.external>>>16&61440)!==(v?16384:32768))throw new Error(`Browser project ZIP entry type is invalid: ${b.name}`);const A=b.external>>>16&4095;if(v&&b.size!==0)throw new Error("Browser project ZIP directory contains data.");if(b.size>kl-g||b.compressed>jh)throw new Error(`Browser project exceeds ${kl} file bytes.`);if(b.localOffset>=i)throw new Error("Browser project ZIP local record overlaps its directory.");if(Dm(e,b.localOffset,30),r.getUint32(b.localOffset,!0)!==67324752)throw new Error("Browser project ZIP local header is invalid.");const T=r.getUint16(b.localOffset+26,!0),D=r.getUint16(b.localOffset+28,!0),I=b.localOffset+30+T+D;if(Dm(e,b.localOffset+30,T+D),_b(e.subarray(b.localOffset+30,b.localOffset+30+T))!==b.name||r.getUint16(b.localOffset+6,!0)!==b.flags||r.getUint16(b.localOffset+8,!0)!==b.method||r.getUint32(b.localOffset+14,!0)!==b.crc||r.getUint32(b.localOffset+18,!0)!==b.compressed||r.getUint32(b.localOffset+22,!0)!==b.size||I+b.compressed>i)throw new Error(`Browser project ZIP local and central records disagree: ${b.name}`);const U=e.slice(I,I+b.compressed),O=b.method===0?U:await JZ(U,b.size);if(O.byteLength!==b.size||H$(O)!==b.crc)throw new Error(`Browser project ZIP entry is corrupt: ${b.name}`);if(v){if(O.byteLength!==0)throw new Error("Browser project ZIP directory contains data.");m.push({path:S,type:"directory",mode:A,mtimeMs:x.mtimeMs,bytes:0});continue}const _=await jc(O);if(x.integrity!==_)throw new Error(`Browser project ZIP file failed its integrity check: ${b.name}`);if(g+=O.byteLength,g>kl)throw new Error(`Browser project exceeds ${kl} file bytes.`);m.push({path:S,type:"file",mode:A,mtimeMs:x.mtimeMs,bytes:O.byteLength,integrity:_,content:As(O)})}return m.sort(k6),S6(m),{format:"zip",entries:m,integrity:c,fileBytes:g}}function Q8(e,t,r,n,s){const i=r.split("/").filter(Boolean);let a="";for(let o=0;o<i.length;o++){if(a+=`/${i[o]}`,!e.existsSync(a))continue;const l=e.lstatSync(a);if(l.isSymbolicLink())throw new Error(`Browser project import cannot follow a symbolic link: ${a}`);if(!l.isDirectory()&&(a!==r||!n))throw new Error(`Browser project import parent is not a directory: ${a}`)}if(s&&e.existsSync(r)&&(!e.lstatSync(r).isDirectory()||e.readdirSync(r).length>0))throw new Error(`Browser project import target is not empty: ${r}`);if(!n)for(const o of[...t].sort(k6)){const l=o.path===""?r:`${r==="/"?"":r}/${o.path}`;if(!e.existsSync(l))continue;const c=e.lstatSync(l);if(c.isSymbolicLink()||c.isDirectory()!==(o.type==="directory"))throw new Error(`Browser project import conflicts with an existing entry: ${l}`)}}function XZ(e,t,r,n){if(e.existsSync(r)&&!e.statSync(r).isDirectory()){if(!n)throw new Error(`Browser project import root is not a directory: ${r}`);e.unlinkSync(r)}n&&e.existsSync(r)&&ha(e,r),e.existsSync(r)||e.mkdirSync(r,{recursive:!0});for(const s of t){const i=s.path===""?r:`${r==="/"?"":r}/${s.path}`;if(s.type==="directory")e.mkdirSync(i,{recursive:!0});else{const a=i.slice(0,i.lastIndexOf("/"))||"/";e.mkdirSync(a,{recursive:!0}),e.writeFileSync(i,Xa(s.content??""))}}for(const s of[...t].sort((i,a)=>a.path.length-i.path.length)){const i=s.path===""?r:`${r==="/"?"":r}/${s.path}`;e.chmodSync?.(i,s.mode),e.utimesSync?.(i,new Date(s.mtimeMs),new Date(s.mtimeMs))}}function S6(e){if(e.length===0||e.length>xf)throw new Error("Browser project archive has no valid root.");const t=new Map;for(const r of e){if(t.has(r.path))throw new Error(`Browser project contains a duplicate path: ${r.path}`);t.set(r.path,r)}if(t.get("")?.type!=="directory")throw new Error("Browser project archive has no root directory.");for(const r of e){if(r.path==="")continue;const n=r.path.split("/");for(let s=1;s<n.length;s+=1){const i=n.slice(0,s).join("/");if(t.get(i)?.type!=="directory")throw new Error(`Browser project entry has no parent directory: ${r.path}`)}}}function KZ(e){const t=e.type==="file"?lY(e.integrity??""):new Uint8Array,r=new Uint8Array(9+t.byteLength),n=new DataView(r.buffer);r[0]=zc,n.setFloat64(1,e.mtimeMs,!0),r.set(t,9);const s=new Uint8Array(4+r.byteLength),i=new DataView(s.buffer);return i.setUint16(0,B$,!0),i.setUint16(2,r.byteLength,!0),s.set(r,4),s}function QZ(e,t){let r=0;for(;r+4<=e.byteLength;){const n=new DataView(e.buffer,e.byteOffset+r,e.byteLength-r),s=n.getUint16(0,!0),i=n.getUint16(2,!0);if(r+4+i>e.byteLength)throw new Error("Browser project ZIP metadata is truncated.");if(s===B$){if(i!==(t?9:41)||e[r+4]!==zc)throw new Error("Browser project ZIP metadata has an unsupported version.");const a=new DataView(e.buffer,e.byteOffset+r+5,8).getFloat64(0,!0);if(!A6(a))throw new Error("Browser project ZIP metadata has an invalid time.");return t?{mtimeMs:a}:{mtimeMs:a,integrity:`sha256-${As(e.slice(r+13,r+45))}`}}r+=4+i}throw new Error("Browser project ZIP entry has no versioned metadata.")}async function JZ(e,t){if(typeof DecompressionStream!="function")throw new Error("This browser cannot import deflated ZIP entries.");const n=new Blob([Uint8Array.from(e)]).stream().pipeThrough(new DecompressionStream("deflate-raw")).getReader(),s=new Uint8Array(t);let i=0;try{for(;;){const a=await n.read();if(a.done)break;if(a.value.byteLength>t-i)throw new Error("Browser project ZIP entry exceeds its declared byte length.");s.set(a.value,i),i+=a.value.byteLength}if(i!==t)throw new Error("Browser project ZIP entry is truncated.");return s}finally{await n.cancel().catch(()=>{}),n.releaseLock()}}function eY(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let r=e.byteLength-22;r>=Math.max(0,e.byteLength-65557);r-=1)if(t.getUint32(r,!0)===101010256)return r;throw new Error("Browser project ZIP has no end record.")}function tY(e){const t=e[0]?.split("/")[0]??"";if(!t||!e.includes(`${t}/`)||e.some(r=>!r.startsWith(`${t}/`)))throw new Error("Browser project ZIP must contain one rooted project directory.");return t}function rY(e){return(((e.type==="directory"?16384:32768)|e.mode)<<16>>>0|(e.type==="directory"?16:0))>>>0}function J8(e){const t=new Date(Math.min(Math.max(e,Date.UTC(1980,0,1)),Date.UTC(2107,11,31,23,59,58)));return{time:t.getUTCHours()<<11|t.getUTCMinutes()<<5|Math.floor(t.getUTCSeconds()/2),date:t.getUTCFullYear()-1980<<9|t.getUTCMonth()+1<<5|t.getUTCDate()}}function nY(e,t){const r=e??(t==="/"?"project":t.slice(t.lastIndexOf("/")+1));if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(r)||r==="."||r==="..")throw new Error("Browser project archive name must be a safe 1..128 character filename.");return r}function gv(e){if(!e.startsWith("/")||e.includes("\0")||e.includes("//")||e.length>z$||e.split("/").some(t=>t==="."||t===".."))throw new Error("Browser project root must be a normalized absolute path.");return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function sY(e,t){return t===e?"":e==="/"?t.slice(1):t.slice(e.length+1)}function E6(e){if(e.length>z$||e.startsWith("/")||e.endsWith("/")||e.includes("\\")||/[\0-\x1f\x7f]/u.test(e)||e!==""&&e.split("/").some(t=>!t||t==="."||t===".."))throw new Error(`Browser project contains an unsafe path: ${e}`)}function k6(e,t){const r=e.path===""?0:t7(e.path),n=t.path===""?0:t7(t.path);return r-n||e.path.localeCompare(t.path)}function iY(e){return e[0]===80&&e[1]===75?"zip":"json"}async function aY(e){const t=typeof e=="string"?e.length:e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof Blob<"u"&&e instanceof Blob?e.size:void 0;if(t!==void 0&&(t===0||t>jh))throw new Error(`Browser project archive must contain 1..${jh} bytes.`);if(typeof e=="string")return Sf(e);if(e instanceof Uint8Array)return e.slice();if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(typeof Blob<"u"&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw new Error("Browser project import requires JSON text, Blob, ArrayBuffer, or Uint8Array input.")}function yv(e){if(e.byteLength===0||e.byteLength>jh)throw new Error(`Browser project archive must contain 1..${jh} bytes.`)}function Dm(e,t,r){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(r)||t<0||r<0||t+r>e.byteLength)throw new Error("Browser project ZIP contains an out-of-bounds record.")}function j$(e){return Number.isSafeInteger(e)&&e>=0&&e<=4095}function A6(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function bv(e,t,r){const n=new Set(t);if(Object.keys(e).some(s=>!n.has(s))||t.some(s=>!(s in e)))throw new Error(`${r} contains unsupported fields.`)}function W$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function oY(e){return e.reduce((t,r)=>t+r.bytes,0)}async function jc(e){const t=new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e).buffer));return`sha256-${As(t)}`}function lY(e){if(!/^sha256-[A-Za-z0-9+/]{43}=$/u.test(e))throw new Error("Browser project file has an invalid SHA-256 integrity value.");const t=Xa(e.slice(7));if(t.byteLength!==32)throw new Error("Browser project file has an invalid SHA-256 digest.");return t}function Sf(e){return new TextEncoder().encode(e)}function _b(e){return new TextDecoder("utf-8",{fatal:!0}).decode(e)}const cY=(()=>{const e=new Uint32Array(2048);for(let t=0;t<256;t+=1){let r=t;for(let n=0;n<8;n+=1)r=r>>>1^3988292384&-(r&1);e[t]=r>>>0}for(let t=0;t<256;t+=1)for(let r=1;r<8;r+=1){const n=e[(r-1)*256+t];e[r*256+t]=n>>>8^e[n&255]}return e})();function H$(e){const t=cY;let r=4294967295,n=0;const s=e.byteLength-e.byteLength%8;for(;n<s;n+=8){const i=r^(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24);r=t[7*256+(i&255)]^t[6*256+(i>>>8&255)]^t[5*256+(i>>>16&255)]^t[4*256+(i>>>24)]^t[3*256+e[n+4]]^t[2*256+e[n+5]]^t[256+e[n+6]]^t[e[n+7]]}for(;n<e.byteLength;n+=1)r=r>>>8^t[(r^e[n])&255];return(r^4294967295)>>>0}function e7(e,t=e.reduce((r,n)=>r+n.byteLength,0)){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.byteLength;return r}function t7(e){let t=1;for(let r=0;r<e.length;r+=1)e.charCodeAt(r)===47&&(t+=1);return t}function uY(e,t){return e.existsSync(t)?e.statSync(t).isDirectory()&&e.readdirSync(t).length===0:!0}async function fY(e,t,r,n=globalThis.fetch.bind(globalThis)){const s=Date.now();if(!t.replace&&!uY(e,r))throw new Error(`The template target ${r} is not empty.`);let i=t.bytes,a="bytes";if(!i){if(!t.url)throw new Error("A template needs bytes or a url.");const l=await n(t.url);if(!l.ok)throw new Error(`Template ${t.url} answered ${l.status}.`);i=new Uint8Array(await l.arrayBuffer()),a="url"}const o=await x6(e,i,{root:r,replace:!0,requireEmpty:!t.replace,...t.integrity!==void 0?{integrity:t.integrity}:{}});return{integrity:o.integrity,entries:o.entries,fileBytes:o.fileBytes,durationMs:Date.now()-s,source:a}}var bl;(function(e){e[e.Inspect=1]="Inspect",e[e.Read=2]="Read",e[e.WriteStart=3]="WriteStart",e[e.WriteChunk=4]="WriteChunk",e[e.WriteFinish=5]="WriteFinish",e[e.Remove=6]="Remove"})(bl||(bl={}));const dY=1024*1024,r7=512*1024,Dd=256*1024*1024,hY=5,n7=-125,pY=new TextEncoder,mY=new TextDecoder("utf-8",{fatal:!0});class gY{filesystems=new WeakMap;attach(t,r,n,s){const i=new Int32Array(t.control),a=new Uint8Array(t.payload),o=this.state(r);let l,c,u=!1,d;const p=()=>{if(u)throw Object.assign(new Error("File-coherence channel was closed."),{errno:-n7})};return t.port.onmessage=m=>{const g=m.data;u||d!==void 0||!Number.isSafeInteger(g)||g<1||g>1073741821||g%2!==1||Atomics.load(i,0)!==g||(d=g,(async()=>{try{const b=Atomics.load(i,1),v=Ju(Atomics.load(i,3),0,a.byteLength),S=v===0?{}:JSON.parse(mY.decode(a.slice(0,v)));if(!S||typeof S!="object"||Array.isArray(S))throw Fn("Invalid coherent file request.");let x;if(b===bl.Inspect){c=void 0,await o.tail,p();const E=uf(S.path);if(!r.existsSync(E))x={exists:!1};else{const A=r.statSync(E);if(A.isDirectory())throw Fn("A coherent file cannot be a directory.");if(A.size!==void 0&&A.size>Dd)throw Fn("Coherent file exceeds 256 MiB.");const T=await r.readFile(E);if(p(),T.byteLength>Dd)throw Fn("Coherent file exceeds 256 MiB.");T.byteLength&&(c={path:E,bytes:Uint8Array.from(T)}),x={exists:!0,length:T.byteLength,...A.mode===void 0?{}:{mode:A.mode},...A.mtimeMs===void 0?{}:{mtimeMs:A.mtimeMs},parents:yY(r,E)}}}else if(b===bl.Read){const E=uf(S.path),A=Ju(S.offset,0,Dd),T=Ju(S.length,0,r7);if(!c||c.path!==E)throw Fn("Inspect the coherent file before reading its chunks.");const D=c.bytes;if(A+T>D.byteLength)throw Fn("Invalid coherent file range.");x={content:As(D.subarray(A,A+T))},A+T===D.byteLength&&(c=void 0)}else if(b===bl.WriteStart){c=void 0;const E=uf(S.path),A=Ju(S.length,0,Dd);l={path:E,bytes:new Uint8Array(A),offset:0,...T6(S),parents:V$(E,S.parents)}}else if(b===bl.WriteChunk){const E=Ju(S.offset,0,Dd),A=Xa(Z$(S.content));if(!l||E!==l.offset||A.byteLength>r7||E+A.byteLength>l.bytes.byteLength)throw Fn("Invalid coherent file chunk.");l.bytes.set(A,E),l.offset+=A.byteLength}else if(b===bl.WriteFinish){if(!l||l.offset!==l.bytes.byteLength)throw Fn("Incomplete coherent file write.");const E=l;l=void 0,await this.enqueue(o,async()=>{p(),bY(r,E.path,E.parents),r.writeFileSync(E.path,E.bytes),E.mode!==void 0&&r.chmodSync?.(E.path,E.mode),E.mtimeMs!==void 0&&r.utimesSync?.(E.path,new Date(E.mtimeMs),new Date(E.mtimeMs)),s?.(E.path),await n?.(r)})}else if(b===bl.Remove){const E=uf(S.path);await this.enqueue(o,async()=>{if(p(),r.existsSync(E)){if(r.statSync(E).isDirectory())throw Fn("A coherent file cannot be a directory.");r.unlinkSync(E)}s?.(E),await n?.(r)})}else throw Fn("Unknown file-coherence operation.");p(),Ib(i,a,g,0,x)}catch(b){l=void 0,c=void 0,Ib(i,a,g,vY(b))}finally{d=void 0}})())},t.port.start(),()=>{if(u)return;u=!0,l=void 0,c=void 0,t.port.onmessage=null,Atomics.store(i,hY,1);const m=Atomics.load(i,0);m>0&&m%2===1&&Ib(i,a,m,n7),Atomics.notify(i,0),t.port.close()}}state(t){const r=t;let n=this.filesystems.get(r);return n||(n={tail:Promise.resolve()},this.filesystems.set(r,n)),n}async enqueue(t,r){const n=t.tail.then(r);t.tail=n.catch(()=>{}),await n}}const q$=new gY;function G$(){const e=new MessageChannel,t=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*8),r=new SharedArrayBuffer(dY);return e.port1.start(),{client:{port:e.port1,control:t,payload:r},server:{port:e.port2,control:t,payload:r}}}function yY(e,t){return C6(t).flatMap(r=>{if(!e.existsSync(r))return[];const n=e.statSync(r);if(!n.isDirectory())throw Fn("A coherent file parent must be a directory.");return[{path:r,...T6({mode:n.mode,mtimeMs:n.mtimeMs})}]})}function bY(e,t,r){const n=new Map(V$(t,r).map(s=>[s.path,s]));for(const s of C6(t)){if(e.existsSync(s)){if(!e.statSync(s).isDirectory())throw Fn("A coherent file parent must be a directory.");continue}e.mkdirSync(s);const i=n.get(s);i?.mode!==void 0&&e.chmodSync?.(s,i.mode),i?.mtimeMs!==void 0&&e.utimesSync?.(s,new Date(i.mtimeMs),new Date(i.mtimeMs))}}function V$(e,t){if(t===void 0)return[];const r=new Set(C6(e));if(!Array.isArray(t)||t.length>r.size)throw Fn("Invalid coherent file parents.");return t.map(n=>{if(typeof n!="object"||n===null)throw Fn("Invalid coherent file parent.");const s=n,i=uf(s.path);if(!r.delete(i))throw Fn("Coherent metadata must name distinct ancestors of its file.");return{path:i,...T6(s)}})}function C6(e){const t=[];for(const r of uf(e).split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return t.slice(0,-1).map((r,n)=>`/${t.slice(0,n+1).join("/")}`)}function T6(e){const t=e.mode===void 0?void 0:Ju(e.mode,0,65535),r=e.mtimeMs===void 0?void 0:wY(e.mtimeMs);return{...t===void 0?{}:{mode:t},...r===void 0?{}:{mtimeMs:r}}}function uf(e){const t=Z$(e);if(!t.startsWith("/")||t.length>4096||t.includes("\0"))throw Fn("Invalid coherent file path.");return t}function Z$(e){if(typeof e!="string")throw Fn("Expected a string.");return e}function Ju(e,t,r){if(!Number.isSafeInteger(e)||e<t||e>r)throw Fn("Expected a bounded integer.");return e}function wY(e){if(typeof e!="number"||!Number.isFinite(e))throw Fn("Expected a finite number.");return e}function Fn(e){return Object.assign(new Error(e),{errno:22})}function vY(e){const t=typeof e=="object"&&e!==null&&"errno"in e?Number(e.errno):5;return-(Number.isSafeInteger(t)&&t>0?t:5)}function Ib(e,t,r,n,s){let i;try{i=s===void 0?new Uint8Array:pY.encode(JSON.stringify(s))}catch{i=new Uint8Array,n=-5}Atomics.compareExchange(e,0,r,-r)===r&&(i.byteLength>t.byteLength?(Atomics.store(e,2,-90),Atomics.store(e,4,0)):(i.byteLength>0&&t.set(i),Atomics.store(e,2,n),Atomics.store(e,4,i.byteLength)),Atomics.store(e,0,r+1),Atomics.notify(e,0))}const xY=64*1024,SY=-11,Mb=-4,EY=3;class kY{locks=[];pending=[];attach(t,r){if(typeof r!="string"||!r||r.includes("\0"))throw new Error("Invalid file-lock owner prefix.");const n=new Int32Array(t.control),s=new Uint8Array(t.payload),i=new TextDecoder("utf-8",{fatal:!0});let a=!1,o;return t.port.onmessage=l=>{const c=l.data;if(a||o!==void 0||!Number.isSafeInteger(c)||c<1||c>1073741821||c%2!==1||Atomics.load(n,0)!==c)return;let u;try{const d=Atomics.load(n,1);if(d<1||d>s.byteLength)throw new Error("Invalid file-lock request length.");u=JSON.parse(i.decode(s.slice(0,d))),AY(u,r)}catch{Db(n,s,c,{result:-22});return}o=c,this.dispatch(u,d=>{o===c&&(o=void 0),Db(n,s,c,d)})},t.port.start(),()=>{if(a)return;a=!0,t.port.onmessage=null,Atomics.store(n,EY,1),this.releasePrefix(r);const l=Atomics.load(n,0);l>0&&l%2===1&&Db(n,s,l,{result:Mb}),Atomics.notify(n,0),t.port.close()}}dispatch(t,r){if(t.operation==="release-owner"){this.releaseOwner(t.owner),r({result:0});return}if(t.operation==="unlock"){this.removeRange(t.owner,t.namespace,t.path,t.range),this.drain(),r({result:0});return}const n=this.conflict(t);if(t.operation==="query"){r({result:0,...n?{conflict:NY(n)}:{}});return}if(n){t.blocking?this.pending.push({request:t,complete:r}):r({result:SY});return}this.install(t),r({result:0})}conflict(t){return this.locks.find(r=>r.namespace===t.namespace&&r.path===t.path&&r.owner!==t.owner&&s7(r,t.range)&&(r.mode==="write"||t.mode==="write"))}install(t){this.removeRange(t.owner,t.namespace,t.path,t.range),this.locks.push({owner:t.owner,namespace:t.namespace,path:t.path,mode:t.mode,pid:t.pid,...t.range})}removeRange(t,r,n,s){for(let i=this.locks.length-1;i>=0;i-=1){const a=this.locks[i];a.owner!==t||a.namespace!==r||a.path!==n||!s7(a,s)||this.locks.splice(i,1,...$Y(a,s))}}releaseOwner(t){for(let r=this.locks.length-1;r>=0;r-=1)this.locks[r].owner===t&&this.locks.splice(r,1);for(let r=this.pending.length-1;r>=0;r-=1)if(this.pending[r].request.owner===t){const[n]=this.pending.splice(r,1);n.complete({result:Mb})}this.drain()}releasePrefix(t){const r=n=>n===t||n.startsWith(`${t}:`);for(let n=this.locks.length-1;n>=0;n-=1)r(this.locks[n].owner)&&this.locks.splice(n,1);for(let n=this.pending.length-1;n>=0;n-=1)if(r(this.pending[n].request.owner)){const[s]=this.pending.splice(n,1);s.complete({result:Mb})}this.drain()}drain(){for(let t=0;t<this.pending.length;){const r=this.pending[t];if(this.conflict(r.request)){t+=1;continue}this.pending.splice(t,1),this.install(r.request),r.complete({result:0})}}}const Y$=new kY;function X$(){const e=new MessageChannel,t=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*4),r=new SharedArrayBuffer(xY);return e.port1.start(),{client:{port:e.port1,control:t,payload:r},server:{port:e.port2,control:t,payload:r}}}function AY(e,t){if(!e||typeof e!="object"||!TY(t,e.owner))throw new Error("Invalid lock owner.");if(!["query","set","unlock","release-owner"].includes(e.operation))throw new Error("Invalid file lock operation.");if(e.operation==="release-owner")return;if(!["posix","ofd","flock"].includes(e.namespace)||typeof e.path!="string"||!e.path.startsWith("/")||e.path.length>4096||e.path.includes("\0")||!CY(e.range))throw new Error("Invalid file lock request.");const r=[];for(const n of e.path.split("/"))!n||n==="."||(n===".."?r.pop():r.push(n));if(e.path=`/${r.join("/")}`,e.operation==="set"&&e.blocking!==void 0&&typeof e.blocking!="boolean")throw new Error("Invalid file lock blocking option.");if(e.operation!=="unlock"&&(!["read","write"].includes(e.mode)||!Number.isSafeInteger(e.pid)||e.pid<0))throw new Error("Invalid file lock request.")}function CY(e){return!!e&&typeof e=="object"&&Number.isSafeInteger(e.start)&&e.start>=0&&(e.end===void 0||Number.isSafeInteger(e.end)&&e.end>e.start)}function TY(e,t){return typeof t=="string"&&(t===e||t.startsWith(`${e}:`))}function NY(e){return{mode:e.mode,start:e.start,...e.end===void 0?{}:{end:e.end},pid:e.pid}}function s7(e,t){return e.start<(t.end??Number.POSITIVE_INFINITY)&&t.start<(e.end??Number.POSITIVE_INFINITY)}function $Y(e,t){const r=[];e.start<t.start&&r.push({...e,end:t.start});const n=e.end??Number.POSITIVE_INFINITY,s=t.end??Number.POSITIVE_INFINITY;return s<n&&r.push({...e,start:s,...e.end===void 0?{}:{end:e.end}}),r}function Db(e,t,r,n){let s=new TextEncoder().encode(JSON.stringify(n));s.byteLength>t.byteLength&&(s=new TextEncoder().encode('{"result":-90}')),Atomics.compareExchange(e,0,r,-r)===r&&(t.set(s),Atomics.store(e,2,s.byteLength),Atomics.store(e,0,r+1),Atomics.notify(e,0))}const RY=1,OY=["browser.open-url","filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","media.webcodecs","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],K$=Object.freeze({version:1,capabilities:OY});function Kg(e){const t=ci(e,"manifest");if(la(t,["schemaVersion","id","displayName","version","engine","artifact","resources","presenter","entry","executable","actions","storage","environment","requirements","terminal","network","openUrls"],"manifest"),t.schemaVersion!==RY)throw new Error(`Unsupported browser program manifest version: ${String(t.schemaVersion)}`);if(Lm(t.id,"manifest.id"),Lb(t.displayName,"manifest.displayName",80),Lb(t.version,"manifest.version",80),!new Set(["wali","node","python","emscripten"]).has(String(t.engine)))throw new Error("manifest.engine must be wali, node, python, or emscripten.");if(t.entry!==void 0){if(t.engine!=="emscripten")throw new Error("manifest.entry is an Emscripten pack's glue; other engines have none.");if(typeof t.entry!="string"||t.entry===""||t.entry.startsWith("/")||t.entry.includes(".."))throw new Error("manifest.entry must be a relative path inside resources.root.")}if(t.engine==="emscripten"&&t.entry===void 0)throw new Error("an Emscripten pack names its glue in manifest.entry.");const r=ci(t.artifact,"manifest.artifact");if(la(r,["url","upstream","integrity","license","redistribution"],"manifest.artifact"),Pm(r.url,"manifest.artifact.url"),r.upstream!==void 0&&Q$(r.upstream,"manifest.artifact.upstream"),typeof r.integrity!="string"||!/^sha256-[A-Za-z0-9+/]{43}=$/u.test(r.integrity))throw new Error("manifest.artifact.integrity must be an exact SHA-256 base64 SRI value.");if(Lb(r.license,"manifest.artifact.license",80),!new Set(["cleared","unresolved","prohibited"]).has(String(r.redistribution)))throw new Error("manifest.artifact.redistribution is invalid.");if(t.resources!==void 0){const m=ci(t.resources,"manifest.resources");if(la(m,["url","integrity","root"],"manifest.resources"),Pm(m.url,"manifest.resources.url"),typeof m.integrity!="string"||!/^sha256-[A-Za-z0-9+/]{43}=$/u.test(m.integrity))throw new Error("manifest.resources.integrity must be an exact SHA-256 base64 SRI value.");DY(m.root,"manifest.resources.root")}if(t.presenter!==void 0){const m=ci(t.presenter,"manifest.presenter");if(la(m,["url","integrity","bytes"],"manifest.presenter"),Pm(m.url,"manifest.presenter.url"),typeof m.integrity!="string"||!/^sha256-[A-Za-z0-9+/]{43}=$/u.test(m.integrity))throw new Error("manifest.presenter.integrity must be an exact SHA-256 base64 SRI value.");if(!Number.isSafeInteger(m.bytes)||Number(m.bytes)<=0)throw new Error("manifest.presenter.bytes must be the module's byte count.")}i7(t.executable,"manifest.executable");const n=ci(t.actions,"manifest.actions");if(!("start"in n))throw new Error("manifest.actions.start is required.");for(const[m,g]of Object.entries(n))Lm(m,`manifest.actions.${m}`),Ld(g,`manifest.actions.${m}`,32).forEach(MY);const s=ci(t.storage,"manifest.storage");if(la(s,["home","privateFiles"],"manifest.storage"),a7(s.home,"manifest.storage.home"),!Array.isArray(s.privateFiles)||s.privateFiles.length>16)throw new Error("manifest.storage.privateFiles must be a bounded array.");for(const[m,g]of s.privateFiles.entries()){const b=ci(g,`manifest.storage.privateFiles[${m}]`);if(la(b,["path","vault","defaultContent","clearOnActions"],`manifest.storage.privateFiles[${m}]`),a7(b.path,`manifest.storage.privateFiles[${m}].path`),Lm(b.vault,`manifest.storage.privateFiles[${m}].vault`),b.defaultContent!==void 0&&IY(b.defaultContent,`manifest.storage.privateFiles[${m}].defaultContent`,16384),b.clearOnActions!==void 0){const v=Ld(b.clearOnActions,`manifest.storage.privateFiles[${m}].clearOnActions`,16);v.forEach(S=>Lm(S,`manifest.storage.privateFiles[${m}].clearOnActions`));for(const S of v)if(!(S in n))throw new Error(`Private file clear action is not declared: ${S}`);Um(v,`manifest.storage.privateFiles[${m}].clearOnActions`)}}const i=LY(t.environment,"manifest.environment");for(const m of Object.keys(i))if(!/^[A-Z_][A-Z0-9_]*$/u.test(m))throw new Error(`Invalid environment name: ${m}`);const a=ci(t.requirements,"manifest.requirements");la(a,["capabilities","programs","workers"],"manifest.requirements");const o=Ld(a.capabilities,"manifest.requirements.capabilities",32),l=new Set(K$.capabilities);for(const m of o)if(!l.has(m))throw new Error(`Unknown browser runtime capability: ${m}`);Um(o,"manifest.requirements.capabilities");const c=Ld(a.programs,"manifest.requirements.programs",64);if(c.forEach(m=>i7(m,"manifest.requirements.programs")),Um(c,"manifest.requirements.programs"),a.workers!==void 0&&(!Number.isSafeInteger(a.workers)||Number(a.workers)<1||Number(a.workers)>128))throw new Error("manifest.requirements.workers must be 1..128.");const u=ci(t.terminal,"manifest.terminal");if(la(u,["input"],"manifest.terminal"),!new Set(["bytes","canonical-lines","kitty-key-events"]).has(String(u.input)))throw new Error("manifest.terminal.input is invalid.");const d=ci(t.network,"manifest.network");la(d,["relayPath","allowedHosts","httpTransportPolicy"],"manifest.network"),d.relayPath!==void 0&&wv(d.relayPath,"manifest.network.relayPath");const p=Ld(d.allowedHosts,"manifest.network.allowedHosts",64);if(p.forEach(m=>o7(m,"manifest.network.allowedHosts")),Um(p,"manifest.network.allowedHosts"),d.httpTransportPolicy!==void 0){const m=ci(d.httpTransportPolicy,"manifest.network.httpTransportPolicy");if(la(m,["url","integrity"],"manifest.network.httpTransportPolicy"),Pm(m.url,"manifest.network.httpTransportPolicy.url"),typeof m.integrity!="string"||!/^sha256-[A-Za-z0-9+/]{43}=$/u.test(m.integrity))throw new Error("manifest.network.httpTransportPolicy.integrity must be an exact SHA-256 base64 SRI value.")}if(!Array.isArray(t.openUrls)||t.openUrls.length>16)throw new Error("manifest.openUrls must be a bounded array.");for(const[m,g]of t.openUrls.entries()){const b=ci(g,`manifest.openUrls[${m}]`);if(la(b,["protocol","hostname","pathname"],`manifest.openUrls[${m}]`),b.protocol!=="https:")throw new Error("Program open URL protocol must be https:.");o7(b.hostname,`manifest.openUrls[${m}].hostname`),wv(b.pathname,`manifest.openUrls[${m}].pathname`)}return J$(e)}function _Y(e,t,r=K$){const n=new Set(r.capabilities),s=e.requirements.capabilities.filter(a=>!n.has(a)),i=e.requirements.programs.filter(a=>!t.has(a));if(s.length>0||i.length>0)throw new Error([`${e.id} is incompatible with browser runtime profile ${r.version}.`,...s.length>0?[`missing capabilities: ${s.join(", ")}`]:[],...i.length>0?[`missing programs: ${i.join(", ")}`]:[]].join(" "))}function ci(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function la(e,t,r){const n=new Set(t),s=Object.keys(e).filter(i=>!n.has(i));if(s.length>0)throw new Error(`${r} has unknown fields: ${s.join(", ")}`)}function Lb(e,t,r){if(typeof e!="string"||e.length<1||e.length>r||/[\u0000\r\n]/u.test(e))throw new Error(`${t} must be a non-empty bounded string.`)}function IY(e,t,r){if(typeof e!="string"||e.length>r||e.includes("\0"))throw new Error(`${t} must be bounded text.`)}function Lm(e,t){if(typeof e!="string"||!/^[a-z][a-z0-9-]{0,63}$/u.test(e))throw new Error(`${t} is invalid.`)}function i7(e,t){if(typeof e!="string"||!/^[A-Za-z0-9._+-]+$/u.test(e))throw new Error(`${t} is invalid.`)}function MY(e){if(!e||e.length>256||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Manifest command argument is invalid.")}function DY(e,t){if(typeof e!="string"||!/^\/[^\\]*[^/\\]$/u.test(e)||e.includes(".."))throw new Error(`${t} must be an absolute path with no trailing slash.`)}function a7(e,t){if(typeof e!="string"||!/^(?:\/|\$\{HOME\}\/)[^\u0000\\]*$/u.test(e)||e.includes(".."))throw new Error(`${t} must be an absolute HOME-templated path.`)}function Pm(e,t){if(typeof e!="string")throw new Error(`${t} must be a URL or same-origin path.`);if(e.startsWith("/"))return wv(e,t);Q$(e,t)}function wv(e,t){if(typeof e!="string"||!/^\/(?!\/)[^\u0000-\u001f\\]*$/u.test(e))throw new Error(`${t} must be a same-origin absolute path.`)}function Q$(e,t){if(typeof e!="string")throw new Error(`${t} must be an HTTPS URL.`);const r=new URL(e);if(r.protocol!=="https:"||r.username||r.password)throw new Error(`${t} must be an HTTPS URL.`)}function o7(e,t){if(typeof e!="string"||!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/u.test(e))throw new Error(`${t} contains an invalid hostname.`)}function Ld(e,t,r){if(!Array.isArray(e)||e.length>r||e.some(n=>typeof n!="string"))throw new Error(`${t} must be a bounded string array.`);return e}function LY(e,t){const r=ci(e,t);if(Object.values(r).some(n=>typeof n!="string"))throw new Error(`${t} values must be strings.`);return r}function Um(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must not contain duplicates.`)}function J$(e){return e&&typeof e=="object"&&(Object.freeze(e),Object.values(e).forEach(t=>J$(t))),e}const l7="browser-substrate.pack",c7=1,u7="browser-substrate.pack-catalog",f7=1,d7="browser-substrate.environment-lock",h7=1;class eR extends Error{category;path;constructor(t,r,n){super(`${r}: ${n}`),this.name="BrowserPackContractError",this.category=t,this.path=r}}const p7=128*1024*1024,tR="application/octet-stream";function Pb(e){const t=Qr(e,"manifest","invalid-manifest");N6(t,l7,c7,"manifest","invalid-manifest"),Hr(t,["kind","version","name","upstreamVersion","packKind","coordinate","buildKey","runtime","capabilities","limits","artifacts","dependencies","integration","provenance"],"manifest","invalid-manifest");const r=Ef(t.packKind,["node-archive","browser-module","wali","emscripten"],"manifest.packKind"),n=Qr(t.runtime,"manifest.runtime","invalid-manifest");Hr(n,["name","abi"],"manifest.runtime","invalid-manifest");const s=Qr(t.limits,"manifest.limits","invalid-manifest");Hr(s,["workers","memoryBytes","storageBytes"],"manifest.limits","invalid-manifest");for(const u of["workers","memoryBytes","storageBytes"])s[u]!==void 0&&dh(s[u],`manifest.limits.${u}`,"invalid-manifest");const i=Gi(t.artifacts,"manifest.artifacts",128,"invalid-manifest").map((u,d)=>BY(u,`manifest.artifacts[${d}]`));i.length===0&&Ke("invalid-manifest","manifest.artifacts","must not be empty"),Vi(i.map(u=>u.role),"manifest.artifacts roles","invalid-manifest"),Vi(i.flatMap(u=>u.path===void 0?[]:[u.path]),"manifest.artifacts paths","invalid-manifest");const a=Gi(t.dependencies,"manifest.dependencies",512,"invalid-manifest").map((u,d)=>zY(u,`manifest.dependencies[${d}]`));Vi(a.map(u=>u.slot),"manifest.dependencies slots","invalid-manifest");const o=jY(t.integration,r);r!=="browser-module"&&i.some(u=>u.path!==void 0)&&Ke("invalid-manifest","manifest.artifacts","only a browser-module pack serves artifacts at paths");const l=Qr(t.provenance,"manifest.provenance","invalid-manifest");Hr(l,["upstream","recipe","license","redistribution"],"manifest.provenance","invalid-manifest");const c={kind:l7,version:c7,name:$6(t.name,"manifest.name"),upstreamVersion:mi(t.upstreamVersion,"manifest.upstreamVersion",128,"invalid-manifest"),packKind:r,coordinate:Do(t.coordinate,"manifest.coordinate","invalid-manifest"),buildKey:Do(t.buildKey,"manifest.buildKey","invalid-manifest"),runtime:{name:Sa(n.name,"manifest.runtime.name","invalid-manifest"),abi:Do(n.abi,"manifest.runtime.abi","invalid-manifest")},capabilities:pg(t.capabilities,"manifest.capabilities",128,"invalid-manifest").map(u=>qY(u,"manifest.capabilities")),limits:{...s.workers!==void 0?{workers:s.workers}:{},...s.memoryBytes!==void 0?{memoryBytes:s.memoryBytes}:{},...s.storageBytes!==void 0?{storageBytes:s.storageBytes}:{}},artifacts:i,dependencies:a,integration:o,provenance:{upstream:nR(l.upstream,"manifest.provenance.upstream","invalid-manifest"),recipe:Do(l.recipe,"manifest.provenance.recipe","invalid-manifest"),license:mi(l.license,"manifest.provenance.license",128,"invalid-manifest"),redistribution:Ef(l.redistribution,["cleared","unresolved","prohibited"],"manifest.provenance.redistribution")}};return Vi(c.capabilities,"manifest.capabilities","invalid-manifest"),Qg(c)}function PY(e){const t=Qr(e,"catalog","invalid-manifest");N6(t,u7,f7,"catalog","invalid-manifest"),Hr(t,["kind","version","retention","entries"],"catalog","invalid-manifest");const r=Qr(t.retention,"catalog.retention","invalid-manifest");Hr(r,["policy","repair"],"catalog.retention","invalid-manifest"),(r.policy!=="supported-locks"||r.repair!=="exact-only")&&Ke("invalid-manifest","catalog.retention","must retain supported locks and repair exact bytes only");const n=Gi(t.entries,"catalog.entries",1e5,"invalid-manifest").map((s,i)=>{const a=`catalog.entries[${i}]`,o=Qr(s,a,"invalid-manifest");Hr(o,["name","upstreamVersion","packKind","buildKey","manifest","closure","state","evidence","withdrawalReason"],a,"invalid-manifest");const l=Ef(o.state,["candidate","measured","withdrawn"],`${a}.state`);return l==="measured"&&o.evidence===void 0&&Ke("invalid-manifest",`${a}.evidence`,"is required for a measured entry"),l==="withdrawn"&&o.withdrawalReason===void 0&&Ke("invalid-manifest",`${a}.withdrawalReason`,"is required for a withdrawn entry"),{name:$6(o.name,`${a}.name`),upstreamVersion:mi(o.upstreamVersion,`${a}.upstreamVersion`,128,"invalid-manifest"),packKind:Ef(o.packKind,["node-archive","browser-module","wali","emscripten"],`${a}.packKind`),buildKey:Do(o.buildKey,`${a}.buildKey`,"invalid-manifest"),manifest:Po(o.manifest,`${a}.manifest`,"invalid-manifest"),closure:Po(o.closure,`${a}.closure`,"invalid-manifest"),state:l,...o.evidence!==void 0?{evidence:nR(o.evidence,`${a}.evidence`,"invalid-manifest")}:{},...o.withdrawalReason!==void 0?{withdrawalReason:mi(o.withdrawalReason,`${a}.withdrawalReason`,512,"invalid-manifest")}:{}}});return Vi(n.map(s=>`${s.name}
60
- ${s.buildKey}`),"catalog build selections","invalid-manifest"),Qg({kind:u7,version:f7,retention:{policy:"supported-locks",repair:"exact-only"},entries:n})}function m7(e){const t=Qr(e,"lock","invalid-lock");N6(t,d7,h7,"lock","invalid-lock"),Hr(t,["kind","version","runtime","roots","nodes","layout","preparedOutputs"],"lock","invalid-lock");const r=Qr(t.runtime,"lock.runtime","invalid-lock");Hr(r,["name","version","abi"],"lock.runtime","invalid-lock");const n=Gi(t.nodes,"lock.nodes",1e5,"invalid-lock").map((d,p)=>WY(d,`lock.nodes[${p}]`)),s=new Set(n.map(d=>d.id));s.size!==n.length&&Ke("unresolved-graph","lock.nodes","contains duplicate node IDs");const i=pg(t.roots,"lock.roots",1e4,"invalid-lock").map(d=>Sa(d,"lock.roots","invalid-lock"));Vi(i,"lock.roots","invalid-lock");for(const d of i)s.has(d)||Ke("unresolved-graph","lock.roots",`references missing node ${d}`);for(const d of n)for(const[p,m]of Object.entries(d.dependencies))typeof m=="string"&&!s.has(m)&&Ke("unresolved-graph",`lock.nodes.${d.id}.dependencies.${p}`,`references missing node ${m}`);const a=HY(t.layout,s),o=new Set(a.aliases.map(d=>d.target));for(const d of n)for(const[p,m]of Object.entries(d.dependencies))m!==null&&typeof m!="string"&&!o.has(m.workspace)&&Ke("unresolved-graph",`lock.nodes.${d.id}.dependencies.${p}`,`references missing workspace ${m.workspace}`);const l=new Map;for(const d of n)for(const p of d.exports){const m=l.get(p.path);m!==void 0&&m!==d.id&&Ke("export-conflict",`lock.nodes.${d.id}.exports`,`${p.path} is also exported by ${m}`),l.set(p.path,d.id)}const c=Gi(t.preparedOutputs,"lock.preparedOutputs",1e4,"invalid-lock").map((d,p)=>{const m=`lock.preparedOutputs[${p}]`,g=Qr(d,m,"invalid-lock");return Hr(g,["name","digest","inputs"],m,"invalid-lock"),{name:Sa(g.name,`${m}.name`,"invalid-lock"),digest:Po(g.digest,`${m}.digest`,"invalid-lock"),inputs:Po(g.inputs,`${m}.inputs`,"invalid-lock")}});Vi(c.map(d=>d.name),"lock.preparedOutputs names","invalid-lock");const u={kind:d7,version:h7,runtime:{name:Sa(r.name,"lock.runtime.name","invalid-lock"),version:mi(r.version,"lock.runtime.version",128,"invalid-lock"),abi:Do(r.abi,"lock.runtime.abi","invalid-lock")},roots:i,nodes:n,layout:a,preparedOutputs:c};return Qg(u)}function vv(e,t){const r=[];(e.runtime.name!==t.name||e.runtime.abi!==t.abi)&&r.push(`requires ${e.runtime.name}/${e.runtime.abi}`);const n=new Set(t.capabilities),s=e.capabilities.filter(i=>!n.has(i));s.length>0&&r.push(`missing capabilities: ${s.join(", ")}`);for(const i of["workers","memoryBytes","storageBytes"]){const a=e.limits[i],o=t[i];a!==void 0&&(o===void 0||o<a)&&r.push(`${i} requires ${a}, available ${o??0}`)}r.length>0&&Ke("incompatible-runtime","manifest.runtime",r.join("; "))}function UY(e,t,r){const n=new Map(e.nodes.map(s=>[s.id,s]));for(const s of e.nodes){const i=t.get(s.manifest);i||Ke("unresolved-graph",`lock.nodes.${s.id}.manifest`,`manifest ${s.manifest} is unavailable`),i.buildKey!==s.buildKey&&Ke("unresolved-graph",`lock.nodes.${s.id}.buildKey`,`does not match manifest build key ${i.buildKey}`),(i.runtime.name!==e.runtime.name||i.runtime.abi!==e.runtime.abi)&&Ke("incompatible-runtime",`lock.nodes.${s.id}.manifest`,`requires ${i.runtime.name}/${i.runtime.abi}, lock selects ${e.runtime.name}/${e.runtime.abi}`),r&&vv(i,r);const a=new Map(i.dependencies.map(o=>[o.slot,o]));for(const o of Object.keys(s.dependencies))a.has(o)||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o}`,"is not declared by the manifest");for(const o of i.dependencies){o.slot in s.dependencies||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,"has no binding");const l=s.dependencies[o.slot];if(l===void 0&&Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,"has no binding"),l===null){o.optional||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,"omits a required dependency");continue}if(typeof l!="string"){const d=e.layout.aliases.find(p=>p.target===l.workspace);d||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`references missing workspace ${l.workspace}`),d.coordinate!==o.coordinate&&Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`requires ${o.coordinate}, selected ${d.coordinate}`);continue}const c=n.get(l);c||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`references missing node ${l}`);const u=t.get(c.manifest);u||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`target manifest ${c.manifest} is unavailable`),u.coordinate!==o.coordinate&&Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`requires ${o.coordinate}, selected ${u.coordinate}`)}}}function rR(e){return JSON.stringify(xv(e,"$"))}async function Fm(e){const t=new TextEncoder().encode(rR(e));return hg(t)}async function hg(e){return`sha256:${[...new Uint8Array(await crypto.subtle.digest("SHA-256",new Uint8Array(e)))].map(r=>r.toString(16).padStart(2,"0")).join("")}`}async function FY(e,t){Po(t,"expected","integrity-failure");const r=await hg(e);r!==t&&Ke("integrity-failure","$",`expected ${t}, received ${r}`);let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{Ke("invalid-manifest","$","is not valid UTF-8")}let s;try{s=JSON.parse(n)}catch{Ke("invalid-manifest","$","is not valid JSON")}return rR(s)!==n&&Ke("invalid-manifest","$","is not the deterministic publication representation"),s}function BY(e,t){const r=Qr(e,t,"invalid-manifest");Hr(r,["role","digest","bytes","mediaType","archive","expandedBytes","files","parts","path"],t,"invalid-manifest"),r.path!==void 0&&r.archive!==void 0&&Ke("invalid-manifest",`${t}.path`,"an archive expands at the module root; only a single file has a path"),dh(r.bytes,`${t}.bytes`,"invalid-manifest",!0),r.archive!==void 0&&Ef(r.archive,["tar","tar+gzip","zip"],`${t}.archive`),r.expandedBytes!==void 0&&dh(r.expandedBytes,`${t}.expandedBytes`,"invalid-manifest",!0),r.files!==void 0&&dh(r.files,`${t}.files`,"invalid-manifest",!0),r.archive!==void 0&&(r.expandedBytes===void 0||r.files===void 0)&&Ke("invalid-manifest",t,"an archive requires expandedBytes and files bounds");let n;return r.parts!==void 0&&(r.archive!==void 0&&Ke("invalid-manifest",`${t}.parts`,"an archive cannot be parted"),n=Gi(r.parts,`${t}.parts`,4096,"invalid-manifest").map((s,i)=>{const a=Qr(s,`${t}.parts[${i}]`,"invalid-manifest");return Hr(a,["digest","bytes"],`${t}.parts[${i}]`,"invalid-manifest"),dh(a.bytes,`${t}.parts[${i}].bytes`,"invalid-manifest"),a.bytes>p7&&Ke("invalid-manifest",`${t}.parts[${i}].bytes`,`exceeds ${p7}`),{digest:Po(a.digest,`${t}.parts[${i}].digest`,"invalid-manifest"),bytes:a.bytes}}),n.length<2&&Ke("invalid-manifest",`${t}.parts`,"a parted artifact has at least two parts"),n.reduce((s,i)=>s+i.bytes,0)!==r.bytes&&Ke("invalid-manifest",`${t}.parts`,"part sizes must sum to the artifact's bytes")),{role:Sa(r.role,`${t}.role`,"invalid-manifest"),digest:Po(r.digest,`${t}.digest`,"invalid-manifest"),bytes:r.bytes,mediaType:GY(r.mediaType,`${t}.mediaType`,"invalid-manifest"),...r.archive!==void 0?{archive:r.archive}:{},...r.expandedBytes!==void 0?{expandedBytes:r.expandedBytes}:{},...r.files!==void 0?{files:r.files}:{},...n?{parts:n}:{},...r.path!==void 0?{path:VY(r.path,`${t}.path`)}:{}}}function zY(e,t){const r=Qr(e,t,"invalid-manifest");return Hr(r,["slot","coordinate","kind","optional"],t,"invalid-manifest"),r.optional!==void 0&&typeof r.optional!="boolean"&&Ke("invalid-manifest",`${t}.optional`,"must be a boolean"),{slot:Sa(r.slot,`${t}.slot`,"invalid-manifest"),coordinate:Do(r.coordinate,`${t}.coordinate`,"invalid-manifest"),kind:Ef(r.kind,["build","runtime","peer"],`${t}.kind`),...r.optional!==void 0?{optional:r.optional}:{}}}function jY(e,t){const r=Qr(e,"manifest.integration","invalid-manifest");if(t==="node-archive")return Hr(r,["kind","package"],"manifest.integration","invalid-manifest"),r.kind!=="node-archive"&&Ke("invalid-manifest","manifest.integration.kind","must match packKind"),{kind:"node-archive",package:$6(r.package,"manifest.integration.package")};if(t==="browser-module"){Hr(r,["kind","entries","chunks"],"manifest.integration","invalid-manifest"),r.kind!=="browser-module"&&Ke("invalid-manifest","manifest.integration.kind","must match packKind");const o=pg(r.entries,"manifest.integration.entries",512,"invalid-manifest").map(c=>ba(c,"manifest.integration.entries","invalid-manifest")),l=pg(r.chunks,"manifest.integration.chunks",2048,"invalid-manifest").map(c=>ba(c,"manifest.integration.chunks","invalid-manifest"));return o.length===0&&Ke("invalid-manifest","manifest.integration.entries","must not be empty"),Vi(o,"manifest.integration.entries","invalid-manifest"),Vi(l,"manifest.integration.chunks","invalid-manifest"),{kind:"browser-module",entries:o,chunks:l}}Hr(r,["kind","engine","executable","configuration","resourcesRoot","entry"],"manifest.integration","invalid-manifest"),(r.kind!=="program"||r.engine!==t)&&Ke("invalid-manifest","manifest.integration","program engine must match packKind"),t==="emscripten"&&r.entry===void 0&&Ke("invalid-manifest","manifest.integration.entry","is required for Emscripten"),t==="wali"&&r.entry!==void 0&&Ke("invalid-manifest","manifest.integration.entry","is only valid for Emscripten");const n=ZY(r.executable,"manifest.integration.executable","invalid-manifest"),s=r.resourcesRoot!==void 0?sR(r.resourcesRoot,"manifest.integration.resourcesRoot","invalid-manifest"):void 0;s&&!s.startsWith("/opt/")&&Ke("invalid-manifest","manifest.integration.resourcesRoot","live program resources must mount below /opt");const i=r.entry!==void 0?ba(r.entry,"manifest.integration.entry","invalid-manifest"):void 0;let a;try{const o=Qr(r.configuration,"manifest.integration.configuration","invalid-manifest");Hr(o,["displayName","actions","storage","environment","programs","terminal","network","openUrls"],"manifest.integration.configuration","invalid-manifest"),a=Kg({schemaVersion:1,id:"pack",displayName:o.displayName,version:"1",engine:t,artifact:{url:"/pack.wasm",integrity:`sha256-${"A".repeat(43)}=`,license:"pack",redistribution:"cleared"},...s?{resources:{url:"/resources.zip",integrity:`sha256-${"A".repeat(43)}=`,root:s}}:{},...i?{entry:i}:{},executable:n,actions:o.actions,storage:o.storage,environment:o.environment,requirements:{capabilities:[],programs:o.programs},terminal:o.terminal,network:o.network,openUrls:o.openUrls})}catch(o){Ke("invalid-manifest","manifest.integration.configuration",o instanceof Error?o.message:String(o))}return{kind:"program",engine:t,executable:n,configuration:{displayName:a.displayName,actions:a.actions,storage:a.storage,environment:a.environment,programs:a.requirements.programs,terminal:a.terminal,network:a.network,openUrls:a.openUrls},...s?{resourcesRoot:s}:{},...i?{entry:i}:{}}}function WY(e,t){const r=Qr(e,t,"invalid-lock");Hr(r,["id","manifest","buildKey","dependencies","exports"],t,"invalid-lock");const n=Qr(r.dependencies,`${t}.dependencies`,"invalid-lock"),s={};for(const[a,o]of Object.entries(n))if(Sa(a,`${t}.dependencies`,"invalid-lock"),o===null)s[a]=null;else if(typeof o=="string")s[a]=Sa(o,`${t}.dependencies.${a}`,"invalid-lock");else{const l=Qr(o,`${t}.dependencies.${a}`,"invalid-lock");Hr(l,["workspace"],`${t}.dependencies.${a}`,"invalid-lock"),s[a]={workspace:ba(l.workspace,`${t}.dependencies.${a}.workspace`,"invalid-lock")}}const i=Gi(r.exports,`${t}.exports`,512,"invalid-lock").map((a,o)=>{const l=`${t}.exports[${o}]`,c=Qr(a,l,"invalid-lock");return Hr(c,["name","path"],l,"invalid-lock"),{name:Sa(c.name,`${l}.name`,"invalid-lock"),path:sR(c.path,`${l}.path`,"invalid-lock")}});return Vi(i.map(a=>a.path),`${t}.exports paths`,"invalid-lock"),{id:Sa(r.id,`${t}.id`,"invalid-lock"),manifest:Po(r.manifest,`${t}.manifest`,"invalid-lock"),buildKey:Do(r.buildKey,`${t}.buildKey`,"invalid-lock"),dependencies:s,exports:i}}function HY(e,t){const r=Qr(e,"lock.layout","invalid-lock");Hr(r,["packages","bins","aliases","entries"],"lock.layout","invalid-lock");const n=Gi(r.packages,"lock.layout.packages",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.packages[${u}]`,p=Qr(c,d,"invalid-lock");Hr(p,["path","node"],d,"invalid-lock");const m=Sa(p.node,`${d}.node`,"invalid-lock");return t.has(m)||Ke("unresolved-graph",`${d}.node`,`references missing node ${m}`),{path:ba(p.path,`${d}.path`,"invalid-lock"),node:m}}),s=Gi(r.bins,"lock.layout.bins",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.bins[${u}]`,p=Qr(c,d,"invalid-lock");return Hr(p,["path","target"],d,"invalid-lock"),{path:ba(p.path,`${d}.path`,"invalid-lock"),target:ba(p.target,`${d}.target`,"invalid-lock")}}),i=Gi(r.aliases,"lock.layout.aliases",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.aliases[${u}]`,p=Qr(c,d,"invalid-lock");return Hr(p,["path","target","coordinate"],d,"invalid-lock"),{path:ba(p.path,`${d}.path`,"invalid-lock"),target:ba(p.target,`${d}.target`,"invalid-lock"),coordinate:Do(p.coordinate,`${d}.coordinate`,"invalid-lock")}}),a=Gi(r.entries,"lock.layout.entries",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.entries[${u}]`,p=Qr(c,d,"invalid-lock");return Hr(p,["path","digest"],d,"invalid-lock"),{path:ba(p.path,`${d}.path`,"invalid-lock"),digest:Po(p.digest,`${d}.digest`,"invalid-lock")}});for(const[c,u]of[["packages",n.map(d=>d.path)],["bins",s.map(d=>d.path)],["aliases",i.map(d=>d.path)],["entries",a.map(d=>d.path)]])Vi(u,`lock.layout.${c} paths`,"export-conflict");const o=[...n.map(c=>c.path),...s.map(c=>c.path),...i.map(c=>c.path),...a.map(c=>c.path)];Vi(o,"lock.layout destinations","export-conflict");const l=new Map;for(const c of i){const u=l.get(c.target);u!==void 0&&u!==c.coordinate&&Ke("unresolved-graph","lock.layout.aliases",`${c.target} has conflicting coordinates`),l.set(c.target,c.coordinate)}return{packages:n,bins:s,aliases:i,entries:a}}function N6(e,t,r,n,s){e.kind!==t&&Ke(s,`${n}.kind`,`must be ${t}`),e.version!==r&&Ke("unsupported-schema",`${n}.version`,`unsupported version ${String(e.version)}`)}function xv(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ke("invalid-manifest",t,"contains a non-finite number"),e;if(Array.isArray(e))return e.map((n,s)=>xv(n,`${t}[${s}]`));typeof e!="object"&&Ke("invalid-manifest",t,"contains an unsupported value"),Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null&&Ke("invalid-manifest",t,"must contain only plain JSON objects");const r={};for(const n of Object.keys(e).sort())r[n]=xv(e[n],`${t}.${n}`);return r}function Qr(e,t,r){return(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)&&Ke(r,t,"must be a plain object"),e}function Gi(e,t,r,n){return(!Array.isArray(e)||e.length>r)&&Ke(n,t,`must be an array of at most ${r} entries`),e}function Hr(e,t,r,n){const s=new Set(t),i=Object.keys(e).filter(a=>!s.has(a));i.length>0&&Ke(n,r,`has unknown fields: ${i.join(", ")}`)}function mi(e,t,r,n){return(typeof e!="string"||e.length<1||e.length>r||/[\u0000\r\n]/u.test(e))&&Ke(n,t,"must be a non-empty bounded string"),e}function Sa(e,t,r){const n=mi(e,t,128,r);return/^[a-z][a-z0-9._-]*$/u.test(n)||Ke(r,t,"must be a lowercase identifier"),n}function $6(e,t){const r=mi(e,t,214,"invalid-manifest");return/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/u.test(r)||Ke("invalid-manifest",t,"must be a normalized package name"),r}function Do(e,t,r){const n=mi(e,t,512,r);return/^[A-Za-z0-9][A-Za-z0-9._/+@:=,-]*$/u.test(n)||Ke(r,t,"contains unsupported characters"),n}function Po(e,t,r){return(typeof e!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e))&&Ke(r,t,"must be a sha256:<64 lowercase hex> digest"),e}function qY(e,t){return/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/u.test(e)||Ke("invalid-manifest",t,`invalid capability ${e}`),e}function GY(e,t,r){const n=mi(e,t,128,r);return/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/u.test(n)||Ke(r,t,"must be a lowercase media type"),n}function nR(e,t,r){const n=mi(e,t,2048,r);let s;try{s=new URL(n)}catch{Ke(r,t,"must be an HTTPS URL")}return(s.protocol!=="https:"||s.username||s.password||s.hash)&&Ke(r,t,"must be an HTTPS URL without credentials or fragment"),n}function VY(e,t){const r=ba(e,t,"invalid-manifest");return/[?#]|%2e/iu.test(r)&&Ke("invalid-manifest",t,"must not contain a query, a fragment or an encoded dot"),r}function ba(e,t,r){const n=mi(e,t,1024,r);return(n.startsWith("/")||n.includes("\\")||n.split("/").some(s=>s===""||s==="."||s===".."))&&Ke(r,t,"must be a normalized relative path"),n}function sR(e,t,r){const n=mi(e,t,1024,r);return(!n.startsWith("/")||n==="/"||n.includes("\\")||n.split("/").slice(1).some(s=>s===""||s==="."||s===".."))&&Ke(r,t,"must be a normalized non-root absolute path"),n}function ZY(e,t,r){const n=mi(e,t,128,r);return/^[A-Za-z0-9._+-]+$/u.test(n)||Ke(r,t,"must be a command name"),n}function pg(e,t,r,n){const s=Gi(e,t,r,n);return s.some(i=>typeof i!="string")&&Ke(n,t,"must contain only strings"),s}function Vi(e,t,r){new Set(e).size!==e.length&&Ke(r,t,"must not contain duplicates")}function dh(e,t,r,n=!1){(!Number.isSafeInteger(e)||e<(n?0:1))&&Ke(r,t,`must be a safe integer ${n?"at least zero":"greater than zero"}`)}function Ef(e,t,r){return(typeof e!="string"||!t.includes(e))&&Ke("invalid-manifest",r,`must be one of ${t.join(", ")}`),e}function Ke(e,t,r){throw new eR(e,t,r)}function Qg(e){if(e&&typeof e=="object"){Object.freeze(e);for(const t of Object.values(e))Qg(t)}return e}class g7{#t;#r;#s;#e;#n;#c;constructor(t){t.endpoints.length===0&&Pr("invalid-manifest","catalog.endpoints","must not be empty"),this.#t=t.endpoints.map(n=>({...n,baseUrl:XY(n.baseUrl,t.allowInsecureLocalhost===!0)})),this.#r=new Set(t.trustedOrigins.map(n=>new URL(n).origin)),this.#s=t.pinnedCatalog,this.#e=t.deniedDigests??new Map;const r=t.fetch??globalThis.fetch.bind(globalThis);this.#n=(n,s)=>r(n,s),this.#c=t.allowInsecureLocalhost===!0;for(const n of this.#t)this.#a(new URL(n.baseUrl),"catalog.endpoints")}async selectExact(t,r,n){const{catalog:s,digest:i}=await this.catalog(),a=s.entries.find(u=>u.name===t&&u.buildKey===r);a||Pr("catalog-miss","catalog.entries",`has no exact build ${t}/${r}`),a.state==="withdrawn"&&Pr("withdrawn","catalog.entries",a.withdrawalReason??`${t}/${r} is withdrawn`),a.state!=="measured"&&Pr("catalog-miss","catalog.entries",`${t}/${r} is a candidate, not a measured build`),this.#l(a.manifest,"catalog.entry.manifest"),this.#l(a.closure,"catalog.entry.closure");const o=Pb(await this.#o("manifests",a.manifest));y7(a,o),vv(o,n);const l=m7(await this.#o("locks",a.closure));l.nodes.some(u=>u.manifest===a.manifest)||Pr("unresolved-graph","catalog.entry.closure","does not contain its selected manifest");const c=await this.#u(l,new Map([[a.manifest,o]]));return{catalog:s,catalogDigest:i,entry:a,manifest:o,manifests:c,closure:l}}async catalog(){let t=this.#s;if(!t){const n=await this.#i("pointer","/v1/catalog.json",this.#t.slice(0,1),"application/json");let s;try{s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{Pr("invalid-manifest","catalog.pointer","is not valid UTF-8 JSON")}t=YY(s).catalog}return this.#l(t,"catalog.digest"),{catalog:PY(await this.#o("catalogs",t)),digest:t}}async restorePinned(t,r,n){this.#l(t,"restore.manifest"),this.#l(r,"restore.closure");const{catalog:s,digest:i}=await this.catalog(),a=s.entries.find(d=>d.manifest===t&&d.closure===r),o=[];a?a.state==="withdrawn"?o.push(`Pinned build is withdrawn: ${a.withdrawalReason??"no reason supplied"}`):a.state==="candidate"&&o.push("Pinned build is only a candidate, not a measured catalog entry."):o.push(`Pinned build ${t}/${r} is no longer listed; repairing exact retained bytes only.`);const l=Pb(await this.#o("manifests",t));a&&y7(a,l),vv(l,n);const c=m7(await this.#o("locks",r));c.nodes.some(d=>d.manifest===t)||Pr("unresolved-graph","restore.closure","does not contain the pinned manifest");const u=await this.#u(c,new Map([[t,l]]));return{catalog:s,catalogDigest:i,manifest:l,manifests:u,closure:c,warnings:o}}async artifact(t){this.#l(t.digest,`artifact.${t.role}`);const r=await this.#i("artifact",Ub("artifacts",t.digest),this.#t,t.mediaType);r.byteLength!==t.bytes&&Pr("integrity-failure",`artifact.${t.role}.bytes`,`expected ${t.bytes}, received ${r.byteLength}`);const n=await hg(r);return n!==t.digest&&Pr("integrity-failure",`artifact.${t.role}.digest`,`expected ${t.digest}, received ${n}`),r}async artifactPart(t,r){const n=t.parts?.[r];n||Pr("invalid-manifest",`artifact.${t.role}.parts[${r}]`,"is not declared"),this.#l(t.digest,`artifact.${t.role}`),this.#l(n.digest,`artifact.${t.role}.parts[${r}]`);const s=`artifact.${t.role}.parts[${r}]`,i=await this.#i(s,Ub("artifacts",n.digest),this.#t,tR);i.byteLength!==n.bytes&&Pr("integrity-failure",`${s}.bytes`,`expected ${n.bytes}, received ${i.byteLength}`);const a=await hg(i);return a!==n.digest&&Pr("integrity-failure",`${s}.digest`,`expected ${n.digest}, received ${a}`),i}async#o(t,r){const n=await this.#i(t,Ub(t,r),this.#t,"application/json");return FY(n,r)}async#u(t,r){const n=[...new Set(t.nodes.map(s=>s.manifest))].filter(s=>!r.has(s));return await Promise.all(n.map(async s=>{r.set(s,Pb(await this.#o("manifests",s)))})),r}async#i(t,r,n,s){let i=!1;for(const a of n){let o=new URL(r,a.baseUrl);for(let l=0;l<=3;l+=1){this.#a(o,t);const c=new URL(a.baseUrl).origin,u=o.origin===c?await a.authorization?.():void 0;let d;try{d=await this.#n(o,{redirect:"manual",headers:{accept:s,...u?{authorization:u}:{}}})}catch{break}if([301,302,303,307,308].includes(d.status)){const b=d.headers.get("location");b||Pr("unavailable-artifact",t,"redirect has no location"),o=new URL(b,o);continue}if(d.status===401||d.status===403){i=!0;break}if(d.status===404)break;d.ok||Pr("unavailable-artifact",t,`request failed with HTTP ${d.status}`);const p=d.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase();p!==s&&Pr("integrity-failure",t,`expected content-type ${s}, received ${p??"none"}`);const m=new Uint8Array(await d.arrayBuffer()),g=d.headers.get("content-length");return(g===null||Number(g)!==m.byteLength)&&Pr("integrity-failure",t,`partial response: declared ${g??"none"}, received ${m.byteLength}`),m}}i&&Pr("authentication-failure",t,"catalog credentials were refused"),Pr("unavailable-artifact",t,`content is unavailable at every configured endpoint: ${r}`)}#a(t,r){(!(this.#c&&t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname))&&t.protocol!=="https:"||!this.#r.has(t.origin))&&Pr("denied-origin",r,`origin is not trusted: ${t.origin}`)}#l(t,r){const n=this.#e.get(t);n&&Pr("withdrawn",r,`security policy denies ${t}: ${n}`)}}function Ub(e,t){/^sha256:[a-f0-9]{64}$/u.test(t)||Pr("invalid-manifest","digest","must be sha256:<64 lowercase hex>");const r=t.slice(7);return`/v1/${e}/sha256/${r}${e==="artifacts"?"":".json"}`}function YY(e){(!e||typeof e!="object"||Array.isArray(e))&&Pr("invalid-manifest","catalog.pointer","must be an object");const t=e;return(Object.keys(t).some(r=>!["kind","version","catalog"].includes(r))||t.kind!=="browser-substrate.pack-catalog-pointer"||t.version!==1||typeof t.catalog!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.catalog))&&Pr("invalid-manifest","catalog.pointer","has an unsupported shape"),t}function XY(e,t){let r;try{r=new URL(e)}catch{Pr("invalid-manifest","catalog.endpoints","base URL is invalid")}return(!(t&&r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname))&&r.protocol!=="https:"||r.username||r.password||r.search||r.hash)&&Pr("denied-origin","catalog.endpoints","base URL must be HTTPS without credentials, query or fragment"),`${r.origin}${r.pathname.replace(/\/+$/u,"")}/`}function y7(e,t){const r=[e.name===t.name?void 0:`name ${e.name}/${t.name}`,e.upstreamVersion===t.upstreamVersion?void 0:`upstreamVersion ${e.upstreamVersion}/${t.upstreamVersion}`,e.packKind===t.packKind?void 0:`packKind ${e.packKind}/${t.packKind}`,e.buildKey===t.buildKey?void 0:`buildKey ${e.buildKey}/${t.buildKey}`].filter(n=>n!==void 0);r.length>0&&Pr("invalid-manifest","catalog.entry",`does not describe its pinned manifest: ${r.join(", ")}`)}function Pr(e,t,r){throw new eR(e,t,r)}class b7 extends Error{category;constructor(t,r){super(r),this.category=t,this.name="BrowserPackArchiveError"}}new TextDecoder("utf-8",{fatal:!0});class vn extends Error{category;constructor(t,r){super(r),this.category=t,this.name="BrowserPackInstallError"}}class KY{persistence;store;concurrency;retries;#t=new Map;constructor(t,r,n=4,s=2){this.persistence=t,this.store=r,this.concurrency=n,this.retries=s}async plan(t){if(await Fm(t.lock)!==t.lockDigest)throw new Error(`Environment lock bytes do not match ${t.lockDigest}.`);for(const[u,d]of t.manifests)if(await Fm(d)!==u)throw new Error(`Pack manifest bytes do not match ${u}.`);UY(t.lock,t.manifests,t.profile);const r=await this.persistence.environment(t.environment),n=v7(w7(t.lock,t.manifests)),s=[];for(const u of n)await this.store.has(u.artifact.digest)||s.push(u);const i=s.reduce((u,d)=>u+d.artifact.bytes+(d.part?0:d.artifact.expandedBytes??d.artifact.bytes),0),a=await this.store.availableBytes?.();if(a!==void 0&&i>a)throw new vn("quota-exceeded",`Install needs ${i} bytes including staging; ${a} are available.`);const o=await Fm({verb:t.verb??"install",lock:t.lockDigest,environment:t.environment}),l=await this.persistence.operation(t.environment,t.operationId);if(l){if(l.request!==o)throw new vn("operation-conflict",`Operation ${t.operationId} was already used for another request.`);return l}const c={environment:t.environment,id:t.operationId,request:o,verb:t.verb??"install",phase:"plan",...r.active?{baseRevision:r.active.revision}:{},targetRevision:QY(t.lockDigest),lock:t.lockDigest,bytes:i,completedBytes:0,committed:!1};return await this.persistence.saveOperation(c),t.onProgress?.(c),c}async install(t){const r=`${t.environment}/${t.operationId}`,n=this.#t.get(r);if(n)return n;const s=this.executeInstall(t);this.#t.set(r,s);try{return await s}finally{this.#t.get(r)===s&&this.#t.delete(r)}}async executeInstall(t){let r=await this.plan(t);if(C1(r))return r;try{cc(t.signal),r=await this.advance(r,"authorize",t);for(const m of t.manifests.values())await t.authorize(m);cc(t.signal);const n=v7(w7(t.lock,t.manifests)),s=n.map(m=>m.artifact);r=await this.advance(r,"fetch",t);for(const m of n){if(!m.part||await this.store.has(m.artifact.digest))continue;if(cc(t.signal),!t.fetchArtifactPart)throw new vn("recovery-failure",`Artifact ${m.part.of.digest} is parted and this catalog cannot fetch parts.`);const g=await S7(this.retries,t.signal,()=>t.fetchArtifactPart(m.part.of,m.part.index,t.signal));if(g.byteLength!==m.artifact.bytes||await x7(g)!==m.artifact.digest)throw new Error(`Part ${m.part.index} of artifact ${m.part.of.digest} failed exact byte verification.`);await this.store.stageArtifact(m.artifact.digest,g,m.artifact,t.signal),r.completedBytes+=g.byteLength,await this.persistence.saveOperation(r),t.onProgress?.({...r})}const i=new Map;await JY(n.filter(m=>!m.part).map(m=>m.artifact),this.concurrency,async m=>{if(await this.store.has(m.digest))return;const g=await S7(this.retries,t.signal,()=>t.fetchArtifact(m,t.signal));i.set(m.digest,g),r.completedBytes+=g.byteLength,await this.persistence.saveOperation(r),t.onProgress?.({...r})}),cc(t.signal),r=await this.advance(r,"verify",t);for(const m of s){const g=i.get(m.digest);if(!g)continue;if(await x7(g)!==m.digest||g.byteLength!==m.bytes)throw new Error(`Artifact ${m.digest} failed exact byte verification.`)}cc(t.signal),r=await this.advance(r,"stage",t);for(const m of s){const g=i.get(m.digest);g&&await this.store.stageArtifact(m.digest,g,m,t.signal)}if(await this.store.stageEnvironment(t.lockDigest,t.lock),await this.store.retainEnvironment?.(t.lockDigest,s),t.verb==="offline"){const m={...r,phase:"installed",committed:!1};return await this.persistence.saveOperation(m),t.onProgress?.(m),m}cc(t.signal),r=await this.advance(r,"activate",t);const a=await this.persistence.environment(t.environment),o=r.baseRevision,l={revision:r.targetRevision,lock:t.lockDigest};if(a.active?.revision===l.revision&&a.active.lock===l.lock){const m={...r,phase:"installed",committed:!0};return await this.persistence.saveOperation(m),t.onProgress?.(m),m}const c=a.active&&!a.retained.some(m=>m.revision===a.active.revision)?[...a.retained,a.active]:a.retained,u={...r,committed:!0};if(!await this.persistence.compareAndSwap(t.environment,o,{active:l,retained:c},u)){const m=await this.persistence.operation(t.environment,t.operationId);if(m?.request===r.request&&m.committed){const g={...m,phase:"installed"};return await this.persistence.saveOperation(g),g}throw new vn("revision-conflict","The environment revision changed; re-plan against the new active revision.")}const p={...u,phase:"installed"};return await this.persistence.saveOperation(p),t.onProgress?.(p),p}catch(n){if(r.committed)return{...r,phase:"installed"};const s=n instanceof vn&&n.category==="cancellation"||n instanceof b7&&n.category==="cancellation",i=n instanceof vn||n instanceof b7?n.category:"install-failure",a={...r,phase:s?"cancelled":"failed",error:{category:i,message:n instanceof Error?n.message:String(n)}};return await this.persistence.saveOperation(a),t.onProgress?.(a),a}}async inspect(t){return this.persistence.environment(t)}async rollback(t,r,n){const s=await this.persistence.environment(t),i=s.retained.find(a=>a.revision===n);if(!i)throw new vn("recovery-failure",`Retained revision ${n} is unavailable.`);return this.switchRevision(t,r,"rollback",s,i,s.active?[...s.retained.filter(a=>a.revision!==n),s.active]:s.retained.filter(a=>a.revision!==n))}async remove(t,r){const n=await this.persistence.environment(t);if(!n.active)throw new vn("recovery-failure","The environment has no active revision.");return this.switchRevision(t,r,"remove",n,void 0,[...n.retained,n.active])}async recover(t,r){const n=await this.persistence.operation(t,r);if(!n)throw new vn("recovery-failure",`Operation ${r} has no recovery record.`);if(C1(n))return n;const s=await this.persistence.environment(t);if(n.targetRevision&&s.active?.revision===n.targetRevision){const a={...n,phase:"installed",committed:!0};return await this.persistence.saveOperation(a),a}const i={...n,phase:"failed",committed:!1,error:{category:"recovery-failure",message:"Recovered the previous complete revision; staged content was not activated."}};return await this.persistence.saveOperation(i),i}async advance(t,r,n){const s={...t,phase:r};return await this.persistence.saveOperation(s),n.onProgress?.(s),s}async switchRevision(t,r,n,s,i,a){const o=await Fm({environment:t,verb:n,...i?{active:i}:{}}),l=await this.persistence.operation(t,r);if(l){if(l.request!==o)throw new vn("operation-conflict",`Operation ${r} was already used.`);if(C1(l))return l}const c={environment:t,id:r,request:o,verb:n,phase:"activate",...s.active?{baseRevision:s.active.revision}:{},...i?{targetRevision:i.revision,lock:i.lock}:{},bytes:0,completedBytes:0,committed:!0};if(!await this.persistence.compareAndSwap(t,s.active?.revision,{...i?{active:i}:{},retained:a},c))throw new vn("revision-conflict","The environment revision changed; re-plan the operation.");const d={...c,phase:"installed"};return await this.persistence.saveOperation(d),d}}function w7(e,t){const r=new Map;for(const n of e.nodes)for(const s of t.get(n.manifest)?.artifacts??[])r.set(s.digest,s);return[...r.values()]}function v7(e){const t=new Map;for(const r of e){if(!r.parts){t.set(r.digest,{artifact:r});continue}r.parts.forEach((n,s)=>{t.has(n.digest)||t.set(n.digest,{artifact:{role:`${r.role}-part-${s}`,digest:n.digest,bytes:n.bytes,mediaType:tR},part:{of:r,index:s}})})}return[...t.values()]}async function x7(e){const t=await crypto.subtle.digest("SHA-256",new Uint8Array(e));return`sha256:${[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}`}function QY(e){return`revision-${e.slice(7)}`}function C1(e){return e.phase==="installed"||e.phase==="failed"||e.phase==="cancelled"}function cc(e){if(e?.aborted)throw new vn("cancellation","Installation was cancelled before activation.")}async function S7(e,t,r){let n;for(let s=0;s<=e;s+=1){cc(t);try{return await r()}catch(i){n=i}}throw n}async function JY(e,t,r){let n=0;await Promise.all(Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;n<e.length;){const s=n++;await r(e[s])}}))}class eX{databaseName;constructor(t="browser-substrate-pack-installs"){this.databaseName=t}async environment(t){return await this.get("environments",t)??{retained:[]}}async operation(t,r){return this.get("operations",`${t}/${r}`)}async saveOperation(t){const r=await this.open();try{await new Promise((n,s)=>{const i=r.transaction("operations","readwrite"),a=i.objectStore("operations"),o=`${t.environment}/${t.id}`,l=a.get(o);l.onsuccess=()=>{const c=l.result;(!c||!c.committed&&!C1(c)||c.committed&&t.committed&&t.phase==="installed")&&a.put(t,o)},i.oncomplete=()=>n(),i.onerror=()=>s(i.error??new Error("Pack install persistence failed."))})}finally{r.close()}}async compareAndSwap(t,r,n,s){const i=await this.open();try{return await new Promise((a,o)=>{const l=i.transaction(["environments","operations"],"readwrite"),c=l.objectStore("environments"),u=c.get(t);let d=!1;u.onsuccess=()=>{u.result?.active?.revision===r&&(d=!0,c.put(n,t),l.objectStore("operations").put(s,`${t}/${s.id}`))},l.oncomplete=()=>a(d),l.onerror=()=>o(l.error??new Error("Pack install persistence failed.")),l.onabort=()=>o(l.error??new Error("Pack install persistence was aborted."))})}finally{i.close()}}async get(t,r){const n=await this.open();try{return await new Promise((s,i)=>{const o=n.transaction(t,"readonly").objectStore(t).get(r);o.onsuccess=()=>s(o.result),o.onerror=()=>i(o.error)})}finally{n.close()}}async put(t,r,n){const s=await this.open();try{await new Promise((i,a)=>{const o=s.transaction(t,"readwrite");o.objectStore(t).put(n,r),o.oncomplete=()=>i(),o.onerror=()=>a(o.error??new Error("Pack install persistence failed."))})}finally{s.close()}}open(){return new Promise((t,r)=>{const n=indexedDB.open(this.databaseName,1);n.onupgradeneeded=()=>{for(const s of["environments","operations"])n.result.objectStoreNames.contains(s)||n.result.createObjectStore(s)},n.onsuccess=()=>{n.result.onversionchange=()=>n.result.close(),t(n.result)},n.onerror=()=>r(n.error??new Error("Pack install database failed to open.")),n.onblocked=()=>r(new Error("Pack install database is blocked by another tab."))})}}const Sv=".browser-program-archives";function tX(e){if(e.length===0)throw new Error("A program's layer names at least one archive.");return`/packages/.programs/${e.map(r=>{const n=/^sha256-([A-Za-z0-9+/]{43}=)$/u.exec(r);if(!n)throw new Error(`A program archive's integrity is not a SHA-256: ${r}`);return[...atob(n[1])].map(s=>s.charCodeAt(0).toString(16).padStart(2,"0")).join("")}).join("-")}`}function rX(e){return`${e.join(`
60
+ ${s.buildKey}`),"catalog build selections","invalid-manifest"),Qg({kind:u7,version:f7,retention:{policy:"supported-locks",repair:"exact-only"},entries:n})}function m7(e){const t=Qr(e,"lock","invalid-lock");N6(t,d7,h7,"lock","invalid-lock"),Hr(t,["kind","version","runtime","roots","nodes","layout","preparedOutputs"],"lock","invalid-lock");const r=Qr(t.runtime,"lock.runtime","invalid-lock");Hr(r,["name","version","abi"],"lock.runtime","invalid-lock");const n=Gi(t.nodes,"lock.nodes",1e5,"invalid-lock").map((d,p)=>WY(d,`lock.nodes[${p}]`)),s=new Set(n.map(d=>d.id));s.size!==n.length&&Ke("unresolved-graph","lock.nodes","contains duplicate node IDs");const i=pg(t.roots,"lock.roots",1e4,"invalid-lock").map(d=>Sa(d,"lock.roots","invalid-lock"));Vi(i,"lock.roots","invalid-lock");for(const d of i)s.has(d)||Ke("unresolved-graph","lock.roots",`references missing node ${d}`);for(const d of n)for(const[p,m]of Object.entries(d.dependencies))typeof m=="string"&&!s.has(m)&&Ke("unresolved-graph",`lock.nodes.${d.id}.dependencies.${p}`,`references missing node ${m}`);const a=HY(t.layout,s),o=new Set(a.aliases.map(d=>d.target));for(const d of n)for(const[p,m]of Object.entries(d.dependencies))m!==null&&typeof m!="string"&&!o.has(m.workspace)&&Ke("unresolved-graph",`lock.nodes.${d.id}.dependencies.${p}`,`references missing workspace ${m.workspace}`);const l=new Map;for(const d of n)for(const p of d.exports){const m=l.get(p.path);m!==void 0&&m!==d.id&&Ke("export-conflict",`lock.nodes.${d.id}.exports`,`${p.path} is also exported by ${m}`),l.set(p.path,d.id)}const c=Gi(t.preparedOutputs,"lock.preparedOutputs",1e4,"invalid-lock").map((d,p)=>{const m=`lock.preparedOutputs[${p}]`,g=Qr(d,m,"invalid-lock");return Hr(g,["name","digest","inputs"],m,"invalid-lock"),{name:Sa(g.name,`${m}.name`,"invalid-lock"),digest:Po(g.digest,`${m}.digest`,"invalid-lock"),inputs:Po(g.inputs,`${m}.inputs`,"invalid-lock")}});Vi(c.map(d=>d.name),"lock.preparedOutputs names","invalid-lock");const u={kind:d7,version:h7,runtime:{name:Sa(r.name,"lock.runtime.name","invalid-lock"),version:mi(r.version,"lock.runtime.version",128,"invalid-lock"),abi:Do(r.abi,"lock.runtime.abi","invalid-lock")},roots:i,nodes:n,layout:a,preparedOutputs:c};return Qg(u)}function vv(e,t){const r=[];(e.runtime.name!==t.name||e.runtime.abi!==t.abi)&&r.push(`requires ${e.runtime.name}/${e.runtime.abi}`);const n=new Set(t.capabilities),s=e.capabilities.filter(i=>!n.has(i));s.length>0&&r.push(`missing capabilities: ${s.join(", ")}`);for(const i of["workers","memoryBytes","storageBytes"]){const a=e.limits[i],o=t[i];a!==void 0&&(o===void 0||o<a)&&r.push(`${i} requires ${a}, available ${o??0}`)}r.length>0&&Ke("incompatible-runtime","manifest.runtime",r.join("; "))}function UY(e,t,r){const n=new Map(e.nodes.map(s=>[s.id,s]));for(const s of e.nodes){const i=t.get(s.manifest);i||Ke("unresolved-graph",`lock.nodes.${s.id}.manifest`,`manifest ${s.manifest} is unavailable`),i.buildKey!==s.buildKey&&Ke("unresolved-graph",`lock.nodes.${s.id}.buildKey`,`does not match manifest build key ${i.buildKey}`),(i.runtime.name!==e.runtime.name||i.runtime.abi!==e.runtime.abi)&&Ke("incompatible-runtime",`lock.nodes.${s.id}.manifest`,`requires ${i.runtime.name}/${i.runtime.abi}, lock selects ${e.runtime.name}/${e.runtime.abi}`),r&&vv(i,r);const a=new Map(i.dependencies.map(o=>[o.slot,o]));for(const o of Object.keys(s.dependencies))a.has(o)||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o}`,"is not declared by the manifest");for(const o of i.dependencies){o.slot in s.dependencies||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,"has no binding");const l=s.dependencies[o.slot];if(l===void 0&&Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,"has no binding"),l===null){o.optional||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,"omits a required dependency");continue}if(typeof l!="string"){const d=e.layout.aliases.find(p=>p.target===l.workspace);d||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`references missing workspace ${l.workspace}`),d.coordinate!==o.coordinate&&Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`requires ${o.coordinate}, selected ${d.coordinate}`);continue}const c=n.get(l);c||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`references missing node ${l}`);const u=t.get(c.manifest);u||Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`target manifest ${c.manifest} is unavailable`),u.coordinate!==o.coordinate&&Ke("unresolved-graph",`lock.nodes.${s.id}.dependencies.${o.slot}`,`requires ${o.coordinate}, selected ${u.coordinate}`)}}}function rR(e){return JSON.stringify(xv(e,"$"))}async function Fm(e){const t=new TextEncoder().encode(rR(e));return hg(t)}async function hg(e){return`sha256:${[...new Uint8Array(await crypto.subtle.digest("SHA-256",new Uint8Array(e)))].map(r=>r.toString(16).padStart(2,"0")).join("")}`}async function FY(e,t){Po(t,"expected","integrity-failure");const r=await hg(e);r!==t&&Ke("integrity-failure","$",`expected ${t}, received ${r}`);let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{Ke("invalid-manifest","$","is not valid UTF-8")}let s;try{s=JSON.parse(n)}catch{Ke("invalid-manifest","$","is not valid JSON")}return rR(s)!==n&&Ke("invalid-manifest","$","is not the deterministic publication representation"),s}function BY(e,t){const r=Qr(e,t,"invalid-manifest");Hr(r,["role","digest","bytes","mediaType","archive","expandedBytes","files","parts","path"],t,"invalid-manifest"),r.path!==void 0&&r.archive!==void 0&&Ke("invalid-manifest",`${t}.path`,"an archive expands at the module root; only a single file has a path"),dh(r.bytes,`${t}.bytes`,"invalid-manifest",!0),r.archive!==void 0&&Ef(r.archive,["tar","tar+gzip","zip"],`${t}.archive`),r.expandedBytes!==void 0&&dh(r.expandedBytes,`${t}.expandedBytes`,"invalid-manifest",!0),r.files!==void 0&&dh(r.files,`${t}.files`,"invalid-manifest",!0),r.archive!==void 0&&(r.expandedBytes===void 0||r.files===void 0)&&Ke("invalid-manifest",t,"an archive requires expandedBytes and files bounds");let n;return r.parts!==void 0&&(r.archive!==void 0&&Ke("invalid-manifest",`${t}.parts`,"an archive cannot be parted"),n=Gi(r.parts,`${t}.parts`,4096,"invalid-manifest").map((s,i)=>{const a=Qr(s,`${t}.parts[${i}]`,"invalid-manifest");return Hr(a,["digest","bytes"],`${t}.parts[${i}]`,"invalid-manifest"),dh(a.bytes,`${t}.parts[${i}].bytes`,"invalid-manifest"),a.bytes>p7&&Ke("invalid-manifest",`${t}.parts[${i}].bytes`,`exceeds ${p7}`),{digest:Po(a.digest,`${t}.parts[${i}].digest`,"invalid-manifest"),bytes:a.bytes}}),n.length<2&&Ke("invalid-manifest",`${t}.parts`,"a parted artifact has at least two parts"),n.reduce((s,i)=>s+i.bytes,0)!==r.bytes&&Ke("invalid-manifest",`${t}.parts`,"part sizes must sum to the artifact's bytes")),{role:Sa(r.role,`${t}.role`,"invalid-manifest"),digest:Po(r.digest,`${t}.digest`,"invalid-manifest"),bytes:r.bytes,mediaType:GY(r.mediaType,`${t}.mediaType`,"invalid-manifest"),...r.archive!==void 0?{archive:r.archive}:{},...r.expandedBytes!==void 0?{expandedBytes:r.expandedBytes}:{},...r.files!==void 0?{files:r.files}:{},...n?{parts:n}:{},...r.path!==void 0?{path:VY(r.path,`${t}.path`)}:{}}}function zY(e,t){const r=Qr(e,t,"invalid-manifest");return Hr(r,["slot","coordinate","kind","optional"],t,"invalid-manifest"),r.optional!==void 0&&typeof r.optional!="boolean"&&Ke("invalid-manifest",`${t}.optional`,"must be a boolean"),{slot:Sa(r.slot,`${t}.slot`,"invalid-manifest"),coordinate:Do(r.coordinate,`${t}.coordinate`,"invalid-manifest"),kind:Ef(r.kind,["build","runtime","peer"],`${t}.kind`),...r.optional!==void 0?{optional:r.optional}:{}}}function jY(e,t){const r=Qr(e,"manifest.integration","invalid-manifest");if(t==="node-archive")return Hr(r,["kind","package"],"manifest.integration","invalid-manifest"),r.kind!=="node-archive"&&Ke("invalid-manifest","manifest.integration.kind","must match packKind"),{kind:"node-archive",package:$6(r.package,"manifest.integration.package")};if(t==="browser-module"){Hr(r,["kind","entries","chunks"],"manifest.integration","invalid-manifest"),r.kind!=="browser-module"&&Ke("invalid-manifest","manifest.integration.kind","must match packKind");const o=pg(r.entries,"manifest.integration.entries",512,"invalid-manifest").map(c=>ba(c,"manifest.integration.entries","invalid-manifest")),l=pg(r.chunks,"manifest.integration.chunks",2048,"invalid-manifest").map(c=>ba(c,"manifest.integration.chunks","invalid-manifest"));return o.length===0&&Ke("invalid-manifest","manifest.integration.entries","must not be empty"),Vi(o,"manifest.integration.entries","invalid-manifest"),Vi(l,"manifest.integration.chunks","invalid-manifest"),{kind:"browser-module",entries:o,chunks:l}}Hr(r,["kind","engine","executable","configuration","resourcesRoot","entry"],"manifest.integration","invalid-manifest"),(r.kind!=="program"||r.engine!==t)&&Ke("invalid-manifest","manifest.integration","program engine must match packKind"),t==="emscripten"&&r.entry===void 0&&Ke("invalid-manifest","manifest.integration.entry","is required for Emscripten"),t==="wali"&&r.entry!==void 0&&Ke("invalid-manifest","manifest.integration.entry","is only valid for Emscripten");const n=ZY(r.executable,"manifest.integration.executable","invalid-manifest"),s=r.resourcesRoot!==void 0?sR(r.resourcesRoot,"manifest.integration.resourcesRoot","invalid-manifest"):void 0;s&&!s.startsWith("/opt/")&&Ke("invalid-manifest","manifest.integration.resourcesRoot","live program resources must mount below /opt");const i=r.entry!==void 0?ba(r.entry,"manifest.integration.entry","invalid-manifest"):void 0;let a;try{const o=Qr(r.configuration,"manifest.integration.configuration","invalid-manifest");Hr(o,["displayName","actions","storage","environment","programs","terminal","network","openUrls"],"manifest.integration.configuration","invalid-manifest"),a=Kg({schemaVersion:1,id:"pack",displayName:o.displayName,version:"1",engine:t,artifact:{url:"/pack.wasm",integrity:`sha256-${"A".repeat(43)}=`,license:"pack",redistribution:"cleared"},...s?{resources:{url:"/resources.zip",integrity:`sha256-${"A".repeat(43)}=`,root:s}}:{},...i?{entry:i}:{},executable:n,actions:o.actions,storage:o.storage,environment:o.environment,requirements:{capabilities:[],programs:o.programs},terminal:o.terminal,network:o.network,openUrls:o.openUrls})}catch(o){Ke("invalid-manifest","manifest.integration.configuration",o instanceof Error?o.message:String(o))}return{kind:"program",engine:t,executable:n,configuration:{displayName:a.displayName,actions:a.actions,storage:a.storage,environment:a.environment,programs:a.requirements.programs,terminal:a.terminal,network:a.network,openUrls:a.openUrls},...s?{resourcesRoot:s}:{},...i?{entry:i}:{}}}function WY(e,t){const r=Qr(e,t,"invalid-lock");Hr(r,["id","manifest","buildKey","dependencies","exports"],t,"invalid-lock");const n=Qr(r.dependencies,`${t}.dependencies`,"invalid-lock"),s={};for(const[a,o]of Object.entries(n))if(Sa(a,`${t}.dependencies`,"invalid-lock"),o===null)s[a]=null;else if(typeof o=="string")s[a]=Sa(o,`${t}.dependencies.${a}`,"invalid-lock");else{const l=Qr(o,`${t}.dependencies.${a}`,"invalid-lock");Hr(l,["workspace"],`${t}.dependencies.${a}`,"invalid-lock"),s[a]={workspace:ba(l.workspace,`${t}.dependencies.${a}.workspace`,"invalid-lock")}}const i=Gi(r.exports,`${t}.exports`,512,"invalid-lock").map((a,o)=>{const l=`${t}.exports[${o}]`,c=Qr(a,l,"invalid-lock");return Hr(c,["name","path"],l,"invalid-lock"),{name:Sa(c.name,`${l}.name`,"invalid-lock"),path:sR(c.path,`${l}.path`,"invalid-lock")}});return Vi(i.map(a=>a.path),`${t}.exports paths`,"invalid-lock"),{id:Sa(r.id,`${t}.id`,"invalid-lock"),manifest:Po(r.manifest,`${t}.manifest`,"invalid-lock"),buildKey:Do(r.buildKey,`${t}.buildKey`,"invalid-lock"),dependencies:s,exports:i}}function HY(e,t){const r=Qr(e,"lock.layout","invalid-lock");Hr(r,["packages","bins","aliases","entries"],"lock.layout","invalid-lock");const n=Gi(r.packages,"lock.layout.packages",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.packages[${u}]`,p=Qr(c,d,"invalid-lock");Hr(p,["path","node"],d,"invalid-lock");const m=Sa(p.node,`${d}.node`,"invalid-lock");return t.has(m)||Ke("unresolved-graph",`${d}.node`,`references missing node ${m}`),{path:ba(p.path,`${d}.path`,"invalid-lock"),node:m}}),s=Gi(r.bins,"lock.layout.bins",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.bins[${u}]`,p=Qr(c,d,"invalid-lock");return Hr(p,["path","target"],d,"invalid-lock"),{path:ba(p.path,`${d}.path`,"invalid-lock"),target:ba(p.target,`${d}.target`,"invalid-lock")}}),i=Gi(r.aliases,"lock.layout.aliases",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.aliases[${u}]`,p=Qr(c,d,"invalid-lock");return Hr(p,["path","target","coordinate"],d,"invalid-lock"),{path:ba(p.path,`${d}.path`,"invalid-lock"),target:ba(p.target,`${d}.target`,"invalid-lock"),coordinate:Do(p.coordinate,`${d}.coordinate`,"invalid-lock")}}),a=Gi(r.entries,"lock.layout.entries",1e5,"invalid-lock").map((c,u)=>{const d=`lock.layout.entries[${u}]`,p=Qr(c,d,"invalid-lock");return Hr(p,["path","digest"],d,"invalid-lock"),{path:ba(p.path,`${d}.path`,"invalid-lock"),digest:Po(p.digest,`${d}.digest`,"invalid-lock")}});for(const[c,u]of[["packages",n.map(d=>d.path)],["bins",s.map(d=>d.path)],["aliases",i.map(d=>d.path)],["entries",a.map(d=>d.path)]])Vi(u,`lock.layout.${c} paths`,"export-conflict");const o=[...n.map(c=>c.path),...s.map(c=>c.path),...i.map(c=>c.path),...a.map(c=>c.path)];Vi(o,"lock.layout destinations","export-conflict");const l=new Map;for(const c of i){const u=l.get(c.target);u!==void 0&&u!==c.coordinate&&Ke("unresolved-graph","lock.layout.aliases",`${c.target} has conflicting coordinates`),l.set(c.target,c.coordinate)}return{packages:n,bins:s,aliases:i,entries:a}}function N6(e,t,r,n,s){e.kind!==t&&Ke(s,`${n}.kind`,`must be ${t}`),e.version!==r&&Ke("unsupported-schema",`${n}.version`,`unsupported version ${String(e.version)}`)}function xv(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||Ke("invalid-manifest",t,"contains a non-finite number"),e;if(Array.isArray(e))return e.map((n,s)=>xv(n,`${t}[${s}]`));typeof e!="object"&&Ke("invalid-manifest",t,"contains an unsupported value"),Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null&&Ke("invalid-manifest",t,"must contain only plain JSON objects");const r={};for(const n of Object.keys(e).sort())r[n]=xv(e[n],`${t}.${n}`);return r}function Qr(e,t,r){return(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)&&Ke(r,t,"must be a plain object"),e}function Gi(e,t,r,n){return(!Array.isArray(e)||e.length>r)&&Ke(n,t,`must be an array of at most ${r} entries`),e}function Hr(e,t,r,n){const s=new Set(t),i=Object.keys(e).filter(a=>!s.has(a));i.length>0&&Ke(n,r,`has unknown fields: ${i.join(", ")}`)}function mi(e,t,r,n){return(typeof e!="string"||e.length<1||e.length>r||/[\u0000\r\n]/u.test(e))&&Ke(n,t,"must be a non-empty bounded string"),e}function Sa(e,t,r){const n=mi(e,t,128,r);return/^[a-z][a-z0-9._-]*$/u.test(n)||Ke(r,t,"must be a lowercase identifier"),n}function $6(e,t){const r=mi(e,t,214,"invalid-manifest");return/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/u.test(r)||Ke("invalid-manifest",t,"must be a normalized package name"),r}function Do(e,t,r){const n=mi(e,t,512,r);return/^[A-Za-z0-9][A-Za-z0-9._/+@:=,-]*$/u.test(n)||Ke(r,t,"contains unsupported characters"),n}function Po(e,t,r){return(typeof e!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e))&&Ke(r,t,"must be a sha256:<64 lowercase hex> digest"),e}function qY(e,t){return/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/u.test(e)||Ke("invalid-manifest",t,`invalid capability ${e}`),e}function GY(e,t,r){const n=mi(e,t,128,r);return/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/u.test(n)||Ke(r,t,"must be a lowercase media type"),n}function nR(e,t,r){const n=mi(e,t,2048,r);let s;try{s=new URL(n)}catch{Ke(r,t,"must be an HTTPS URL")}return(s.protocol!=="https:"||s.username||s.password||s.hash)&&Ke(r,t,"must be an HTTPS URL without credentials or fragment"),n}function VY(e,t){const r=ba(e,t,"invalid-manifest");return/[?#]|%2e/iu.test(r)&&Ke("invalid-manifest",t,"must not contain a query, a fragment or an encoded dot"),r}function ba(e,t,r){const n=mi(e,t,1024,r);return(n.startsWith("/")||n.includes("\\")||n.split("/").some(s=>s===""||s==="."||s===".."))&&Ke(r,t,"must be a normalized relative path"),n}function sR(e,t,r){const n=mi(e,t,1024,r);return(!n.startsWith("/")||n==="/"||n.includes("\\")||n.split("/").slice(1).some(s=>s===""||s==="."||s===".."))&&Ke(r,t,"must be a normalized non-root absolute path"),n}function ZY(e,t,r){const n=mi(e,t,128,r);return/^[A-Za-z0-9._+-]+$/u.test(n)||Ke(r,t,"must be a command name"),n}function pg(e,t,r,n){const s=Gi(e,t,r,n);return s.some(i=>typeof i!="string")&&Ke(n,t,"must contain only strings"),s}function Vi(e,t,r){new Set(e).size!==e.length&&Ke(r,t,"must not contain duplicates")}function dh(e,t,r,n=!1){(!Number.isSafeInteger(e)||e<(n?0:1))&&Ke(r,t,`must be a safe integer ${n?"at least zero":"greater than zero"}`)}function Ef(e,t,r){return(typeof e!="string"||!t.includes(e))&&Ke("invalid-manifest",r,`must be one of ${t.join(", ")}`),e}function Ke(e,t,r){throw new eR(e,t,r)}function Qg(e){if(e&&typeof e=="object"){Object.freeze(e);for(const t of Object.values(e))Qg(t)}return e}class g7{#t;#r;#s;#e;#n;#c;constructor(t){t.endpoints.length===0&&Pr("invalid-manifest","catalog.endpoints","must not be empty"),this.#t=t.endpoints.map(n=>({...n,baseUrl:XY(n.baseUrl,t.allowInsecureLocalhost===!0)})),this.#r=new Set(t.trustedOrigins.map(n=>new URL(n).origin)),this.#s=t.pinnedCatalog,this.#e=t.deniedDigests??new Map;const r=t.fetch??globalThis.fetch.bind(globalThis);this.#n=(n,s)=>r(n,s),this.#c=t.allowInsecureLocalhost===!0;for(const n of this.#t)this.#a(new URL(n.baseUrl),"catalog.endpoints")}async selectExact(t,r,n){const{catalog:s,digest:i}=await this.catalog(),a=s.entries.find(u=>u.name===t&&u.buildKey===r);a||Pr("catalog-miss","catalog.entries",`has no exact build ${t}/${r}`),a.state==="withdrawn"&&Pr("withdrawn","catalog.entries",a.withdrawalReason??`${t}/${r} is withdrawn`),a.state!=="measured"&&Pr("catalog-miss","catalog.entries",`${t}/${r} is a candidate, not a measured build`),this.#l(a.manifest,"catalog.entry.manifest"),this.#l(a.closure,"catalog.entry.closure");const o=Pb(await this.#o("manifests",a.manifest));y7(a,o),vv(o,n);const l=m7(await this.#o("locks",a.closure));l.nodes.some(u=>u.manifest===a.manifest)||Pr("unresolved-graph","catalog.entry.closure","does not contain its selected manifest");const c=await this.#u(l,new Map([[a.manifest,o]]));return{catalog:s,catalogDigest:i,entry:a,manifest:o,manifests:c,closure:l}}async catalog(){let t=this.#s;if(!t){const n=await this.#i("pointer","/v1/catalog.json",this.#t.slice(0,1),"application/json");let s;try{s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{Pr("invalid-manifest","catalog.pointer","is not valid UTF-8 JSON")}t=YY(s).catalog}return this.#l(t,"catalog.digest"),{catalog:PY(await this.#o("catalogs",t)),digest:t}}async restorePinned(t,r,n){this.#l(t,"restore.manifest"),this.#l(r,"restore.closure");const{catalog:s,digest:i}=await this.catalog(),a=s.entries.find(d=>d.manifest===t&&d.closure===r),o=[];a?a.state==="withdrawn"?o.push(`Pinned build is withdrawn: ${a.withdrawalReason??"no reason supplied"}`):a.state==="candidate"&&o.push("Pinned build is only a candidate, not a measured catalog entry."):o.push(`Pinned build ${t}/${r} is no longer listed; repairing exact retained bytes only.`);const l=Pb(await this.#o("manifests",t));a&&y7(a,l),vv(l,n);const c=m7(await this.#o("locks",r));c.nodes.some(d=>d.manifest===t)||Pr("unresolved-graph","restore.closure","does not contain the pinned manifest");const u=await this.#u(c,new Map([[t,l]]));return{catalog:s,catalogDigest:i,manifest:l,manifests:u,closure:c,warnings:o}}async artifact(t){this.#l(t.digest,`artifact.${t.role}`);const r=await this.#i("artifact",Ub("artifacts",t.digest),this.#t,t.mediaType);r.byteLength!==t.bytes&&Pr("integrity-failure",`artifact.${t.role}.bytes`,`expected ${t.bytes}, received ${r.byteLength}`);const n=await hg(r);return n!==t.digest&&Pr("integrity-failure",`artifact.${t.role}.digest`,`expected ${t.digest}, received ${n}`),r}async artifactPart(t,r){const n=t.parts?.[r];n||Pr("invalid-manifest",`artifact.${t.role}.parts[${r}]`,"is not declared"),this.#l(t.digest,`artifact.${t.role}`),this.#l(n.digest,`artifact.${t.role}.parts[${r}]`);const s=`artifact.${t.role}.parts[${r}]`,i=await this.#i(s,Ub("artifacts",n.digest),this.#t,tR);i.byteLength!==n.bytes&&Pr("integrity-failure",`${s}.bytes`,`expected ${n.bytes}, received ${i.byteLength}`);const a=await hg(i);return a!==n.digest&&Pr("integrity-failure",`${s}.digest`,`expected ${n.digest}, received ${a}`),i}async#o(t,r){const n=await this.#i(t,Ub(t,r),this.#t,"application/json");return FY(n,r)}async#u(t,r){const n=[...new Set(t.nodes.map(s=>s.manifest))].filter(s=>!r.has(s));return await Promise.all(n.map(async s=>{r.set(s,Pb(await this.#o("manifests",s)))})),r}async#i(t,r,n,s){let i=!1;for(const a of n){let o=new URL(r.replace(/^\/+/u,""),a.baseUrl);for(let l=0;l<=3;l+=1){this.#a(o,t);const c=new URL(a.baseUrl).origin,u=o.origin===c?await a.authorization?.():void 0;let d;try{d=await this.#n(o,{redirect:"manual",headers:{accept:s,...u?{authorization:u}:{}}})}catch{break}if([301,302,303,307,308].includes(d.status)){const b=d.headers.get("location");b||Pr("unavailable-artifact",t,"redirect has no location"),o=new URL(b,o);continue}if(d.status===401||d.status===403){i=!0;break}if(d.status===404)break;d.ok||Pr("unavailable-artifact",t,`request failed with HTTP ${d.status}`);const p=d.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase();p!==s&&Pr("integrity-failure",t,`expected content-type ${s}, received ${p??"none"}`);const m=new Uint8Array(await d.arrayBuffer()),g=d.headers.get("content-length");return(g===null||Number(g)!==m.byteLength)&&Pr("integrity-failure",t,`partial response: declared ${g??"none"}, received ${m.byteLength}`),m}}i&&Pr("authentication-failure",t,"catalog credentials were refused"),Pr("unavailable-artifact",t,`content is unavailable at every configured endpoint: ${r}`)}#a(t,r){(!(this.#c&&t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname))&&t.protocol!=="https:"||!this.#r.has(t.origin))&&Pr("denied-origin",r,`origin is not trusted: ${t.origin}`)}#l(t,r){const n=this.#e.get(t);n&&Pr("withdrawn",r,`security policy denies ${t}: ${n}`)}}function Ub(e,t){/^sha256:[a-f0-9]{64}$/u.test(t)||Pr("invalid-manifest","digest","must be sha256:<64 lowercase hex>");const r=t.slice(7);return`/v1/${e}/sha256/${r}${e==="artifacts"?"":".json"}`}function YY(e){(!e||typeof e!="object"||Array.isArray(e))&&Pr("invalid-manifest","catalog.pointer","must be an object");const t=e;return(Object.keys(t).some(r=>!["kind","version","catalog"].includes(r))||t.kind!=="browser-substrate.pack-catalog-pointer"||t.version!==1||typeof t.catalog!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.catalog))&&Pr("invalid-manifest","catalog.pointer","has an unsupported shape"),t}function XY(e,t){let r;try{r=new URL(e)}catch{Pr("invalid-manifest","catalog.endpoints","base URL is invalid")}return(!(t&&r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname))&&r.protocol!=="https:"||r.username||r.password||r.search||r.hash)&&Pr("denied-origin","catalog.endpoints","base URL must be HTTPS without credentials, query or fragment"),`${r.origin}${r.pathname.replace(/\/+$/u,"")}/`}function y7(e,t){const r=[e.name===t.name?void 0:`name ${e.name}/${t.name}`,e.upstreamVersion===t.upstreamVersion?void 0:`upstreamVersion ${e.upstreamVersion}/${t.upstreamVersion}`,e.packKind===t.packKind?void 0:`packKind ${e.packKind}/${t.packKind}`,e.buildKey===t.buildKey?void 0:`buildKey ${e.buildKey}/${t.buildKey}`].filter(n=>n!==void 0);r.length>0&&Pr("invalid-manifest","catalog.entry",`does not describe its pinned manifest: ${r.join(", ")}`)}function Pr(e,t,r){throw new eR(e,t,r)}class b7 extends Error{category;constructor(t,r){super(r),this.category=t,this.name="BrowserPackArchiveError"}}new TextDecoder("utf-8",{fatal:!0});class vn extends Error{category;constructor(t,r){super(r),this.category=t,this.name="BrowserPackInstallError"}}class KY{persistence;store;concurrency;retries;#t=new Map;constructor(t,r,n=4,s=2){this.persistence=t,this.store=r,this.concurrency=n,this.retries=s}async plan(t){if(await Fm(t.lock)!==t.lockDigest)throw new Error(`Environment lock bytes do not match ${t.lockDigest}.`);for(const[u,d]of t.manifests)if(await Fm(d)!==u)throw new Error(`Pack manifest bytes do not match ${u}.`);UY(t.lock,t.manifests,t.profile);const r=await this.persistence.environment(t.environment),n=v7(w7(t.lock,t.manifests)),s=[];for(const u of n)await this.store.has(u.artifact.digest)||s.push(u);const i=s.reduce((u,d)=>u+d.artifact.bytes+(d.part?0:d.artifact.expandedBytes??d.artifact.bytes),0),a=await this.store.availableBytes?.();if(a!==void 0&&i>a)throw new vn("quota-exceeded",`Install needs ${i} bytes including staging; ${a} are available.`);const o=await Fm({verb:t.verb??"install",lock:t.lockDigest,environment:t.environment}),l=await this.persistence.operation(t.environment,t.operationId);if(l){if(l.request!==o)throw new vn("operation-conflict",`Operation ${t.operationId} was already used for another request.`);return l}const c={environment:t.environment,id:t.operationId,request:o,verb:t.verb??"install",phase:"plan",...r.active?{baseRevision:r.active.revision}:{},targetRevision:QY(t.lockDigest),lock:t.lockDigest,bytes:i,completedBytes:0,committed:!1};return await this.persistence.saveOperation(c),t.onProgress?.(c),c}async install(t){const r=`${t.environment}/${t.operationId}`,n=this.#t.get(r);if(n)return n;const s=this.executeInstall(t);this.#t.set(r,s);try{return await s}finally{this.#t.get(r)===s&&this.#t.delete(r)}}async executeInstall(t){let r=await this.plan(t);if(C1(r))return r;try{cc(t.signal),r=await this.advance(r,"authorize",t);for(const m of t.manifests.values())await t.authorize(m);cc(t.signal);const n=v7(w7(t.lock,t.manifests)),s=n.map(m=>m.artifact);r=await this.advance(r,"fetch",t);for(const m of n){if(!m.part||await this.store.has(m.artifact.digest))continue;if(cc(t.signal),!t.fetchArtifactPart)throw new vn("recovery-failure",`Artifact ${m.part.of.digest} is parted and this catalog cannot fetch parts.`);const g=await S7(this.retries,t.signal,()=>t.fetchArtifactPart(m.part.of,m.part.index,t.signal));if(g.byteLength!==m.artifact.bytes||await x7(g)!==m.artifact.digest)throw new Error(`Part ${m.part.index} of artifact ${m.part.of.digest} failed exact byte verification.`);await this.store.stageArtifact(m.artifact.digest,g,m.artifact,t.signal),r.completedBytes+=g.byteLength,await this.persistence.saveOperation(r),t.onProgress?.({...r})}const i=new Map;await JY(n.filter(m=>!m.part).map(m=>m.artifact),this.concurrency,async m=>{if(await this.store.has(m.digest))return;const g=await S7(this.retries,t.signal,()=>t.fetchArtifact(m,t.signal));i.set(m.digest,g),r.completedBytes+=g.byteLength,await this.persistence.saveOperation(r),t.onProgress?.({...r})}),cc(t.signal),r=await this.advance(r,"verify",t);for(const m of s){const g=i.get(m.digest);if(!g)continue;if(await x7(g)!==m.digest||g.byteLength!==m.bytes)throw new Error(`Artifact ${m.digest} failed exact byte verification.`)}cc(t.signal),r=await this.advance(r,"stage",t);for(const m of s){const g=i.get(m.digest);g&&await this.store.stageArtifact(m.digest,g,m,t.signal)}if(await this.store.stageEnvironment(t.lockDigest,t.lock),await this.store.retainEnvironment?.(t.lockDigest,s),t.verb==="offline"){const m={...r,phase:"installed",committed:!1};return await this.persistence.saveOperation(m),t.onProgress?.(m),m}cc(t.signal),r=await this.advance(r,"activate",t);const a=await this.persistence.environment(t.environment),o=r.baseRevision,l={revision:r.targetRevision,lock:t.lockDigest};if(a.active?.revision===l.revision&&a.active.lock===l.lock){const m={...r,phase:"installed",committed:!0};return await this.persistence.saveOperation(m),t.onProgress?.(m),m}const c=a.active&&!a.retained.some(m=>m.revision===a.active.revision)?[...a.retained,a.active]:a.retained,u={...r,committed:!0};if(!await this.persistence.compareAndSwap(t.environment,o,{active:l,retained:c},u)){const m=await this.persistence.operation(t.environment,t.operationId);if(m?.request===r.request&&m.committed){const g={...m,phase:"installed"};return await this.persistence.saveOperation(g),g}throw new vn("revision-conflict","The environment revision changed; re-plan against the new active revision.")}const p={...u,phase:"installed"};return await this.persistence.saveOperation(p),t.onProgress?.(p),p}catch(n){if(r.committed)return{...r,phase:"installed"};const s=n instanceof vn&&n.category==="cancellation"||n instanceof b7&&n.category==="cancellation",i=n instanceof vn||n instanceof b7?n.category:"install-failure",a={...r,phase:s?"cancelled":"failed",error:{category:i,message:n instanceof Error?n.message:String(n)}};return await this.persistence.saveOperation(a),t.onProgress?.(a),a}}async inspect(t){return this.persistence.environment(t)}async rollback(t,r,n){const s=await this.persistence.environment(t),i=s.retained.find(a=>a.revision===n);if(!i)throw new vn("recovery-failure",`Retained revision ${n} is unavailable.`);return this.switchRevision(t,r,"rollback",s,i,s.active?[...s.retained.filter(a=>a.revision!==n),s.active]:s.retained.filter(a=>a.revision!==n))}async remove(t,r){const n=await this.persistence.environment(t);if(!n.active)throw new vn("recovery-failure","The environment has no active revision.");return this.switchRevision(t,r,"remove",n,void 0,[...n.retained,n.active])}async recover(t,r){const n=await this.persistence.operation(t,r);if(!n)throw new vn("recovery-failure",`Operation ${r} has no recovery record.`);if(C1(n))return n;const s=await this.persistence.environment(t);if(n.targetRevision&&s.active?.revision===n.targetRevision){const a={...n,phase:"installed",committed:!0};return await this.persistence.saveOperation(a),a}const i={...n,phase:"failed",committed:!1,error:{category:"recovery-failure",message:"Recovered the previous complete revision; staged content was not activated."}};return await this.persistence.saveOperation(i),i}async advance(t,r,n){const s={...t,phase:r};return await this.persistence.saveOperation(s),n.onProgress?.(s),s}async switchRevision(t,r,n,s,i,a){const o=await Fm({environment:t,verb:n,...i?{active:i}:{}}),l=await this.persistence.operation(t,r);if(l){if(l.request!==o)throw new vn("operation-conflict",`Operation ${r} was already used.`);if(C1(l))return l}const c={environment:t,id:r,request:o,verb:n,phase:"activate",...s.active?{baseRevision:s.active.revision}:{},...i?{targetRevision:i.revision,lock:i.lock}:{},bytes:0,completedBytes:0,committed:!0};if(!await this.persistence.compareAndSwap(t,s.active?.revision,{...i?{active:i}:{},retained:a},c))throw new vn("revision-conflict","The environment revision changed; re-plan the operation.");const d={...c,phase:"installed"};return await this.persistence.saveOperation(d),d}}function w7(e,t){const r=new Map;for(const n of e.nodes)for(const s of t.get(n.manifest)?.artifacts??[])r.set(s.digest,s);return[...r.values()]}function v7(e){const t=new Map;for(const r of e){if(!r.parts){t.set(r.digest,{artifact:r});continue}r.parts.forEach((n,s)=>{t.has(n.digest)||t.set(n.digest,{artifact:{role:`${r.role}-part-${s}`,digest:n.digest,bytes:n.bytes,mediaType:tR},part:{of:r,index:s}})})}return[...t.values()]}async function x7(e){const t=await crypto.subtle.digest("SHA-256",new Uint8Array(e));return`sha256:${[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}`}function QY(e){return`revision-${e.slice(7)}`}function C1(e){return e.phase==="installed"||e.phase==="failed"||e.phase==="cancelled"}function cc(e){if(e?.aborted)throw new vn("cancellation","Installation was cancelled before activation.")}async function S7(e,t,r){let n;for(let s=0;s<=e;s+=1){cc(t);try{return await r()}catch(i){n=i}}throw n}async function JY(e,t,r){let n=0;await Promise.all(Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;n<e.length;){const s=n++;await r(e[s])}}))}class eX{databaseName;constructor(t="browser-substrate-pack-installs"){this.databaseName=t}async environment(t){return await this.get("environments",t)??{retained:[]}}async operation(t,r){return this.get("operations",`${t}/${r}`)}async saveOperation(t){const r=await this.open();try{await new Promise((n,s)=>{const i=r.transaction("operations","readwrite"),a=i.objectStore("operations"),o=`${t.environment}/${t.id}`,l=a.get(o);l.onsuccess=()=>{const c=l.result;(!c||!c.committed&&!C1(c)||c.committed&&t.committed&&t.phase==="installed")&&a.put(t,o)},i.oncomplete=()=>n(),i.onerror=()=>s(i.error??new Error("Pack install persistence failed."))})}finally{r.close()}}async compareAndSwap(t,r,n,s){const i=await this.open();try{return await new Promise((a,o)=>{const l=i.transaction(["environments","operations"],"readwrite"),c=l.objectStore("environments"),u=c.get(t);let d=!1;u.onsuccess=()=>{u.result?.active?.revision===r&&(d=!0,c.put(n,t),l.objectStore("operations").put(s,`${t}/${s.id}`))},l.oncomplete=()=>a(d),l.onerror=()=>o(l.error??new Error("Pack install persistence failed.")),l.onabort=()=>o(l.error??new Error("Pack install persistence was aborted."))})}finally{i.close()}}async get(t,r){const n=await this.open();try{return await new Promise((s,i)=>{const o=n.transaction(t,"readonly").objectStore(t).get(r);o.onsuccess=()=>s(o.result),o.onerror=()=>i(o.error)})}finally{n.close()}}async put(t,r,n){const s=await this.open();try{await new Promise((i,a)=>{const o=s.transaction(t,"readwrite");o.objectStore(t).put(n,r),o.oncomplete=()=>i(),o.onerror=()=>a(o.error??new Error("Pack install persistence failed."))})}finally{s.close()}}open(){return new Promise((t,r)=>{const n=indexedDB.open(this.databaseName,1);n.onupgradeneeded=()=>{for(const s of["environments","operations"])n.result.objectStoreNames.contains(s)||n.result.createObjectStore(s)},n.onsuccess=()=>{n.result.onversionchange=()=>n.result.close(),t(n.result)},n.onerror=()=>r(n.error??new Error("Pack install database failed to open.")),n.onblocked=()=>r(new Error("Pack install database is blocked by another tab."))})}}const Sv=".browser-program-archives";function tX(e){if(e.length===0)throw new Error("A program's layer names at least one archive.");return`/packages/.programs/${e.map(r=>{const n=/^sha256-([A-Za-z0-9+/]{43}=)$/u.exec(r);if(!n)throw new Error(`A program archive's integrity is not a SHA-256: ${r}`);return[...atob(n[1])].map(s=>s.charCodeAt(0).toString(16).padStart(2,"0")).join("")}).join("-")}`}function rX(e){return`${e.join(`
61
61
  `)}
62
62
  `}const Fb=new Map;function nX(e,t,r={}){const n=t.resources;if(n)return Wh(e,n.root,r.url??n.url,r.integrity??n.integrity,r)}const sX=Sv;function Wh(e,t,r,n,s={}){const i=`${t}
63
63
  ${n}`;let a=Fb.get(i);return a||(a=iX(e,t,r,n,s).catch(o=>{throw Fb.delete(i),o}),Fb.set(i,a)),a}async function iX(e,t,r,n,s){const i=Date.now(),a=`${t.replace(/\/+$/u,"")}/${sX}`,o=e.existsSync(a)?(await e.readFile(a,"utf8")).split(`
@@ -1712,7 +1712,7 @@ ${u}`:u,n)}if(!n.terminal){const o=await U1e(n.stdinStream,n.stdin);return o.tri
1712
1712
  # git-remote-https: runtime-registered program
1713
1713
  `),e.filesystem.chmodSync?.(i,493));const a=t.share===!1?void 0:new GK(e);a&&e.registerProgram("share",a.run);const o=F1e((l,c)=>e.spawn(l,c),l=>e.filesystem.readFile(l,"utf8").catch(()=>{}));e.filesystem.mkdirSync("/bin",{recursive:!0});for(const l of["sh","bash"]){e.registerProgram(l,o);const c=`/bin/${l}`;e.filesystem.existsSync(c)||(e.filesystem.writeFileSync(c,`#!/bin/sh
1714
1714
  # ${l}: runtime-registered program
1715
- `),e.filesystem.chmodSync?.(c,493))}return{shell:r,...a?{share:a}:{},dispose:()=>a?.close()}}const bF="browser-substrate-volter-sign-in",ege="/api/auth/volter/authorize",tge="/api/auth/volter/callback",rge="/api/auth/volter/token",nge="/api/auth/volter/refresh",sge="openid profile email offline_access",ige=300*1e3,age=16*1024;let Zu;async function oge(e=location.origin){const n=(await(await fetch(new URL("/api/ready",e),{credentials:"omit"})).json().catch(()=>({}))).capabilities?.identity;return typeof n?.issuer=="string"&&typeof n.clientId=="string"?{issuer:n.issuer,clientId:n.clientId}:void 0}function lge(e,t={}){if(Zu)return vT(Zu.url),Zu.done;const r=new URL(t.gateway??location.origin).origin,n=`${location.origin}${location.pathname}`,s=r===location.origin?crypto.randomUUID():`${crypto.randomUUID()}.${zx(new TextEncoder().encode(n))}`,i=zx(crypto.getRandomValues(new Uint8Array(48))),a=vT("about:blank"),o=new BroadcastChannel(bF),l=(async()=>{const c=await fge(i),u=new URL(ege,r);u.search=new URLSearchParams({client_id:e.clientId,response_type:"code",redirect_uri:new URL(tge,r).href,scope:sge,state:s,code_challenge:c,code_challenge_method:"S256",...t.provider?{provider:t.provider}:{}}).toString();const d=new Promise(m=>{o.onmessage=g=>{g.data?.state===s&&m(g.data)}});Zu.url=u.href,a.location.href=u.href;const p=await d;if(!p.code)throw new Error(p.error??"Volter returned no code");return wF(r,rge,{code:p.code,code_verifier:i})})().finally(()=>{o.close(),Zu=void 0});return l.catch(()=>{try{a.location.href==="about:blank"&&a.close()}catch{}}),Zu={state:s,url:"",done:l},l}function cge(){const e="#volter-sign-in=";if(!location.hash.startsWith(e))return!1;let t;try{t=JSON.parse(decodeURIComponent(location.hash.slice(e.length)))}catch{return!1}history.replaceState(null,"",`${location.pathname}${location.search}`);const r=new BroadcastChannel(bF);return r.postMessage(t),r.close(),document.body.textContent=t.error?`Sign-in did not complete: ${t.error}`:"Signed in. You can close this window.",t.error||setTimeout(()=>window.close(),300),!0}function uge(e,t={}){return e.refreshToken?wF(new URL(t.gateway??location.origin).origin,nge,{refresh_token:e.refreshToken}):Promise.reject(new Error("The sign-in cannot be renewed; sign in again."))}async function wF(e,t,r){const n=await fetch(new URL(t,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),credentials:"omit",signal:AbortSignal.timeout(3e4)}),s=await n.json().catch(()=>({}));if(!n.ok||!s.access_token)throw new Error(s.error?.message??`The gateway answered ${n.status}.`);const i=wT(s.id_token??s.access_token);if(typeof i.sub!="string")throw new Error("The sign-in named no one.");const a=wT(s.access_token),o=l=>typeof i[l]=="string"?i[l]:typeof a[l]=="string"?a[l]:void 0;return{accessToken:s.access_token,...s.refresh_token?{refreshToken:s.refresh_token}:{},expiresAt:Date.now()+(s.expires_in??3600)*1e3,subject:i.sub,...o("name")?{name:o("name")}:{},...o("email")?{email:o("email")}:{},...o("https://volter.ai/github_login")?{githubLogin:o("https://volter.ai/github_login")}:{}}}function wT(e){try{const t=e.split(".")[1]??"";return JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(t.replace(/-/gu,"+").replace(/_/gu,"/")),r=>r.charCodeAt(0))))}catch{return{}}}async function fge(e){return zx(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))))}function zx(e){return btoa(String.fromCharCode(...e)).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function vT(e){const t=window.open(e,"browser-substrate-volter-sign-in","popup,width=520,height=720");if(!t)throw new Error("the browser blocked the sign-in window; allow pop-ups for this page and press Sign in again");return t}class dge{vault;options;constructor(t,r={}){this.vault=t,this.options=r}load(){return this.lock(async()=>{const t=await this.read();if(t?.rotationId){await this.vault.clear();return}return t&&xT(t)})}current(){return this.lock(async()=>{const t=await this.read();if(!t)return;if(t.rotationId){await this.vault.clear();return}const r=xT(t);if(r.expiresAt-ige>Date.now())return r;if(!r.refreshToken){await this.vault.clear();return}await this.write(r,crypto.randomUUID());let n;try{n=await uge(r,this.options.gateway?{gateway:this.options.gateway}:{})}catch{await this.vault.clear();return}return await this.write(n),n})}save(t){return this.lock(()=>this.write(t))}clear(){return this.lock(()=>this.vault.clear())}async read(){const t=await this.vault.load();if(t)try{const r=JSON.parse(new TextDecoder().decode(t));return r.version!==1||typeof r.accessToken!="string"||typeof r.subject!="string"||typeof r.expiresAt!="number"?void 0:r}catch{return}}async write(t,r){const n={...t,version:1,savedAt:Date.now(),...r?{rotationId:r}:{}},s=new TextEncoder().encode(JSON.stringify(n));if(s.byteLength>age)throw new Error("The Volter session record is unexpectedly large.");await this.vault.save(s,{backup:"current"})}async lock(t){if(this.options.lock)return this.options.lock(t);if(!globalThis.navigator?.locks)throw new Error("Volter session storage requires browser Web Locks.");return await navigator.locks.request("browser-substrate-volter-session",t)}}function xT(e){const{version:t,savedAt:r,rotationId:n,...s}=e;return s}function hge(e){const t=e;if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.url!="string"||!t.url.startsWith("/substrate/")||typeof t.digest!="string"||!/^[0-9a-f]{16,64}$/u.test(t.digest)||!Number.isSafeInteger(t.parts)||!Number.isSafeInteger(t.units)||!Number.isSafeInteger(t.bytes))throw new Error("The image manifest's layers block is malformed.");const r=t.prepared;if(r&&(typeof r.url!="string"||!r.url.startsWith("/substrate/")||r.url.split("/").includes("..")||typeof r.digest!="string"||!/^[a-f0-9]{64}$/u.test(r.digest)||r.project!==void 0&&r.project!==!0||r.files!==void 0&&(!Array.isArray(r.files)||r.files.length>4||!r.files.every(n=>n!==null&&typeof n=="object"&&typeof n.url=="string"&&/^\/substrate\/[A-Za-z0-9._-]+\.layers\/[a-f0-9]{64}\.bin$/u.test(n.url)&&Number.isSafeInteger(n.bytes)&&n.bytes>=0&&Number.isSafeInteger(n.raw)&&n.raw>=0&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/u.test(n.sha256)))))throw new Error("Malformed prepared layers descriptor.");return{url:t.url,digest:t.digest,parts:t.parts,units:t.units,bytes:t.bytes,...r?{prepared:r}:{}}}function pge(e){const t=e;if(typeof t!="object"||t===null||typeof t.url!="string"||!t.url.startsWith("/substrate/")||t.url.split("/").includes("..")||!Number.isSafeInteger(t.entries)||!Number.isSafeInteger(t.bytes))throw new Error("The image manifest's caches block is malformed.");return{url:t.url,entries:t.entries,bytes:t.bytes}}function mge(e){const t=e?.entries;if(!Array.isArray(t))throw new Error("The image's caches document is malformed.");for(const r of t)if(!r||typeof r.cache!="string"||r.cache.length===0||r.cache.length>256||typeof r.url!="string"||!r.url.startsWith("/")||r.url.startsWith("//")||!Number.isSafeInteger(r.status)||r.status<200||r.status>299||!Array.isArray(r.headers)||r.headers.some(n=>!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")||!Number.isSafeInteger(r.bytes)||typeof r.sha256!="string"||!/^[0-9a-f]{64}$/u.test(r.sha256)||typeof r.file!="string"||!r.file.startsWith("/substrate/")||r.file.split("/").includes(".."))throw new Error("The image's caches document has a malformed entry.");return t}function gge(e){const t=e;if(typeof t!="object"||t===null||typeof t.url!="string"||!t.url.startsWith("/substrate/")||t.url.split("/").includes("..")||!Number.isSafeInteger(t.files)||!Number.isSafeInteger(t.bytes))throw new Error("The image manifest's warm block is malformed.");return{url:t.url,files:t.files,bytes:t.bytes}}function yge(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("The image manifest's packs block is malformed.");const t=e;if(typeof t.url!="string"||!Number.isInteger(t.count))throw new Error("The image manifest's packs block is malformed.");if(t.digest!==void 0&&typeof t.digest!="string")throw new Error("The image manifest's packs block is malformed.");return{url:t.url,count:t.count,...typeof t.digest=="string"?{digest:t.digest}:{}}}const ST=new WeakMap;function bge(e,t){const r=e,n=ST.get(e);if(n){n.jar=t;return}if(typeof r.handleServiceWorkerMessage!="function"||typeof r.handleRequest!="function")throw new Error("The installed tabnode port bridge changed; update the cookie jar adapter.");if(r.messageChannel||r.serviceWorkerReady)throw new Error("Attach the cookie jar before the service worker is initialized: the bridge has bound its message handler.");const s={jar:t};ST.set(e,s);const i=new WeakMap,a=r.handleServiceWorkerMessage,o=r.handleRequest,l=r.handleStreamingRequest,c=d=>globalThis.isSecureContext===!0||Rj(d);r.handleServiceWorkerMessage=d=>{const p=d?.data,m=p?.data;if(p?.type==="request"&&m&&typeof m.url=="string"&&m.headers&&typeof m.headers=="object"&&!Array.isArray(m.headers)){const g={};for(const[E,A]of Object.entries(m.headers))E.toLowerCase()!=="cookie"&&(g[E]=A);const b=Object.keys(g).find(E=>E.toLowerCase()==="host"),v=b?g[b]:`localhost:${Number(m.port)}`,S={host:v,path:m.url,secure:c(v)},x=s.jar.requestHeader(S);if(x&&(g.cookie=x),i.set(g,S),m.headers=g,m.streaming===!0&&m.flowControl!==1&&typeof l=="function")return u(Number(p.id),m,g)}return a.call(e,d)};const u=async(d,p,m)=>{const g=b=>{r.messageChannel?.port1.postMessage(b)};try{await r.handleStreamingRequest.call(e,Number(p.port),String(p.method),String(p.url),m,p.body??void 0,{start:(v,S,x)=>g({type:"stream-start",id:d,data:{statusCode:v,statusMessage:S,headers:x}}),chunk:v=>g({type:"stream-chunk",id:d,data:{chunkBase64:As(v)}}),end:()=>g({type:"stream-end",id:d})})||(g({type:"stream-start",id:d,data:{statusCode:503,statusMessage:"Service Unavailable",headers:{}}}),g({type:"stream-end",id:d}))}catch(b){g({type:"response",id:d,error:b instanceof Error?b.message:"Unknown error"})}};r.handleRequest=async(d,p,m,g,b)=>{const v=await o.call(e,d,p,m,g,b),S=i.get(g);return S&&i.delete(g)&&s.jar.storeResponse(S,v.headers),v},typeof l=="function"&&(r.handleStreamingRequest=(d,p,m,g,b,v,S)=>{const x=i.get(g);return x?l.call(e,d,p,m,g,b,{start:(E,A,T)=>{i.delete(g)&&s.jar.storeResponse(x,T),v.start(E,A,T)},chunk:E=>v.chunk(E),end:()=>v.end()},S):l.call(e,d,p,m,g,b,v,S)})}function jx(e,t){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{getServerPorts:()=>e.getServerPorts(),registerServer:(r,n,s)=>{e.registerServer(r,n,s)},unregisterServer:r=>e.unregisterServer(r),handleRequest:(r,n,s,i,a)=>e.handleRequest(r,n,s,i,a),async handleStreamingRequest(r,n,s,i,a,o,l){if(t&&await t.handleStreamingRequest(r,n,s,i,a,o,l))return!0;const c=e.handleStreamingRequest;if(typeof c=="function")return c.call(e,r,n,s,i,a,o,l);if(!e.getServerPorts().includes(r))return!1;const u=await e.handleRequest(r,n,s,i,a);return o.start(u.statusCode,u.statusMessage??"",u.headers),u.body&&o.chunk(u.body),o.end(),!0}})}var wge=Object.defineProperty,vge=(e,t,r)=>t in e?wge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pi=(e,t,r)=>vge(e,typeof t!="symbol"?t+"":t,r);const ET=8192;function kT(e){const t=[];for(let r=0;r<e.length;r+=ET)t.push(String.fromCharCode.apply(null,Array.from(e.subarray(r,r+ET))));return btoa(t.join(""))}const rh=new TextEncoder,xge=64*1024*1024,N2=65536,AT=4;function Yu(e){const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}class Sge{constructor(){Pi(this,"listenersByEvent",new Map)}on(t,r){const n=this.listenersByEvent.get(t)??[];return n.push(r),this.listenersByEvent.set(t,n),this}addListener(t,r){return this.on(t,r)}once(t,r){const n=(...s)=>{this.off(t,n),r(...s)};return n.listener=r,this.on(t,n)}off(t,r){const n=this.listenersByEvent.get(t);if(!n)return this;const s=n.findIndex(i=>i===r||i.listener===r);return s>=0&&n.splice(s,1),n.length===0&&this.listenersByEvent.delete(t),this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this.listenersByEvent.clear():this.listenersByEvent.delete(t),this}listenerCount(t){var r;return((r=this.listenersByEvent.get(t))==null?void 0:r.length)??0}emit(t,...r){const n=this.listenersByEvent.get(t);if(!n||n.length===0)return!1;for(const s of[...n])s(...r);return!0}}const vF=class Ua extends Sge{constructor(t={}){super(),Pi(this,"servers",new Map),Pi(this,"baseUrl"),Pi(this,"options"),Pi(this,"messageChannel",null),Pi(this,"serviceWorkerReady",!1),Pi(this,"keepaliveInterval",null),Pi(this,"primaryPort",null),Pi(this,"ownDocuments"),Pi(this,"binaryChunkPorts",new WeakSet),Pi(this,"controlledStreams",new Map),this.options=t,typeof location<"u"?this.baseUrl=t.baseUrl||`${location.protocol}//${location.host}`:this.baseUrl=t.baseUrl||"http://localhost"}close(){this.keepaliveInterval!==null&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null)}registerServer(t,r,n="0.0.0.0"){this.servers.set(r,{server:t,port:r,hostname:n});const s=this.getServerUrl(r);this.emit("server-ready",r,s),this.options.onServerReady&&this.options.onServerReady(r,s),this.notifyServiceWorker("server-registered",{port:r,hostname:n,primary:r===this.primaryPort})}unregisterServer(t){this.servers.delete(t),this.primaryPort===t&&(this.primaryPort=null),this.notifyServiceWorker("server-unregistered",{port:t})}setPrimaryPort(t){const r=this.primaryPort;if(this.primaryPort=t,r!==null&&r!==t){const n=this.servers.get(r);n&&this.notifyServiceWorker("server-registered",{port:r,hostname:n.hostname,primary:!1})}if(t!==null){const n=this.servers.get(t);this.notifyServiceWorker("server-registered",{port:t,hostname:n?.hostname??"0.0.0.0",primary:!0})}}announceServers(){this.ownDocuments&&this.notifyServiceWorker("own-documents",{paths:this.ownDocuments});for(const[t,r]of this.servers)this.notifyServiceWorker("server-registered",{port:t,hostname:r.hostname,primary:t===this.primaryPort})}getServerUrl(t){return`${this.baseUrl}/__virtual__/${t}`}getServerPorts(){return[...this.servers.keys()]}async handleRequest(t,r,n,s,i){const a=this.servers.get(t);if(!a)return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:rh.encode(`No server listening on port ${t}`)};try{const o=i?this.bodyOf(new Uint8Array(i)):void 0,l=Object.keys(s).some(d=>d.toLowerCase()==="host"),c=`${a.hostname&&a.hostname!=="0.0.0.0"&&a.hostname!=="::"?a.hostname:"127.0.0.1"}:${t}`,u=l?s:{...s,host:c};return a.server?await a.server.handleRequest(r,n,u,o):await this.requestGuest(t,r,n,u,o)}catch(o){const l=o instanceof Error?o.message:"Internal Server Error";return{statusCode:500,statusMessage:"Internal Server Error",headers:{"Content-Type":"text/plain"},body:rh.encode(l)}}}async initServiceWorker(t){if(!("serviceWorker"in navigator))throw new Error("Service Workers not supported");const r=t?.swUrl??"/__sw__.js",n=navigator.serviceWorker.controller?Promise.resolve():new Promise(o=>{navigator.serviceWorker.addEventListener("controllerchange",()=>o(),{once:!0})}),s=await navigator.serviceWorker.register(r,{scope:"/"}),i=s.active||s.waiting||s.installing;if(!i)throw new Error("Service Worker registration failed");await new Promise(o=>{if(i.state==="activated")o();else{const l=()=>{i.state==="activated"&&(i.removeEventListener("statechange",l),o())};i.addEventListener("statechange",l)}}),this.messageChannel=new MessageChannel,this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this),this.ownDocuments=t?.ownDocuments,i.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]),await n;const a=()=>{if(navigator.serviceWorker.controller){for(const o of[...this.controlledStreams.values()])o.cancel();this.messageChannel=new MessageChannel,this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this),navigator.serviceWorker.controller.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]),this.announceServers()}};navigator.serviceWorker.addEventListener("controllerchange",a),navigator.serviceWorker.addEventListener("message",o=>{var l;((l=o.data)==null?void 0:l.type)==="sw-needs-init"&&a()}),this.keepaliveInterval=setInterval(()=>{var o;(o=this.messageChannel)==null||o.port1.postMessage({type:"keepalive"})},2e4),this.serviceWorkerReady=!0,this.announceServers(),this.emit("sw-ready")}postChunk(t,r,n){t&&(this.binaryChunkPorts.has(t)?t.postMessage({type:"stream-chunk",id:r,data:{chunk:n}},[n.buffer]):t.postMessage({type:"stream-chunk",id:r,data:{chunkBase64:kT(n)}}))}async handleServiceWorkerMessage(t){var r,n,s;const{type:i,id:a,data:o}=t.data;if(i==="sw-capabilities"){o?.binaryChunks===1&&t.target instanceof MessagePort&&this.binaryChunkPorts.add(t.target);return}if(Ua.DEBUG&&console.log("[ServerBridge] SW message:",i,a,o?.url),i==="stream-pull"||i==="stream-cancel"){const l=this.controlledStreams.get(a);i==="stream-pull"?l?.pull():l?.cancel();return}if(i==="request"&&o?.flowControl===1){const{port:l,method:c,url:u,headers:d,body:p}=o;await this.controlledStream(a,l,c,u,d,p);return}if(i==="request"){const{port:l,method:c,url:u,headers:d,body:p,streaming:m}=o;Ua.DEBUG&&console.log("[ServerBridge] Handling request:",l,c,u,"streaming:",m),m&&Ua.DEBUG&&console.log("[ServerBridge] 🔴 Will use streaming handler");try{if(m)await this.streamToServiceWorker(a,l,c,u,d,p);else{const g=await this.handleRequest(l,c,u,d,p);Ua.DEBUG&&console.log("[ServerBridge] Response:",g.statusCode,"body length:",(r=g.body)==null?void 0:r.length);let b="";if(g.body&&g.body.length>0){const v=g.body instanceof Uint8Array?g.body:new Uint8Array(0);b=kT(v)}Ua.DEBUG&&console.log("[ServerBridge] Sending response to SW, body base64 length:",b.length),(n=this.messageChannel)==null||n.port1.postMessage({type:"response",id:a,data:{statusCode:g.statusCode,statusMessage:g.statusMessage,headers:g.headers,bodyBase64:b}})}}catch(g){(s=this.messageChannel)==null||s.port1.postMessage({type:"response",id:a,error:g instanceof Error?g.message:"Unknown error"})}}}async handleStreamingRequest(t,r,n,s,i,a,o){const l=this.servers.get(t);if(!l)return!1;const c=i?this.bodyOf(new Uint8Array(i)):void 0;if(this.isGuest(l)){const p=Object.keys(s).some(g=>g.toLowerCase()==="host"),m=`${l.hostname&&l.hostname!=="0.0.0.0"&&l.hostname!=="::"?l.hostname:"127.0.0.1"}:${t}`;return await this.streamGuest(t,r,n,p?s:{...s,host:m},c,(g,b,v)=>a.start(g,b,v),g=>a.chunk(Yu(g)),()=>a.end(),o),!0}const u=l.server;if(typeof u.handleStreamingRequest=="function")return await u.handleStreamingRequest(r,n,s,c,(p,m,g)=>a.start(p,m,g),p=>a.chunk(typeof p=="string"?rh.encode(p):Yu(p)),()=>a.end(),o),!0;const d=await this.handleRequest(t,r,n,s,i);if(a.start(d.statusCode,d.statusMessage??"",d.headers),d.body){const p=typeof d.body=="string"?rh.encode(d.body):d.body;a.chunk(Yu(p))}return a.end(),!0}async streamToServiceWorker(t,r,n,s,i,a){var o,l,c,u,d;const p=this.servers.get(r);if(!p){(o=this.messageChannel)==null||o.port1.postMessage({type:"stream-start",id:t,data:{statusCode:503,statusMessage:"Service Unavailable",headers:{}}}),(l=this.messageChannel)==null||l.port1.postMessage({type:"stream-end",id:t});return}if(this.isGuest(p)){const g=a?this.bodyOf(new Uint8Array(a)):void 0,b=Object.keys(i).some(S=>S.toLowerCase()==="host"),v=`${p.hostname&&p.hostname!=="0.0.0.0"&&p.hostname!=="::"?p.hostname:"127.0.0.1"}:${r}`;await this.streamGuest(r,n,s,b?i:{...i,host:v},g,(S,x,E)=>{var A;(A=this.messageChannel)==null||A.port1.postMessage({type:"stream-start",id:t,data:{statusCode:S,statusMessage:x,headers:E}})},S=>{var x;const E=Yu(S);(x=this.messageChannel)==null||x.port1.postMessage({type:"stream-chunk",id:t,data:E.buffer},[E.buffer])},()=>{var S;(S=this.messageChannel)==null||S.port1.postMessage({type:"stream-end",id:t})});return}const m=p.server;if(m)if(typeof m.handleStreamingRequest=="function"){Ua.DEBUG&&console.log("[ServerBridge] 🟢 Server has streaming support, calling handleStreamingRequest");const g=a?this.bodyOf(new Uint8Array(a)):void 0;await m.handleStreamingRequest(n,s,i,g,(b,v,S)=>{var x;Ua.DEBUG&&console.log("[ServerBridge] 🟢 onStart called, sending stream-start"),(x=this.messageChannel)==null||x.port1.postMessage({type:"stream-start",id:t,data:{statusCode:b,statusMessage:v,headers:S}})},b=>{var v;const S=typeof b=="string"?rh.encode(b):Yu(b);Ua.DEBUG&&console.log("[ServerBridge] 🟡 onChunk called, sending stream-chunk, size:",S.byteLength),this.postChunk((v=this.messageChannel)==null?void 0:v.port1,t,S)},()=>{var b;Ua.DEBUG&&console.log("[ServerBridge] 🟢 onEnd called, sending stream-end"),(b=this.messageChannel)==null||b.port1.postMessage({type:"stream-end",id:t})})}else{const g=a?this.bodyOf(new Uint8Array(a)):void 0,b=await m.handleRequest(n,s,i,g);if((c=this.messageChannel)==null||c.port1.postMessage({type:"stream-start",id:t,data:{statusCode:b.statusCode,statusMessage:b.statusMessage,headers:b.headers}}),b.body&&b.body.length>0){const v=b.body instanceof Uint8Array?Yu(b.body):new Uint8Array(0);this.postChunk((u=this.messageChannel)==null?void 0:u.port1,t,v)}(d=this.messageChannel)==null||d.port1.postMessage({type:"stream-end",id:t})}}notifyServiceWorker(t,r){if(this.serviceWorkerReady&&this.messageChannel){const n=t==="server-registered"?{flowControl:1,maxRequestBytes:xge,maxChunkBytes:N2}:{};this.messageChannel.port1.postMessage({type:t,data:{...r,...n}})}}async controlledStream(t,r,n,s,i,a){const o=this.messageChannel,l=(E,A)=>{o?.port1.postMessage({type:E,id:t,...A===void 0?{}:{data:A}})},c=[],u=new AbortController;let d=0,p=!1,m=!1,g=!1,b=()=>{},v=()=>{};const S=()=>{m=!0,this.controlledStreams.delete(t)},x=()=>{if(!m){for(;d>0&&c.length>0;)d-=1,this.postChunk(o?.port1,t,c.shift());if(p&&c.length===0){l("stream-end"),S();return}c.length>=AT&&!g?(g=!0,b()):c.length<AT&&g&&(g=!1,v())}};this.controlledStreams.set(t,{pull:()=>{d+=1,x()},cancel:()=>{m||(S(),c.length=0,u.abort())}});try{await this.handleStreamingRequest(r,n,s,i,a,{start:(A,T,D)=>l("stream-start",{statusCode:A,statusMessage:T,headers:D}),chunk:A=>{if(!m){for(let T=0;T<A.byteLength;T+=N2)c.push(A.slice(T,T+N2));x()}},end:()=>{p=!0,x()}},{signal:u.signal,control:(A,T)=>{b=A,v=T}})||(l("stream-start",{statusCode:503,statusMessage:"Service Unavailable",headers:{}}),l("stream-end"),S())}catch(E){m||(l("stream-error",{message:E instanceof Error?E.message:String(E)}),S())}}createFetchHandler(){return async t=>{const r=new URL(t.url),n=r.pathname.match(/^\/__virtual__\/(\d+)(\/.*)?$/);if(!n)throw new Error("Not a virtual server request");const s=parseInt(n[1],10),i=n[2]||"/",a={};t.headers.forEach((u,d)=>{a[d]=u});let o;t.method!=="GET"&&t.method!=="HEAD"&&(o=await t.arrayBuffer());const l=await this.handleRequest(s,t.method,i+r.search,a,o),c=new Headers;for(const[u,d]of Object.entries(l.headers))for(const p of Array.isArray(d)?d:[d])c.append(u,p);return new Response(l.body,{status:l.statusCode,statusText:l.statusMessage??"",headers:c})}}isGuest(t){return t.server===null}requestGuest(t,r,n,s,i){return Promise.reject(new Error(`Port ${t} has no server in this realm.`))}streamGuest(t,r,n,s,i,a,o,l,c){return Promise.reject(new Error(`Port ${t} has no server in this realm.`))}bodyOf(t){return t}};Pi(vF,"DEBUG",!1);let Ege=vF,$2=null;function kge(e){return $2||($2=new Ege(e)),$2}function Age(e){return e.map(t=>/^[A-Za-z0-9_./:@%+=,-]+$/u.test(t)?t:`'${t.replaceAll("'","'\\''")}'`).join(" ")}const Cge="vite-ws-channel",Tge="supercode-virtual:";function Nge(){const e=new BroadcastChannel(Cge);return{post:t=>e.postMessage(t),listen:t=>{const r=n=>t(n.data);return e.addEventListener("message",r),()=>e.removeEventListener("message",r)},close:()=>e.close()}}class JS{channel;sockets=new Map;clientNamespace=crypto.randomUUID();stopListening;sequence=0;constructor(t){this.channel=t??Nge(),this.stopListening=this.channel.listen(this.onMessage)}open(t,r,n,s,i){const a=`browser-client-${this.clientNamespace}-${++this.sequence}`,o=`${Tge}//localhost:${t}${r}`,l={handlers:s,protocol:n[0]??"",url:o};return this.sockets.set(a,l),this.channel.post({type:"connect",clientId:a,url:o,protocols:[...n],...i?.framing?{framing:i.framing}:{},...i?.host?{host:i.host}:{},...typeof location<"u"&&location.origin!=="null"?{origin:location.origin}:{}}),{send:c=>{const u=c.kind==="text"?new TextEncoder().encode(c.text):op(c);if(u.byteLength>w$)throw new Error("Virtual WebSocket frame exceeds 32 MiB.");this.channel.post({type:"message",clientId:a,url:o,payload:c.kind==="text"?c.text:u})},close:(c=1e3,u="")=>{$ge(c,u),this.channel.post({type:"disconnect",clientId:a,url:o,code:c,reason:u})},abort:()=>{this.sockets.delete(a),this.channel.post({type:"disconnect",clientId:a,url:o,code:1001,reason:"Host closed"})}}}dispose(){this.sockets.clear(),this.stopListening(),this.channel.close()}onMessage=t=>{const r=t;if(!r||typeof r.type!="string"||typeof r.targetClient!="string")return;const n=this.sockets.get(r.targetClient);if(n)if(r.type==="connected")n.handlers.open(n.protocol);else if(r.type==="message")try{n.handlers.message(xF(r.payload))}catch(s){n.handlers.error(s instanceof Error?s.message:String(s))}else r.type==="close"&&(this.sockets.delete(r.targetClient),n.handlers.close(typeof r.code=="number"?r.code:1e3,typeof r.reason=="string"?r.reason:"",!0))}}function xF(e){if(typeof e=="string")return{kind:"text",text:e};if(e instanceof ArrayBuffer)return{kind:"binary",bytes:new Uint8Array(e.slice(0))};if(ArrayBuffer.isView(e))return{kind:"binary",bytes:new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice()};if(e&&typeof e=="object"&&"data"in e)return xF(e.data);throw new Error("Unsupported virtual WebSocket frame type.")}function $ge(e,t){if(!Number.isSafeInteger(e)||e!==1e3&&(e<3e3||e>4999))throw new Error("Invalid virtual WebSocket close code.");if(new TextEncoder().encode(t).byteLength>123)throw new Error("Virtual WebSocket close reason is too long.")}class Rge{id;post;onClosed;listeners=new Map;ended=!1;outstanding=0;drainWaiters=[];constructor(t,r,n){this.id=t,this.post=r,this.onClosed=n}on(t,r){const n=this.listeners.get(t)??[];return n.push(r),this.listeners.set(t,n),this}write(t,r){if(this.ended)return!1;const n=Uint8Array.from(t).buffer;return this.outstanding+=1,this.post({type:"net-data",socket:this.id,chunk:n},[n]),r?.(),!0}taken(){this.outstanding=Math.max(0,this.outstanding-1);for(const t of[...this.drainWaiters])this.outstanding>=t.below||(this.drainWaiters.splice(this.drainWaiters.indexOf(t),1),t.resume())}drained(t){return this.ended||this.outstanding<t?Promise.resolve():new Promise(r=>this.drainWaiters.push({below:t,resume:r}))}end(){return this.ended||(this.post({type:"net-end",socket:this.id}),this.finish()),this}destroy(){return this.end()}receive(t){if(!this.ended)for(const r of this.listeners.get("data")??[])r(t)}finish(){if(this.ended)return;this.ended=!0,this.onClosed();for(const r of this.drainWaiters.splice(0))r.resume();const t=[...this.listeners.get("end")??[],...this.listeners.get("close")??[]];this.listeners.clear();for(const r of t)r(void 0)}}function CT(e){return{onData:t=>{e.on("data",t)},onClose:t=>{e.on("close",t)},write:t=>{e.write(t)},close:()=>{e.end()}}}const R2=64*1024;function TT(e){return typeof e=="number"&&Number.isInteger(e)&&e>=3&&e<=63}class Oge{run;send;children=new Map;disposed=!1;constructor(t,r){this.run=t,this.send=r}receive(t){if(!["child-run","child-abort","child-stdin","child-stdin-end","child-resize","child-fd","child-fd-end"].includes(t.type))return!1;if(this.disposed)return!0;if(t.type==="child-run"){if(!Number.isSafeInteger(t.id)||t.id<1||this.children.has(t.id))throw new Error("Invalid or duplicate child process identity.");if(t.descriptors!==void 0&&(!Array.isArray(t.descriptors)||!t.descriptors.every(TT)||new Set(t.descriptors).size!==t.descriptors.length))throw new Error("Child process descriptors must be distinct integers from 3 through 63.");return this.start(t).catch(n=>console.error("Child process transport failed.",n)),!0}if(!("id"in t)||typeof t.id!="number")return!0;const r=this.children.get(t.id);if(!r)return!0;if(t.type==="child-abort"){r.controller.abort(),r.input?.cancel();for(const n of r.descriptors.values())n.cancel()}else if(t.type==="child-fd"||t.type==="child-fd-end"){const n=TT(t.fd)?r.descriptors.get(t.fd):void 0;if(!n)return r.controller.abort(new Error("Child process has no such descriptor.")),!0;if(t.type==="child-fd-end")return n.end(),!0;if(!(t.bytes instanceof ArrayBuffer)||t.bytes.byteLength>R2){const i=new Error("Child process descriptor chunks must be at most 64 KiB.");return r.controller.abort(i),n.cancel(i),!0}const s=t.fd;n.write(new Uint8Array(t.bytes)).then(()=>{!this.disposed&&this.children.get(t.id)===r&&this.send({type:"child-fd-consumed",id:t.id,fd:s})}).catch(i=>{r.controller.abort(i)})}else if(t.type==="child-stdin"){if(!r.input)return r.controller.abort(new Error("Child process has no live input.")),!0;if(t.bytes.byteLength>64*1024){const n=new Error("Child process input chunks must be at most 64 KiB.");return r.controller.abort(n),r.input.cancel(n),!0}r.input.write(new Uint8Array(t.bytes)).then(()=>{!this.disposed&&this.children.get(t.id)===r&&this.send({type:"child-input-consumed",id:t.id})}).catch(n=>{!this.disposed&&this.children.get(t.id)===r&&r.controller.abort(n)})}else if(t.type==="child-stdin-end")r.input?.end();else if(t.type==="child-resize"&&r.terminal){r.terminal.columns=t.columns,r.terminal.rows=t.rows;for(const n of[...r.resizes])try{n(t.columns,t.rows)}catch(s){r.controller.abort(s)}}return!0}detach(){this.close(!1)}dispose(){this.close(!0)}close(t){if(!this.disposed){this.disposed=!0;for(const r of this.children.values()){if(t){r.controller.abort(),r.input?.cancel();for(const n of r.descriptors.values())n.cancel()}else{r.input?.end();for(const n of r.descriptors.values())n.end()}r.resizes.clear()}this.children.clear()}}async start(t){const r={controller:new AbortController,resizes:new Set,descriptors:new Map((t.descriptors??[]).map(s=>[s,new T7])),...t.liveStdin?{input:new T7}:{}};t.terminal&&(r.terminal={...t.terminal,onResize:s=>(r.resizes.add(s),()=>{r.resizes.delete(s)})}),this.children.set(t.id,r);const n={};for(const[s,i]of r.descriptors)n[s]=this.descriptor(t.id,s,i,r);try{const s=await this.run(t,{...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{},...t.executablePath!==void 0?{executablePath:t.executablePath}:{},...t.filesystemPolicy!==void 0?{filesystemPolicy:t.filesystemPolicy}:{},...t.stdin!==void 0?{stdin:t.stdin}:{},...r.input?{stdinStream:r.input}:{},...r.terminal?{terminal:r.terminal}:{},...r.descriptors.size>0?{descriptors:n}:{},signal:r.controller.signal,onStdout:i=>{this.disposed||this.send({type:"child-output",id:t.id,stream:"stdout",chunk:i})},onStderr:i=>{this.disposed||this.send({type:"child-output",id:t.id,stream:"stderr",chunk:i})}});this.disposed||this.send({type:"child-result",id:t.id,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,...s.signal?{signal:s.signal}:{}})}catch(s){if(!this.disposed)try{this.send({type:"child-error",id:t.id,error:s instanceof Error?s.message:String(s)})}catch(i){console.error("Child process result transport failed.",i)}}finally{r.input?.cancel();for(const s of r.descriptors.values())s.cancel();r.resizes.clear(),this.children.delete(t.id)}}descriptor(t,r,n,s){let i=!1;const a=()=>!i&&!this.disposed&&this.children.get(t)===s;return{input:n,write:o=>{for(let l=0;l<o.byteLength&&a();l+=R2){const c=Uint8Array.from(o.subarray(l,l+R2)).buffer;this.send({type:"child-fd-output",id:t,fd:r,bytes:c},[c])}},end:()=>{a()&&(i=!0,this.send({type:"child-fd-close",id:t,fd:r}))}}}}const NT=32,_ge=64,Ige=3e4,Mge=5*6e4,Dge=50,$T=20,RT=18e4,Lge=18e4;class Oc{filesystemPolicySupported=!1;inputBytesSupported=!1;get capabilities(){return this.filesystemPolicySupported?Object.freeze({filesystemPolicy:!0}):Object.freeze({})}vfs;serverBridge;webSocketTransport={post:t=>this.send({type:"ws",message:t}),listen:t=>(this.webSocketListeners.add(t),()=>this.webSocketListeners.delete(t)),close:()=>this.webSocketListeners.clear()};webSocketListeners=new Set;isolated=!0;host;workspaceStore;pendingStoreStats=new Map;pendingImageStartup=new Map;pendingImagePrefetch=new Map;imagePrefetchDone=new Map;pendingLinks=new Map;pendingPrograms=new Map;pendingLayers=new Map;layerSources=new Set;pendingPacks=new Map;pendingPackStore=new Map;port;localServers=new Map;hostPortsKey="";remotePorts=new Set;remoteRegistrations=new Map;stopObservingPorts;runs=new Map;settledRuns=new Map;tokens=new Map;requests=new Map;portStreams=new Map;nativeFetch=globalThis.fetch.bind(globalThis);assetUrls=new Set;planPackUrls=new Set;lifetime=new AbortController;fetchControllers=new Map;fetchAuthorities=new Map;relayCapabilities;fetchPullWaiters=new Map;fetchPullCredits=new Map;sequence=1;executionPolicy;stopExecutionPolicy;activeFetches=0;fetchSlots=[];networkBytes=0;responsivenessProfiles=new Map;nextProfileProbe=1;profileTimer;disposed=!1;treeImportSupported=!1;entryReadSupported=!1;startupWaiters=new Set;constructor(t,r,n,s){this.host=t,this.port=r,this.vfs=n,this.serverBridge=s??{getServerPorts:()=>[...this.localServers.keys()].sort((i,a)=>i-a),getServerUrl:i=>`http://localhost:${i}/`,registerServer:(i,a)=>{if(this.localServers.has(a))throw new Error(`Virtual port ${a} is already registered.`);this.localServers.set(a,i)},unregisterServer:i=>{this.localServers.delete(i)},handleRequest:(i,a,o,l,c)=>{const u=this.localServers.get(i);return u?u.handleRequest(a,o,l,c?new Uint8Array(c):void 0):Promise.resolve({statusCode:503,statusMessage:"Service Unavailable",headers:{},body:new Uint8Array})}},this.stopObservingPorts=l6(this.serverBridge,i=>{i.type==="close"&&(this.remotePorts.delete(i.port),this.remoteRegistrations.delete(i.port));const a=this.serverBridge.getServerPorts().filter(l=>og(this.serverBridge,l)?.fetch),o=a.join(",");if(o!==this.hostPortsKey){this.hostPortsKey=o;try{this.send({type:"host-ports",ports:a})}catch{}}}),this.port.addEventListener("message",i=>{this.receive(i.data).catch(a=>this.failTransport(a))}),this.port.addEventListener("messageerror",()=>this.failTransport(new Error("Browser Node host returned an unreadable message."))),this.port.addEventListener("close",()=>this.failTransport(new Error("Browser Node host port closed."))),this.port.start()}static async create(t){const r=new URL(t.hostUrl,location.href);if(r.origin===location.origin)throw new Error("Browser Node host must use a different origin.");if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error("Browser Node host must use HTTP(S).");if(r.protocol==="http:"&&r.hostname!=="localhost"&&r.hostname!=="127.0.0.1")throw new Error("Browser Node host requires HTTPS outside loopback development.");const n=crypto.randomUUID().replaceAll("-","")+crypto.randomUUID().replaceAll("-","");r.searchParams.set("parentOrigin",location.origin),r.hash=n;const s=document.createElement("iframe");s.hidden=!0,s.sandbox.add("allow-scripts","allow-same-origin"),s.allow="cross-origin-isolated",s.referrerPolicy="no-referrer",s.src=r.href;const i=Pge(s);document.body.appendChild(s);let a,o;try{if(await i,!s.contentWindow)throw new Error("Browser Node host has no content window.");o=new MessageChannel;const{filesystem:l,bind:c}=Oc.storeClient(t,r.origin);a=new Oc({dispose:()=>s.remove()},o.port1,l,t.portBridge),c(a);const u=a.waitFor("attached",t.startupTimeoutMs??15e3);return u.catch(()=>{}),s.contentWindow.postMessage({channel:zj,nonce:n,port:o.port2},r.origin,[o.port2]),await u,await a.initialize(t,l,t.startupTimeoutMs??15e3),a}catch(l){try{a?.dispose()}catch(c){console.error("Browser Node startup cleanup failed.",c)}throw o?.port1.close(),o?.port2.close(),s.remove(),l}}static storeClient(t,r=location.origin){let n;const s={apply:i=>n?.applyStoreOperations(i),read:i=>n?n.readStoreFile(i):Promise.reject(new Error("The browser Node host is not attached.")),readEntry:i=>n?n.readStoreEntry(i):Promise.reject(new Error("The browser Node host is not attached.")),flush:()=>n?.flushStore()??Promise.resolve(),importTree:i=>n?n.importStoreTree(i):Promise.reject(new Error("The browser Node host is not attached."))};return{filesystem:new Ev(s,[],t.store.projectId,r),bind:i=>{n=i}}}async initialize(t,r,n){const s=t.store.image;if(s){const u=new URL(s.url,location.href),d=new URL(`${u.pathname.slice(0,-5)}/`,u),p=new URL(s.prepared.url,u);if(u.origin!==location.origin||!u.pathname.endsWith(".layers.json")||!p.href.startsWith(d.href)||!/^[a-f0-9]{16,64}$/u.test(s.digest)||!/^[a-f0-9]{64}$/u.test(s.prepared.digest))throw new Error("The fresh project index is outside this image's immutable transport.");this.layerSources.add(p.href),this.layerSources.add(d.href)}const i=t.bundler?.rollupModuleUrl;for(const u of[t.bundler?.esbuildWasmUrl,...i?[new URL("bindings_wasm_bg.wasm",new URL(i,location.href)).href]:[],t.toolchain?.standIns?.prismaSchemaModuleUrl,t.toolchain?.standIns?.prismaSchemaWasmUrl]){if(!u)continue;const d=new URL(u,location.href);d.origin===location.origin&&!d.username&&!d.password&&this.assetUrls.add(d.href)}const a=this.sequence++,o=this.waitForInitialized(n,a);o.catch(()=>{});const l=t.container??{};this.send({type:"init",childInputVersion:1,...typeof SharedArrayBuffer<"u"&&r.storeOrigin===location.origin?{sharedPageIndexVersion:2}:{},id:a,options:{...l.cwd?{cwd:l.cwd}:{},...l.env?{env:l.env}:{},...l.baseUrl?{baseUrl:l.baseUrl}:{}},store:t.store,...t.bundler?{bundler:t.bundler}:{},...t.toolchain?{toolchain:t.toolchain}:{}});const c=await o;if(t.store.limits&&c.limitsVersion!==1)throw new Error("This Node worker does not support the requested workspace limits.");this.treeImportSupported=c.treeImport===!0,this.entryReadSupported=c.entryReadVersion===1,c.sharedIndex?r.initializeSharedIndex(c.sharedIndex):r.applyIndex(c.index),this.workspaceStore={opened:c.opened,...c.preparedImage?{preparedImage:c.preparedImage}:{},...c.preparedImage&&c.preparedTrees?{preparedTrees:c.preparedTrees}:{},stats:()=>this.requestStoreStats(),flush:()=>r.flush()}}static async createInWorker(t){console.log("[boot-trace]",JSON.stringify({event:"worker-create",at:Date.now()}));const r=bf(new Worker(new URL(t.workerUrl,location.href).href,{type:"module",name:"browser-node-execution"})),n=new MessageChannel,{filesystem:s,bind:i}=Oc.storeClient(t),a=new Oc({dispose:()=>r.terminate()},n.port1,s,t.portBridge);let o=!1;r.addEventListener("error",l=>{const c=l;if(!o){a.failTransport(new Error(`Browser Node worker failed before attachment: ${c.message||String(c.error??"unknown worker error")}`));return}a.reportWorkerUncaught(c)}),r.addEventListener("exit",()=>a.failTransport(new Error("Browser Node worker exited."))),i(a);try{const l=a.waitFor("attached",t.startupTimeoutMs??Lge);return l.catch(()=>{}),console.log("[boot-trace]",JSON.stringify({event:"worker-attach-sent",at:Date.now()})),r.postMessage({type:"attach",port:n.port2,lazyEngine:!0},[n.port2]),await l,o=!0,await a.initialize(t,s,t.startupTimeoutMs??15e3),a}catch(l){try{a.dispose()}catch(c){console.error("Browser Node startup cleanup failed.",c)}throw n.port2.close(),r.terminate(),l}}pendingReads=new Map;pendingEntryReads=new Map;pendingFlushes=new Map;pendingImports=new Map;importStoreTree(t){if(this.disposed)return Promise.reject(new Error("The browser Node host is disposed."));if(!this.treeImportSupported)return Promise.resolve({applied:!1,changes:[]});const r=this.sequence++;return new Promise((n,s)=>{this.pendingImports.set(r,{resolve:n,reject:s});try{const i=[...new Set(t.entries.flatMap(a=>a.type==="file"?[a.bytes.buffer]:[]))];this.send({type:"fs-import",id:r,tree:t},i)}catch(i){this.pendingImports.delete(r),s(i)}})}applyStoreOperations(t){this.assertActive();const r=[],n=t.map(s=>{if(s.op!=="write")return s;const i=s.bytes.buffer.slice(s.bytes.byteOffset,s.bytes.byteOffset+s.bytes.byteLength);return r.push(i),{...s,bytes:i}});this.send({type:"fs-apply",operations:n},r)}readStoreFile(t){if(this.disposed)return Promise.reject(new Error("The browser Node host is disposed."));const r=this.sequence++;return new Promise((n,s)=>{this.pendingReads.set(r,{resolve:n,reject:s});try{this.send({type:"fs-read",id:r,path:t})}catch(i){this.pendingReads.delete(r),s(i)}})}readStoreEntry(t){if(this.disposed)return Promise.reject(new Error("The browser Node host is disposed."));if(!this.entryReadSupported)return Promise.reject(new Error("This Node worker does not support coherent filesystem entry reads."));const r=this.sequence++;return new Promise((n,s)=>{this.pendingEntryReads.set(r,{resolve:n,reject:s});try{this.send({type:"fs-entry",id:r,path:t})}catch(i){this.pendingEntryReads.delete(r),s(i)}})}flushStore(){if(this.disposed)return Promise.reject(new Error("Browser Node host was disposed before filesystem flush."));const t=this.sequence++;return new Promise((r,n)=>{this.pendingFlushes.set(t,{resolve:r,reject:n});try{this.send({type:"fs-flush",id:t})}catch(s){this.pendingFlushes.delete(t),n(s)}})}settleStore(){this.vfs.flushPending()}pendingWatchedPaths=new Map;requestWatchedPaths(){if(this.disposed)return Promise.resolve([]);const t=this.sequence++;return new Promise(r=>{this.pendingWatchedPaths.set(t,r),this.send({type:"watched-paths",id:t}),globalThis.setTimeout(()=>{this.pendingWatchedPaths.delete(t)&&r([])},5e3)})}imageStartupSet(){if(this.disposed)return Promise.resolve([]);const t=this.sequence++;return new Promise(r=>{this.pendingImageStartup.set(t,r),this.send({type:"image-startup-set",id:t}),globalThis.setTimeout(()=>{this.pendingImageStartup.delete(t)&&r([])},1e4)})}prefetchImage(t,r,n=[]){if(this.disposed)return Promise.resolve(0);const s=this.sequence++;return r&&this.imagePrefetchDone.set(s,r),new Promise(i=>{this.pendingImagePrefetch.set(s,a=>{a===0&&this.imagePrefetchDone.delete(s),i(a)}),this.send({type:"image-prefetch",id:s,ranges:[...t],...n.length?{streams:[...n]}:{}}),globalThis.setTimeout(()=>{this.pendingImagePrefetch.delete(s)&&i(0)},1e4)})}requestStoreStats(){if(this.disposed)return Promise.resolve(void 0);const t=this.sequence++;return new Promise(r=>{this.pendingStoreStats.set(t,r),this.send({type:"store-stats",id:t}),globalThis.setTimeout(()=>{this.pendingStoreStats.delete(t)&&r(void 0)},1e4)})}linkPackages(t,r,n){this.assertActive();const s=r.packages.filter(a=>!a.pack||new URL(a.pack.url,location.href).origin!==location.origin);if(s.length>0){const a=s.slice(0,5).map(o=>`${o.name}@${o.version}`).join(", ");try{_c({door:"plan",subject:`${s.length} of the ${r.packages.length} packages for ${t} have no pack this page serves (${a}${s.length>5?", …":""})`,detail:{root:t,unpacked:s.length}})}catch(o){return Promise.reject(o)}}for(const a of r.packages)a.pack&&this.planPackUrls.add(new URL(a.pack.url,location.href).href);const i=this.sequence++;return new Promise((a,o)=>{this.pendingLinks.set(i,{resolve:a,reject:o,...n?{progress:n}:{}}),this.send({type:"link-packages",id:i,root:t,plan:r})})}warmEngine(){this.assertActive(),this.send({type:"warm-engine"})}linkImageProgram(t,r){if(this.assertActive(),!t.startsWith("/packages/.programs/")||!r.startsWith("/"))return Promise.reject(new Error(`${t} is not a program the image's layers place, or ${r} is not a root.`));const n=this.sequence++;return new Promise((s,i)=>{this.pendingPrograms.set(n,{resolve:s,reject:i}),this.send({type:"link-program",id:n,source:t,target:r})})}applyImageLayers(t,r,n,s){this.assertActive();const i=new URL(t,location.href);if(i.origin!==location.origin||!i.pathname.endsWith(".json"))return Promise.reject(new Error(`${t} is not an image layers document this page serves.`));if(s&&!new URL(s.url,i).href.startsWith(new URL(`${i.pathname.slice(0,-5)}/`,i).href))return Promise.reject(new Error("The prepared layers descriptor is outside its image's immutable transport."));this.layerSources.add(i.href),s&&this.layerSources.add(new URL(s.url,i).href),this.layerSources.add(new URL(`${i.pathname.slice(0,-5)}/`,i).href);const a=this.sequence++;return new Promise((o,l)=>{this.pendingLayers.set(a,{resolve:o,reject:l,...n?{progress:n}:{}}),this.send({type:"apply-layers",id:a,url:i.href,digest:r,...s?{prepared:{...s,url:new URL(s.url,i).href}}:{}})})}async readImagePacks(t){this.assertActive(),this.send({type:"image-packs-expected"});try{return await this.readImagePackIndex(t)}catch(r){throw this.disposed||this.send({type:"image-packs-abandoned"}),r}}async readImagePackIndex(t){const r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`The image's packs could not be read: ${r.status}`);const n=await r.json();this.imagePackUrls.clear();for(const o of n.packs??[])typeof o?.key!="string"||typeof o.path!="string"||this.imagePackUrls.set(o.key,new URL(o.path,r.url||t).href);const s=[];for(const o of n.modules??[])typeof o?.key!="string"||!/^[0-9a-f]{64}$/u.test(o.key)||typeof o.path!="string"||(this.imagePackUrls.set(o.key,new URL(o.path,r.url||t).href),s.push(o.key));const i=new Set(s),a=this.sequence++;return new Promise((o,l)=>{this.pendingPacks.set(a,{resolve:o,reject:l}),this.send({type:"image-packs",id:a,keys:[...this.imagePackUrls.keys()].filter(c=>!i.has(c)),bodies:s})})}imagePackUrls=new Map;async sendImagePack(t,r){const n=this.imagePackUrls.get(r);try{if(!n)throw new Error("the image carries no such pack");const s=await fetch(n,{cache:"no-store"});if(!s.ok)throw new Error(`${s.status}`);this.send({type:"image-pack",id:t,text:await s.text()})}catch(s){this.send({type:"image-pack",id:t,error:s instanceof Error?s.message:String(s)})}}async sendImageFile(t,r,n){try{const s=new URL(r,location.href),i=Bg.get(s.href);Bg.delete(s.href);const a=i!==void 0&&(i.part===void 0?n===void 0:n!==void 0&&n.bytes===i.part.bytes&&n.raw===i.part.raw&&n.sha256===i.part.sha256),o=await(i&&a&&this.imageFileAdmitted(s)?i.reading:this.readImageFile(s.href,n));this.send({type:"image-file",id:t,bytes:o.bytes,...o.inflated?{inflated:!0}:{}},[o.bytes])}catch(s){this.send({type:"image-file",id:t,error:s instanceof Error?s.message:String(s)})}}imageFileAdmitted(t){const r=!t.search&&!t.hash&&[...this.layerSources].some(n=>n.endsWith("/")?t.href.startsWith(n)&&/^[0-9a-f]{64}\.bin$/u.test(t.href.slice(n.length)):t.href===n);return t.origin===location.origin&&(this.planPackUrls.has(t.href)||r)}async readImageFile(t,r){const n=new URL(t,location.href);if(!this.imageFileAdmitted(n))throw new Error(`${t} is not a pack a plan linked here names`);return SF(n,r)}browserPackStore(){return{has:async t=>!!(await this.requestPackStore({action:"has",digest:t})).present,readArtifact:async t=>{const r=(await this.requestPackStore({action:"read-artifact",digest:t})).bytes;if(!r)throw new Error(`Pack artifact ${t} returned no bytes.`);return new Uint8Array(r)},linkArchive:async(t,r)=>{await this.requestPackStore({action:"link-archive",digest:t,target:r})},availableBytes:async()=>(await this.requestPackStore({action:"available"})).availableBytes,stageArtifact:async(t,r,n,s)=>{const i=r.slice().buffer;await this.requestPackStore({action:"stage-artifact",digest:t,artifact:n,bytes:i},[i],s)},stageEnvironment:async(t,r)=>{await this.requestPackStore({action:"stage-environment",digest:t,lock:r})},retainEnvironment:async(t,r)=>{await this.requestPackStore({action:"retain-environment",digest:t,artifacts:[...r]})}}}requestPackStore(t,r=[],n){this.assertActive();const s=this.sequence++;return new Promise((i,a)=>{if(n?.aborted){a(n.reason??new Error("Pack staging was cancelled."));return}const o=()=>this.send({type:"pack-store-abort",id:s});n&&n.addEventListener("abort",o,{once:!0}),this.pendingPackStore.set(s,{resolve:i,reject:a,...n?{removeAbort:()=>n.removeEventListener("abort",o)}:{}}),this.send({type:"pack-store",id:s,...t},r)})}configureExecutionPolicy(t){this.stopExecutionPolicy?.(),this.executionPolicy=t,this.networkBytes=0,this.stopExecutionPolicy=t.onChange(()=>{for(const[r,n]of this.fetchAuthorities)try{t.authorize(n.program,n.url)}catch{this.fetchControllers.get(r)?.abort(new Error("Browser Node egress grant was revoked."))}})}listenNet(t,r){if(this.assertActive(),!Number.isInteger(t)||t<1||t>65535)throw new RangeError("Invalid loopback listener port.");if(this.netListeners.has(t))throw Object.assign(new Error(`Port ${t} is already in use.`),{code:"EADDRINUSE"});return this.netListeners.set(t,r),this.send({type:"listen-net",port:t}),()=>{this.netListeners.get(t)===r&&(this.netListeners.delete(t),this.send({type:"unlisten-net",port:t}))}}netListeners=new Map;netSockets=new Map;acceptNetConnection(t,r){const n=this.netListeners.get(t);if(!n){this.send({type:"net-end",socket:r});return}if(!Number.isSafeInteger(r)||r<1||this.netSockets.has(r))throw new Error("Invalid loopback socket identity.");const s=new Rge(r,(i,a)=>this.send(i,a),()=>this.netSockets.delete(r));this.netSockets.set(r,s),n(s)}configureChildProcesses(t){this.childRunner=t}childRunner;childProcesses=new Oge(async(t,r)=>{if(this.assertActive(),!this.childRunner)throw new Error(`${t.command.split(" ",1)[0]}: command not found`);const n=t.owner===null?void 0:this.runs.get(t.owner)?.options??this.settledRuns.get(t.owner);if(t.owner!==null&&!n)throw new Error("The child process's parent context is no longer available.");const s=n?.filesystemPolicy?Xg(n.filesystemPolicy,t.filesystemPolicy):t.filesystemPolicy===void 0?void 0:es(t.filesystemPolicy),i=n?.signal?AbortSignal.any([n.signal,r.signal]):r.signal;i?.throwIfAborted();const{cwd:a,env:o,signal:l,filesystemPolicy:c,...u}=r,d=r.cwd??n?.cwd,p=r.env??n?.env;return this.childRunner(t.command,{...u,...s!==void 0?{filesystemPolicy:s}:{},...d!==void 0?{cwd:d}:{},...p!==void 0?{env:p}:{},...i?{signal:i}:{},held:!1},t.argv)},(t,r)=>this.send(t,r));run(t,r={}){if(r={...r,...r.env!==void 0?{env:{...r.env}}:{},...r.terminal!==void 0?{terminal:{...r.terminal}}:{},...r.filesystemPolicy===void 0?{}:{filesystemPolicy:es(r.filesystemPolicy)}},Ic(r.filesystemPolicy,this.capabilities),this.assertActive(),r.signal?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:130});this.settleStore();const n=this.sequence++,s=r[lR],i=r.processToken;if(typeof i=="string")for(this.tokens.set(i,n);this.tokens.size>NT;){const a=this.tokens.keys().next().value;if(a===void 0)break;this.tokens.delete(a)}return new Promise((a,o)=>{const l=new AbortController;let c,u;const d=()=>{l.abort(r.signal?.reason),u?.reject(l.signal.reason),u=void 0,this.settledRuns.delete(n);try{this.send({type:"abort",id:n})}catch(p){this.failTransport(p)}};r.signal?.addEventListener("abort",d,{once:!0}),this.runs.set(n,{resolve:a,reject:o,options:r,consumeInput:()=>{const p=u;u=void 0,p?.resolve()},removeAbort:()=>{r.signal?.removeEventListener("abort",d),l.abort(new DOMException("The process finished.","AbortError")),u?.reject(l.signal.reason),u=void 0;const p=c;c=void 0;try{p?.()}catch(m){console.error("Process resize subscription cleanup failed.",m)}},...s!==void 0?{runtimePid:s}:{}});try{if(this.send({type:"run",...r.filesystemPolicy?{filesystemPolicy:r.filesystemPolicy}:{},id:n,command:t,...r.executablePath?{executablePath:r.executablePath}:{},...r.cwd?{cwd:r.cwd}:{},...r.env?{env:{...r.env}}:{},interactive:r.held===!0,...typeof r.stdin=="string"?{stdin:r.stdin}:{},...r.stdinStream?{liveStdin:!0}:{},...r.terminal?{terminal:{columns:r.terminal.columns,rows:r.terminal.rows}}:{}}),r.stdinStream){const p=new TextDecoder("utf-8",{fatal:!0});bX(r.stdinStream,async m=>{if(!this.inputBytesSupported){this.send({type:"stdin",id:n,data:p.decode(m,{stream:!0})});return}for(let g=0;g<m.byteLength;g+=64*1024){l.signal.throwIfAborted();const b=Uint8Array.from(m.subarray(g,g+64*1024)).buffer;await new Promise((v,S)=>{u={resolve:v,reject:S};try{this.send({type:"stdin",id:n,data:"",bytes:b},[b])}catch(x){u=void 0,S(x)}})}},l.signal).then(()=>{if(l.signal.aborted||this.disposed)return;const m=p.decode();m&&this.send({type:"stdin",id:n,data:m}),this.send({type:"stdin-end",id:n})}).catch(m=>{if(l.signal.aborted||this.disposed)return;const g=this.runs.get(n);g&&(g.inputFailure=m instanceof Error?m:new Error(String(m)),d())})}c=r.terminal?.onResize?.((p,m)=>{if(!this.disposed&&!l.signal.aborted)try{this.send({type:"resize",id:n,columns:p,rows:m})}catch(g){this.failTransport(g)}}),s!==void 0&&this.startProfiling(s)}catch(p){const m=this.runs.get(n);this.runs.delete(n),m?.removeAbort(),this.stopProfiling(s);try{this.send({type:"abort",id:n})}catch{}o(p)}})}processProfile(t){const r=this.responsivenessProfiles.get(t);if(!r)return;const n=r.pending?Math.max(0,performance.now()-r.pending.sentAt-$T):0;return{busyMs:Math.round(r.busyMs+n),fidelity:"visible-tab event-loop responsiveness estimate; wall clock and output bytes"}}sendInput(t,r){if(this.assertActive(),r!==void 0){const n=this.tokens.get(r);if(n===void 0)return;this.send({type:"stdin",id:n,data:t});return}this.send({type:"stdin",data:t})}stopProcess(t){const r=this.tokens.get(t);return r===void 0?!1:(this.tokens.delete(t),this.settledRuns.delete(r),this.disposed||this.send({type:"abort",id:r}),!0)}reportWorkerUncaught(t){const r=t.message||String(t.error??"Error");let n="";const s=t.error instanceof Error?t.error.stack:void 0;if(typeof s=="string")for(const o of s.split(`
1715
+ `),e.filesystem.chmodSync?.(c,493))}return{shell:r,...a?{share:a}:{},dispose:()=>a?.close()}}const bF="browser-substrate-volter-sign-in",ege="/api/auth/volter/authorize",tge="/api/auth/volter/callback",rge="/api/auth/volter/token",nge="/api/auth/volter/refresh",sge="openid profile email offline_access",ige=300*1e3,age=16*1024;let Zu;async function oge(e=location.origin){const n=(await(await fetch(new URL("/api/ready",e),{credentials:"omit"})).json().catch(()=>({}))).capabilities?.identity;return typeof n?.issuer=="string"&&typeof n.clientId=="string"?{issuer:n.issuer,clientId:n.clientId}:void 0}function lge(e,t={}){if(Zu)return vT(Zu.url),Zu.done;const r=new URL(t.gateway??location.origin).origin,n=`${location.origin}${location.pathname}`,s=r===location.origin?crypto.randomUUID():`${crypto.randomUUID()}.${zx(new TextEncoder().encode(n))}`,i=zx(crypto.getRandomValues(new Uint8Array(48))),a=vT("about:blank"),o=new BroadcastChannel(bF),l=(async()=>{const c=await fge(i),u=new URL(ege,r);u.search=new URLSearchParams({client_id:e.clientId,response_type:"code",redirect_uri:new URL(tge,r).href,scope:sge,state:s,code_challenge:c,code_challenge_method:"S256",...t.provider?{provider:t.provider}:{}}).toString();const d=new Promise(m=>{o.onmessage=g=>{g.data?.state===s&&m(g.data)}});Zu.url=u.href,a.location.href=u.href;const p=await d;if(!p.code)throw new Error(p.error??"Volter returned no code");return wF(r,rge,{code:p.code,code_verifier:i})})().finally(()=>{o.close(),Zu=void 0});return l.catch(()=>{try{a.location.href==="about:blank"&&a.close()}catch{}}),Zu={state:s,url:"",done:l},l}function cge(){const e="#volter-sign-in=";if(!location.hash.startsWith(e))return!1;let t;try{t=JSON.parse(decodeURIComponent(location.hash.slice(e.length)))}catch{return!1}history.replaceState(null,"",`${location.pathname}${location.search}`);const r=new BroadcastChannel(bF);return r.postMessage(t),r.close(),document.body.textContent=t.error?`Sign-in did not complete: ${t.error}`:"Signed in. You can close this window.",t.error||setTimeout(()=>window.close(),300),!0}function uge(e,t={}){return e.refreshToken?wF(new URL(t.gateway??location.origin).origin,nge,{refresh_token:e.refreshToken}):Promise.reject(new Error("The sign-in cannot be renewed; sign in again."))}async function wF(e,t,r){const n=await fetch(new URL(t,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),credentials:"omit",signal:AbortSignal.timeout(3e4)}),s=await n.json().catch(()=>({}));if(!n.ok||!s.access_token)throw new Error(s.error?.message??`The gateway answered ${n.status}.`);const i=wT(s.id_token??s.access_token);if(typeof i.sub!="string")throw new Error("The sign-in named no one.");const a=wT(s.access_token),o=l=>typeof i[l]=="string"?i[l]:typeof a[l]=="string"?a[l]:void 0;return{accessToken:s.access_token,...s.refresh_token?{refreshToken:s.refresh_token}:{},expiresAt:Date.now()+(s.expires_in??3600)*1e3,subject:i.sub,...o("name")?{name:o("name")}:{},...o("email")?{email:o("email")}:{},...o("https://volter.ai/github_login")?{githubLogin:o("https://volter.ai/github_login")}:{}}}function wT(e){try{const t=e.split(".")[1]??"";return JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(t.replace(/-/gu,"+").replace(/_/gu,"/")),r=>r.charCodeAt(0))))}catch{return{}}}async function fge(e){return zx(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))))}function zx(e){return btoa(String.fromCharCode(...e)).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function vT(e){const t=window.open(e,"browser-substrate-volter-sign-in","popup,width=520,height=720");if(!t)throw new Error("the browser blocked the sign-in window; allow pop-ups for this page and press Sign in again");return t}class dge{vault;options;constructor(t,r={}){this.vault=t,this.options=r}load(){return this.lock(async()=>{const t=await this.read();if(t?.rotationId){await this.vault.clear();return}return t&&xT(t)})}current(){return this.lock(async()=>{const t=await this.read();if(!t)return;if(t.rotationId){await this.vault.clear();return}const r=xT(t);if(r.expiresAt-ige>Date.now())return r;if(!r.refreshToken){await this.vault.clear();return}await this.write(r,crypto.randomUUID());let n;try{n=await uge(r,this.options.gateway?{gateway:this.options.gateway}:{})}catch{await this.vault.clear();return}return await this.write(n),n})}save(t){return this.lock(()=>this.write(t))}clear(){return this.lock(()=>this.vault.clear())}async read(){const t=await this.vault.load();if(t)try{const r=JSON.parse(new TextDecoder().decode(t));return r.version!==1||typeof r.accessToken!="string"||typeof r.subject!="string"||typeof r.expiresAt!="number"?void 0:r}catch{return}}async write(t,r){const n={...t,version:1,savedAt:Date.now(),...r?{rotationId:r}:{}},s=new TextEncoder().encode(JSON.stringify(n));if(s.byteLength>age)throw new Error("The Volter session record is unexpectedly large.");await this.vault.save(s,{backup:"current"})}async lock(t){if(this.options.lock)return this.options.lock(t);if(!globalThis.navigator?.locks)throw new Error("Volter session storage requires browser Web Locks.");return await navigator.locks.request("browser-substrate-volter-session",t)}}function xT(e){const{version:t,savedAt:r,rotationId:n,...s}=e;return s}function hge(e){const t=e;if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.url!="string"||!t.url.startsWith("/substrate/")||typeof t.digest!="string"||!/^[0-9a-f]{16,64}$/u.test(t.digest)||!Number.isSafeInteger(t.parts)||!Number.isSafeInteger(t.units)||!Number.isSafeInteger(t.bytes))throw new Error("The image manifest's layers block is malformed.");const r=t.prepared;if(r&&(typeof r.url!="string"||!r.url.startsWith("/substrate/")||r.url.split("/").includes("..")||typeof r.digest!="string"||!/^[a-f0-9]{64}$/u.test(r.digest)||r.project!==void 0&&r.project!==!0||r.files!==void 0&&(!Array.isArray(r.files)||r.files.length>4||!r.files.every(n=>n!==null&&typeof n=="object"&&typeof n.url=="string"&&/^\/substrate\/[A-Za-z0-9._-]+\.layers\/[a-f0-9]{64}\.bin$/u.test(n.url)&&Number.isSafeInteger(n.bytes)&&n.bytes>=0&&Number.isSafeInteger(n.raw)&&n.raw>=0&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/u.test(n.sha256)))))throw new Error("Malformed prepared layers descriptor.");return{url:t.url,digest:t.digest,parts:t.parts,units:t.units,bytes:t.bytes,...r?{prepared:r}:{}}}function pge(e){const t=e;if(typeof t!="object"||t===null||typeof t.url!="string"||!t.url.startsWith("/substrate/")||t.url.split("/").includes("..")||!Number.isSafeInteger(t.entries)||!Number.isSafeInteger(t.bytes))throw new Error("The image manifest's caches block is malformed.");return{url:t.url,entries:t.entries,bytes:t.bytes}}function mge(e){const t=e?.entries;if(!Array.isArray(t))throw new Error("The image's caches document is malformed.");for(const r of t)if(!r||typeof r.cache!="string"||r.cache.length===0||r.cache.length>256||typeof r.url!="string"||!r.url.startsWith("/")||r.url.startsWith("//")||!Number.isSafeInteger(r.status)||r.status<200||r.status>299||!Array.isArray(r.headers)||r.headers.some(n=>!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")||!Number.isSafeInteger(r.bytes)||typeof r.sha256!="string"||!/^[0-9a-f]{64}$/u.test(r.sha256)||typeof r.file!="string"||!r.file.startsWith("/substrate/")||r.file.split("/").includes(".."))throw new Error("The image's caches document has a malformed entry.");return t}function gge(e){const t=e;if(typeof t!="object"||t===null||typeof t.url!="string"||!t.url.startsWith("/substrate/")||t.url.split("/").includes("..")||!Number.isSafeInteger(t.files)||!Number.isSafeInteger(t.bytes))throw new Error("The image manifest's warm block is malformed.");return{url:t.url,files:t.files,bytes:t.bytes}}function yge(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("The image manifest's packs block is malformed.");const t=e;if(typeof t.url!="string"||!Number.isInteger(t.count))throw new Error("The image manifest's packs block is malformed.");if(t.digest!==void 0&&typeof t.digest!="string")throw new Error("The image manifest's packs block is malformed.");return{url:t.url,count:t.count,...typeof t.digest=="string"?{digest:t.digest}:{}}}const ST=new WeakMap;function bge(e,t){const r=e,n=ST.get(e);if(n){n.jar=t;return}if(typeof r.handleServiceWorkerMessage!="function"||typeof r.handleRequest!="function")throw new Error("The installed tabnode port bridge changed; update the cookie jar adapter.");if(r.messageChannel||r.serviceWorkerReady)throw new Error("Attach the cookie jar before the service worker is initialized: the bridge has bound its message handler.");const s={jar:t};ST.set(e,s);const i=new WeakMap,a=r.handleServiceWorkerMessage,o=r.handleRequest,l=r.handleStreamingRequest,c=d=>globalThis.isSecureContext===!0||Rj(d);r.handleServiceWorkerMessage=d=>{const p=d?.data,m=p?.data;if(p?.type==="request"&&m&&typeof m.url=="string"&&m.headers&&typeof m.headers=="object"&&!Array.isArray(m.headers)){const g={};for(const[E,A]of Object.entries(m.headers))E.toLowerCase()!=="cookie"&&(g[E]=A);const b=Object.keys(g).find(E=>E.toLowerCase()==="host"),v=b?g[b]:`localhost:${Number(m.port)}`,S={host:v,path:m.url,secure:c(v)},x=s.jar.requestHeader(S);if(x&&(g.cookie=x),i.set(g,S),m.headers=g,m.streaming===!0&&m.flowControl!==1&&typeof l=="function")return u(Number(p.id),m,g)}return a.call(e,d)};const u=async(d,p,m)=>{const g=b=>{r.messageChannel?.port1.postMessage(b)};try{await r.handleStreamingRequest.call(e,Number(p.port),String(p.method),String(p.url),m,p.body??void 0,{start:(v,S,x)=>g({type:"stream-start",id:d,data:{statusCode:v,statusMessage:S,headers:x}}),chunk:v=>g({type:"stream-chunk",id:d,data:{chunkBase64:As(v)}}),end:()=>g({type:"stream-end",id:d})})||(g({type:"stream-start",id:d,data:{statusCode:503,statusMessage:"Service Unavailable",headers:{}}}),g({type:"stream-end",id:d}))}catch(b){g({type:"response",id:d,error:b instanceof Error?b.message:"Unknown error"})}};r.handleRequest=async(d,p,m,g,b)=>{const v=await o.call(e,d,p,m,g,b),S=i.get(g);return S&&i.delete(g)&&s.jar.storeResponse(S,v.headers),v},typeof l=="function"&&(r.handleStreamingRequest=(d,p,m,g,b,v,S)=>{const x=i.get(g);return x?l.call(e,d,p,m,g,b,{start:(E,A,T)=>{i.delete(g)&&s.jar.storeResponse(x,T),v.start(E,A,T)},chunk:E=>v.chunk(E),end:()=>v.end()},S):l.call(e,d,p,m,g,b,v,S)})}function jx(e,t){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{getServerPorts:()=>e.getServerPorts(),registerServer:(r,n,s)=>{e.registerServer(r,n,s)},unregisterServer:r=>e.unregisterServer(r),handleRequest:(r,n,s,i,a)=>e.handleRequest(r,n,s,i,a),async handleStreamingRequest(r,n,s,i,a,o,l){if(t&&await t.handleStreamingRequest(r,n,s,i,a,o,l))return!0;const c=e.handleStreamingRequest;if(typeof c=="function")return c.call(e,r,n,s,i,a,o,l);if(!e.getServerPorts().includes(r))return!1;const u=await e.handleRequest(r,n,s,i,a);return o.start(u.statusCode,u.statusMessage??"",u.headers),u.body&&o.chunk(u.body),o.end(),!0}})}var wge=Object.defineProperty,vge=(e,t,r)=>t in e?wge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pi=(e,t,r)=>vge(e,typeof t!="symbol"?t+"":t,r);const ET=8192;function kT(e){const t=[];for(let r=0;r<e.length;r+=ET)t.push(String.fromCharCode.apply(null,Array.from(e.subarray(r,r+ET))));return btoa(t.join(""))}const rh=new TextEncoder,xge=64*1024*1024,N2=65536,AT=4;function Yu(e){const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}class Sge{constructor(){Pi(this,"listenersByEvent",new Map)}on(t,r){const n=this.listenersByEvent.get(t)??[];return n.push(r),this.listenersByEvent.set(t,n),this}addListener(t,r){return this.on(t,r)}once(t,r){const n=(...s)=>{this.off(t,n),r(...s)};return n.listener=r,this.on(t,n)}off(t,r){const n=this.listenersByEvent.get(t);if(!n)return this;const s=n.findIndex(i=>i===r||i.listener===r);return s>=0&&n.splice(s,1),n.length===0&&this.listenersByEvent.delete(t),this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this.listenersByEvent.clear():this.listenersByEvent.delete(t),this}listenerCount(t){var r;return((r=this.listenersByEvent.get(t))==null?void 0:r.length)??0}emit(t,...r){const n=this.listenersByEvent.get(t);if(!n||n.length===0)return!1;for(const s of[...n])s(...r);return!0}}const vF=class Ua extends Sge{constructor(t={}){super(),Pi(this,"servers",new Map),Pi(this,"baseUrl"),Pi(this,"options"),Pi(this,"messageChannel",null),Pi(this,"serviceWorkerReady",!1),Pi(this,"keepaliveInterval",null),Pi(this,"primaryPort",null),Pi(this,"ownDocuments"),Pi(this,"binaryChunkPorts",new WeakSet),Pi(this,"controlledStreams",new Map),this.options=t,typeof location<"u"?this.baseUrl=t.baseUrl||`${location.protocol}//${location.host}`:this.baseUrl=t.baseUrl||"http://localhost"}close(){this.keepaliveInterval!==null&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null)}registerServer(t,r,n="0.0.0.0"){this.servers.set(r,{server:t,port:r,hostname:n});const s=this.getServerUrl(r);this.emit("server-ready",r,s),this.options.onServerReady&&this.options.onServerReady(r,s),this.notifyServiceWorker("server-registered",{port:r,hostname:n,primary:r===this.primaryPort})}unregisterServer(t){this.servers.delete(t),this.primaryPort===t&&(this.primaryPort=null),this.notifyServiceWorker("server-unregistered",{port:t})}setPrimaryPort(t){const r=this.primaryPort;if(this.primaryPort=t,r!==null&&r!==t){const n=this.servers.get(r);n&&this.notifyServiceWorker("server-registered",{port:r,hostname:n.hostname,primary:!1})}if(t!==null){const n=this.servers.get(t);this.notifyServiceWorker("server-registered",{port:t,hostname:n?.hostname??"0.0.0.0",primary:!0})}}announceServers(){this.ownDocuments&&this.notifyServiceWorker("own-documents",{paths:this.ownDocuments});for(const[t,r]of this.servers)this.notifyServiceWorker("server-registered",{port:t,hostname:r.hostname,primary:t===this.primaryPort})}getServerUrl(t){return`${this.baseUrl}/__virtual__/${t}`}getServerPorts(){return[...this.servers.keys()]}async handleRequest(t,r,n,s,i){const a=this.servers.get(t);if(!a)return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:rh.encode(`No server listening on port ${t}`)};try{const o=i?this.bodyOf(new Uint8Array(i)):void 0,l=Object.keys(s).some(d=>d.toLowerCase()==="host"),c=`${a.hostname&&a.hostname!=="0.0.0.0"&&a.hostname!=="::"?a.hostname:"127.0.0.1"}:${t}`,u=l?s:{...s,host:c};return a.server?await a.server.handleRequest(r,n,u,o):await this.requestGuest(t,r,n,u,o)}catch(o){const l=o instanceof Error?o.message:"Internal Server Error";return{statusCode:500,statusMessage:"Internal Server Error",headers:{"Content-Type":"text/plain"},body:rh.encode(l)}}}async initServiceWorker(t){if(!("serviceWorker"in navigator))throw new Error("Service Workers not supported");const r=t?.swUrl??"/__sw__.js",n=navigator.serviceWorker.controller?Promise.resolve():new Promise(l=>{navigator.serviceWorker.addEventListener("controllerchange",()=>l(),{once:!0})}),s=await navigator.serviceWorker.register(r,{scope:"/",updateViaCache:"none"});try{await Promise.race([s.update(),new Promise(l=>setTimeout(l,5e3))])}catch{}const i=s.installing||s.waiting||s.active;if(!i)throw new Error("Service Worker registration failed");await new Promise(l=>{if(i.state==="activated"||i.state==="redundant")l();else{const c=()=>{(i.state==="activated"||i.state==="redundant")&&(i.removeEventListener("statechange",c),l())};i.addEventListener("statechange",c)}});const a=i.state==="redundant"?s.active:i;if(!a)throw new Error("Service Worker failed to install");navigator.serviceWorker.controller&&navigator.serviceWorker.controller!==a&&await new Promise(l=>{const c=setTimeout(()=>{console.warn("tabnode: the new service worker did not take control within 10 s; starting under the one in control"),u()},1e4);function u(){clearTimeout(c),navigator.serviceWorker.removeEventListener("controllerchange",d),l()}function d(){navigator.serviceWorker.controller===a&&u()}navigator.serviceWorker.addEventListener("controllerchange",d),d()}),this.messageChannel=new MessageChannel,this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this),this.ownDocuments=t?.ownDocuments,a.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]),await n;const o=()=>{if(navigator.serviceWorker.controller){for(const l of[...this.controlledStreams.values()])l.cancel();this.messageChannel=new MessageChannel,this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this),navigator.serviceWorker.controller.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]),this.announceServers()}};navigator.serviceWorker.addEventListener("controllerchange",o),navigator.serviceWorker.addEventListener("message",l=>{var c;((c=l.data)==null?void 0:c.type)==="sw-needs-init"&&o()}),this.keepaliveInterval=setInterval(()=>{var l;(l=this.messageChannel)==null||l.port1.postMessage({type:"keepalive"})},2e4),this.serviceWorkerReady=!0,this.announceServers(),this.emit("sw-ready")}postChunk(t,r,n){t&&(this.binaryChunkPorts.has(t)?t.postMessage({type:"stream-chunk",id:r,data:{chunk:n}},[n.buffer]):t.postMessage({type:"stream-chunk",id:r,data:{chunkBase64:kT(n)}}))}async handleServiceWorkerMessage(t){var r,n,s;const{type:i,id:a,data:o}=t.data;if(i==="sw-capabilities"){o?.binaryChunks===1&&t.target instanceof MessagePort&&this.binaryChunkPorts.add(t.target);return}if(Ua.DEBUG&&console.log("[ServerBridge] SW message:",i,a,o?.url),i==="stream-pull"||i==="stream-cancel"){const l=this.controlledStreams.get(a);i==="stream-pull"?l?.pull():l?.cancel();return}if(i==="request"&&o?.flowControl===1){const{port:l,method:c,url:u,headers:d,body:p}=o;await this.controlledStream(a,l,c,u,d,p);return}if(i==="request"){const{port:l,method:c,url:u,headers:d,body:p,streaming:m}=o;Ua.DEBUG&&console.log("[ServerBridge] Handling request:",l,c,u,"streaming:",m),m&&Ua.DEBUG&&console.log("[ServerBridge] 🔴 Will use streaming handler");try{if(m)await this.streamToServiceWorker(a,l,c,u,d,p);else{const g=await this.handleRequest(l,c,u,d,p);Ua.DEBUG&&console.log("[ServerBridge] Response:",g.statusCode,"body length:",(r=g.body)==null?void 0:r.length);let b="";if(g.body&&g.body.length>0){const v=g.body instanceof Uint8Array?g.body:new Uint8Array(0);b=kT(v)}Ua.DEBUG&&console.log("[ServerBridge] Sending response to SW, body base64 length:",b.length),(n=this.messageChannel)==null||n.port1.postMessage({type:"response",id:a,data:{statusCode:g.statusCode,statusMessage:g.statusMessage,headers:g.headers,bodyBase64:b}})}}catch(g){(s=this.messageChannel)==null||s.port1.postMessage({type:"response",id:a,error:g instanceof Error?g.message:"Unknown error"})}}}async handleStreamingRequest(t,r,n,s,i,a,o){const l=this.servers.get(t);if(!l)return!1;const c=i?this.bodyOf(new Uint8Array(i)):void 0;if(this.isGuest(l)){const p=Object.keys(s).some(g=>g.toLowerCase()==="host"),m=`${l.hostname&&l.hostname!=="0.0.0.0"&&l.hostname!=="::"?l.hostname:"127.0.0.1"}:${t}`;return await this.streamGuest(t,r,n,p?s:{...s,host:m},c,(g,b,v)=>a.start(g,b,v),g=>a.chunk(Yu(g)),()=>a.end(),o),!0}const u=l.server;if(typeof u.handleStreamingRequest=="function")return await u.handleStreamingRequest(r,n,s,c,(p,m,g)=>a.start(p,m,g),p=>a.chunk(typeof p=="string"?rh.encode(p):Yu(p)),()=>a.end(),o),!0;const d=await this.handleRequest(t,r,n,s,i);if(a.start(d.statusCode,d.statusMessage??"",d.headers),d.body){const p=typeof d.body=="string"?rh.encode(d.body):d.body;a.chunk(Yu(p))}return a.end(),!0}async streamToServiceWorker(t,r,n,s,i,a){var o,l,c,u,d;const p=this.servers.get(r);if(!p){(o=this.messageChannel)==null||o.port1.postMessage({type:"stream-start",id:t,data:{statusCode:503,statusMessage:"Service Unavailable",headers:{}}}),(l=this.messageChannel)==null||l.port1.postMessage({type:"stream-end",id:t});return}if(this.isGuest(p)){const g=a?this.bodyOf(new Uint8Array(a)):void 0,b=Object.keys(i).some(S=>S.toLowerCase()==="host"),v=`${p.hostname&&p.hostname!=="0.0.0.0"&&p.hostname!=="::"?p.hostname:"127.0.0.1"}:${r}`;await this.streamGuest(r,n,s,b?i:{...i,host:v},g,(S,x,E)=>{var A;(A=this.messageChannel)==null||A.port1.postMessage({type:"stream-start",id:t,data:{statusCode:S,statusMessage:x,headers:E}})},S=>{var x;const E=Yu(S);(x=this.messageChannel)==null||x.port1.postMessage({type:"stream-chunk",id:t,data:E.buffer},[E.buffer])},()=>{var S;(S=this.messageChannel)==null||S.port1.postMessage({type:"stream-end",id:t})});return}const m=p.server;if(m)if(typeof m.handleStreamingRequest=="function"){Ua.DEBUG&&console.log("[ServerBridge] 🟢 Server has streaming support, calling handleStreamingRequest");const g=a?this.bodyOf(new Uint8Array(a)):void 0;await m.handleStreamingRequest(n,s,i,g,(b,v,S)=>{var x;Ua.DEBUG&&console.log("[ServerBridge] 🟢 onStart called, sending stream-start"),(x=this.messageChannel)==null||x.port1.postMessage({type:"stream-start",id:t,data:{statusCode:b,statusMessage:v,headers:S}})},b=>{var v;const S=typeof b=="string"?rh.encode(b):Yu(b);Ua.DEBUG&&console.log("[ServerBridge] 🟡 onChunk called, sending stream-chunk, size:",S.byteLength),this.postChunk((v=this.messageChannel)==null?void 0:v.port1,t,S)},()=>{var b;Ua.DEBUG&&console.log("[ServerBridge] 🟢 onEnd called, sending stream-end"),(b=this.messageChannel)==null||b.port1.postMessage({type:"stream-end",id:t})})}else{const g=a?this.bodyOf(new Uint8Array(a)):void 0,b=await m.handleRequest(n,s,i,g);if((c=this.messageChannel)==null||c.port1.postMessage({type:"stream-start",id:t,data:{statusCode:b.statusCode,statusMessage:b.statusMessage,headers:b.headers}}),b.body&&b.body.length>0){const v=b.body instanceof Uint8Array?Yu(b.body):new Uint8Array(0);this.postChunk((u=this.messageChannel)==null?void 0:u.port1,t,v)}(d=this.messageChannel)==null||d.port1.postMessage({type:"stream-end",id:t})}}notifyServiceWorker(t,r){if(this.serviceWorkerReady&&this.messageChannel){const n=t==="server-registered"?{flowControl:1,maxRequestBytes:xge,maxChunkBytes:N2}:{};this.messageChannel.port1.postMessage({type:t,data:{...r,...n}})}}async controlledStream(t,r,n,s,i,a){const o=this.messageChannel,l=(E,A)=>{o?.port1.postMessage({type:E,id:t,...A===void 0?{}:{data:A}})},c=[],u=new AbortController;let d=0,p=!1,m=!1,g=!1,b=()=>{},v=()=>{};const S=()=>{m=!0,this.controlledStreams.delete(t)},x=()=>{if(!m){for(;d>0&&c.length>0;)d-=1,this.postChunk(o?.port1,t,c.shift());if(p&&c.length===0){l("stream-end"),S();return}c.length>=AT&&!g?(g=!0,b()):c.length<AT&&g&&(g=!1,v())}};this.controlledStreams.set(t,{pull:()=>{d+=1,x()},cancel:()=>{m||(S(),c.length=0,u.abort())}});try{await this.handleStreamingRequest(r,n,s,i,a,{start:(A,T,D)=>l("stream-start",{statusCode:A,statusMessage:T,headers:D}),chunk:A=>{if(!m){for(let T=0;T<A.byteLength;T+=N2)c.push(A.slice(T,T+N2));x()}},end:()=>{p=!0,x()}},{signal:u.signal,control:(A,T)=>{b=A,v=T}})||(l("stream-start",{statusCode:503,statusMessage:"Service Unavailable",headers:{}}),l("stream-end"),S())}catch(E){m||(l("stream-error",{message:E instanceof Error?E.message:String(E)}),S())}}createFetchHandler(){return async t=>{const r=new URL(t.url),n=r.pathname.match(/^\/__virtual__\/(\d+)(\/.*)?$/);if(!n)throw new Error("Not a virtual server request");const s=parseInt(n[1],10),i=n[2]||"/",a={};t.headers.forEach((u,d)=>{a[d]=u});let o;t.method!=="GET"&&t.method!=="HEAD"&&(o=await t.arrayBuffer());const l=await this.handleRequest(s,t.method,i+r.search,a,o),c=new Headers;for(const[u,d]of Object.entries(l.headers))for(const p of Array.isArray(d)?d:[d])c.append(u,p);return new Response(l.body,{status:l.statusCode,statusText:l.statusMessage??"",headers:c})}}isGuest(t){return t.server===null}requestGuest(t,r,n,s,i){return Promise.reject(new Error(`Port ${t} has no server in this realm.`))}streamGuest(t,r,n,s,i,a,o,l,c){return Promise.reject(new Error(`Port ${t} has no server in this realm.`))}bodyOf(t){return t}};Pi(vF,"DEBUG",!1);let Ege=vF,$2=null;function kge(e){return $2||($2=new Ege(e)),$2}function Age(e){return e.map(t=>/^[A-Za-z0-9_./:@%+=,-]+$/u.test(t)?t:`'${t.replaceAll("'","'\\''")}'`).join(" ")}const Cge="vite-ws-channel",Tge="supercode-virtual:";function Nge(){const e=new BroadcastChannel(Cge);return{post:t=>e.postMessage(t),listen:t=>{const r=n=>t(n.data);return e.addEventListener("message",r),()=>e.removeEventListener("message",r)},close:()=>e.close()}}class JS{channel;sockets=new Map;clientNamespace=crypto.randomUUID();stopListening;sequence=0;constructor(t){this.channel=t??Nge(),this.stopListening=this.channel.listen(this.onMessage)}open(t,r,n,s,i){const a=`browser-client-${this.clientNamespace}-${++this.sequence}`,o=`${Tge}//localhost:${t}${r}`,l={handlers:s,protocol:n[0]??"",url:o};return this.sockets.set(a,l),this.channel.post({type:"connect",clientId:a,url:o,protocols:[...n],...i?.framing?{framing:i.framing}:{},...i?.host?{host:i.host}:{},...typeof location<"u"&&location.origin!=="null"?{origin:location.origin}:{}}),{send:c=>{const u=c.kind==="text"?new TextEncoder().encode(c.text):op(c);if(u.byteLength>w$)throw new Error("Virtual WebSocket frame exceeds 32 MiB.");this.channel.post({type:"message",clientId:a,url:o,payload:c.kind==="text"?c.text:u})},close:(c=1e3,u="")=>{$ge(c,u),this.channel.post({type:"disconnect",clientId:a,url:o,code:c,reason:u})},abort:()=>{this.sockets.delete(a),this.channel.post({type:"disconnect",clientId:a,url:o,code:1001,reason:"Host closed"})}}}dispose(){this.sockets.clear(),this.stopListening(),this.channel.close()}onMessage=t=>{const r=t;if(!r||typeof r.type!="string"||typeof r.targetClient!="string")return;const n=this.sockets.get(r.targetClient);if(n)if(r.type==="connected")n.handlers.open(n.protocol);else if(r.type==="message")try{n.handlers.message(xF(r.payload))}catch(s){n.handlers.error(s instanceof Error?s.message:String(s))}else r.type==="close"&&(this.sockets.delete(r.targetClient),n.handlers.close(typeof r.code=="number"?r.code:1e3,typeof r.reason=="string"?r.reason:"",!0))}}function xF(e){if(typeof e=="string")return{kind:"text",text:e};if(e instanceof ArrayBuffer)return{kind:"binary",bytes:new Uint8Array(e.slice(0))};if(ArrayBuffer.isView(e))return{kind:"binary",bytes:new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice()};if(e&&typeof e=="object"&&"data"in e)return xF(e.data);throw new Error("Unsupported virtual WebSocket frame type.")}function $ge(e,t){if(!Number.isSafeInteger(e)||e!==1e3&&(e<3e3||e>4999))throw new Error("Invalid virtual WebSocket close code.");if(new TextEncoder().encode(t).byteLength>123)throw new Error("Virtual WebSocket close reason is too long.")}class Rge{id;post;onClosed;listeners=new Map;ended=!1;outstanding=0;drainWaiters=[];constructor(t,r,n){this.id=t,this.post=r,this.onClosed=n}on(t,r){const n=this.listeners.get(t)??[];return n.push(r),this.listeners.set(t,n),this}write(t,r){if(this.ended)return!1;const n=Uint8Array.from(t).buffer;return this.outstanding+=1,this.post({type:"net-data",socket:this.id,chunk:n},[n]),r?.(),!0}taken(){this.outstanding=Math.max(0,this.outstanding-1);for(const t of[...this.drainWaiters])this.outstanding>=t.below||(this.drainWaiters.splice(this.drainWaiters.indexOf(t),1),t.resume())}drained(t){return this.ended||this.outstanding<t?Promise.resolve():new Promise(r=>this.drainWaiters.push({below:t,resume:r}))}end(){return this.ended||(this.post({type:"net-end",socket:this.id}),this.finish()),this}destroy(){return this.end()}receive(t){if(!this.ended)for(const r of this.listeners.get("data")??[])r(t)}finish(){if(this.ended)return;this.ended=!0,this.onClosed();for(const r of this.drainWaiters.splice(0))r.resume();const t=[...this.listeners.get("end")??[],...this.listeners.get("close")??[]];this.listeners.clear();for(const r of t)r(void 0)}}function CT(e){return{onData:t=>{e.on("data",t)},onClose:t=>{e.on("close",t)},write:t=>{e.write(t)},close:()=>{e.end()}}}const R2=64*1024;function TT(e){return typeof e=="number"&&Number.isInteger(e)&&e>=3&&e<=63}class Oge{run;send;children=new Map;disposed=!1;constructor(t,r){this.run=t,this.send=r}receive(t){if(!["child-run","child-abort","child-stdin","child-stdin-end","child-resize","child-fd","child-fd-end"].includes(t.type))return!1;if(this.disposed)return!0;if(t.type==="child-run"){if(!Number.isSafeInteger(t.id)||t.id<1||this.children.has(t.id))throw new Error("Invalid or duplicate child process identity.");if(t.descriptors!==void 0&&(!Array.isArray(t.descriptors)||!t.descriptors.every(TT)||new Set(t.descriptors).size!==t.descriptors.length))throw new Error("Child process descriptors must be distinct integers from 3 through 63.");return this.start(t).catch(n=>console.error("Child process transport failed.",n)),!0}if(!("id"in t)||typeof t.id!="number")return!0;const r=this.children.get(t.id);if(!r)return!0;if(t.type==="child-abort"){r.controller.abort(),r.input?.cancel();for(const n of r.descriptors.values())n.cancel()}else if(t.type==="child-fd"||t.type==="child-fd-end"){const n=TT(t.fd)?r.descriptors.get(t.fd):void 0;if(!n)return r.controller.abort(new Error("Child process has no such descriptor.")),!0;if(t.type==="child-fd-end")return n.end(),!0;if(!(t.bytes instanceof ArrayBuffer)||t.bytes.byteLength>R2){const i=new Error("Child process descriptor chunks must be at most 64 KiB.");return r.controller.abort(i),n.cancel(i),!0}const s=t.fd;n.write(new Uint8Array(t.bytes)).then(()=>{!this.disposed&&this.children.get(t.id)===r&&this.send({type:"child-fd-consumed",id:t.id,fd:s})}).catch(i=>{r.controller.abort(i)})}else if(t.type==="child-stdin"){if(!r.input)return r.controller.abort(new Error("Child process has no live input.")),!0;if(t.bytes.byteLength>64*1024){const n=new Error("Child process input chunks must be at most 64 KiB.");return r.controller.abort(n),r.input.cancel(n),!0}r.input.write(new Uint8Array(t.bytes)).then(()=>{!this.disposed&&this.children.get(t.id)===r&&this.send({type:"child-input-consumed",id:t.id})}).catch(n=>{!this.disposed&&this.children.get(t.id)===r&&r.controller.abort(n)})}else if(t.type==="child-stdin-end")r.input?.end();else if(t.type==="child-resize"&&r.terminal){r.terminal.columns=t.columns,r.terminal.rows=t.rows;for(const n of[...r.resizes])try{n(t.columns,t.rows)}catch(s){r.controller.abort(s)}}return!0}detach(){this.close(!1)}dispose(){this.close(!0)}close(t){if(!this.disposed){this.disposed=!0;for(const r of this.children.values()){if(t){r.controller.abort(),r.input?.cancel();for(const n of r.descriptors.values())n.cancel()}else{r.input?.end();for(const n of r.descriptors.values())n.end()}r.resizes.clear()}this.children.clear()}}async start(t){const r={controller:new AbortController,resizes:new Set,descriptors:new Map((t.descriptors??[]).map(s=>[s,new T7])),...t.liveStdin?{input:new T7}:{}};t.terminal&&(r.terminal={...t.terminal,onResize:s=>(r.resizes.add(s),()=>{r.resizes.delete(s)})}),this.children.set(t.id,r);const n={};for(const[s,i]of r.descriptors)n[s]=this.descriptor(t.id,s,i,r);try{const s=await this.run(t,{...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{},...t.executablePath!==void 0?{executablePath:t.executablePath}:{},...t.filesystemPolicy!==void 0?{filesystemPolicy:t.filesystemPolicy}:{},...t.stdin!==void 0?{stdin:t.stdin}:{},...r.input?{stdinStream:r.input}:{},...r.terminal?{terminal:r.terminal}:{},...r.descriptors.size>0?{descriptors:n}:{},signal:r.controller.signal,onStdout:i=>{this.disposed||this.send({type:"child-output",id:t.id,stream:"stdout",chunk:i})},onStderr:i=>{this.disposed||this.send({type:"child-output",id:t.id,stream:"stderr",chunk:i})}});this.disposed||this.send({type:"child-result",id:t.id,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,...s.signal?{signal:s.signal}:{}})}catch(s){if(!this.disposed)try{this.send({type:"child-error",id:t.id,error:s instanceof Error?s.message:String(s)})}catch(i){console.error("Child process result transport failed.",i)}}finally{r.input?.cancel();for(const s of r.descriptors.values())s.cancel();r.resizes.clear(),this.children.delete(t.id)}}descriptor(t,r,n,s){let i=!1;const a=()=>!i&&!this.disposed&&this.children.get(t)===s;return{input:n,write:o=>{for(let l=0;l<o.byteLength&&a();l+=R2){const c=Uint8Array.from(o.subarray(l,l+R2)).buffer;this.send({type:"child-fd-output",id:t,fd:r,bytes:c},[c])}},end:()=>{a()&&(i=!0,this.send({type:"child-fd-close",id:t,fd:r}))}}}}const NT=32,_ge=64,Ige=3e4,Mge=5*6e4,Dge=50,$T=20,RT=18e4,Lge=18e4;class Oc{filesystemPolicySupported=!1;inputBytesSupported=!1;get capabilities(){return this.filesystemPolicySupported?Object.freeze({filesystemPolicy:!0}):Object.freeze({})}vfs;serverBridge;webSocketTransport={post:t=>this.send({type:"ws",message:t}),listen:t=>(this.webSocketListeners.add(t),()=>this.webSocketListeners.delete(t)),close:()=>this.webSocketListeners.clear()};webSocketListeners=new Set;isolated=!0;host;workspaceStore;pendingStoreStats=new Map;pendingImageStartup=new Map;pendingImagePrefetch=new Map;imagePrefetchDone=new Map;pendingLinks=new Map;pendingPrograms=new Map;pendingLayers=new Map;layerSources=new Set;pendingPacks=new Map;pendingPackStore=new Map;port;localServers=new Map;hostPortsKey="";remotePorts=new Set;remoteRegistrations=new Map;stopObservingPorts;runs=new Map;settledRuns=new Map;tokens=new Map;requests=new Map;portStreams=new Map;nativeFetch=globalThis.fetch.bind(globalThis);assetUrls=new Set;planPackUrls=new Set;lifetime=new AbortController;fetchControllers=new Map;fetchAuthorities=new Map;relayCapabilities;fetchPullWaiters=new Map;fetchPullCredits=new Map;sequence=1;executionPolicy;stopExecutionPolicy;activeFetches=0;fetchSlots=[];networkBytes=0;responsivenessProfiles=new Map;nextProfileProbe=1;profileTimer;disposed=!1;treeImportSupported=!1;entryReadSupported=!1;startupWaiters=new Set;constructor(t,r,n,s){this.host=t,this.port=r,this.vfs=n,this.serverBridge=s??{getServerPorts:()=>[...this.localServers.keys()].sort((i,a)=>i-a),getServerUrl:i=>`http://localhost:${i}/`,registerServer:(i,a)=>{if(this.localServers.has(a))throw new Error(`Virtual port ${a} is already registered.`);this.localServers.set(a,i)},unregisterServer:i=>{this.localServers.delete(i)},handleRequest:(i,a,o,l,c)=>{const u=this.localServers.get(i);return u?u.handleRequest(a,o,l,c?new Uint8Array(c):void 0):Promise.resolve({statusCode:503,statusMessage:"Service Unavailable",headers:{},body:new Uint8Array})}},this.stopObservingPorts=l6(this.serverBridge,i=>{i.type==="close"&&(this.remotePorts.delete(i.port),this.remoteRegistrations.delete(i.port));const a=this.serverBridge.getServerPorts().filter(l=>og(this.serverBridge,l)?.fetch),o=a.join(",");if(o!==this.hostPortsKey){this.hostPortsKey=o;try{this.send({type:"host-ports",ports:a})}catch{}}}),this.port.addEventListener("message",i=>{this.receive(i.data).catch(a=>this.failTransport(a))}),this.port.addEventListener("messageerror",()=>this.failTransport(new Error("Browser Node host returned an unreadable message."))),this.port.addEventListener("close",()=>this.failTransport(new Error("Browser Node host port closed."))),this.port.start()}static async create(t){const r=new URL(t.hostUrl,location.href);if(r.origin===location.origin)throw new Error("Browser Node host must use a different origin.");if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error("Browser Node host must use HTTP(S).");if(r.protocol==="http:"&&r.hostname!=="localhost"&&r.hostname!=="127.0.0.1")throw new Error("Browser Node host requires HTTPS outside loopback development.");const n=crypto.randomUUID().replaceAll("-","")+crypto.randomUUID().replaceAll("-","");r.searchParams.set("parentOrigin",location.origin),r.hash=n;const s=document.createElement("iframe");s.hidden=!0,s.sandbox.add("allow-scripts","allow-same-origin"),s.allow="cross-origin-isolated",s.referrerPolicy="no-referrer",s.src=r.href;const i=Pge(s);document.body.appendChild(s);let a,o;try{if(await i,!s.contentWindow)throw new Error("Browser Node host has no content window.");o=new MessageChannel;const{filesystem:l,bind:c}=Oc.storeClient(t,r.origin);a=new Oc({dispose:()=>s.remove()},o.port1,l,t.portBridge),c(a);const u=a.waitFor("attached",t.startupTimeoutMs??15e3);return u.catch(()=>{}),s.contentWindow.postMessage({channel:zj,nonce:n,port:o.port2},r.origin,[o.port2]),await u,await a.initialize(t,l,t.startupTimeoutMs??15e3),a}catch(l){try{a?.dispose()}catch(c){console.error("Browser Node startup cleanup failed.",c)}throw o?.port1.close(),o?.port2.close(),s.remove(),l}}static storeClient(t,r=location.origin){let n;const s={apply:i=>n?.applyStoreOperations(i),read:i=>n?n.readStoreFile(i):Promise.reject(new Error("The browser Node host is not attached.")),readEntry:i=>n?n.readStoreEntry(i):Promise.reject(new Error("The browser Node host is not attached.")),flush:()=>n?.flushStore()??Promise.resolve(),importTree:i=>n?n.importStoreTree(i):Promise.reject(new Error("The browser Node host is not attached."))};return{filesystem:new Ev(s,[],t.store.projectId,r),bind:i=>{n=i}}}async initialize(t,r,n){const s=t.store.image;if(s){const u=new URL(s.url,location.href),d=new URL(`${u.pathname.slice(0,-5)}/`,u),p=new URL(s.prepared.url,u);if(u.origin!==location.origin||!u.pathname.endsWith(".layers.json")||!p.href.startsWith(d.href)||!/^[a-f0-9]{16,64}$/u.test(s.digest)||!/^[a-f0-9]{64}$/u.test(s.prepared.digest))throw new Error("The fresh project index is outside this image's immutable transport.");this.layerSources.add(p.href),this.layerSources.add(d.href)}const i=t.bundler?.rollupModuleUrl;for(const u of[t.bundler?.esbuildWasmUrl,...i?[new URL("bindings_wasm_bg.wasm",new URL(i,location.href)).href]:[],t.toolchain?.standIns?.prismaSchemaModuleUrl,t.toolchain?.standIns?.prismaSchemaWasmUrl]){if(!u)continue;const d=new URL(u,location.href);d.origin===location.origin&&!d.username&&!d.password&&this.assetUrls.add(d.href)}const a=this.sequence++,o=this.waitForInitialized(n,a);o.catch(()=>{});const l=t.container??{};this.send({type:"init",childInputVersion:1,...typeof SharedArrayBuffer<"u"&&r.storeOrigin===location.origin?{sharedPageIndexVersion:2}:{},id:a,options:{...l.cwd?{cwd:l.cwd}:{},...l.env?{env:l.env}:{},...l.baseUrl?{baseUrl:l.baseUrl}:{}},store:t.store,...t.bundler?{bundler:t.bundler}:{},...t.toolchain?{toolchain:t.toolchain}:{}});const c=await o;if(t.store.limits&&c.limitsVersion!==1)throw new Error("This Node worker does not support the requested workspace limits.");this.treeImportSupported=c.treeImport===!0,this.entryReadSupported=c.entryReadVersion===1,c.sharedIndex?r.initializeSharedIndex(c.sharedIndex):r.applyIndex(c.index),this.workspaceStore={opened:c.opened,...c.preparedImage?{preparedImage:c.preparedImage}:{},...c.preparedImage&&c.preparedTrees?{preparedTrees:c.preparedTrees}:{},stats:()=>this.requestStoreStats(),flush:()=>r.flush()}}static async createInWorker(t){console.log("[boot-trace]",JSON.stringify({event:"worker-create",at:Date.now()}));const r=bf(new Worker(new URL(t.workerUrl,location.href).href,{type:"module",name:"browser-node-execution"})),n=new MessageChannel,{filesystem:s,bind:i}=Oc.storeClient(t),a=new Oc({dispose:()=>r.terminate()},n.port1,s,t.portBridge);let o=!1;r.addEventListener("error",l=>{const c=l;if(!o){a.failTransport(new Error(`Browser Node worker failed before attachment: ${c.message||String(c.error??"unknown worker error")}`));return}a.reportWorkerUncaught(c)}),r.addEventListener("exit",()=>a.failTransport(new Error("Browser Node worker exited."))),i(a);try{const l=a.waitFor("attached",t.startupTimeoutMs??Lge);return l.catch(()=>{}),console.log("[boot-trace]",JSON.stringify({event:"worker-attach-sent",at:Date.now()})),r.postMessage({type:"attach",port:n.port2,lazyEngine:!0},[n.port2]),await l,o=!0,await a.initialize(t,s,t.startupTimeoutMs??15e3),a}catch(l){try{a.dispose()}catch(c){console.error("Browser Node startup cleanup failed.",c)}throw n.port2.close(),r.terminate(),l}}pendingReads=new Map;pendingEntryReads=new Map;pendingFlushes=new Map;pendingImports=new Map;importStoreTree(t){if(this.disposed)return Promise.reject(new Error("The browser Node host is disposed."));if(!this.treeImportSupported)return Promise.resolve({applied:!1,changes:[]});const r=this.sequence++;return new Promise((n,s)=>{this.pendingImports.set(r,{resolve:n,reject:s});try{const i=[...new Set(t.entries.flatMap(a=>a.type==="file"?[a.bytes.buffer]:[]))];this.send({type:"fs-import",id:r,tree:t},i)}catch(i){this.pendingImports.delete(r),s(i)}})}applyStoreOperations(t){this.assertActive();const r=[],n=t.map(s=>{if(s.op!=="write")return s;const i=s.bytes.buffer.slice(s.bytes.byteOffset,s.bytes.byteOffset+s.bytes.byteLength);return r.push(i),{...s,bytes:i}});this.send({type:"fs-apply",operations:n},r)}readStoreFile(t){if(this.disposed)return Promise.reject(new Error("The browser Node host is disposed."));const r=this.sequence++;return new Promise((n,s)=>{this.pendingReads.set(r,{resolve:n,reject:s});try{this.send({type:"fs-read",id:r,path:t})}catch(i){this.pendingReads.delete(r),s(i)}})}readStoreEntry(t){if(this.disposed)return Promise.reject(new Error("The browser Node host is disposed."));if(!this.entryReadSupported)return Promise.reject(new Error("This Node worker does not support coherent filesystem entry reads."));const r=this.sequence++;return new Promise((n,s)=>{this.pendingEntryReads.set(r,{resolve:n,reject:s});try{this.send({type:"fs-entry",id:r,path:t})}catch(i){this.pendingEntryReads.delete(r),s(i)}})}flushStore(){if(this.disposed)return Promise.reject(new Error("Browser Node host was disposed before filesystem flush."));const t=this.sequence++;return new Promise((r,n)=>{this.pendingFlushes.set(t,{resolve:r,reject:n});try{this.send({type:"fs-flush",id:t})}catch(s){this.pendingFlushes.delete(t),n(s)}})}settleStore(){this.vfs.flushPending()}pendingWatchedPaths=new Map;requestWatchedPaths(){if(this.disposed)return Promise.resolve([]);const t=this.sequence++;return new Promise(r=>{this.pendingWatchedPaths.set(t,r),this.send({type:"watched-paths",id:t}),globalThis.setTimeout(()=>{this.pendingWatchedPaths.delete(t)&&r([])},5e3)})}imageStartupSet(){if(this.disposed)return Promise.resolve([]);const t=this.sequence++;return new Promise(r=>{this.pendingImageStartup.set(t,r),this.send({type:"image-startup-set",id:t}),globalThis.setTimeout(()=>{this.pendingImageStartup.delete(t)&&r([])},1e4)})}prefetchImage(t,r,n=[]){if(this.disposed)return Promise.resolve(0);const s=this.sequence++;return r&&this.imagePrefetchDone.set(s,r),new Promise(i=>{this.pendingImagePrefetch.set(s,a=>{a===0&&this.imagePrefetchDone.delete(s),i(a)}),this.send({type:"image-prefetch",id:s,ranges:[...t],...n.length?{streams:[...n]}:{}}),globalThis.setTimeout(()=>{this.pendingImagePrefetch.delete(s)&&i(0)},1e4)})}requestStoreStats(){if(this.disposed)return Promise.resolve(void 0);const t=this.sequence++;return new Promise(r=>{this.pendingStoreStats.set(t,r),this.send({type:"store-stats",id:t}),globalThis.setTimeout(()=>{this.pendingStoreStats.delete(t)&&r(void 0)},1e4)})}linkPackages(t,r,n){this.assertActive();const s=r.packages.filter(a=>!a.pack||new URL(a.pack.url,location.href).origin!==location.origin);if(s.length>0){const a=s.slice(0,5).map(o=>`${o.name}@${o.version}`).join(", ");try{_c({door:"plan",subject:`${s.length} of the ${r.packages.length} packages for ${t} have no pack this page serves (${a}${s.length>5?", …":""})`,detail:{root:t,unpacked:s.length}})}catch(o){return Promise.reject(o)}}for(const a of r.packages)a.pack&&this.planPackUrls.add(new URL(a.pack.url,location.href).href);const i=this.sequence++;return new Promise((a,o)=>{this.pendingLinks.set(i,{resolve:a,reject:o,...n?{progress:n}:{}}),this.send({type:"link-packages",id:i,root:t,plan:r})})}warmEngine(){this.assertActive(),this.send({type:"warm-engine"})}linkImageProgram(t,r){if(this.assertActive(),!t.startsWith("/packages/.programs/")||!r.startsWith("/"))return Promise.reject(new Error(`${t} is not a program the image's layers place, or ${r} is not a root.`));const n=this.sequence++;return new Promise((s,i)=>{this.pendingPrograms.set(n,{resolve:s,reject:i}),this.send({type:"link-program",id:n,source:t,target:r})})}applyImageLayers(t,r,n,s){this.assertActive();const i=new URL(t,location.href);if(i.origin!==location.origin||!i.pathname.endsWith(".json"))return Promise.reject(new Error(`${t} is not an image layers document this page serves.`));if(s&&!new URL(s.url,i).href.startsWith(new URL(`${i.pathname.slice(0,-5)}/`,i).href))return Promise.reject(new Error("The prepared layers descriptor is outside its image's immutable transport."));this.layerSources.add(i.href),s&&this.layerSources.add(new URL(s.url,i).href),this.layerSources.add(new URL(`${i.pathname.slice(0,-5)}/`,i).href);const a=this.sequence++;return new Promise((o,l)=>{this.pendingLayers.set(a,{resolve:o,reject:l,...n?{progress:n}:{}}),this.send({type:"apply-layers",id:a,url:i.href,digest:r,...s?{prepared:{...s,url:new URL(s.url,i).href}}:{}})})}async readImagePacks(t){this.assertActive(),this.send({type:"image-packs-expected"});try{return await this.readImagePackIndex(t)}catch(r){throw this.disposed||this.send({type:"image-packs-abandoned"}),r}}async readImagePackIndex(t){const r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`The image's packs could not be read: ${r.status}`);const n=await r.json();this.imagePackUrls.clear();for(const o of n.packs??[])typeof o?.key!="string"||typeof o.path!="string"||this.imagePackUrls.set(o.key,new URL(o.path,r.url||t).href);const s=[];for(const o of n.modules??[])typeof o?.key!="string"||!/^[0-9a-f]{64}$/u.test(o.key)||typeof o.path!="string"||(this.imagePackUrls.set(o.key,new URL(o.path,r.url||t).href),s.push(o.key));const i=new Set(s),a=this.sequence++;return new Promise((o,l)=>{this.pendingPacks.set(a,{resolve:o,reject:l}),this.send({type:"image-packs",id:a,keys:[...this.imagePackUrls.keys()].filter(c=>!i.has(c)),bodies:s})})}imagePackUrls=new Map;async sendImagePack(t,r){const n=this.imagePackUrls.get(r);try{if(!n)throw new Error("the image carries no such pack");const s=await fetch(n,{cache:"no-store"});if(!s.ok)throw new Error(`${s.status}`);this.send({type:"image-pack",id:t,text:await s.text()})}catch(s){this.send({type:"image-pack",id:t,error:s instanceof Error?s.message:String(s)})}}async sendImageFile(t,r,n){try{const s=new URL(r,location.href),i=Bg.get(s.href);Bg.delete(s.href);const a=i!==void 0&&(i.part===void 0?n===void 0:n!==void 0&&n.bytes===i.part.bytes&&n.raw===i.part.raw&&n.sha256===i.part.sha256),o=await(i&&a&&this.imageFileAdmitted(s)?i.reading:this.readImageFile(s.href,n));this.send({type:"image-file",id:t,bytes:o.bytes,...o.inflated?{inflated:!0}:{}},[o.bytes])}catch(s){this.send({type:"image-file",id:t,error:s instanceof Error?s.message:String(s)})}}imageFileAdmitted(t){const r=!t.search&&!t.hash&&[...this.layerSources].some(n=>n.endsWith("/")?t.href.startsWith(n)&&/^[0-9a-f]{64}\.bin$/u.test(t.href.slice(n.length)):t.href===n);return t.origin===location.origin&&(this.planPackUrls.has(t.href)||r)}async readImageFile(t,r){const n=new URL(t,location.href);if(!this.imageFileAdmitted(n))throw new Error(`${t} is not a pack a plan linked here names`);return SF(n,r)}browserPackStore(){return{has:async t=>!!(await this.requestPackStore({action:"has",digest:t})).present,readArtifact:async t=>{const r=(await this.requestPackStore({action:"read-artifact",digest:t})).bytes;if(!r)throw new Error(`Pack artifact ${t} returned no bytes.`);return new Uint8Array(r)},linkArchive:async(t,r)=>{await this.requestPackStore({action:"link-archive",digest:t,target:r})},availableBytes:async()=>(await this.requestPackStore({action:"available"})).availableBytes,stageArtifact:async(t,r,n,s)=>{const i=r.slice().buffer;await this.requestPackStore({action:"stage-artifact",digest:t,artifact:n,bytes:i},[i],s)},stageEnvironment:async(t,r)=>{await this.requestPackStore({action:"stage-environment",digest:t,lock:r})},retainEnvironment:async(t,r)=>{await this.requestPackStore({action:"retain-environment",digest:t,artifacts:[...r]})}}}requestPackStore(t,r=[],n){this.assertActive();const s=this.sequence++;return new Promise((i,a)=>{if(n?.aborted){a(n.reason??new Error("Pack staging was cancelled."));return}const o=()=>this.send({type:"pack-store-abort",id:s});n&&n.addEventListener("abort",o,{once:!0}),this.pendingPackStore.set(s,{resolve:i,reject:a,...n?{removeAbort:()=>n.removeEventListener("abort",o)}:{}}),this.send({type:"pack-store",id:s,...t},r)})}configureExecutionPolicy(t){this.stopExecutionPolicy?.(),this.executionPolicy=t,this.networkBytes=0,this.stopExecutionPolicy=t.onChange(()=>{for(const[r,n]of this.fetchAuthorities)try{t.authorize(n.program,n.url)}catch{this.fetchControllers.get(r)?.abort(new Error("Browser Node egress grant was revoked."))}})}listenNet(t,r){if(this.assertActive(),!Number.isInteger(t)||t<1||t>65535)throw new RangeError("Invalid loopback listener port.");if(this.netListeners.has(t))throw Object.assign(new Error(`Port ${t} is already in use.`),{code:"EADDRINUSE"});return this.netListeners.set(t,r),this.send({type:"listen-net",port:t}),()=>{this.netListeners.get(t)===r&&(this.netListeners.delete(t),this.send({type:"unlisten-net",port:t}))}}netListeners=new Map;netSockets=new Map;acceptNetConnection(t,r){const n=this.netListeners.get(t);if(!n){this.send({type:"net-end",socket:r});return}if(!Number.isSafeInteger(r)||r<1||this.netSockets.has(r))throw new Error("Invalid loopback socket identity.");const s=new Rge(r,(i,a)=>this.send(i,a),()=>this.netSockets.delete(r));this.netSockets.set(r,s),n(s)}configureChildProcesses(t){this.childRunner=t}childRunner;childProcesses=new Oge(async(t,r)=>{if(this.assertActive(),!this.childRunner)throw new Error(`${t.command.split(" ",1)[0]}: command not found`);const n=t.owner===null?void 0:this.runs.get(t.owner)?.options??this.settledRuns.get(t.owner);if(t.owner!==null&&!n)throw new Error("The child process's parent context is no longer available.");const s=n?.filesystemPolicy?Xg(n.filesystemPolicy,t.filesystemPolicy):t.filesystemPolicy===void 0?void 0:es(t.filesystemPolicy),i=n?.signal?AbortSignal.any([n.signal,r.signal]):r.signal;i?.throwIfAborted();const{cwd:a,env:o,signal:l,filesystemPolicy:c,...u}=r,d=r.cwd??n?.cwd,p=r.env??n?.env;return this.childRunner(t.command,{...u,...s!==void 0?{filesystemPolicy:s}:{},...d!==void 0?{cwd:d}:{},...p!==void 0?{env:p}:{},...i?{signal:i}:{},held:!1},t.argv)},(t,r)=>this.send(t,r));run(t,r={}){if(r={...r,...r.env!==void 0?{env:{...r.env}}:{},...r.terminal!==void 0?{terminal:{...r.terminal}}:{},...r.filesystemPolicy===void 0?{}:{filesystemPolicy:es(r.filesystemPolicy)}},Ic(r.filesystemPolicy,this.capabilities),this.assertActive(),r.signal?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:130});this.settleStore();const n=this.sequence++,s=r[lR],i=r.processToken;if(typeof i=="string")for(this.tokens.set(i,n);this.tokens.size>NT;){const a=this.tokens.keys().next().value;if(a===void 0)break;this.tokens.delete(a)}return new Promise((a,o)=>{const l=new AbortController;let c,u;const d=()=>{l.abort(r.signal?.reason),u?.reject(l.signal.reason),u=void 0,this.settledRuns.delete(n);try{this.send({type:"abort",id:n})}catch(p){this.failTransport(p)}};r.signal?.addEventListener("abort",d,{once:!0}),this.runs.set(n,{resolve:a,reject:o,options:r,consumeInput:()=>{const p=u;u=void 0,p?.resolve()},removeAbort:()=>{r.signal?.removeEventListener("abort",d),l.abort(new DOMException("The process finished.","AbortError")),u?.reject(l.signal.reason),u=void 0;const p=c;c=void 0;try{p?.()}catch(m){console.error("Process resize subscription cleanup failed.",m)}},...s!==void 0?{runtimePid:s}:{}});try{if(this.send({type:"run",...r.filesystemPolicy?{filesystemPolicy:r.filesystemPolicy}:{},id:n,command:t,...r.executablePath?{executablePath:r.executablePath}:{},...r.cwd?{cwd:r.cwd}:{},...r.env?{env:{...r.env}}:{},interactive:r.held===!0,...typeof r.stdin=="string"?{stdin:r.stdin}:{},...r.stdinStream?{liveStdin:!0}:{},...r.terminal?{terminal:{columns:r.terminal.columns,rows:r.terminal.rows}}:{}}),r.stdinStream){const p=new TextDecoder("utf-8",{fatal:!0});bX(r.stdinStream,async m=>{if(!this.inputBytesSupported){this.send({type:"stdin",id:n,data:p.decode(m,{stream:!0})});return}for(let g=0;g<m.byteLength;g+=64*1024){l.signal.throwIfAborted();const b=Uint8Array.from(m.subarray(g,g+64*1024)).buffer;await new Promise((v,S)=>{u={resolve:v,reject:S};try{this.send({type:"stdin",id:n,data:"",bytes:b},[b])}catch(x){u=void 0,S(x)}})}},l.signal).then(()=>{if(l.signal.aborted||this.disposed)return;const m=p.decode();m&&this.send({type:"stdin",id:n,data:m}),this.send({type:"stdin-end",id:n})}).catch(m=>{if(l.signal.aborted||this.disposed)return;const g=this.runs.get(n);g&&(g.inputFailure=m instanceof Error?m:new Error(String(m)),d())})}c=r.terminal?.onResize?.((p,m)=>{if(!this.disposed&&!l.signal.aborted)try{this.send({type:"resize",id:n,columns:p,rows:m})}catch(g){this.failTransport(g)}}),s!==void 0&&this.startProfiling(s)}catch(p){const m=this.runs.get(n);this.runs.delete(n),m?.removeAbort(),this.stopProfiling(s);try{this.send({type:"abort",id:n})}catch{}o(p)}})}processProfile(t){const r=this.responsivenessProfiles.get(t);if(!r)return;const n=r.pending?Math.max(0,performance.now()-r.pending.sentAt-$T):0;return{busyMs:Math.round(r.busyMs+n),fidelity:"visible-tab event-loop responsiveness estimate; wall clock and output bytes"}}sendInput(t,r){if(this.assertActive(),r!==void 0){const n=this.tokens.get(r);if(n===void 0)return;this.send({type:"stdin",id:n,data:t});return}this.send({type:"stdin",data:t})}stopProcess(t){const r=this.tokens.get(t);return r===void 0?!1:(this.tokens.delete(t),this.settledRuns.delete(r),this.disposed||this.send({type:"abort",id:r}),!0)}reportWorkerUncaught(t){const r=t.message||String(t.error??"Error");let n="";const s=t.error instanceof Error?t.error.stack:void 0;if(typeof s=="string")for(const o of s.split(`
1716
1716
  `).slice(1)){const l=o.trim();if(l.startsWith("at ")){n=l;break}}!n&&t.filename&&(n=`at ${t.filename}:${t.lineno}:${t.colno}`);let i="";for(const o of this.runs.values())if(o.runtimePid!==void 0){i=o.runtimePid;break}const a=i===""?"run":`run ${i}`;console.error(`[${a}] ended uncaught: ${r}${n?` ${n}`:""}`)}failTransport(t){if(this.disposed)return;const r=t instanceof Error?t:new Error(String(t));console.error(`Browser Node worker stopped: ${r.message}`,r);for(const n of this.startupWaiters)n(r);for(const n of this.runs.values())n.removeAbort(),n.reject(r);this.runs.clear();for(const n of this.requests.values())n.reject(r);this.requests.clear();for(const n of this.pendingReads.values())n.reject(r);this.pendingReads.clear();for(const n of this.pendingEntryReads.values())n.reject(r);this.pendingEntryReads.clear();for(const n of this.pendingFlushes.values())n.reject(r);this.pendingFlushes.clear();for(const n of this.pendingImports.values())n.reject(r);this.pendingImports.clear();for(const n of this.pendingPackStore.values())n.removeAbort?.(),n.reject(r);this.pendingPackStore.clear();for(const n of this.pendingLinks.values())n.reject(r);this.pendingLinks.clear();for(const n of this.pendingLayers.values())n.reject(r);this.pendingLayers.clear();for(const n of this.pendingPrograms.values())n.reject(r);this.pendingPrograms.clear();try{this.dispose()}catch(n){console.error("Browser Node transport cleanup failed.",n)}}dispose(){if(this.disposed)return;this.disposed=!0;for(const n of this.startupWaiters)n(new Error("Browser Node host was disposed during startup."));const t=[],r=n=>{try{n()}catch(s){t.push(s)}};r(()=>this.send({type:"dispose"})),r(()=>this.lifetime.abort(new Error("Browser Node host was disposed.")));for(const n of[...this.portStreams.values()])r(()=>n.fail(new Error("Browser Node host was disposed during a streamed response.")));for(const n of this.fetchControllers.values())r(()=>n.abort(this.lifetime.signal.reason));this.fetchControllers.clear(),r(()=>this.stopExecutionPolicy?.()),this.stopExecutionPolicy=void 0;for(const n of this.fetchSlots.splice(0))n();r(()=>this.childProcesses.dispose()),this.profileTimer!==void 0&&globalThis.clearInterval(this.profileTimer),this.profileTimer=void 0,this.responsivenessProfiles.clear(),r(()=>this.port.close()),r(()=>this.host.dispose());for(const n of this.netSockets.values())r(()=>n.finish());this.netSockets.clear(),this.netListeners.clear();for(const n of this.pendingFlushes.values())n.reject(new Error("Browser Node host was disposed before filesystem flush."));this.pendingFlushes.clear();for(const n of this.pendingReads.values())n.reject(new Error("Browser Node host was disposed before filesystem read."));this.pendingReads.clear();for(const n of this.pendingEntryReads.values())n.reject(new Error("Browser Node host was disposed before filesystem entry read."));this.pendingEntryReads.clear();for(const n of this.pendingImports.values())n.reject(new Error("Browser Node host was disposed before workspace import completed."));this.pendingImports.clear();for(const n of this.runs.values())r(()=>n.removeAbort()),n.resolve({stdout:"",stderr:"",exitCode:143});this.runs.clear();for(const n of this.requests.values())n.reject(new Error("Browser Node host was disposed."));this.requests.clear();for(const n of this.pendingStoreStats.values())n(void 0);this.pendingStoreStats.clear();for(const n of this.pendingImageStartup.values())n([]);this.pendingImageStartup.clear();for(const n of this.pendingImagePrefetch.values())n(0);this.pendingImagePrefetch.clear(),this.imagePrefetchDone.clear();for(const n of this.pendingPackStore.values())n.removeAbort?.(),n.reject(new Error("Browser Node host was disposed during pack staging."));this.pendingPackStore.clear();for(const[n,s]of this.remoteRegistrations)r(()=>ov(this.serverBridge,n,s));if(this.remoteRegistrations.clear(),r(this.stopObservingPorts),this.remotePorts.clear(),this.localServers.clear(),this.settledRuns.clear(),this.tokens.clear(),t.length)throw new AggregateError(t,"Browser Node host cleanup failed.")}async receive(t){if(!this.disposed&&!this.childProcesses.receive(t)){if(t.type==="stdin-consumed"){this.runs.get(t.id)?.consumeInput?.();return}if(t.type==="fs-index")this.vfs instanceof Ev&&this.vfs.applyIndex(t.changes);else if(t.type==="fs-read-result"){const r=this.pendingReads.get(t.id);this.pendingReads.delete(t.id),r?.resolve(new Uint8Array(t.bytes))}else if(t.type==="fs-entry-result"){const r=this.pendingEntryReads.get(t.id);this.pendingEntryReads.delete(t.id),r?.resolve(t.entry)}else if(t.type==="fs-flushed"){const r=this.pendingFlushes.get(t.id);this.pendingFlushes.delete(t.id),r?.resolve()}else if(t.type==="fs-imported"){const r=this.pendingImports.get(t.id);this.pendingImports.delete(t.id),r?.resolve({applied:t.applied,changes:t.changes})}else if(t.type==="ws")for(const r of this.webSocketListeners)r(t.message);else if(t.type==="watched-paths"){const r=this.pendingWatchedPaths.get(t.id);this.pendingWatchedPaths.delete(t.id),r?.(t.paths)}else if(t.type==="image-startup-set"){const r=this.pendingImageStartup.get(t.id);this.pendingImageStartup.delete(t.id),r?.(t.ranges)}else if(t.type==="image-prefetch"){const r=this.pendingImagePrefetch.get(t.id);this.pendingImagePrefetch.delete(t.id),r?.(t.queued)}else if(t.type==="image-prefetched"){const r=this.imagePrefetchDone.get(t.id);this.imagePrefetchDone.delete(t.id),r?.(t.ms)}else if(t.type==="store-stats"){const r=this.pendingStoreStats.get(t.id);this.pendingStoreStats.delete(t.id),r?.(t.stats??void 0)}else if(t.type==="linking-packages")this.pendingLinks.get(t.id)?.progress?.(t.linked,t.total,t.waiting);else if(t.type==="applying-layers")this.pendingLayers.get(t.id)?.progress?.(t.parts,t.total);else if(t.type==="layers-applied"){const r=this.pendingLayers.get(t.id);if(this.pendingLayers.delete(t.id),!r)return;t.error!==void 0?r.reject(new Error(t.error)):r.resolve({parts:t.parts,units:t.units,bytes:t.bytes,skipped:t.skipped})}else if(t.type==="linked-program"){const r=this.pendingPrograms.get(t.id);if(this.pendingPrograms.delete(t.id),!r)return;t.error!==void 0?r.reject(new Error(t.error)):r.resolve({linked:t.linked,files:t.files})}else if(t.type==="linked-packages"){const r=this.pendingLinks.get(t.id);if(this.pendingLinks.delete(t.id),!r)return;t.error!==void 0?r.reject(new Error(t.error)):r.resolve({linked:t.linked,fetched:t.fetched,fromStore:t.fromStore})}else if(t.type==="image-pack-read")this.sendImagePack(t.id,t.key);else if(t.type==="image-file-read")this.sendImageFile(t.id,t.url,t.part);else if(t.type==="image-packs-read"){const r=this.pendingPacks.get(t.id);if(this.pendingPacks.delete(t.id),!r)return;t.error!==void 0?r.reject(new Error(t.error)):r.resolve(t.packs)}else if(t.type==="pack-store-result"){const r=this.pendingPackStore.get(t.id);if(this.pendingPackStore.delete(t.id),r?.removeAbort?.(),!r)return;if(t.error){const n=new Error(t.error.message);t.error.category&&(n.category=t.error.category),r.reject(n)}else r.resolve({...t.present!==void 0?{present:t.present}:{},...t.availableBytes!==void 0?{availableBytes:t.availableBytes}:{},...t.bytes!==void 0?{bytes:t.bytes}:{}})}else if(t.type==="profile-pong")this.acceptProfilePong(t.id);else if(t.type==="output"){const r=this.runs.get(t.id)?.options??this.settledRuns.get(t.id);t.stream==="stdout"?r?.onStdout?.(t.chunk):r?.onStderr?.(t.chunk)}else if(t.type==="result"){const r=this.runs.get(t.id);if(!r)return;if(this.runs.delete(t.id),r.removeAbort(),this.stopProfiling(r.runtimePid),r.inputFailure){r.reject(r.inputFailure);return}for(this.settledRuns.set(t.id,r.options);this.settledRuns.size>NT;){const n=this.settledRuns.keys().next().value;if(n===void 0)break;this.settledRuns.delete(n)}r.resolve({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}else if(t.type==="error"){const r=new Error(t.error);t.stack&&(r.stack=t.stack);const n=this.runs.get(t.id);if(n){if(this.runs.delete(t.id),n.removeAbort(),this.stopProfiling(n.runtimePid),n.inputFailure){n.reject(n.inputFailure);return}n.reject(r);return}const s=this.requests.get(t.id);if(s){this.requests.delete(t.id),s.reject(r);return}const i=this.portStreams.get(t.id);if(i){i.fail(r);return}const a=this.pendingReads.get(t.id);a&&(this.pendingReads.delete(t.id),a.reject(r));const o=this.pendingEntryReads.get(t.id);o&&(this.pendingEntryReads.delete(t.id),o.reject(r));const l=this.pendingFlushes.get(t.id);l&&(this.pendingFlushes.delete(t.id),l.reject(r));const c=this.pendingImports.get(t.id);c&&(this.pendingImports.delete(t.id),c.reject(r))}else if(t.type==="port"){if(console.log(`[port] ${t.action} ${t.port} reached the page at ${Math.round(performance.now())} ms`),t.action==="open"){if(this.remotePorts.has(t.port))return;const r={listening:!0,address:()=>({port:t.port,address:"0.0.0.0",family:"IPv4"}),handleRequest:(n,s,i,a)=>this.requestRemote(t.port,n,s,i,typeof a=="string"?new TextEncoder().encode(a):a),handleStreamingRequest:(n,s,i,a,o,l,c,u)=>this.streamRemote(t.port,n,s,i,a,o,l,c,u)};this.remotePorts.add(t.port);try{this.serverBridge.registerServer(r,t.port,t.hostname);const n=d$(this.serverBridge,t.port,r);n?this.remoteRegistrations.set(t.port,n):this.remotePorts.delete(t.port)}catch(n){this.remotePorts.delete(t.port),this.abortForIsolationFailure(n)}}else if(this.remotePorts.delete(t.port)){const r=this.remoteRegistrations.get(t.port);this.remoteRegistrations.delete(t.port),r&&ov(this.serverBridge,t.port,r)}}else if(t.type==="port-stream-head")this.portStreams.get(t.id)?.head(t.statusCode,t.statusMessage,t.headers);else if(t.type==="port-stream-chunk")this.portStreams.get(t.id)?.chunk(new Uint8Array(t.body));else if(t.type==="port-stream-end")this.portStreams.get(t.id)?.end();else if(t.type==="response"){const r=this.requests.get(t.id);if(!r)return;this.requests.delete(t.id),r.resolve({statusCode:t.statusCode,statusMessage:t.statusMessage,headers:t.headers,body:new Uint8Array(t.body)})}else if(t.type==="fetch")await this.handleFetch(t);else if(t.type==="fetch-abort")this.fetchControllers.get(t.id)?.abort(new DOMException("The request was cancelled.","AbortError"));else if(t.type==="fetch-pull"){const r=this.fetchPullWaiters.get(t.id);r?(this.fetchPullWaiters.delete(t.id),r()):this.fetchPullCredits.set(t.id,(this.fetchPullCredits.get(t.id)??0)+1)}else if(t.type==="net-connect")this.acceptNetConnection(t.port,t.socket);else if(t.type==="net-guest-data")this.netSockets.get(t.socket)?.receive(new Uint8Array(t.chunk));else if(t.type==="net-taken")this.netSockets.get(t.socket)?.taken();else if(t.type==="net-guest-end"){const r=this.netSockets.get(t.socket);this.netSockets.delete(t.socket),r?.finish()}}}handleRequest(t,r,n,s,i,a){return a&&this.remotePorts.has(t)?this.requestRemote(t,r,n,s,i?new Uint8Array(i):void 0,a):a?.aborted?Promise.reject(a.reason):a?new Promise((o,l)=>{const c=()=>{a.removeEventListener("abort",c),l(a.reason)};a.addEventListener("abort",c,{once:!0}),Promise.resolve().then(()=>(a.throwIfAborted(),this.serverBridge.handleRequest(t,r,n,s,i))).then(u=>{a.removeEventListener("abort",c),o(u)},u=>{a.removeEventListener("abort",c),l(u)})}):this.serverBridge.handleRequest(t,r,n,s,i)}streamRemote(t,r,n,s,i,a,o,l,c){if(this.settleStore(),!this.remotePorts.has(t))return a(503,"Service Unavailable",{}),l(),Promise.resolve();const u=this.sequence++,d=i?Uint8Array.from(i).buffer:void 0,p=m=>{try{this.send({type:"port-stream-control",id:u,action:m})}catch{}};return new Promise((m,g)=>{const b=()=>this.portStreams.delete(u)?(c?.signal?.removeEventListener("abort",S),!0):!1,v=x=>{try{x()}catch(E){b()&&(p("cancel"),g(E))}},S=()=>{b()&&(p("cancel"),v(l),m())};if(this.portStreams.set(u,{head:(x,E,A)=>v(()=>a(x,E,A)),chunk:x=>v(()=>o(x)),end:()=>{this.portStreams.has(u)&&(v(l),b()&&m())},fail:x=>{b()&&g(x)}}),c?.signal?.aborted){S();return}c?.signal?.addEventListener("abort",S,{once:!0}),c?.control?.(()=>p("pause"),()=>p("resume"));try{this.send({type:"port-stream-request",id:u,port:t,method:r,url:n,headers:s,...d?{body:d}:{}},d?[d]:[])}catch(x){b()&&g(x)}})}requestRemote(t,r,n,s,i,a){if(this.settleStore(),!this.remotePorts.has(t))return Promise.resolve({statusCode:503,statusMessage:"Service Unavailable",headers:{},body:new Uint8Array});const o=this.sequence++,l=i?Uint8Array.from(i).buffer:void 0;return new Promise((c,u)=>{const d=()=>{this.requests.delete(o),a?.removeEventListener("abort",d),u(a?.reason)};if(a?.aborted){u(a.reason);return}this.requests.set(o,{resolve:p=>{a?.removeEventListener("abort",d),c(p)},reject:p=>{a?.removeEventListener("abort",d),u(p)}}),a?.addEventListener("abort",d,{once:!0});try{this.send({type:"request",id:o,port:t,method:r,url:n,headers:s,...l?{body:l}:{}},l?[l]:[])}catch(p){this.requests.delete(o),a?.removeEventListener("abort",d),u(p)}})}async handleFetch(t){const r=new AbortController,n=r.signal,s=setTimeout(()=>r.abort(new DOMException("Browser Node request timed out.","TimeoutError")),Mge),i=()=>{clearTimeout(s)},a=()=>r.abort(this.lifetime.signal.reason);let o;this.fetchControllers.set(t.id,r),this.lifetime.signal.addEventListener("abort",a,{once:!0});try{this.assertActive();const l=new URL(t.url),c=globalThis.location,u=l.port?Number(l.port):l.protocol==="https:"?443:80,d=c?c.port?Number(c.port):c.protocol==="https:"?443:80:void 0,p=!!c&&O2(l.hostname)&&O2(c.hostname)&&u===d&&!this.serverBridge.getServerPorts().includes(u);if((this.assetUrls.has(l.href)||p)&&t.method==="GET"&&!t.body){const v=p?new URL(`${l.pathname}${l.search}`,c.origin).href:l.href,S=await this.nativeFetch(v,{credentials:"omit",redirect:"error",signal:n}),x=await S.arrayBuffer();this.send({type:"fetch-response",id:t.id,status:S.status,statusText:S.statusText,headers:[...S.headers.entries()],body:x},[x]);return}if((l.protocol==="http:"||l.protocol==="https:")&&O2(l.hostname)){const v=await _2(t.body,16777216,n),S=l.port?Number(l.port):l.protocol==="https:"?443:80;if(!this.serverBridge.getServerPorts().includes(S))throw new Error(`Virtual loopback port ${S} is not listening (${l.href}; this page is ${globalThis.location?.host??"unknown"}).`);const x=Object.fromEntries(Uge(t.headers).entries());x.host=l.host;const E=og(this.serverBridge,S)?.fetch;if(E){const I=await E(new Request(`http://127.0.0.1:${S}${l.pathname}${l.search}`,{method:t.method,headers:x,...v.byteLength>0&&t.method!=="GET"&&t.method!=="HEAD"?{body:v}:{},signal:n}));i();try{this.send({type:"fetch-response-start",id:t.id,status:I.status,statusText:I.statusText,headers:[...I.headers.entries()]})}catch(O){throw await I.body?.cancel(O).catch(()=>{}),O}const U=I.body?.getReader();try{for(;;){await this.waitForFetchPull(t.id,n);const O=U?await U.read():{done:!0,value:void 0};if(O.done){this.send({type:"fetch-response-end",id:t.id});break}const _=Uint8Array.from(O.value).buffer;this.send({type:"fetch-response-chunk",id:t.id,body:_},[_])}}catch(O){throw await U?.cancel(O).catch(()=>{}),O}finally{U?.releaseLock()}return}const A=await this.handleRequest(S,t.method,`${l.pathname}${l.search}`,x,v.byteLength>0?v:void 0,n);n.throwIfAborted();const T=A.body?Uint8Array.from(A.body):new Uint8Array,D=T.buffer.slice(T.byteOffset,T.byteOffset+T.byteLength);this.send({type:"fetch-response",id:t.id,status:A.statusCode,statusText:A.statusMessage??"",headers:Object.entries(A.headers).map(([I,U])=>[I,Array.isArray(U)?U.join(", "):U]),body:D},[D]);return}const m=this.executionPolicy;if(!m)throw new Error("Browser Node egress has no embedding grant.");if(l.protocol!=="https:")throw new Error("Browser Node external requests require HTTPS.");if(l.username||l.password)throw new Error("Browser Node external requests cannot contain URL credentials.");let g=t.program;if(!t.attributed&&t.activePrograms.length>1){const v=t.activePrograms.filter(S=>{try{return m.authorize(S,l),!0}catch{return!1}});if(v.length===0&&m.authorize(g,l),v.length<t.activePrograms.length){const S=t.activePrograms.filter(x=>!v.includes(x));throw new Error(`Browser Node egress to ${l.hostname} came from no attributable program while ${t.activePrograms.join(", ")} run together; ${S.join(", ")} may not reach it, so the request is refused.`)}g=v.includes(g)?g:v[0]}try{m.authorize(g,l)}catch{const v=t.pid!==void 0?`, via child pid ${t.pid}`:"",S=t.activePrograms.length>1?`, with ${t.activePrograms.join(", ")} running`:"",x=`${t.attributed?"attributed to":"charged to"} ${g}${S}${v}`;throw new Error(`${g} may not reach ${l.hostname} (${x}): the tab's network is closed unless granted, by the World the tab is attached to or the page that embeds it. Grant ${g} egress to ${l.hostname} there to allow it.`)}for(this.fetchAuthorities.set(t.id,{program:g,url:l});this.activeFetches>=m.maxConnections;){if(this.assertActive(),n.throwIfAborted(),this.fetchSlots.length>=_ge)throw new Error("Browser Node egress queue is full.");await new Promise((v,S)=>{let x;const E=()=>{const D=this.fetchSlots.indexOf(A);D>=0&&this.fetchSlots.splice(D,1),n.removeEventListener("abort",T),clearTimeout(x)},A=()=>{E(),v()},T=()=>{E(),S(n.reason??new DOMException("The request was cancelled.","AbortError"))};this.fetchSlots.push(A),n.addEventListener("abort",T,{once:!0}),x=setTimeout(()=>{E(),S(new Error("Browser Node egress queue timed out."))},Ige),n.aborted&&T()})}this.assertActive(),n.throwIfAborted(),m.authorize(g,l);const b=!0;this.activeFetches+=1;try{if(b&&this.networkBytes>=m.maxBytes)throw new Error("Browser Node egress byte limit exceeded.");const v=ER(t.headers),S=v.some(([_])=>_.toLowerCase()==="cookie")?"explicit-guest":"omit",x=new Headers(v),E=m.resolveTransport({program:g,url:l,method:t.method,headerNames:v.map(([_])=>_),credentialMode:S,profile:t.profile??"browser-compatible"}),A=E.transport;o={attemptId:`node-${t.id}`,program:g,origin:l.origin,transport:A,ruleId:E.ruleId,policyRevision:E.policyRevision},console.info(`[browser-node-http] ${JSON.stringify({event:"selected",...o})}`);let T,D,I,U;if(A==="relay"){const _=this.meterRequestBody(t.body,m.maxBytes,n);await this.requireRelayProfile(m.fetchProxyUrl,E.profile,n),m.authorize(g,l),n.throwIfAborted();const $={version:1,id:`node-${t.id}`,url:l.href,method:t.method,headers:v,profile:E.profile,timeoutMs:3e4};let F;const P=v.filter(([V])=>V.toLowerCase()==="content-length"),W=P.length===1&&/^(?:0|[1-9][0-9]*)$/u.test(P[0][1])?Number(P[0][1]):t.body instanceof Blob?t.body.size:void 0;if(!_)F=kK($);else if(W!==void 0&&W<=vR){const V=new Uint8Array(await _2(_,W,n));if(V.byteLength!==W)throw new Error("Node HTTP request length does not match its body.");F=xR($,V)}else F=AK($,_);m.authorize(g,l),n.throwIfAborted();const K=await this.nativeFetch(m.fetchProxyUrl,{method:"POST",headers:{"Content-Type":Vb},body:F,credentials:"omit",redirect:"error",signal:n,...F instanceof ReadableStream?{duplex:"half"}:{}});if(!K.ok||K.headers.get("Content-Type")?.split(";",1)[0]?.trim()!==Vb||!K.body){const V=await Fge(K);throw new Error(`Browser Node relay refused the request (${K.status})${V?`: ${V}`:"."}`)}const Y=await CK(K.body,TK);if(Y.metadata.id!==$.id)throw await Y.body.cancel().catch(()=>{}),new Error("Browser Node relay returned a mismatched request identity.");if(t.profile==="server-http"&&Y.metadata.bodyEncoding!=="identity")throw await Y.body.cancel(),new Error("TRANSPORT_REQUIRED: server HTTP requires unchanged response bytes.");T=Y.body,D=Y.metadata.headers,I=Y.metadata.status,U=Y.metadata.statusText}else{for(const[F]of v)if(/^(?:cookie|host|origin|referer|content-length|connection|transfer-encoding|accept-encoding|sec-.*|proxy-.*)$/iu.test(F))throw new Error(`TRANSPORT_REQUIRED: direct browser transport cannot preserve ${F}.`);let _;t.body instanceof Blob||t.body instanceof ArrayBuffer?(_=t.body,this.consumeNetwork(t.body instanceof Blob?t.body.size:t.body.byteLength,m.maxBytes)):_=this.meterRequestBody(t.body,m.maxBytes,n);const $=await this.nativeFetch(l.href,{method:t.method,headers:x,..._?{body:_}:{},..._ instanceof ReadableStream?{duplex:"half"}:{},credentials:"omit",redirect:"manual",signal:n});if($.type==="opaqueredirect")throw new Error(`${l.origin} answered with a redirect, which the direct browser transport does not follow; the page cannot see its target to check the World admits it.`);T=$.body,D=[...$.headers.entries()],I=$.status,U=$.statusText}if(!Number.isInteger(I)||I<200||I>599)throw await T?.cancel().catch(()=>{}),new Error("Browser Node relay returned an invalid upstream status.");if(b){const _=Number(new Headers(D).get("content-length"));if(Number.isFinite(_)&&_>=0&&_>m.maxBytes-this.networkBytes)throw await T?.cancel().catch(()=>{}),new Error("Browser Node egress byte limit exceeded.")}i(),this.send({type:"fetch-response-start",id:t.id,status:I,statusText:U,headers:D});const O=T?.getReader();try{for(;;){await this.waitForFetchPull(t.id,n);const _=O?await O.read():{done:!0,value:void 0};if(_.done){this.send({type:"fetch-response-end",id:t.id});break}if(b){if(_.value.byteLength>m.maxBytes-this.networkBytes)throw this.networkBytes=m.maxBytes,new Error("Browser Node egress byte limit exceeded.");this.consumeNetwork(_.value.byteLength,m.maxBytes)}const $=Uint8Array.from(_.value).buffer;this.send({type:"fetch-response-chunk",id:t.id,body:$},[$])}console.info(`[browser-node-http] ${JSON.stringify({event:"completed",...o,outcome:"response-received"})}`)}catch(_){throw await O?.cancel(_).catch(()=>{}),_}finally{O?.releaseLock()}}finally{this.activeFetches-=1,this.fetchSlots.shift()?.()}}catch(l){r.abort(l),console.error(`[browser-node-http] ${JSON.stringify({event:"failed",...o??{attemptId:`node-${t.id}`,program:t.program},outcome:o?"possibly-sent":"not-sent",error:l instanceof Error?l.message.replace(/[\r\n]/gu," ").slice(0,512):String(l).slice(0,512)})}`),this.send({type:"fetch-error",id:t.id,error:l instanceof Error?l.message:String(l)})}finally{clearTimeout(s),this.lifetime.signal.removeEventListener("abort",a),this.fetchControllers.get(t.id)===r&&this.fetchControllers.delete(t.id),this.fetchAuthorities.delete(t.id),this.fetchPullWaiters.delete(t.id),this.fetchPullCredits.delete(t.id)}}async requireRelayProfile(t,r,n){this.relayCapabilities??=(async()=>{const i=new URL("/api/ready",new URL(t,location.href)),a=await this.nativeFetch(i,{credentials:"omit",redirect:"error",signal:AbortSignal.timeout(1e4)});if(!a.headers.get("content-type")?.includes("application/json"))throw await a.body?.cancel(),new Error("RELAY_UNAVAILABLE: the configured relay has no ready HTTP capability endpoint.");const o=await _2(a.body??void 0,32*1024,AbortSignal.timeout(1e4)),c=JSON.parse(new TextDecoder().decode(o))?.capabilities?.nodeHttp;if(c?.ready!==!0||c.protocol!==1||c.mediaType!==Vb||!Array.isArray(c.profiles)||c.profiles.some(u=>typeof u!="string"))throw new Error("RELAY_UNAVAILABLE: the configured relay does not support HTTP protocol v1.");return c.profiles})().catch(i=>{throw this.relayCapabilities=void 0,i});const s=await this.relayCapabilities;if(n.throwIfAborted(),!s.includes(r))throw new Error(`TRANSPORT_REQUIRED: the configured relay does not support ${r}.`)}waitForFetchPull(t,r){const n=this.fetchPullCredits.get(t)??0;return n>0?(n===1?this.fetchPullCredits.delete(t):this.fetchPullCredits.set(t,n-1),Promise.resolve()):new Promise((s,i)=>{const a=()=>{this.fetchPullWaiters.delete(t),i(r.reason)};this.fetchPullWaiters.set(t,()=>{r.removeEventListener("abort",a),s()}),r.addEventListener("abort",a,{once:!0}),r.aborted&&a()})}consumeNetwork(t,r){if(!Number.isSafeInteger(t)||t<0||this.networkBytes>r-t)throw new Error("Browser Node egress byte limit exceeded.");this.networkBytes+=t}meterRequestBody(t,r,n){if(!t)return null;const i=(t instanceof ArrayBuffer?new Blob([t]).stream():t instanceof Blob?t.stream():t).getReader();let a=!1;const o=()=>{a||(a=!0,n.removeEventListener("abort",c),i.releaseLock())},l=async u=>{if(!a)try{await i.cancel(u)}finally{o()}},c=()=>{l(n.reason).catch(()=>{})};return n.addEventListener("abort",c,{once:!0}),n.aborted&&c(),new ReadableStream({pull:async u=>{try{n.throwIfAborted();const d=await i.read();if(n.throwIfAborted(),d.done){o(),u.close();return}if(d.value.byteLength>r-this.networkBytes)throw this.networkBytes=r,new Error("Browser Node egress byte limit exceeded.");this.consumeNetwork(d.value.byteLength,r),u.enqueue(d.value)}catch(d){await l(d).catch(()=>{}),u.error(d)}},cancel:l},{highWaterMark:0})}startProfiling(t){this.responsivenessProfiles.set(t,{busyMs:0,pending:void 0}),this.profileTimer===void 0&&(this.profileTimer=globalThis.setInterval(()=>this.probeProfiles(),Dge)),this.probeProfiles()}stopProfiling(t){t!==void 0&&this.responsivenessProfiles.delete(t),this.responsivenessProfiles.size===0&&this.profileTimer!==void 0&&(globalThis.clearInterval(this.profileTimer),this.profileTimer=void 0)}probeProfiles(){if(document.visibilityState!=="visible"){for(const r of this.responsivenessProfiles.values())r.pending=void 0;return}const t=performance.now();for(const r of this.responsivenessProfiles.values()){if(r.pending)continue;const n=this.nextProfileProbe++;r.pending={id:n,sentAt:t},this.send({type:"profile-probe",id:n})}}acceptProfilePong(t){for(const r of this.responsivenessProfiles.values())if(r.pending?.id===t){r.busyMs+=Math.max(0,performance.now()-r.pending.sentAt-$T),r.pending=void 0;return}}abortForIsolationFailure(t){console.error("Browser Node filesystem synchronization failed.",t);const r=this.runs.entries().next().value;if(!r)return;const[n,s]=r;this.send({type:"abort",id:n}),this.runs.delete(n),this.stopProfiling(s.runtimePid),s.removeAbort(),s.reject(t instanceof Error?t:new Error(String(t)))}send(t,r=[]){(!this.disposed||t.type==="dispose")&&this.port.postMessage(t,r)}waitForInitialized(t,r){return this.disposed?Promise.reject(new Error("Browser Node host is disposed.")):new Promise((n,s)=>{let i;const a=()=>{globalThis.clearTimeout(c),this.port.removeEventListener("message",u),this.startupWaiters.delete(o)},o=d=>{a(),s(d)},l=()=>{o(new Error(i?`Browser Node host timed out while ${i}.`:"Browser Node host initialization timed out."))};let c=globalThis.setTimeout(l,t);const u=d=>{const p=d.data;if(p.type==="error"&&p.id===r){o(new Error(p.error));return}if(p.type==="initializing"){if(p.id!==r)return;i=p.work,globalThis.clearTimeout(c),c=globalThis.setTimeout(l,Math.max(t,RT));return}p.type!=="initialized"||p.id!==r||(a(),this.filesystemPolicySupported=p.filesystemPolicyVersion===1,this.inputBytesSupported=p.inputBytesVersion===1,n(p.store))};this.port.addEventListener("message",u),this.startupWaiters.add(o)})}waitFor(t,r,n){return this.disposed?Promise.reject(new Error("Browser Node host is disposed.")):new Promise((s,i)=>{const a=()=>{globalThis.clearTimeout(u),this.port.removeEventListener("message",d),this.startupWaiters.delete(o)},o=p=>{a(),i(p)};let l;const c=()=>o(new Error(l?`Browser Node host timed out while ${l}.`:`Browser Node host ${t} timed out.`));let u=globalThis.setTimeout(c,r);const d=p=>{if(t==="attached"&&p.data.type==="attach-error"){o(new Error(p.data.error));return}if(t==="attached"&&p.data.type==="attaching"&&l===void 0){l=p.data.work,console.log("[boot-trace]",JSON.stringify({event:"worker-loading",at:Date.now(),work:l})),globalThis.clearTimeout(u),u=globalThis.setTimeout(c,Math.max(r,RT));return}if(p.data.type==="error"&&n!==void 0&&p.data.id===n){o(new Error(p.data.error));return}p.data.type!==t||n!==void 0&&(!("id"in p.data)||p.data.id!==n)||(a(),s())};this.port.addEventListener("message",d),this.startupWaiters.add(o)})}assertActive(){if(this.disposed)throw new Error("Browser Node host is disposed.")}}function Pge(e){return new Promise((t,r)=>{const n=()=>{e.removeEventListener("load",s),e.removeEventListener("error",i)},s=()=>{n(),t()},i=()=>{n(),r(new Error("Browser Node host page failed to load."))};e.addEventListener("load",s),e.addEventListener("error",i)})}function O2(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"}function Uge(e){const t=new Headers;for(const[r,n]of e){const s=r.toLowerCase();["cookie","host","origin","referer"].includes(s)||s.startsWith("sec-")||s.startsWith("proxy-")||t.append(r,n)}return t}async function Fge(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;try{for(;;){const o=await t.read();if(o.done)break;if(o.value.byteLength>4096-n){await t.cancel().catch(()=>{});break}r.push(o.value),n+=o.value.byteLength}}catch{return""}finally{t.releaseLock()}const s=new Uint8Array(n);let i=0;for(const o of r)s.set(o,i),i+=o.byteLength;const a=new TextDecoder().decode(s).replace(/[\r\n]/gu," ").slice(0,1024);try{const o=JSON.parse(a);return typeof o.error?.message=="string"?o.error.message.replace(/[\r\n]/gu," ").slice(0,1024):""}catch{return a}}async function _2(e,t,r){if(!e)return new ArrayBuffer(0);if(e instanceof ArrayBuffer){if(e.byteLength>t)throw new Error("Browser Node request body limit exceeded.");return e}if(e instanceof Blob&&e.size>t)throw new Error("Browser Node request body limit exceeded.");const n=(e instanceof Blob?e.stream():e).getReader(),s=()=>{n.cancel(r.reason).catch(()=>{})};r.addEventListener("abort",s,{once:!0});const i=[];let a=0;try{for(;;){r.throwIfAborted();const c=await n.read();if(r.throwIfAborted(),c.done)break;if(c.value.byteLength>t-a)throw new Error("Browser Node request body limit exceeded.");i.push(c.value),a+=c.value.byteLength}}catch(c){throw await n.cancel(c).catch(()=>{}),c}finally{r.removeEventListener("abort",s),n.releaseLock()}const o=new Uint8Array(a);let l=0;for(const c of i)o.set(c,l),l+=c.byteLength;return o.buffer}const Bge=`onmessage = async ({ data: { id, bytes, raw, sha256 } }) => {
1717
1717
  try {
1718
1718
  // The part as it came, not a Blob's copy of it.