@volter/browser-substrate 0.1.100 → 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.
@@ -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.