@volter/browser-substrate 0.1.100 → 0.1.102
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/shell/assets/browser-sandbox-bridge-BJbQoc4f.js +237 -0
- package/dist/shell/assets/{filesystem-host-BT4CmP6I.js → filesystem-host-DJbFuokb.js} +1 -1
- package/dist/shell/assets/{filesystem-host-BBYqSE7n.js → filesystem-host-yMcJuvmT.js} +2 -2
- package/dist/shell/assets/{filesystem-worker-D88RPdU7.js → filesystem-worker-BbsBhZ9p.js} +3 -3
- package/dist/shell/assets/{fork-worker-CEQ37gcQ.js → fork-worker-BXY2kfdX.js} +1 -1
- package/dist/shell/assets/{node-execution-worker-b410406bb5514b5d.js → node-execution-worker-7e8e0c5321ca0d10.js} +3 -3
- package/dist/shell/assets/{sandbox-CLAYkibu.js → sandbox-bMeKqKBn.js} +1 -1
- package/dist/shell/assets/{shell-1LFMcbJv.js → shell-DLIQ6jHu.js} +6 -6
- package/dist/shell/assets/{worker-CQmX_ncR.js → worker-Ce8bBwSJ.js} +16 -16
- package/dist/shell/assets/{worker-program-worker-CLXTQPjT.js → worker-program-worker-B4OcKVtV.js} +2 -2
- package/dist/shell/bundler-worker.js +3 -3
- package/dist/shell/index.html +2 -2
- package/dist/shell/node-execution-worker.js +1 -1
- package/dist/shell/python-execution-worker.js +4 -4
- package/dist/shell/python-runtime-snapshot.bin +0 -0
- package/dist/shell/python-runtime-snapshot.json +1 -1
- package/dist/shell/rolldown/factory.mjs +42 -10
- package/dist/shell/sandbox.html +2 -2
- package/package.json +1 -1
- package/dist/shell/assets/browser-sandbox-bridge-BRDWHeqY.js +0 -237
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as bf}from"./page-workers-BUcWBF51.js";import{b as hj,D as pj,u as L8,a as P8,F as U8,c as mj,d as gj,M as o6,e as d$,r as ov,f as yj,w as bj,g as wj,h as Xa,B as wf,i as As,j as ha,k as cf,S as h$,O as p$,l as m$,m as g$,o as l6,n as y$,v as b$,p as w$,q as op,s as v$,t as vj,x as x1,y as xj,z as lv,A as F8,C as Sj,E as Ej,G as kj,H as Aj,I as Cj,J as Tj,K as Nj,L as $j,N as Rj,P as og,Q as B8,R as x$,T as Oj,U as S$,V as S1,W as _j,X as Ij,Y as Mj,Z as Dj,_ as lg,$ as z8,a0 as Lj,a1 as Pj,a2 as Uj,a3 as Fj,a4 as Bj}from"./browser-sandbox-bridge-
|
|
1
|
+
import{p as bf}from"./page-workers-BUcWBF51.js";import{b as hj,D as pj,u as L8,a as P8,F as U8,c as mj,d as gj,M as o6,e as d$,r as ov,f as yj,w as bj,g as wj,h as Xa,B as wf,i as As,j as ha,k as cf,S as h$,O as p$,l as m$,m as g$,o as l6,n as y$,v as b$,p as w$,q as op,s as v$,t as vj,x as x1,y as xj,z as lv,A as F8,C as Sj,E as Ej,G as kj,H as Aj,I as Cj,J as Tj,K as Nj,L as $j,N as Rj,P as og,Q as B8,R as x$,T as Oj,U as S$,V as S1,W as _j,X as Ij,Y as Mj,Z as Dj,_ as lg,$ as z8,a0 as Lj,a1 as Pj,a2 as Uj,a3 as Fj,a4 as Bj}from"./browser-sandbox-bridge-BJbQoc4f.js";import{C as zj}from"./cross-origin-container-protocol-hIp9vH-t.js";const jj=1,Wj="blender",Hj="Blender",qj="5.2.0",Gj="wali",Vj={url:"/blender/5.2.0/fbe62287-54323db8/blender.wasm",integrity:"sha256-VDI9uO1b2cxjqRRUwLf8HJw7N3ZkWfY0aSDog1XmCxA=",upstream:"https://projects.blender.org/blender/blender",license:"GPL-2.0-or-later",redistribution:"cleared"},Zj="blender",Yj={start:["blender","--version"]},Xj={home:"${HOME}/.blender",privateFiles:[]},Kj={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",BLENDER_SYSTEM_RESOURCES:"/opt/programs/blender/5.2.0",BLENDER_SYSTEM_SCRIPTS:"/opt/programs/blender/5.2.0/scripts",BLENDER_SYSTEM_DATAFILES:"/opt/programs/blender/5.2.0/datafiles",BLENDER_SYSTEM_PYTHON:"/opt/programs/blender/5.2.0/python",PYTHONPATH:"/opt/programs/blender/5.2.0/python/lib/numpy313.zip:/opt/programs/blender/5.2.0/python/lib/wheels313.zip",TMPDIR:"/tmp",VGAI_PRESENTER_ROOT:"/tmp/vgai-presenter",VGAI_EXPORT_BUFFER_PATH:"/tmp/vgai-presenter/arena.bin",OPENIMAGEIO_THREADS:"1"},Qj={capabilities:["filesystem.project","threads.pthread"],programs:["wali"],workers:16},Jj={input:"bytes"},eW={allowedHosts:[]},tW=[],rW={url:"/blender/5.2.0/fbe62287-c897ea1a/blender-resources.zip",integrity:"sha256-vwqwbrnOvoIQu3366ENlAGa/fLJ15nfoTqA36XDsFrI=",root:"/opt/programs/blender/5.2.0"},nW={url:"/blender/5.2.0/fbe62287-f3551ac5/blender-three.mjs",integrity:"sha256-81Uaxf5dret1seLjYQHEvuFGK/dUU6hBZkW71fyTng8=",bytes:6110908},sW={schemaVersion:jj,id:Wj,displayName:Hj,version:qj,engine:Gj,artifact:Vj,executable:Zj,actions:Yj,storage:Xj,environment:Kj,requirements:Qj,terminal:Jj,network:eW,openUrls:tW,resources:rW,presenter:nW},iW=1,aW="codex",oW="Codex CLI",lW="0.151.0",cW="wali",uW={url:"/codex/0.151.0/78c29080-7b58fe3e/codex.wasm",integrity:"sha256-e1j+PgqECkgNTy8lOtcWzoLVRNd2ez2sbULSE7E29GM=",upstream:"https://github.com/openai/codex",license:"Apache-2.0",redistribution:"cleared"},fW="codex",dW={start:["codex","--model","gpt-5.4","--sandbox","danger-full-access"],login:["codex","login","--device-auth"],logout:["codex","logout"]},hW={home:"${HOME}/.codex",privateFiles:[{path:"${HOME}/.codex/auth.json",vault:"codex-cli-auth",clearOnActions:["logout"]},{path:"${HOME}/.codex/config.toml",vault:"codex-cli-config",defaultContent:`cli_auth_credentials_store = "file"
|
|
2
2
|
`}]},pW={HOME:"${HOME}",CODEX_HOME:"${HOME}/.codex",PATH:"/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color",TOKIO_WORKER_THREADS:"1"},mW={capabilities:["browser.open-url","filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:32},gW={input:"bytes"},yW={relayPath:"/api/wali/tcp",allowedHosts:["api.openai.com","auth.openai.com","chat.openai.com","chatgpt.com"]},bW=[{protocol:"https:",hostname:"auth.openai.com",pathname:"/codex/device"}],wW={schemaVersion:iW,id:aW,displayName:oW,version:lW,engine:cW,artifact:uW,executable:fW,actions:dW,storage:hW,environment:pW,requirements:mW,terminal:gW,network:yW,openUrls:bW},vW=1,xW="ffprobe",SW="ffprobe",EW="9.0.1",kW="wali",AW={url:"/ffprobe/9.0.1/bf1b838f-99dc0c0c/ffprobe.wasm",integrity:"sha256-mdwMDDTRcYQdFSAqcerAR08HkUxL4mdjCF4OkEcusPI=",upstream:"https://github.com/FFmpeg/FFmpeg",license:"LGPL-2.1-or-later",redistribution:"cleared"},CW="ffprobe",TW={start:["ffprobe","-version"]},NW={home:"${HOME}/.ffmpeg",privateFiles:[]},$W={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin"},RW={capabilities:["filesystem.project","media.webcodecs","threads.pthread"],programs:["wali"],workers:32},OW={input:"bytes"},_W={allowedHosts:[]},IW=[],MW={schemaVersion:vW,id:xW,displayName:SW,version:EW,engine:kW,artifact:AW,executable:CW,actions:TW,storage:NW,environment:$W,requirements:RW,terminal:OW,network:_W,openUrls:IW},DW=1,LW="ffmpeg",PW="FFmpeg",UW="9.0.1",FW="wali",BW={url:"/ffmpeg/9.0.1/bf1b838f-91cb6c14/ffmpeg.wasm",integrity:"sha256-kctsFB9F1jrSTZKAU2TwLVuC3MUao3GhTph/ILE0Wv4=",upstream:"https://github.com/FFmpeg/FFmpeg",license:"LGPL-2.1-or-later",redistribution:"cleared"},zW="ffmpeg",jW={start:["ffmpeg","-version"]},WW={home:"${HOME}/.ffmpeg",privateFiles:[]},HW={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin"},qW={capabilities:["filesystem.project","media.webcodecs","threads.pthread"],programs:["wali"],workers:32},GW={input:"bytes"},VW={allowedHosts:[]},ZW=[],YW={schemaVersion:DW,id:LW,displayName:PW,version:UW,engine:FW,artifact:BW,executable:zW,actions:jW,storage:WW,environment:HW,requirements:qW,terminal:GW,network:VW,openUrls:ZW},XW=1,KW="git",QW="Git",JW="2.55.0",eH="wali",tH={url:"/git/2.55.0/457fdb04-a140f348/git.wasm",integrity:"sha256-oUDzSHWZCggKhKYaxX6eqSTnuNefDdOhtCQhOc3WqOQ=",upstream:"https://www.kernel.org/pub/software/scm/git/",license:"GPL-2.0-only",redistribution:"cleared"},rH="git",nH={start:["git","--version"]},sH={home:"${HOME}/.config/git",privateFiles:[]},iH={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",GIT_EXEC_PATH:"/opt/programs/git/2.55.0/git-core",GIT_TEMPLATE_DIR:"/opt/programs/git/2.55.0/git-core/templates"},aH={capabilities:["filesystem.project","process.spawn","threads.pthread"],programs:["wali"],workers:32},oH={input:"bytes"},lH={allowedHosts:[]},cH=[],uH={url:"/git/2.55.0/457fdb04-e085996d/git-resources.zip",integrity:"sha256-YN1v7wT9s96XxkR4V0rVij7Jz/cB2FZwk4FtrTJyZKs=",root:"/opt/programs/git/2.55.0/git-core"},fH={schemaVersion:XW,id:KW,displayName:QW,version:JW,engine:eH,artifact:tH,executable:rH,actions:nH,storage:sH,environment:iH,requirements:aH,terminal:oH,network:lH,openUrls:cH,resources:uH},dH=1,hH="gitlens",pH="GitLens",mH="2026.9.190513",gH="node",yH={url:"/gitlens/2026.9.190513/b90b6934-9461a1f3/gitlens.zip",integrity:"sha256-lGGh80wH0+azA7pfqu8eFb95WbTHzSYDA8zTjwzAn6E=",upstream:"https://github.com/gitkraken/vscode-gitlens",license:"MIT",redistribution:"cleared"},bH="gitlens",wH={start:["-e","process.stdout.write('gitlens placed')"]},vH={home:"${HOME}/.openvscode-server",privateFiles:[]},xH={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",GITLENS_ROOT:"/opt/programs/gitlens/2026.9.190513"},SH={capabilities:["filesystem.project"],programs:["node","git"]},EH={input:"bytes"},kH={allowedHosts:["api.github.com","api.gitkraken.dev","configs.gitkraken.dev","github.com","gitkraken.com","gitkraken.dev","slack.gitkraken.com"]},AH=[],CH={url:"/gitlens/2026.9.190513/b90b6934-61608219/gitlens-resources.zip",integrity:"sha256-YWCCGc7mnBZTQ2ze9bnAy8NDEYXCqinw2BINaNUkYrA=",root:"/opt/programs/gitlens/2026.9.190513"},TH={schemaVersion:dH,id:hH,displayName:pH,version:mH,engine:gH,artifact:yH,executable:bH,actions:wH,storage:vH,environment:xH,requirements:SH,terminal:EH,network:kH,openUrls:AH,resources:CH},NH=1,$H="grok",RH="Grok CLI",OH="1.0.10",_H="wali",IH={url:"/grok/1.0.10/9684fa3c-894eeadb/xai-grok-pager.wasm",integrity:"sha256-iU7q28AqktlhlVc8mG+AQDI/UScbz+88wTMwJgmSScI=",upstream:"https://github.com/xai-org/grok-build",license:"Apache-2.0",redistribution:"cleared"},MH="grok",DH={start:["grok"],login:["grok","login","--device-auth"],logout:["grok","logout"]},LH={home:"${HOME}/.grok",privateFiles:[{path:"${HOME}/.grok/auth.json",vault:"grok-cli-auth",clearOnActions:["logout"]},{path:"${HOME}/.grok/config.toml",vault:"grok-cli-config"}]},PH={HOME:"${HOME}",GROK_HOME:"${HOME}/.grok",PATH:"/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color",GROK_MEMTRACE:"0",GROK_WORKER_THREADS:"1",GROK_TELEMETRY_ENABLED:"false",GROK_OTEL_FILTER:"off"},UH={capabilities:["browser.open-url","filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:64},FH={input:"kitty-key-events"},BH={relayPath:"/api/wali/tcp",allowedHosts:["api.x.ai","assets.grok.com","auth.x.ai","cli-chat-proxy.grok.com","code.grok.com","grok.com","storage.googleapis.com","x.ai"]},zH=[{protocol:"https:",hostname:"accounts.x.ai",pathname:"/oauth2/device"}],jH={schemaVersion:NH,id:$H,displayName:RH,version:OH,engine:_H,artifact:IH,executable:MH,actions:DH,storage:LH,environment:PH,requirements:UH,terminal:FH,network:BH,openUrls:zH},WH=1,HH="openvscode-server",qH="OpenVSCode Server",GH="1.109.5",VH="node",ZH={url:"/openvscode-server/1.109.5/07258626-29f7eb3e/openvscode-server.zip",integrity:"sha256-KffrPuEdRoxlP1byAy38mDQV8PrdponITCcwMRXzSR4=",upstream:"https://github.com/gitpod-io/openvscode-server",license:"MIT",redistribution:"cleared"},YH="openvscode-server",XH={start:["/opt/programs/openvscode-server/1.109.5/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token","--server-data-dir","/home/user/.openvscode-server","--default-folder","/workspace","--disable-telemetry"]},KH={home:"${HOME}/.openvscode-server",privateFiles:[]},QH={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/openvscode-server/1.109.5"},JH={capabilities:["filesystem.project"],programs:["node","git","sh"]},eq={input:"bytes"},tq={allowedHosts:["open-vsx.org"],httpTransportPolicy:{url:"/openvscode-server/1.109.5/07258626-2e53744a/http-transport-policy.json",integrity:"sha256-LlN0SrN32XKdawOsvZn40BSBC8HRWLtjGiIoFakTrcw="}},rq=[],nq={url:"/openvscode-server/1.109.5/07258626-28b7a378/openvscode-server-resources.zip",integrity:"sha256-KLejeHRuJD73HKrGt7UbFCi6+0vzYFqXxZ3udAk2RjI=",root:"/opt/programs/openvscode-server/1.109.5"},sq={schemaVersion:WH,id:HH,displayName:qH,version:GH,engine:VH,artifact:ZH,executable:YH,actions:XH,storage:KH,environment:QH,requirements:JH,terminal:eq,network:tq,openUrls:rq,resources:nq},iq=1,aq="pi",oq="Pi",lq="0.87.1",cq="node",uq={url:"/pi/0.87.1/f07218c4-66de9250/pi.zip",integrity:"sha256-Zt6SUNC6igr4EhkUVV79dm+AGwlIvwbiBOLv5lFPVt4=",upstream:"https://github.com/earendil-works/pi",license:"MIT",redistribution:"cleared"},fq="pi",dq={start:["/opt/programs/pi/0.87.1/node_modules/@earendil-works/pi-coding-agent/dist/cli.js"]},hq={home:"${HOME}/.pi",privateFiles:[]},pq={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",PI_ROOT:"/opt/programs/pi/0.87.1"},mq={capabilities:["filesystem.project"],programs:["node","sh"]},gq={input:"bytes"},yq={allowedHosts:[]},bq=[],wq={url:"/pi/0.87.1/f07218c4-22a14a3e/pi-resources.zip",integrity:"sha256-IqFKPoZ5lLwimkJdQ2YwV4XGFR72LXhULTr+M5laULc=",root:"/opt/programs/pi/0.87.1"},vq={schemaVersion:iq,id:aq,displayName:oq,version:lq,engine:cq,artifact:uq,executable:fq,actions:dq,storage:hq,environment:pq,requirements:mq,terminal:gq,network:yq,openUrls:bq,resources:wq},xq=1,Sq="supercode",Eq="Volter Harness",kq="0.4.57",Aq="wali",Cq={url:"/supercode/0.4.57/74e379df-7c2abf71/supercode.wasm",integrity:"sha256-fCq/cV9phC80o3L8gSbiopN/Bm73jU0fTe9HbG/O228=",upstream:"https://github.com/volter-ai/supercode",license:"MIT",redistribution:"cleared"},Tq="supercode",Nq={start:["supercode","chat"],loader:["supercode","harness","serve"],login:["supercode","login"],logout:["supercode","logout"]},$q={home:"${HOME}/.config/supercode",privateFiles:[{path:"${HOME}/.config/supercode/config.toml",vault:"supercode-config",clearOnActions:["logout"]},{path:"${HOME}/.config/supercode/credentials.toml",vault:"supercode-credentials",clearOnActions:["logout"]}]},Rq={HOME:"${HOME}",XDG_CONFIG_HOME:"${HOME}/.config",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color"},Oq={capabilities:["filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:32},_q={input:"canonical-lines"},Iq={relayPath:"/api/wali/tcp",allowedHosts:["openrouter.ai"]},Mq=[],Dq={schemaVersion:xq,id:Sq,displayName:Eq,version:kq,engine:Aq,artifact:Cq,executable:Tq,actions:Nq,storage:$q,environment:Rq,requirements:Oq,terminal:_q,network:Iq,openUrls:Mq},Lq=1,Pq="supercode",Uq="Volter Harness",Fq="0.4.68",Bq="wali",zq={url:"/supercode/0.4.68/6d1f3f0c-f0db006e/supercode.wasm",integrity:"sha256-8NsAbubpTiLpW9dd+HxTZ8JBeu/WoBemO39ypduNCvY=",upstream:"https://github.com/volter-ai/supercode",license:"MIT",redistribution:"cleared"},jq="supercode",Wq={start:["supercode","chat"],loader:["supercode","harness","serve"],login:["supercode","login"],logout:["supercode","logout"]},Hq={home:"${HOME}/.config/supercode",privateFiles:[{path:"${HOME}/.config/supercode/config.toml",vault:"supercode-config",clearOnActions:["logout"]},{path:"${HOME}/.config/supercode/credentials.toml",vault:"supercode-credentials",clearOnActions:["logout"]}]},qq={HOME:"${HOME}",XDG_CONFIG_HOME:"${HOME}/.config",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color"},Gq={capabilities:["filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:32},Vq={input:"canonical-lines"},Zq={relayPath:"/api/wali/tcp",allowedHosts:["openrouter.ai"]},Yq=[],Xq={schemaVersion:Lq,id:Pq,displayName:Uq,version:Fq,engine:Bq,artifact:zq,executable:jq,actions:Wq,storage:Hq,environment:qq,requirements:Gq,terminal:Vq,network:Zq,openUrls:Yq},Kq=1,Qq="valkey",Jq="Valkey",eG="9.1.1",tG="node",rG={url:"/valkey/9.1.1/60e471da-75f33eaf/valkey.zip",integrity:"sha256-dfM+r67meqtqcDFtNGcbbUM3j0MtLWjlMbBIzKK3nuo=",upstream:"https://github.com/michaelkremenetsky/valkey-wasm",license:"BSD-3-Clause",redistribution:"cleared"},nG="valkey-server",sG={start:["/opt/programs/valkey/9.1.1/bin/valkey-server.mjs","--port","6379"]},iG={home:"${HOME}/.valkey",privateFiles:[]},aG={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VALKEY_HOME:"/opt/programs/valkey/9.1.1"},oG={capabilities:[],programs:["node"]},lG={input:"bytes"},cG={allowedHosts:[]},uG=[],fG={url:"/valkey/9.1.1/60e471da-21e19cf0/valkey-resources.zip",integrity:"sha256-IeGc8BrPH6eiUs5aWSgeEeqZqbCvWIjOH99Ma8Ey4zQ=",root:"/opt/programs/valkey/9.1.1"},dG={schemaVersion:Kq,id:Qq,displayName:Jq,version:eG,engine:tG,artifact:rG,executable:nG,actions:sG,storage:iG,environment:aG,requirements:oG,terminal:lG,network:cG,openUrls:uG,resources:fG},hG=1,pG="volter-game-editor-workbench",mG="Volter Game Editor workbench",gG="0.5.65",yG="node",bG={url:"/volter-game-editor-workbench/0.5.65/9ef15b1f-af68aba2/volter-game-editor-workbench.zip",integrity:"sha256-r2iroutlBhAOQAGDPXBiHohurp6nIhIlmnFwytapcks=",upstream:"https://github.com/volter-ai/code-oss",license:"MIT",redistribution:"cleared"},wG="code-server-oss",vG={start:["/opt/programs/volter-game-editor-workbench/0.5.65/vscode-reh-web-darwin-arm64/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token"]},xG={home:"${HOME}/.vscode-server-oss",privateFiles:[]},SG={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/volter-game-editor-workbench/0.5.65/vscode-reh-web-darwin-arm64",VOLTER_EDITOR_WORKBENCH_ROOT:"/opt/programs/volter-game-editor-workbench/0.5.65"},EG={capabilities:["filesystem.project"],programs:["node","git","sh"]},kG={input:"bytes"},AG={allowedHosts:[]},CG=[],TG={url:"/volter-game-editor-workbench/0.5.65/9ef15b1f-b499f656/volter-game-editor-workbench-resources.zip",integrity:"sha256-tJn2VgJZ6imhm71f7DXpoZEn57IuvI/9UrRcqoCoebk=",root:"/opt/programs/volter-game-editor-workbench/0.5.65"},NG={schemaVersion:hG,id:pG,displayName:mG,version:gG,engine:yG,artifact:bG,executable:wG,actions:vG,storage:xG,environment:SG,requirements:EG,terminal:kG,network:AG,openUrls:CG,resources:TG},$G=1,RG="volter-model-editor-workbench",OG="Volter Model Editor workbench",_G="0.5.132",IG="node",MG={url:"/volter-model-editor-workbench/0.5.132/f16dc165-b5a7f34d/volter-model-editor-workbench.zip",integrity:"sha256-tafzTfd6HeArQI5SH7Xsh6bAxrLD3m37TxNGYDNx1kQ=",upstream:"https://github.com/volter-ai/code-oss",license:"MIT",redistribution:"cleared"},DG="code-server-oss",LG={start:["/opt/programs/volter-model-editor-workbench/0.5.132/vscode-reh-web-darwin-arm64/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token"]},PG={home:"${HOME}/.vscode-server-oss",privateFiles:[]},UG={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/volter-model-editor-workbench/0.5.132/vscode-reh-web-darwin-arm64",VOLTER_EDITOR_WORKBENCH_ROOT:"/opt/programs/volter-model-editor-workbench/0.5.132"},FG={capabilities:["filesystem.project"],programs:["node","git","sh"]},BG={input:"bytes"},zG={allowedHosts:[]},jG=[],WG={url:"/volter-model-editor-workbench/0.5.132/f16dc165-deec2a31/volter-model-editor-workbench-resources.zip",integrity:"sha256-3uwqMWo8vZU943GXyQtzt1HfojJDWx3ahVnL8RhN2Ko=",root:"/opt/programs/volter-model-editor-workbench/0.5.132"},HG={schemaVersion:$G,id:RG,displayName:OG,version:_G,engine:IG,artifact:MG,executable:DG,actions:LG,storage:PG,environment:UG,requirements:FG,terminal:BG,network:zG,openUrls:jG,resources:WG},qG=1,GG="volter-model-editor-workbench",VG="Volter Model Editor workbench",ZG="0.5.79",YG="node",XG={url:"/volter-model-editor-workbench/0.5.79/f16dc165-30e6a114/volter-model-editor-workbench.zip",integrity:"sha256-MOahFNbINNMkJE/4tqIHfqLWVuB2s/UmSdszMnXNals=",upstream:"https://github.com/volter-ai/code-oss",license:"MIT",redistribution:"cleared"},KG="code-server-oss",QG={start:["/opt/programs/volter-model-editor-workbench/0.5.79/vscode-reh-web-darwin-arm64/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token"]},JG={home:"${HOME}/.vscode-server-oss",privateFiles:[]},eV={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/volter-model-editor-workbench/0.5.79/vscode-reh-web-darwin-arm64",VOLTER_EDITOR_WORKBENCH_ROOT:"/opt/programs/volter-model-editor-workbench/0.5.79"},tV={capabilities:["filesystem.project"],programs:["node","git","sh"]},rV={input:"bytes"},nV={allowedHosts:[]},sV=[],iV={url:"/volter-model-editor-workbench/0.5.79/f16dc165-d9e4a705/volter-model-editor-workbench-resources.zip",integrity:"sha256-2eSnBVad4zRhJUCx9+1b9oJvyuzONmWIkYdba71cNlo=",root:"/opt/programs/volter-model-editor-workbench/0.5.79"},aV={schemaVersion:qG,id:GG,displayName:VG,version:ZG,engine:YG,artifact:XG,executable:KG,actions:QG,storage:JG,environment:eV,requirements:tV,terminal:rV,network:nV,openUrls:sV,resources:iV};class oV{host;hooks;timeoutMs;pages=new Map;stopped=!1;retired=new Set;constructor(t,r,n){this.host=t,this.hooks=r,this.timeoutMs=n}context(t){return this.pages.get(t)?.contextId}opener(t){return this.pages.get(t)?.openerId}openerMark(t){return this.pages.get(t)?.openerMark}ownMark(t){return this.pages.get(t)?.ownMark}owner(t){return this.pages.get(t)?.owner}acceptsSurface(t){if(this.retired.has(t))return!1;const r=this.pages.get(t);return!r||!r.controller.signal.aborted&&!r.closing&&!this.stopped&&(!r.contextId||this.hooks.contextExists(r.contextId))}async create(t,r,n,s,i){if(this.stopped)throw new Error("Browser host is closing");for(const p of Object.keys(r))if(!["url","browserContextId"].includes(p))throw new Error(`Unsupported page option: ${p}`);if(typeof r.url!="string")throw new Error("url must be a string");if(r.browserContextId!==void 0&&typeof r.browserContextId!="string")throw new Error("browserContextId must be a string");const a=r.browserContextId;if(a!==void 0&&!this.hooks.contextExists(a))throw new Error("No browser context with given id");const o={id:crypto.randomUUID().replaceAll("-",""),contextId:a,...n?{openerId:n}:{},...s?{openerMark:s}:{},...i?{ownMark:i}:{},owner:t,controller:new AbortController,ready:!1,settled:!1};this.pages.set(o.id,o);const l=setTimeout(()=>o.controller.abort(new Error("Page creation timed out")),this.timeoutMs);let c=()=>{};const u=new Promise((p,m)=>{c=()=>{this.hooks.disconnectSurface(o.id),m(o.controller.signal.reason)},o.controller.signal.addEventListener("abort",c,{once:!0})}),d=Promise.resolve().then(()=>this.host.createPage({id:o.id,url:r.url,...a!==void 0?{browserContextId:a}:{}},o.controller.signal)).then(async()=>{if(o.settled=!0,!this.acceptsSurface(o.id)||!this.hooks.surfaceExists(o.id)){const p=o.controller.signal.reason??new Error("Host did not register a live page surface");throw o.controller.abort(p),await this.closeEntry(o),p}return o.ready=!0,o.id},async p=>{throw o.settled=!0,o.controller.abort(p),await this.closeEntry(o),p});try{return await Promise.race([d,u])}finally{clearTimeout(l),o.controller.signal.removeEventListener("abort",c)}}closeEntry(t){return t.closing||(t.closing=Promise.resolve().then(()=>this.host.closePage(t.id)).then(()=>{this.hooks.disconnectSurface(t.id),this.retired.add(t.id),this.pages.delete(t.id)},r=>{throw t.closing=void 0,r})),t.closing}async closeTarget(t){const r=this.pages.get(t);if(!r?.ready||!this.hooks.surfaceExists(t))throw new Error("No managed page with given id");await this.closeEntry(r)}disconnect(t){for(const r of this.pages.values())r.owner===t&&!r.ready&&r.controller.abort(new Error("Page creator disconnected"))}async disposeContext(t){const r=[];for(const n of this.pages.values())n.contextId===t&&(n.ready||n.controller.abort(new Error("Browser context disposed")),n.settled&&r.push(this.closeEntry(n)));await Promise.all(r)}async close(){this.stopped=!0;const t=[];for(const r of this.pages.values())r.ready||r.controller.abort(new Error("Browser host is closing")),r.settled&&t.push(this.closeEntry(r));await Promise.all(t)}}class lV{host;timeoutMs;contexts=new Map;closed=!1;constructor(t,r){this.host=t,this.timeoutMs=r}ids(){return[...this.contexts.values()].filter(t=>t.ready&&!t.disposal).map(t=>t.id)}async create(t,r){if(this.closed)throw new Error("Browser host is closing");const n=new Set(["disposeOnDetach","proxyServer","proxyBypassList","originsWithUniversalNetworkAccess"]);for(const d of Object.keys(r))if(!n.has(d))throw new Error(`Unsupported context option: ${d}`);if(r.disposeOnDetach!==void 0&&typeof r.disposeOnDetach!="boolean")throw new Error("disposeOnDetach must be boolean");for(const d of["proxyServer","proxyBypassList"])if(r[d]!==void 0&&typeof r[d]!="string")throw new Error(`${d} must be a string`);const s=r.originsWithUniversalNetworkAccess;if(s!==void 0&&(!Array.isArray(s)||!s.every(d=>typeof d=="string")))throw new Error("originsWithUniversalNetworkAccess must be a string array");const i={id:crypto.randomUUID().replaceAll("-",""),owner:t,disposeOnDetach:r.disposeOnDetach===!0,controller:new AbortController,ready:!1,settled:!1};this.contexts.set(i.id,i);const a=setTimeout(()=>i.controller.abort(new Error("Context creation timed out")),this.timeoutMs),l=Promise.resolve().then(()=>this.host.createContext({id:i.id,...r.proxyServer!==void 0?{proxyServer:r.proxyServer}:{},...r.proxyBypassList!==void 0?{proxyBypassList:r.proxyBypassList}:{},...s!==void 0?{originsWithUniversalNetworkAccess:s}:{}},i.controller.signal)).then(async()=>{if(i.settled=!0,i.controller.signal.aborted||this.closed)throw await this.disposeEntry(i),i.controller.signal.reason??new Error("Browser host is closing");return i.ready=!0,i.id},async d=>{throw i.settled=!0,await this.disposeEntry(i),d});let c=()=>{};const u=new Promise((d,p)=>{c=()=>p(i.controller.signal.reason),i.controller.signal.addEventListener("abort",c,{once:!0})});try{return await Promise.race([l,u])}finally{clearTimeout(a),i.controller.signal.removeEventListener("abort",c)}}disposeEntry(t){return t.disposal||(t.disposal=Promise.resolve().then(()=>this.host.disposeContext(t.id)).then(()=>{this.contexts.delete(t.id)},r=>{throw t.disposal=void 0,r})),t.disposal}async dispose(t){const r=this.contexts.get(t);if(!r?.ready)throw new Error("No browser context with given id");await this.disposeEntry(r)}async disconnect(t){const r=[];for(const n of this.contexts.values())n.owner===t&&(n.ready?n.disposeOnDetach&&r.push(this.disposeEntry(n)):n.controller.abort(new Error("Context creator disconnected")));await Promise.all(r)}async close(){this.closed=!0;for(const t of this.contexts.values())t.ready||t.controller.abort(new Error("Browser host is closing"));await Promise.all([...this.contexts.values()].filter(t=>t.settled).map(t=>this.disposeEntry(t)))}}const cV={adapters:{accessibility:"optional",capture:"optional",browserContexts:"optional-host-owned-storage-isolation",browserPages:"optional-host-owned-page-lifecycle",rrwebCast:"optional",surface:"same-origin DOM"},commands:{hostContext:["Target.createBrowserContext","Target.disposeBrowserContext"],hostPage:["Target.createTarget","Target.closeTarget"],browser:["Browser.cancelDownload","Browser.getBrowserCommandLine","Browser.getVersion","Browser.setDownloadBehavior","Browser.grantPermissions","Browser.resetPermissions","Storage.clearCookies","Storage.getCookies","Storage.setCookies","Target.activateTarget","Target.attachToTarget","Target.attachToBrowserTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getBrowserContexts","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"],surface:["Accessibility.disable","Browser.cancelDownload","Browser.grantPermissions","Browser.resetPermissions","Browser.setDownloadBehavior","Accessibility.enable","Accessibility.getChildAXNodes","Accessibility.getFullAXTree","Accessibility.getPartialAXTree","Accessibility.getRootAXNode","Accessibility.queryAXTree","DOM.describeNode","DOM.disable","DOM.enable","DOM.focus","DOM.getBoxModel","DOM.getContentQuads","DOM.getDocument","DOM.querySelector","DOM.querySelectorAll","DOM.requestNode","DOM.requestChildNodes","DOM.resolveNode","DOM.scrollIntoViewIfNeeded","DOM.setFileInputFiles","Emulation.clearDeviceMetricsOverride","Emulation.clearGeolocationOverride","Audits.disable","Audits.enable","Performance.disable","Performance.enable","Performance.getMetrics","Emulation.setDeviceMetricsOverride","Emulation.setEmulatedMedia","Emulation.setFocusEmulationEnabled","Emulation.setGeolocationOverride","Emulation.setLocaleOverride","Emulation.setTouchEmulationEnabled","Emulation.setUserAgentOverride","Fetch.continueRequest","Fetch.disable","Fetch.enable","Fetch.failRequest","Fetch.fulfillRequest","Input.dispatchDragEvent","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.dispatchTouchEvent","Input.emulateTouchFromMouseEvent","Input.imeSetComposition","Input.insertText","Input.setInterceptDrags","Log.disable","Log.enable","Network.disable","Network.enable","Network.getResponseBody","Network.setCacheDisabled","Network.setExtraHTTPHeaders","Page.addScriptToEvaluateOnNewDocument","Page.bringToFront","Page.captureScreenshot","Page.close","Page.createIsolatedWorld","Page.deleteCookie","Page.disable","Page.enable","Page.getFrameTree","Page.handleJavaScriptDialog","Page.getLayoutMetrics","Page.getNavigationHistory","Page.getResourceTree","Page.navigate","Page.navigateToHistoryEntry","Page.reload","Page.removeScriptToEvaluateOnNewDocument","Page.setFontFamilies","Page.setInterceptFileChooserDialog","Page.screencastFrameAck","Page.setLifecycleEventsEnabled","Page.setTouchEmulationEnabled","Page.startScreencast","Page.stopScreencast","Runtime.addBinding","Runtime.callFunctionOn","Runtime.disable","Runtime.enable","Runtime.evaluate","Runtime.getProperties","Runtime.releaseObject","Runtime.releaseObjectGroup","Runtime.runIfWaitingForDebugger","Schema.getDomains","Storage.clearCookies","Storage.getCookies","Storage.setCookies","Target.activateTarget","Target.setAutoAttach"],refused:["Browser.getWindowForTarget","Emulation.setDefaultBackgroundColorOverride","Emulation.setOrientationOverride","Emulation.setScriptExecutionDisabled","Emulation.setTimezoneOverride","Fetch.continueWithAuth","Network.clearBrowserCache","Network.emulateNetworkConditions","Network.loadNetworkResource","Network.setBypassServiceWorker","Page.setBypassCSP","Security.setIgnoreCertificateErrors"]},unimplemented:{domains:["CSS","Debugger","HeapProfiler","IO","Profiler","Tracing"],commands:["Browser.close","Browser.getWindowBounds","Browser.setDockTile","Browser.setWindowBounds","Console.enable","DOM.getFrameOwner","Page.printToPDF","Target.sendMessageToTarget"]},fidelity:{dialogs:"reported-and-dismissed-synchronously-while-Page-is-observed; accept refused",downloads:"anchor downloads (a[download], blob:, data:) intercepted by the surface and written through the host; downloads the host browser starts from an attachment navigation are its own",capture:"adapter-declared",deviceScaleFactor:"js-visible-only",history:"frame-scoped via the Navigation API; without it, agent-observed entries and traversal refused",pageClose:"host-hook-required",urls:"host-mapped; page script sees the frame's real location",userAgent:"js-visible-only; HTTP headers unchanged; navigator.platform only from the platform parameter",locale:"js-visible-only; Intl constructors, toLocale*String and navigator.language(s)",geolocation:"js-visible-only; navigator.geolocation answers only while geolocation is granted",permissions:"js-visible-only; navigator.permissions.query and Notification.permission; host prompts unchanged",touch:"js-visible-only; navigator.maxTouchPoints and ontouchstart",realmOverrides:"installed when a document finishes loading; scripts that run earlier see host values",cookies:"script-visible-only; HttpOnly cookies unreadable and unsettable; each surface reaches its own host and path",fileChooser:"click-and-showPicker-interception; files assigned only through a host file adapter",fontFamilies:"standard-applied; generic families resolved by host browser; forScripts ignored",screenSize:"js-visible-only",viewport:"frame-element-resized; a top-level surface accepts only its current size",input:"synthetic-isTrusted-false",dragAndDrop:"synthetic-DataTransfer; draggable-element drags only (no text-selection or file drags)",keyboardEditing:"text-controls-code-point-movement-and-deletion; no-platform-word-or-grapheme-segmentation",legacyTouchEmulation:"mouse-events-only",wheel:"synthetic-cancelable-event-and-scrollable-ancestor-default-action",network:"fetch-and-xhr-observation",interception:"fetch-and-xhr-only; synchronous XHR and response-stage interception unavailable; authentication challenges stay with the host browser",responseBodies:"fetch-and-xhr; 8-MiB-LRU; json/document XHR bodies unavailable",cacheDisabled:"fetch-requests-use-no-store; XHR, navigation and subresources keep the HTTP cache",rrweb:"side-channel"},protocol:{devtoolsProtocolPackage:"0.0.1702366",protocolVersion:"1.3"},version:1};function j8(e,t,r){const n=r.length>1?r.replace(/\/$/,""):r,s=/^wss?:\/\//u.test(t)?t:`ws://${t}`,i=s.replace(/^wss?:\/\//u,"");return n==="/json/version"?{status:200,body:{Browser:"AlmostCDP/0.1.0","Protocol-Version":"1.3","User-Agent":"AlmostCDP/0.1.0","V8-Version":"0","WebKit-Version":"0",webSocketDebuggerUrl:`${s}/devtools/browser/${e.browserId}`}}:n==="/json"||n==="/json/list"?{status:200,body:e.targets().map(a=>({description:"",devtoolsFrontendUrl:`/devtools/inspector.html?${s.startsWith("wss:")?"wss":"ws"}=${i}/devtools/page/${a.id}`,id:a.id,title:a.title,type:a.type,url:a.url,webSocketDebuggerUrl:`${s}/devtools/page/${a.id}`}))}:n==="/health"?{status:200,body:{ok:!0,surfaces:e.targets().length}}:n==="/compatibility"?{status:200,body:e.compatibility()}:{status:404,body:{error:"not found"}}}class uV{deliver;readyState=1;listeners={message:[],close:[]};constructor(t){this.deliver=t}send(t){this.readyState===1&&this.deliver({data:t})}close(){this.readyState===1&&(this.deliver({close:!0}),this.closed())}on(t,r){this.listeners[t].push(r)}received(t){if(this.readyState===1)for(const r of this.listeners.message)r(t)}closed(){if(this.readyState!==3){this.readyState=3;for(const t of this.listeners.close)t()}}}let fV=0;const or=(e,t)=>{if((e.bufferedAmount??0)>8*1024*1024){e.close(1013,"Consumer too slow; reconnect for a fresh snapshot");return}e.readyState===1&&e.send(JSON.stringify(t))},Tb=e=>({attached:!1,browserContextId:e.contextId??"default",canAccessOpener:!1,targetId:e.description.id,title:e.description.title,type:e.description.type,url:e.description.url});function dV(e){const{browserId:t,surfaceToken:r}=e,n=new Map,s=new WeakMap,i=(L,G,q)=>G?q.parentId!==void 0&&L.sessions.get(G)===q.parentId:q.parentId===void 0,a=new Map,o=e.successionGraceMs??15e3,l=e.contextHost?new lV({createContext:(L,G)=>e.contextHost.createContext(L,G),disposeContext:async L=>{await c?.disposeContext(L),await e.contextHost.disposeContext(L)}},e.commandTimeoutMs??15e3):void 0,c=e.pageHost?new oV(e.pageHost,{contextExists:L=>l?.ids().includes(L)??!1,surfaceExists:L=>n.get(L)?.ws.readyState===1,disconnectSurface:L=>n.get(L)?.ws.close(1001,"Managed page closed")},e.commandTimeoutMs??15e3):void 0,u=new Set,d=L=>{const G=c?.opener(L.description.id);return{...Tb(L),...G?{openerId:G,canAccessOpener:c?.openerMark(L.description.id)!==void 0}:{}}},p=new Map,m=new Map,g=new Map,b=new Map,v=new Map,S=new Map,x=new Map,E=L=>({id:0,method:"Browser.setDownloadBehavior",params:{[pj]:!0,behavior:L.behavior}});let A=0;const T=(L,G,q={})=>{const J={id:G.id,result:q};G.sessionId&&(J.sessionId=G.sessionId),or(L.ws,J)},D=(L,G,q=P8(G.method))=>{const J={error:q,id:G.id};G.sessionId&&(J.sessionId=G.sessionId),or(L.ws,J)},I=(L,G,q)=>{const J=globalThis.crypto.randomUUID().replaceAll("-","");L.sessions.set(J,G.description.id),L.parents.set(J,q??"");const j={method:"Target.attachedToTarget",...q?{sessionId:q}:{},params:{sessionId:J,targetInfo:{...d(G),attached:!0},waitingForDebugger:!1}};return or(L.ws,j),J},U=(L,G,q)=>{const J=G.params?.files;if(G.method==="DOM.setFileInputFiles"&&e.fileHost&&Array.isArray(J)&&J.length&&G.params?.[U8]===void 0){const fe=e.fileHost,de=`files-${++fV}`;(async()=>{const me=[];for(const _e of J){const $e=String(_e),Pe=await fe.list?.($e);if(!Pe){me.push({path:$e});continue}const De=$e.replace(/[\\/]+$/u,""),lt=De.split(/[\\/]/u).pop()??De;for(const He of Pe)me.push({path:`${De}/${He}`,relativePath:`${lt}/${He}`})}for(const[_e,{path:$e,relativePath:Pe}]of me.entries()){const De=await fe.read($e);or(q.ws,{type:"stage-file",token:de,index:_e,name:De.name??$e.split(/[\\/]/u).pop()??$e,...De.type?{mimeType:De.type}:{},...De.lastModified!==void 0?{lastModified:De.lastModified}:{},...Pe?{relativePath:Pe}:{},dataBase64:mj(De.data)})}return me.length})().then(me=>U(L,{...G,params:{...G.params,files:[],[U8]:{token:de,count:me}}},q),me=>D(L,G,{code:-32e3,message:me instanceof Error?me.message:String(me)}));return}const j=G.sessionId??"direct",z=G.method.split(".")[0];let te;if(G.method===`${z}.enable`||G.method===`${z}.disable`){const fe=L.subscriptionChanges.get(j)??new Map;L.subscriptionChanges.set(j,fe);const de=fe.get(z)??{enabled:L.subscriptions.get(j)?.has(z)??!1,changes:[]};fe.set(z,de);const me={enabled:G.method.endsWith(".enable")};de.changes.push(me);const _e=()=>{let $e=de.enabled;for(const De of de.changes)De.accepted!==!1&&($e=De.enabled);const Pe=L.subscriptions.get(j)??new Set;$e?Pe.add(z):Pe.delete(z),L.subscriptions.set(j,Pe)};_e(),te=$e=>{if(L.subscriptionChanges.get(j)?.get(z)===de){for(me.accepted=$e;de.changes[0]?.accepted!==void 0;){const Pe=de.changes.shift();Pe.accepted&&(de.enabled=Pe.enabled)}_e(),de.changes.length||(fe.delete(z),fe.size||L.subscriptionChanges.delete(j))}}}if(G.method===`${z}.disable`&&[...u].some(de=>[...de.subscriptions].some(([me,_e])=>_e.has(z)&&(me==="direct"?de.directSurfaceId:de.sessions.get(me))===q.description.id))&&z!=="Runtime"&&z!=="DOM"&&z!=="Fetch"){te?.(!0),T(L,G);return}let le;if(G.method.startsWith("Page.")&&["Page.startScreencast","Page.stopScreencast","Page.screencastFrameAck"].includes(G.method)){const fe=b.get(q.description.id);if(fe&&(fe.client!==L||fe.sessionId!==G.sessionId)){D(L,G,{code:-32e3,message:"Screencast belongs to another session"});return}if(G.method==="Page.startScreencast"){const de={client:L,sessionId:G.sessionId};b.set(q.description.id,de),le=me=>{me||b.get(q.description.id)!==de||(b.delete(q.description.id),or(q.ws,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Page.stopScreencast"}}))}}G.method==="Page.stopScreencast"&&(le=de=>{de&&b.get(q.description.id)===fe&&b.delete(q.description.id)})}const ne=`r${++A}`,ge=setTimeout(()=>{m.delete(ne),te?.(!1),le?.(!1),D(L,G,{code:-32e3,message:"Surface command timed out"})},e.commandTimeoutMs??3e4);m.set(ne,{client:L,command:G,surface:q,timer:ge,settleSubscription:te,settleCapture:le});const ve={message:{id:G.id,method:G.method,params:G.params,sessionId:`${L.id}:${j}`},relayId:ne,type:"command"};or(q.ws,ve)},O=(L,G)=>{c?.disconnect(`${L.id}:${G}`),l?.disconnect(`${L.id}:${G}`).catch(()=>{});const q=L.sessions.get(G),J=L.parents.get(G)??"";for(const[z,te]of[...L.parents])te===G&&O(L,z);L.parents.delete(G),L.automaticSessions.delete(G),L.autoAttach.delete(G),L.discover.delete(G),L.sessions.delete(G),L.subscriptions.delete(G),L.subscriptionChanges.delete(G),L.browserSessions.delete(G);const j=q?n.get(q):void 0;if(j){or(j.ws,{type:"session-closed",sessionId:`${L.id}:${G}`});const z=b.get(q);z?.client===L&&z.sessionId===G&&(b.delete(q),or(j.ws,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Page.stopScreencast"}}))}for(const[z,te]of m)te.client!==L||te.command.sessionId!==G||(clearTimeout(te.timer),m.delete(z),D(L,te.command,{code:-32001,message:"Session detached"}));or(L.ws,{...J?{sessionId:J}:{},method:"Target.detachedFromTarget",params:{sessionId:G,...q?{targetId:q}:{}}})},_=L=>{const G=typeof L=="string"?L:"default";if(!(G!=="default"&&!l?.ids().includes(G)))return[...n.values()].filter(q=>(q.contextId??"default")===G)},$=(L,G,q,J=G.params)=>Promise.all(q.map(j=>new Promise(z=>{const te=`fan-${++A}`,le=setTimeout(()=>{m.delete(te),z({id:G.id,error:{code:-32e3,message:"Surface command timed out"}})},e.commandTimeoutMs??3e4);m.set(te,{client:L,command:G,surface:j,timer:le,resolve:z}),or(j.ws,{type:"command",relayId:te,message:{id:G.id,method:G.method,params:J}})}))),F=L=>{const G=L.find(q=>q.error);if(G)throw new Error(G.error.message)},P=(L,G)=>{const q=G.params??{},J=z=>{G.method==="Target.getTargetInfo"&&typeof q.targetId!="string"?T(L,G,{targetInfo:d(z)}):U(L,G,z)};if(L.directSurfaceId){const z=n.get(L.directSurfaceId);if(!z)return D(L,G,{code:-32e3,message:"Target closed"});J(z);return}if(G.sessionId&&!L.browserSessions.has(G.sessionId)){const z=L.sessions.get(G.sessionId),te=z?n.get(z):void 0;if(!te)return D(L,G,{code:-32001,message:"No session with given id"});if(G.method==="Target.setAutoAttach"){const le=G.sessionId;if(q.autoAttach===!0){L.autoAttach.add(le);for(const ne of n.values())i(L,le,ne)&&([...L.sessions].some(([ge,ve])=>ve===ne.description.id&&L.parents.get(ge)===le)||L.automaticSessions.add(I(L,ne,le)))}else{L.autoAttach.delete(le);for(const ne of[...L.automaticSessions])L.parents.get(ne)===le&&O(L,ne)}T(L,G);return}J(te);return}const j=z=>{z.then(te=>T(L,G,te),te=>D(L,G,{code:-32e3,message:te instanceof Error?te.message:String(te)}))};switch(G.method){case"Target.createTarget":c?j(c.create(`${L.id}:${G.sessionId??""}`,q).then(z=>({targetId:z}))):D(L,G);break;case"Target.closeTarget":c?typeof q.targetId!="string"?D(L,G,{code:-32602,message:"targetId must be a string"}):j(c.closeTarget(q.targetId).then(()=>({success:!0}))):D(L,G);break;case"Target.getBrowserContexts":T(L,G,{browserContextIds:l?.ids()??[]});break;case"Target.createBrowserContext":l?j(l.create(`${L.id}:${G.sessionId??""}`,q).then(z=>({browserContextId:z}))):D(L,G);break;case"Target.disposeBrowserContext":l?typeof q.browserContextId!="string"?D(L,G,{code:-32602,message:"browserContextId must be a string"}):j(l.dispose(q.browserContextId).then(()=>({}))):D(L,G);break;case"Target.attachToBrowserTarget":{const z=globalThis.crypto.randomUUID().replaceAll("-","");L.browserSessions.add(z),L.parents.set(z,G.sessionId??""),T(L,G,{sessionId:z});break}case"Browser.getVersion":T(L,G,{jsVersion:"0",product:`Chrome/${/Chrome\/([\d.]+)/u.exec(globalThis.navigator?.userAgent??"")?.[1]??"136.0.0.0"}`,protocolVersion:"1.3",revision:"@almostcdp",userAgent:globalThis.navigator?.userAgent??"Mozilla/5.0 AlmostCDP/0.1.0"});break;case"Browser.getBrowserCommandLine":T(L,G,{arguments:[]});break;case"Browser.grantPermissions":case"Browser.resetPermissions":{const z=typeof q.browserContextId=="string"?q.browserContextId:"default",te=_(q.browserContextId);if(!te){D(L,G,{code:-32e3,message:"Failed to find browser context for id"});break}G.method==="Browser.resetPermissions"?v.delete(z):v.set(z,[...v.get(z)??[],q]),j($(L,G,te).then(le=>(F(le),{})));break}case"Storage.getCookies":case"Storage.setCookies":case"Storage.clearCookies":{const z=_(q.browserContextId);if(!z){D(L,G,{code:-32e3,message:"Failed to find browser context for id"});break}const te=Array.isArray(q.cookies)?q.cookies:[],le=z.length?te.some(ge=>ge.httpOnly===!0)?"HttpOnly cookies are invisible to scripts and cannot be set from a DOM surface":void 0:"no surface of the context is open to reach its cookies";if(le){D(L,G,{code:-32e3,message:`${G.method} is unavailable on a DOM surface: ${le}`});break}const ne=G.method==="Storage.setCookies";j($(L,G,z,ne?{...q,[gj]:!0}:q).then(ge=>{if(F(ge),G.method==="Storage.getCookies"){const ve=new Map;for(const fe of ge)for(const de of fe.result?.cookies??[])ve.set(`${String(de.name)}\0${String(de.domain)}\0${String(de.path)}`,de);return{cookies:[...ve.values()]}}if(ne){const ve=new Set(ge.flatMap(de=>de.result?.applied??[])),fe=te.filter((de,me)=>!ve.has(me)).map(de=>String(de.domain??de.url??""));if(fe.length)throw new Error(`Storage.setCookies is unavailable on a DOM surface: no open surface of the context serves ${fe.join(", ")}`)}return{}}));break}case"Browser.setDownloadBehavior":{if(!e.downloadHost){D(L,G,{code:-32e3,message:"Download policy requires a host download adapter; a live DOM surface cannot enforce it"});break}const z=String(q.behavior??"");if(!["default","deny","allow","allowAndName"].includes(z)){D(L,G,{code:-32602,message:`Invalid download behavior: ${z}`});break}const te=typeof q.downloadPath=="string"&&q.downloadPath?q.downloadPath:void 0;if((z==="allow"||z==="allowAndName")&&!te){D(L,G,{code:-32602,message:"downloadPath is required for allow and allowAndName"});break}const le=_(q.browserContextId);if(!le){D(L,G,{code:-32e3,message:"Failed to find browser context for id"});break}const ne=typeof q.browserContextId=="string"?q.browserContextId:"default",ge=(S.get(ne)?.listeners??[]).filter(fe=>fe.client!==L||fe.sessionId!==G.sessionId);q.eventsEnabled===!0&&ge.push({client:L,sessionId:G.sessionId});const ve={behavior:z,downloadPath:te,listeners:ge};S.set(ne,ve),j($(L,G,le,E(ve).params).then(fe=>(F(fe),{})));break}case"Browser.cancelDownload":{if(!e.downloadHost){D(L,G,L8(G.method));break}const z=String(q.guid??""),te=n.get(x.get(z)??"");if(!te){D(L,G,{code:-32e3,message:`Browser.cancelDownload: no in-flight download with guid ${z}`});break}j($(L,G,[te],{guid:z}).then(le=>(F(le),{})));break}case"Target.getTargets":T(L,G,{targetInfos:[...n.values()].map(Tb)});break;case"Target.getTargetInfo":{const z=typeof q.targetId=="string"?q.targetId:t;if(z===t){T(L,G,{targetInfo:{targetId:t,type:"browser",title:"",url:"",attached:!0,canAccessOpener:!1}});break}const te=z?n.get(z):void 0;te?T(L,G,{targetInfo:d(te)}):D(L,G,{code:-32e3,message:"No target with given id"});break}case"Target.setDiscoverTargets":{const z=G.sessionId??"",te=L.discover.has(z);if(q.discover===!0?L.discover.add(z):L.discover.delete(z),T(L,G),q.discover===!0&&!te)for(const le of n.values())or(L.ws,{...z?{sessionId:z}:{},method:"Target.targetCreated",params:{targetInfo:d(le)}});break}case"Target.setAutoAttach":{const z=G.sessionId??"";if(q.autoAttach===!0?L.autoAttach.add(z):L.autoAttach.delete(z),q.autoAttach===!0)for(const te of n.values())i(L,z,te)&&([...L.sessions].some(([le,ne])=>ne===te.description.id&&L.parents.get(le)===z)||L.automaticSessions.add(I(L,te,G.sessionId)));else for(const te of[...L.automaticSessions])L.parents.get(te)===z&&O(L,te);T(L,G);break}case"Target.attachToTarget":{const z=String(q.targetId??""),te=n.get(z);if(!te)D(L,G,{code:-32e3,message:"No target with given id"});else{const le=I(L,te,G.sessionId);T(L,G,{sessionId:le})}break}case"Target.activateTarget":{const z=n.get(String(q.targetId??""));z?U(L,G,z):D(L,G,{code:-32e3,message:"No target with given id"});break}case"Target.detachFromTarget":{const z=String(q.sessionId??"");if(!L.sessions.get(z)&&!L.browserSessions.has(z)||L.parents.get(z)!==(G.sessionId??"")){D(L,G,{code:-32001,message:"No session with given id"});break}O(L,z),T(L,G);break}default:D(L,G,L8(G.method)??P8(G.method))}},W=(L,G)=>{for(const[q,J]of m)J.surface===L&&(clearTimeout(J.timer),m.delete(q),J.resolve?J.resolve({id:J.command.id,error:{code:-32e3,message:G}}):D(J.client,J.command,{code:-32e3,message:G}))},K=L=>{const G=n.get(L);if(!G)return;const q=a.get(L);q?.suspended&&clearTimeout(q.suspended.timer),a.delete(L),n.delete(L),b.delete(L),W(G,"Target closed");for(const J of p.get(L)??[])J.close(1001,"Target closed");for(const J of u){if(J.directSurfaceId===L){J.subscriptions.clear(),J.subscriptionChanges.clear(),J.ws.close(1001,"Target closed");continue}for(const[j,z]of[...J.sessions])z===L&&O(J,j);for(const j of J.discover)or(J.ws,{...j?{sessionId:j}:{},method:"Target.targetDestroyed",params:{targetId:L}})}},Y=(L,G)=>{const q=n.get(L),J=[];q.ws={readyState:1,send:j=>{J.push(j)},close:()=>K(L),on:()=>{}},W(q,"Inspected target navigated or closed");for(const j of p.get(L)??[])j.close(1012,"Document replaced; reconnect");G.suspended={buffer:J,timer:setTimeout(()=>K(L),o)}},V=(L,G,q="control")=>{const J=new URL(G,"http://localhost");if(q==="view"&&!J.pathname.startsWith("/casts/")){L.close(1008,"View-only access permits only casting");return}if(J.pathname==="/__almostcdp/surface"){if(J.searchParams.get("token")!==r){L.close(1008,"invalid surface token");return}let ne;const ge=new Map;L.on("close",()=>{for(const ve of[...ge.values()])ve.closed()}),L.on("message",ve=>{let fe;try{if(fe=JSON.parse(ve.toString()),!fe||typeof fe!="object")throw new Error("Invalid message")}catch{L.close(1003,"invalid JSON");return}if(fe.type==="hello"){if(!fe.surface||typeof fe.surface.title!="string"||typeof fe.surface.url!="string"||fe.surface.id!==void 0&&(typeof fe.surface.id!="string"||!/^[\w-]+$/.test(fe.surface.id))){L.close(1008,"invalid surface description");return}const de=fe.surface.id??ne??globalThis.crypto.randomUUID().replaceAll("-",""),me=fe.succession?.token;if(fe.succession!==void 0&&(typeof me!="string"||me.length<16)){L.close(1008,"invalid succession token");return}const _e=a.get(de);if(!ne&&_e&&n.has(de)&&n.get(de).ws!==L){if(me!==_e.token){L.close(1008,"surface identity already registered");return}if(!_e.suspended){const gt=n.get(de).ws;Y(de,_e),gt.close(1e3,"Document replaced by its successor")}const Ve=n.get(de);clearTimeout(_e.suspended.timer);const xt=_e.suspended.buffer;_e.suspended=void 0,ne=de,Ve.ws=L,Ve.description.title=fe.surface.title,Ve.description.url=fe.surface.url,or(L,{type:"resume",state:_e.state,..._e.loaderId?{loaderId:_e.loaderId,navigationType:_e.navigationType}:{}}),_e.loaderId=void 0,_e.navigationType=void 0;for(const gt of xt)L.readyState===1&&L.send(gt);for(const gt of u){const ke=new Set(gt.discover);for(const[Le,ct]of gt.sessions)ct===de&&ke.add(gt.parents.get(Le)??"");for(const Le of ke)or(gt.ws,{...Le?{sessionId:Le}:{},method:"Target.targetInfoChanged",params:{targetInfo:Tb(Ve)}})}return}if(ne&&ne!==de||n.has(de)&&n.get(de).ws!==L){L.close(1008,"surface identity already registered");return}const $e=s.get(L);if(c&&$e===void 0&&!c.acceptsSurface(de)){L.close(1008,"Page allocation is no longer active");return}me!==void 0&&!ne&&(a.set(de,{token:me,state:null}),or(L,{type:"resume",state:null}));const Pe=n.has(de);ne=de;const De={contextId:$e!==void 0?n.get($e)?.contextId:c?.context(de),...$e!==void 0?{parentId:$e}:{},description:{id:de,title:fe.surface.title,type:fe.surface.type??"page",url:fe.surface.url},ws:L};n.set(de,De);const lt=c?.openerMark(de),He=c?.ownMark(de);(lt||He)&&or(L,{type:"opener",...lt?{mark:lt}:{},...He?{own:He}:{}});for(const Ve of u){const xt=new Set(Ve.discover);if(Pe)for(const[gt,ke]of Ve.sessions)ke===de&&xt.add(Ve.parents.get(gt)??"");for(const gt of xt)or(Ve.ws,{...gt?{sessionId:gt}:{},method:Pe?"Target.targetInfoChanged":"Target.targetCreated",params:{targetInfo:d(De)}});if(!Pe)for(const gt of Ve.autoAttach)i(Ve,gt,De)&&Ve.automaticSessions.add(I(Ve,De,gt||void 0))}if(!Pe){const Ve=S.get(De.contextId??"default");Ve&&Ve.behavior!=="default"&&or(L,{type:"command",relayId:`cleanup-${++A}`,message:E(Ve)});for(const xt of v.get(De.contextId??"default")??[])or(L,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Browser.grantPermissions",params:xt}})}return}if(fe.type==="succession-state"){const de=ne?a.get(ne):void 0;if(!de||n.get(ne)?.ws!==L)return;if(!fe.state||typeof fe.state!="object"||Array.isArray(fe.state)){L.close(1008,"invalid succession state");return}de.state=fe.state;return}if(fe.type==="response"){const de=m.get(fe.relayId);if(!de||de.surface.ws!==L)return;if(!fe.message||typeof fe.message!="object"){L.close(1008,"invalid response");return}m.delete(fe.relayId),clearTimeout(de.timer);const me=a.get(de.surface.description.id);if(me&&!fe.message.error&&(de.command.method==="Page.navigate"||de.command.method==="Page.reload")){const $e=fe.message.result?.loaderId;me.loaderId=typeof $e=="string"?$e:void 0,me.navigationType=de.command.method==="Page.reload"?"reload":"typed"}if(de.resolve){de.resolve(fe.message);return}de.settleSubscription?.(!fe.message.error),de.settleCapture?.(!fe.message.error);const _e={...fe.message,id:de.command.id};de.command.sessionId&&(_e.sessionId=de.command.sessionId),or(de.client.ws,_e);return}if(fe.type==="cast"&&ne){for(const de of p.get(ne)??[])or(de,fe.event);return}if(fe.type==="sub"&&ne&&typeof fe.sub=="string"){const de=ne;let me=ge.get(fe.sub);if(fe.open===!0&&!me){const _e=fe.sub;me=new uV($e=>or(L,{type:"sub",sub:_e,...$e})),ge.set(_e,me),s.set(me,de),me.on("close",()=>ge.delete(_e)),V(me,`/__almostcdp/surface?token=${encodeURIComponent(r)}`)}typeof fe.data=="string"&&me?.received(fe.data),fe.close===!0&&me?.closed();return}if(fe.type==="close-window"&&ne){const de=ne;c?.closeTarget(de).catch(me=>console.warn(`AlmostCDP: window.close() closed no page: ${me instanceof Error?me.message:String(me)}`));return}if(fe.type==="open-window"&&ne){const de=ne;if(!c||typeof fe.url!="string")return;const me=c.owner(de)??`popup:${de}`,_e=n.get(de)?.contextId,$e=typeof fe.opener=="string"&&/^[\w-]{16,}$/u.test(fe.opener)?fe.opener:void 0,Pe=typeof fe.mark=="string"&&/^[\w-]{16,}$/u.test(fe.mark)?fe.mark:void 0;c.create(me,{url:fe.url,..._e&&_e!=="default"?{browserContextId:_e}:{}},de,$e,Pe).catch(De=>console.warn(`AlmostCDP: window.open(${JSON.stringify(fe.url)}) opened no page: ${De instanceof Error?De.message:String(De)}`));return}if(fe.type==="download"&&ne){const de=ne,me=n.get(de)?.contextId,_e=S.get(me??"default"),$e=lt=>or(L,{type:"download-written",...lt});if(!e.downloadHost||!_e?.downloadPath||_e.behavior!=="allow"&&_e.behavior!=="allowAndName"||typeof fe.guid!="string"||typeof fe.data!="string"){$e({error:"downloads are not accepted for this context",guid:String(fe.guid)});return}const Pe=_e.behavior==="allowAndName"?fe.guid:String(fe.suggestedFilename??"").replace(/[\\/]/g,"_")||fe.guid,De=`${_e.downloadPath.replace(/[\\/]+$/,"")}/${Pe}`;e.downloadHost.write(me,De,hj(fe.data)).then(()=>$e({filePath:De,guid:fe.guid}),lt=>$e({error:lt instanceof Error?lt.message:String(lt),guid:fe.guid}));return}if(fe.type==="event"&&ne){if(!fe.message||typeof fe.message.method!="string"){L.close(1008,"invalid event");return}if(fe.message.method.startsWith("Browser.download")){const De=fe.message.params??{},lt=String(De.guid??"");fe.message.method==="Browser.downloadWillBegin"?x.set(lt,ne):(De.state==="completed"||De.state==="canceled")&&x.delete(lt);const He=S.get(n.get(ne)?.contextId??"default");for(const Ve of He?.listeners??[])or(Ve.client.ws,{method:fe.message.method,params:De,...Ve.sessionId?{sessionId:Ve.sessionId}:{}});return}if(fe.message.method==="Page.screencastFrame"){const De=b.get(ne),{sessionId:lt,...He}=fe.message;De&<===`${De.client.id}:${De.sessionId??"direct"}`&&or(De.client.ws,{...He,...De.sessionId?{sessionId:De.sessionId}:{}});return}const{sessionId:de,...me}=fe.message,_e=me.method.split(".")[0],$e=["Runtime","Network","Log","DOM","Page","Accessibility"].includes(_e),Pe=(De,lt)=>(!de||de===`${De.id}:${lt}`)&&(!$e||De.subscriptions.get(lt)?.has(_e));for(const De of u){if(De.directSurfaceId===ne&&Pe(De,"direct")){or(De.ws,me);continue}for(const[lt,He]of De.sessions)He===ne&&Pe(De,lt)&&or(De.ws,{...me,sessionId:lt})}}}),L.on("close",()=>{if(!ne||n.get(ne)?.ws!==L)return;const ve=a.get(ne);ve?Y(ne,ve):K(ne)});return}const j=J.pathname.match(/^\/devtools\/page\/([^/]+)$/),z=J.pathname.match(/^\/devtools\/browser\/([^/]+)$/),te=J.pathname.match(/^\/casts\/([^/]+)$/);if(te){const ne=te[1];if(!n.has(ne)){L.close(1013,"target not available");return}const ge=p.get(ne)??new Set;ge.add(L),p.set(ne,ge),or(n.get(ne).ws,{type:"cast-reset"}),L.on("message",ve=>{if(q==="view"){L.close(1008,"View-only access cannot send input");return}const fe=n.get(ne);if(!fe)return;let de;try{de=JSON.parse(ve.toString())}catch{L.close(1003,"invalid JSON");return}if(typeof de.method!="string"||!de.method.startsWith("Input.")){L.close(1008,"cast input must be a CDP Input command");return}const me={message:{id:0,method:de.method,params:typeof de.params=="object"&&de.params?de.params:{}},relayId:`cast-${++A}`,type:"command"};or(fe.ws,me)}),L.on("close",()=>{ge.delete(L),ge.size||p.delete(ne)});return}if(!j&&(!z||z[1]!==t)){L.close(1008,"unknown endpoint");return}if(j&&!n.has(j[1])){L.close(1008,"unknown target");return}const le={id:globalThis.crypto.randomUUID(),autoAttach:new Set,automaticSessions:new Set,parents:new Map,browserSessions:new Set,subscriptions:new Map,subscriptionChanges:new Map,directSurfaceId:j?.[1],discover:new Set,sessions:new Map,ws:L};u.add(le),L.on("message",ne=>{let ge;try{if(ge=JSON.parse(ne.toString()),!ge||!Number.isSafeInteger(ge.id)||typeof ge.method!="string"||ge.params!==void 0&&(!ge.params||typeof ge.params!="object"||Array.isArray(ge.params))||ge.sessionId!==void 0&&typeof ge.sessionId!="string")throw new Error("Invalid command")}catch{L.close(1003,"invalid JSON");return}g.set(ge.method,(g.get(ge.method)??0)+1),P(le,ge)}),L.on("close",()=>{u.delete(le);for(const ne of S.values())ne.listeners=ne.listeners.filter(ge=>ge.client!==le);for(const ne of["",...le.browserSessions])c?.disconnect(`${le.id}:${ne}`),l?.disconnect(`${le.id}:${ne}`).catch(()=>{});for(const[ne,ge]of le.sessions){const ve=n.get(ge);ve&&or(ve.ws,{type:"session-closed",sessionId:`${le.id}:${ne}`})}if(le.directSurfaceId){const ne=n.get(le.directSurfaceId);ne&&or(ne.ws,{type:"session-closed",sessionId:`${le.id}:direct`})}for(const[ne,ge]of b){if(ge.client!==le)continue;b.delete(ne);const ve=n.get(ne);ve&&or(ve.ws,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Page.stopScreencast"}})}for(const[ne,ge]of m)ge.client===le&&(clearTimeout(ge.timer),m.delete(ne))})};return{connect:V,targets:()=>[...n.values()].map(L=>({...L.description})),compatibility:()=>({manifest:cV,observedCommands:Object.fromEntries([...g].sort(([L],[G])=>L.localeCompare(G)))}),async close(){for(const q of m.values())clearTimeout(q.timer);m.clear();for(const q of u)q.ws.close(1001,"server closing");for(const q of n.values())q.ws.close(1001,"server closing");for(const q of p.values())for(const J of q)J.close(1001,"server closing");const G=(await Promise.allSettled([c?.close(),l?.close()])).filter(q=>q.status==="rejected");if(G.length===1)throw G[0].reason;if(G.length)throw new AggregateError(G.map(q=>q.reason),"Host cleanup failed")}}}const hV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",pV=64*1024,vf=new TextEncoder;function E$(e){const t=globalThis.crypto.randomUUID().replaceAll("-",""),r=vV(24),n=dV({...e,browserId:t,surfaceToken:r}),s=new Set;let i=!1;const a={browserId:t,targets:n.targets,compatibility:n.compatibility};return{browserId:t,serve:l=>{if(i){l.close();return}s.add(l),l.onClose(()=>s.delete(l));let c=new Uint8Array,u,d,p=!1;const m=(g,b,v=!1)=>{p=!0,c=new Uint8Array,gV(l,g,b,v)};l.onData(g=>{if(u){u(g);return}if(d){d.push(g);return}if(p)return;const b=Math.max(0,c.byteLength-3);c=cv(c,g);const v=wV(c,b);if(v<0){c.byteLength>pV&&(console.warn(`CDP endpoint: a connection sent ${c.byteLength} bytes with no HTTP request header; it is answered 431 and closed. It starts ${JSON.stringify(new TextDecoder().decode(c.subarray(0,32)))}.`),m(431,{error:"request header too large"}));return}const S=yV(new TextDecoder().decode(c.subarray(0,v))),x=c.subarray(v+4);if(!S){m(400,{error:"malformed request"});return}const E=e.authorize?e.authorize(S):"control";if(!E){m(401,{error:"unauthorized"});return}if((S.headers.upgrade??"").toLowerCase()==="websocket"){const D=S.headers["sec-websocket-key"];if(S.method!=="GET"||!D||S.headers["sec-websocket-version"]!=="13"||!/\bupgrade\b/i.test(S.headers.connection??"")){m(400,{error:"invalid WebSocket handshake"});return}d=x.byteLength?[x]:[],bV(D).then(I=>{l.write(vf.encode(`HTTP/1.1 101 Switching Protocols\r
|
|
3
3
|
Upgrade: websocket\r
|
|
4
4
|
Connection: Upgrade\r
|
|
@@ -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.
|
|
@@ -1876,7 +1876,7 @@ connection: close\r
|
|
|
1876
1876
|
`,r=async(n,s)=>(s.onStderr?.(t),{stdout:"",stderr:t,exitCode:1});for(const n of $F)e.runtime.registerProgram(n,r,{descriptors:!0});return _F(e.runtime,e.home,e.roots)}function _F(e,t,r){const n=e.filesystem;let s="";const i=async()=>{const o=(await w0e(n,r)).sort().join(",");o!==s&&(s=o,await v0e(n,`${t}/.cache/ms-playwright`,o?o.split(","):[]))},a=setInterval(()=>{i().catch(o=>console.error("Chromium face placement failed:",o))},2e3);return i().catch(o=>console.error("Chromium face placement failed:",o)),()=>clearInterval(a)}function _0e(e){const t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",xml:"text/xml",csv:"text/csv",pdf:"application/pdf",zip:"application/zip",gz:"application/gzip",wasm:"application/wasm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",mp4:"video/mp4",webm:"video/webm",woff:"font/woff",woff2:"font/woff2"}[t]??""}const eE="314.0.6",I0e=`https://cdn.jsdelivr.net/pyodide/v${eE}/full/`,M0e="/python-runtime-snapshot.bin",D0e="/python-runtime-snapshot.json",L0e=[{file:"pyodide.mjs",integrity:"sha256-aeP2zOw+FLRl32C+V3ymL1NiUUBrmgDM4BnqxSUqJJU=",bytes:17931},{file:"pyodide.asm.mjs",integrity:"sha256-KsXro2XsEoOcdcA7ObO+HdY7eYhSzEYLAUtSI4vgQvc=",bytes:1250344},{file:"pyodide.asm.wasm",integrity:"sha256-OgoA3+qjSKwg+e8JkEIz0y0z9kQzlmLUrzaPiiAQ83o=",bytes:9598218},{file:"python_stdlib.zip",integrity:"sha256-gMW+a6v+AylwaXA0EMPClATc8lJdKxKHRrrlU2+Ugx8=",bytes:2545564},{file:"pyodide-lock.json",integrity:"sha256-P9rvCenjZcheACc3cg+NCrjyeMHCRKLd5qN2Y89IitQ=",bytes:114440}];function P0e(e){const t=L0e.find(r=>r.file===e);if(!t)throw new Error(`Pyodide ${eE} publishes no pinned ${e}.`);return t}async function U0e(e){const t=new Uint8Array(await crypto.subtle.digest("SHA-256",e));let r="";for(const n of t)r+=String.fromCharCode(n);return`sha256-${btoa(r)}`}const F0e="modulepreload",B0e=function(e){return"/"+e},PT={},vh=function(t,r,n){let s=Promise.resolve();if(r&&r.length>0){let l=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),o=a?.nonce||a?.getAttribute("nonce");s=l(r.map(c=>{if(c=B0e(c),c in PT)return;PT[c]=!0;const u=c.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":F0e,u||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),u)return new Promise((m,g)=>{p.addEventListener("load",m),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return s.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})},UT="/workspace",z0e=/^(?:pyodide(?:\.asm)?\.(?:m?js|wasm)|python_stdlib\.zip|pyodide-lock\.json|repodata\.json)$/u;function j0e(e,t,r){if(t!=="GET"&&t!=="HEAD")throw new Error("Managed Python artifacts require GET or HEAD.");if(e.protocol!=="https:"||e.username||e.password||e.hash||e.search)throw new Error("Managed Python artifact URL is invalid.");const n=e.hostname==="cdn.jsdelivr.net"&&e.pathname.startsWith(new URL(I0e).pathname),s=e.pathname.slice(e.pathname.lastIndexOf("/")+1);if(!(r==="runtime"&&n&&z0e.test(s)))throw(n||r==="package")&&_c({door:"python package",subject:e.href,fix:"a Python project's packages cannot yet be carried as packs, so the tab cannot provide them."}),new Error(`Python ${r} artifact request is outside the managed allowlist.`)}const W0e=3e4;class H0e{filesystem;options;filesystemCommitTail=Promise.resolve();standby;standbyTimer;nativeFetch=globalThis.fetch.bind(globalThis);activeFetches=0;networkBytes=0;constructor(t,r){this.filesystem=t,this.options=r}run=async(t,r={})=>{if(Ic(r.filesystemPolicy,void 0),r.signal?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:130});const n=await q0e(r);if(r.signal?.aborted)return{stdout:"",stderr:"",exitCode:130};const s=this.standby!==void 0,i=await this.takeWorker(),a=s?void 0:await this.runtimeSnapshot(),o=new MessageChannel,l=this.options.sharedMemoryChannels!==!1,c=l?`python:${crypto.randomUUID()}`:void 0,u=l?X$():void 0,d=u&&c?Y$.attach(u.server,c):void 0,p=l?G$():void 0,m=p?q$.attach(p.server,this.filesystem,()=>this.persistFilesystem()):void 0,g=S$(this.filesystem);g&&await this.filesystem.flush?.();const b=await S1(this.filesystem,"/",g?{metadataRoots:["/workspace"]}:{});let v=b;const S=this.options.server.attach(o.port1,{base:()=>v,advance:T=>{v=E7(v,T)}});let x=Promise.resolve(),E="",A="";return new Promise(T=>{let D=!1,I;const U=$=>{D||(D=!0,I!==void 0&&clearTimeout(I),r.signal?.removeEventListener("abort",O),S(),i.terminate(),m?.(),d?.(),T($))},O=()=>{i.postMessage({type:"shutdown"}),I=setTimeout(()=>U({stdout:E,stderr:A,exitCode:130}),12e3)};r.signal?.addEventListener("abort",O,{once:!0}),i.onmessage=$=>{const F=$.data;if(F.type==="stdout"){E+=F.chunk,r.onStdout?.(F.chunk);return}if(F.type==="stderr"){A+=F.chunk,r.onStderr?.(F.chunk);return}if(F.type==="network-request"){this.handleNetwork(i,F);return}if(!("patch"in F))return;const P=v;if(v=E7(P,F.patch),x=x.then(()=>this.applyResult(P,F.patch)),F.type==="commit"){x.then(()=>i.postMessage({type:"commit-ack",commitId:F.commitId}),W=>i.postMessage({type:"commit-ack",commitId:F.commitId,error:W instanceof Error?W.message:String(W)}));return}F.type==="result"&&x.then(()=>{D||U({stdout:E,stderr:F.error?`${A}${F.error}
|
|
1877
1877
|
`:A,exitCode:F.exitCode})},W=>U({stdout:E,stderr:`${A}${String(W)}
|
|
1878
1878
|
`,exitCode:1}))},i.onerror=$=>U({stdout:E,stderr:`${A}${$.message}
|
|
1879
|
-
`,exitCode:1});const _={type:"run",argv:[...t],cwd:r.cwd??this.options.cwd??"/workspace",env:{...this.options.env,...r.env},filesystem:b,...g?{store:{projectId:g}}:{},stdinBase64:G0e(n),...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a.slice(0)}:{},serverPort:o.port2,...u&&c?{fileLocks:{channel:u.client,owner:c}}:{},...p?{fileCoherence:p.client}:{},sharedMemoryChannels:l};i.postMessage(_,[_.serverPort,..._.runtimeSnapshot?[_.runtimeSnapshot]:[],..._.fileLocks?[_.fileLocks.channel.port]:[],..._.fileCoherence?[_.fileCoherence.port]:[]])})};snapshot;runtimeSnapshot(){const t=this.options.runtimeSnapshotUrl;return t?(this.snapshot??=(async()=>{try{const r=await this.nativeFetch(t,{cache:"no-cache",credentials:"same-origin"});if(!r.ok)return;const n=await r.json();if(n.format!==1||n.pyodide!==eE||n.engine!==P0e("pyodide.asm.wasm").integrity)return;const s=await this.nativeFetch(new URL(M0e,t),{credentials:"same-origin"});if(!s.ok)return;const i=await s.arrayBuffer();return await U0e(new Uint8Array(i))===n.integrity?i:void 0}catch{return}})(),this.snapshot):Promise.resolve(void 0)}createWorker(){return this.options.createWorker?this.options.createWorker():Promise.resolve(bf(new Worker(new URL("/assets/worker-CQmX_ncR.js",import.meta.url),{type:"module",name:"browser-python"})))}takeWorker(){const t=this.standby;this.standby=void 0,this.standbyTimer!==void 0&&clearTimeout(this.standbyTimer);const r=t??this.createWorker(),n=this.createWorker().then(async s=>{s.onmessage=o=>{const l=o.data;l.type==="network-request"&&this.handleNetwork(s,l)};const a=(await this.runtimeSnapshot())?.slice(0);return s.postMessage({type:"prepare",...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a}:{}},a?[a]:[]),s});return n.catch(()=>{}),this.standby=n,this.standbyTimer=setTimeout(()=>{this.standby===n&&(this.standby=void 0,n.then(s=>s.terminate(),()=>{}))},W0e),r}async applyResult(t,r){const n=this.filesystemCommitTail.then(async()=>{T1(this.filesystem,r,t),await this.options.onFilesystemCommit?.(this.filesystem)});this.filesystemCommitTail=n.catch(()=>{}),await n}async persistFilesystem(){const t=this.filesystemCommitTail.then(()=>this.options.onFilesystemCommit?.(this.filesystem));this.filesystemCommitTail=t.then(()=>{},()=>{}),await t}async handleNetwork(t,r){try{const n=new URL(r.url);if(n.protocol!=="https:"||n.username||n.password)throw new Error("Browser Python external requests require credential-free HTTPS URLs.");if(r.purpose==="program"){if(!this.options.network)throw new Error("Browser Python egress has no embedding grant.");this.options.network.authorize(n)}else j0e(n,r.method,r.purpose);const s=this.options.network?.maxConnections??16,i=this.options.network?.maxBytes??64*1024*1024;if(this.activeFetches>=s)throw new Error("Browser Python egress connection limit exceeded.");this.consumeNetwork(r.body.byteLength,i),this.activeFetches+=1;let a;try{a=await this.nativeFetch(n,{method:r.method,headers:V0e(r.headers),...r.body.byteLength>0?{body:r.body}:{},credentials:"omit",redirect:"error"})}finally{this.activeFetches-=1}const o=Number(a.headers.get("content-length"));if(Number.isFinite(o)&&o>=0&&o>i-this.networkBytes)throw new Error("Browser Python egress byte limit exceeded.");const l=await a.arrayBuffer();this.consumeNetwork(l.byteLength,i),t.postMessage({type:"network-response",requestId:r.requestId,status:a.status,statusText:a.statusText,headers:[...a.headers.entries()],body:l},[l])}catch(n){console.warn(`Browser Python request to ${r.url} failed: ${n instanceof Error?n.message:String(n)}`),t.postMessage({type:"network-error",requestId:r.requestId,error:n instanceof Error?n.message:String(n)})}}consumeNetwork(t,r){if(!Number.isSafeInteger(t)||t<0||this.networkBytes>r-t)throw new Error("Browser Python egress byte limit exceeded.");this.networkBytes+=t}}async function q0e(e){const t=[];let r=0;if(e.stdin){const i=new TextEncoder().encode(e.stdin);t.push(i),r+=i.byteLength}if(e.stdinStream)for await(const i of e.stdinStream){const a=i.slice();if(r+=a.byteLength,r>16*1024*1024)throw new Error("Python stdin exceeds 16 MiB.");t.push(a)}const n=new Uint8Array(r);let s=0;for(const i of t)n.set(i,s),s+=i.byteLength;return n}function G0e(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function V0e(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}const FT=8,Z0e=64*1024,BT=16*1024*1024,Y0e=16*1024*1024,X0e=1024*1024;class K0e{filesystem;sync;backend;controllers=new Map;children=new Map;nextChildId=1;active=0;closed=!1;changeQueue=Promise.resolve();constructor(t,r,n){this.filesystem=t,this.sync=r,this.backend=n}handles(t){return t.type==="process-run"||t.type==="process-cancel"||t.type==="process-start"||t.type==="process-action"}handle(t){t.type==="process-cancel"?this.controllers.get(t.requestId)?.abort(new DOMException("Python subprocess cancelled.","AbortError")):t.type==="process-run"?this.run(t):t.type==="process-start"?this.start(t):this.act(t)}close(){if(!this.closed){this.closed=!0;for(const t of this.controllers.values())t.abort(new DOMException("Python server process exited.","AbortError"));this.controllers.clear();for(const t of this.children.values())t.stdin?.close(),t.controller.abort(new DOMException("Python server process exited.","AbortError"));this.children.clear()}}run(t){if(this.active>=FT){ai(t,{error:"Python subprocess concurrency exceeded."});return}this.active+=1;const r=new AbortController;this.controllers.set(t.requestId,r),this.runOnce(t,r.signal).finally(()=>{this.active-=1,this.controllers.delete(t.requestId)})}async runOnce(t,r){try{const n=this.requiredBackend();WT(t.command,t.cwd,t.env);const s=D2(t.stdinBase64);if(s.byteLength>BT)throw new Error("Python subprocess stdin exceeds 16 MiB.");const i=await n.run(t.command,{cwd:t.cwd,env:t.env,signal:r,...s.byteLength>0?{stdinStream:J0e(s)}:{}});ai(t,{result:i,patch:await this.childChanges()})}catch(n){ai(t,{error:y1(n)})}}childChanges(){const t=this.changeQueue.then(async()=>{const r=this.sync.base(),n=N1(r,this.filesystem.toSnapshot()),s=[];for(const a of n.files){if(!jT(a.path))continue;if(a.type!=="file"||a.content!==void 0){s.push(a);continue}const{size:o,...l}=a;s.push({...l,content:HT(await this.filesystem.readFile(a.path))})}const i={files:s,removed:n.removed.filter(jT)};return this.sync.advance(i),i});return this.changeQueue=t.catch(()=>{}),t}start(t){try{const r=this.requiredBackend();if(this.closed)throw new Error("Python child-process host is closed.");if(this.active>=FT)throw new Error("Python subprocess concurrency exceeded.");WT(t.command,t.cwd,t.env);const n=this.nextChildId++,s=new AbortController,i=t.stdinPipe?new Q0e:void 0,a=t.stdoutPipe?new zT:void 0,o=t.stderrPipe&&!t.stderrToStdout?new zT:void 0,l={controller:s,stdin:i,stdout:a,stderr:o};let c=!1,u=!1;const d=(p,m)=>{if(p)try{p.write(new TextEncoder().encode(m))}catch(g){throw s.abort(g),g}};this.active+=1,l.completion=r.run(t.command,{cwd:t.cwd,env:t.env,signal:s.signal,...i?{stdinStream:i}:{},...a||t.stderrToStdout?{onStdout:p=>{c=!0,d(a,p)}}:{},...o||t.stderrToStdout?{onStderr:p=>{u=!0,d(t.stderrToStdout?a:o,p)}}:{}}).then(p=>(a&&p.stdout&&!c&&d(a,p.stdout),t.stderrToStdout&&p.stderr&&!u?d(a,p.stderr):o&&p.stderr&&!u&&d(o,p.stderr),{result:p}),p=>({error:y1(p)})).then(p=>(l.finished=p,a?.close(),o?.close(),this.active-=1,p)),this.children.set(n,l),ai(t,{childId:n})}catch(r){ai(t,{error:y1(r)})}}async act(t){try{const r=this.children.get(t.childId);if(!r)throw new Error("Unknown browser subprocess.");if(t.action==="poll"){ai(t,{returncode:r.finished?.result?.exitCode??null});return}if(t.action==="write"){if(!r.stdin)throw new Error("Browser subprocess stdin is not a pipe.");const s=D2(t.stdinBase64??"");if(s.byteLength>BT)throw new Error("Python subprocess stdin exceeds 16 MiB.");r.stdin.write(s),ai(t,{written:s.byteLength});return}if(t.action==="read"){const s=t.stream==="stdout"?r.stdout:t.stream==="stderr"?r.stderr:void 0;if(!s)throw new Error("Browser subprocess output is not a pipe.");const i=t.maximum??64*1024;if(!Number.isSafeInteger(i)||i<=0||i>X0e)throw new Error("Invalid browser subprocess read size.");const a=await s.read(i);ai(t,{dataBase64:HT(a.bytes),eof:a.eof});return}if(t.action==="close"){r.stdin?.close(),ai(t,{});return}if(t.action==="terminate"){r.stdin?.close(),r.controller.abort(new DOMException("Python subprocess terminated.","AbortError")),ai(t,{});return}if(t.action==="release"){if(!r.finished)throw new Error("Cannot release a running browser subprocess.");this.children.delete(t.childId),ai(t,{});return}t.stdinBase64&&r.stdin?.write(D2(t.stdinBase64)),t.closeStdin&&r.stdin?.close();const n=await r.completion;ai(t,{...n,patch:await this.childChanges()})}catch(r){ai(t,{error:y1(r)})}}requiredBackend(){if(!this.backend)throw new Error("No browser child-process backend is configured.");return this.backend}}class Q0e{chunks=[];readers=[];closed=!1;[Symbol.asyncIterator](){return this}next(){const t=this.chunks.shift();return t?Promise.resolve({value:t,done:!1}):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise(r=>this.readers.push(r))}write(t){if(this.closed)throw new Error("write to closed browser subprocess stdin");const r=t.slice(),n=this.readers.shift();n?n({value:r,done:!1}):this.chunks.push(r)}close(){if(!this.closed){this.closed=!0;for(const t of this.readers.splice(0))t({value:void 0,done:!0})}}}class zT{chunks=[];readers=[];length=0;closed=!1;write(t){if(!(this.closed||t.byteLength===0)){if(this.length+t.byteLength>Y0e)throw new Error("Python subprocess output pipe exceeded 16 MiB without being drained.");this.chunks.push(t.slice()),this.length+=t.byteLength,this.wake()}}close(){this.closed||(this.closed=!0,this.wake())}async read(t){for(;this.length===0&&!this.closed;)await new Promise(i=>this.readers.push(i));if(this.length===0)return{bytes:new Uint8Array,eof:!0};const r=Math.min(t,this.length),n=new Uint8Array(r);let s=0;for(;s<r;){const i=this.chunks[0],a=Math.min(i.byteLength,r-s);n.set(i.subarray(0,a),s),s+=a,this.length-=a,a===i.byteLength?this.chunks.shift():this.chunks[0]=i.subarray(a)}return{bytes:n,eof:this.closed&&this.length===0}}wake(){for(const t of this.readers.splice(0))t()}}function jT(e){return e===UT||e.startsWith(`${UT}/`)}function WT(e,t,r){if(!e||e.length>Z0e||!t.startsWith("/")||t.length>16384||Object.keys(r).length>256)throw new Error("Invalid Python subprocess request.")}function ai(e,t){const r=new Int32Array(e.control),n=new Uint8Array(e.response);let s=new TextEncoder().encode(JSON.stringify(t));s.byteLength>n.byteLength&&(s=new TextEncoder().encode(JSON.stringify({error:"Python subprocess response exceeds 16 MiB."}))),n.set(s),Atomics.store(r,1,s.byteLength),Atomics.store(r,0,1),Atomics.notify(r,0)}function D2(e){const t=atob(e);return Uint8Array.from(t,r=>r.charCodeAt(0))}function HT(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function*J0e(e){yield e}function y1(e){return e instanceof Error?e.message:String(e)}const L2=32,qT=16*1024*1024,GT=32*1024*1024,IF=100,MF=32*1024,Hx=3e4,eye=1024*1024,DF=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;class tye{filesystem;bridge;processHost;webSocketRegistry;nextWebSocketConnection=1;streamingServers=new Map;constructor(t,r,n,s){this.filesystem=t,this.bridge=r,this.processHost=n,this.webSocketRegistry=s}handleStreamingRequest(t,r,n,s,i,a){return this.streamingServers.get(t)?.(r,n,s,i,a)??Promise.resolve(!1)}attach(t,r){const n=new Set,s=new Map,i=new Map;let a=1;const o=new K0e(this.filesystem,r,this.processHost),l=new Map,c=new Map;let u=!1;const d=b=>{u||t.postMessage(b)},p=(b,v,S,x,E)=>{if(u)return Promise.reject(new Error("Python server process exited."));if(s.size+i.size>=L2)return Promise.resolve(Xu(503,"Service Unavailable",`Python server request concurrency exceeded.
|
|
1879
|
+
`,exitCode:1});const _={type:"run",argv:[...t],cwd:r.cwd??this.options.cwd??"/workspace",env:{...this.options.env,...r.env},filesystem:b,...g?{store:{projectId:g}}:{},stdinBase64:G0e(n),...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a.slice(0)}:{},serverPort:o.port2,...u&&c?{fileLocks:{channel:u.client,owner:c}}:{},...p?{fileCoherence:p.client}:{},sharedMemoryChannels:l};i.postMessage(_,[_.serverPort,..._.runtimeSnapshot?[_.runtimeSnapshot]:[],..._.fileLocks?[_.fileLocks.channel.port]:[],..._.fileCoherence?[_.fileCoherence.port]:[]])})};snapshot;runtimeSnapshot(){const t=this.options.runtimeSnapshotUrl;return t?(this.snapshot??=(async()=>{try{const r=await this.nativeFetch(t,{cache:"no-cache",credentials:"same-origin"});if(!r.ok)return;const n=await r.json();if(n.format!==1||n.pyodide!==eE||n.engine!==P0e("pyodide.asm.wasm").integrity)return;const s=await this.nativeFetch(new URL(M0e,t),{credentials:"same-origin"});if(!s.ok)return;const i=await s.arrayBuffer();return await U0e(new Uint8Array(i))===n.integrity?i:void 0}catch{return}})(),this.snapshot):Promise.resolve(void 0)}createWorker(){return this.options.createWorker?this.options.createWorker():Promise.resolve(bf(new Worker(new URL("/assets/worker-Ce8bBwSJ.js",import.meta.url),{type:"module",name:"browser-python"})))}takeWorker(){const t=this.standby;this.standby=void 0,this.standbyTimer!==void 0&&clearTimeout(this.standbyTimer);const r=t??this.createWorker(),n=this.createWorker().then(async s=>{s.onmessage=o=>{const l=o.data;l.type==="network-request"&&this.handleNetwork(s,l)};const a=(await this.runtimeSnapshot())?.slice(0);return s.postMessage({type:"prepare",...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a}:{}},a?[a]:[]),s});return n.catch(()=>{}),this.standby=n,this.standbyTimer=setTimeout(()=>{this.standby===n&&(this.standby=void 0,n.then(s=>s.terminate(),()=>{}))},W0e),r}async applyResult(t,r){const n=this.filesystemCommitTail.then(async()=>{T1(this.filesystem,r,t),await this.options.onFilesystemCommit?.(this.filesystem)});this.filesystemCommitTail=n.catch(()=>{}),await n}async persistFilesystem(){const t=this.filesystemCommitTail.then(()=>this.options.onFilesystemCommit?.(this.filesystem));this.filesystemCommitTail=t.then(()=>{},()=>{}),await t}async handleNetwork(t,r){try{const n=new URL(r.url);if(n.protocol!=="https:"||n.username||n.password)throw new Error("Browser Python external requests require credential-free HTTPS URLs.");if(r.purpose==="program"){if(!this.options.network)throw new Error("Browser Python egress has no embedding grant.");this.options.network.authorize(n)}else j0e(n,r.method,r.purpose);const s=this.options.network?.maxConnections??16,i=this.options.network?.maxBytes??64*1024*1024;if(this.activeFetches>=s)throw new Error("Browser Python egress connection limit exceeded.");this.consumeNetwork(r.body.byteLength,i),this.activeFetches+=1;let a;try{a=await this.nativeFetch(n,{method:r.method,headers:V0e(r.headers),...r.body.byteLength>0?{body:r.body}:{},credentials:"omit",redirect:"error"})}finally{this.activeFetches-=1}const o=Number(a.headers.get("content-length"));if(Number.isFinite(o)&&o>=0&&o>i-this.networkBytes)throw new Error("Browser Python egress byte limit exceeded.");const l=await a.arrayBuffer();this.consumeNetwork(l.byteLength,i),t.postMessage({type:"network-response",requestId:r.requestId,status:a.status,statusText:a.statusText,headers:[...a.headers.entries()],body:l},[l])}catch(n){console.warn(`Browser Python request to ${r.url} failed: ${n instanceof Error?n.message:String(n)}`),t.postMessage({type:"network-error",requestId:r.requestId,error:n instanceof Error?n.message:String(n)})}}consumeNetwork(t,r){if(!Number.isSafeInteger(t)||t<0||this.networkBytes>r-t)throw new Error("Browser Python egress byte limit exceeded.");this.networkBytes+=t}}async function q0e(e){const t=[];let r=0;if(e.stdin){const i=new TextEncoder().encode(e.stdin);t.push(i),r+=i.byteLength}if(e.stdinStream)for await(const i of e.stdinStream){const a=i.slice();if(r+=a.byteLength,r>16*1024*1024)throw new Error("Python stdin exceeds 16 MiB.");t.push(a)}const n=new Uint8Array(r);let s=0;for(const i of t)n.set(i,s),s+=i.byteLength;return n}function G0e(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function V0e(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}const FT=8,Z0e=64*1024,BT=16*1024*1024,Y0e=16*1024*1024,X0e=1024*1024;class K0e{filesystem;sync;backend;controllers=new Map;children=new Map;nextChildId=1;active=0;closed=!1;changeQueue=Promise.resolve();constructor(t,r,n){this.filesystem=t,this.sync=r,this.backend=n}handles(t){return t.type==="process-run"||t.type==="process-cancel"||t.type==="process-start"||t.type==="process-action"}handle(t){t.type==="process-cancel"?this.controllers.get(t.requestId)?.abort(new DOMException("Python subprocess cancelled.","AbortError")):t.type==="process-run"?this.run(t):t.type==="process-start"?this.start(t):this.act(t)}close(){if(!this.closed){this.closed=!0;for(const t of this.controllers.values())t.abort(new DOMException("Python server process exited.","AbortError"));this.controllers.clear();for(const t of this.children.values())t.stdin?.close(),t.controller.abort(new DOMException("Python server process exited.","AbortError"));this.children.clear()}}run(t){if(this.active>=FT){ai(t,{error:"Python subprocess concurrency exceeded."});return}this.active+=1;const r=new AbortController;this.controllers.set(t.requestId,r),this.runOnce(t,r.signal).finally(()=>{this.active-=1,this.controllers.delete(t.requestId)})}async runOnce(t,r){try{const n=this.requiredBackend();WT(t.command,t.cwd,t.env);const s=D2(t.stdinBase64);if(s.byteLength>BT)throw new Error("Python subprocess stdin exceeds 16 MiB.");const i=await n.run(t.command,{cwd:t.cwd,env:t.env,signal:r,...s.byteLength>0?{stdinStream:J0e(s)}:{}});ai(t,{result:i,patch:await this.childChanges()})}catch(n){ai(t,{error:y1(n)})}}childChanges(){const t=this.changeQueue.then(async()=>{const r=this.sync.base(),n=N1(r,this.filesystem.toSnapshot()),s=[];for(const a of n.files){if(!jT(a.path))continue;if(a.type!=="file"||a.content!==void 0){s.push(a);continue}const{size:o,...l}=a;s.push({...l,content:HT(await this.filesystem.readFile(a.path))})}const i={files:s,removed:n.removed.filter(jT)};return this.sync.advance(i),i});return this.changeQueue=t.catch(()=>{}),t}start(t){try{const r=this.requiredBackend();if(this.closed)throw new Error("Python child-process host is closed.");if(this.active>=FT)throw new Error("Python subprocess concurrency exceeded.");WT(t.command,t.cwd,t.env);const n=this.nextChildId++,s=new AbortController,i=t.stdinPipe?new Q0e:void 0,a=t.stdoutPipe?new zT:void 0,o=t.stderrPipe&&!t.stderrToStdout?new zT:void 0,l={controller:s,stdin:i,stdout:a,stderr:o};let c=!1,u=!1;const d=(p,m)=>{if(p)try{p.write(new TextEncoder().encode(m))}catch(g){throw s.abort(g),g}};this.active+=1,l.completion=r.run(t.command,{cwd:t.cwd,env:t.env,signal:s.signal,...i?{stdinStream:i}:{},...a||t.stderrToStdout?{onStdout:p=>{c=!0,d(a,p)}}:{},...o||t.stderrToStdout?{onStderr:p=>{u=!0,d(t.stderrToStdout?a:o,p)}}:{}}).then(p=>(a&&p.stdout&&!c&&d(a,p.stdout),t.stderrToStdout&&p.stderr&&!u?d(a,p.stderr):o&&p.stderr&&!u&&d(o,p.stderr),{result:p}),p=>({error:y1(p)})).then(p=>(l.finished=p,a?.close(),o?.close(),this.active-=1,p)),this.children.set(n,l),ai(t,{childId:n})}catch(r){ai(t,{error:y1(r)})}}async act(t){try{const r=this.children.get(t.childId);if(!r)throw new Error("Unknown browser subprocess.");if(t.action==="poll"){ai(t,{returncode:r.finished?.result?.exitCode??null});return}if(t.action==="write"){if(!r.stdin)throw new Error("Browser subprocess stdin is not a pipe.");const s=D2(t.stdinBase64??"");if(s.byteLength>BT)throw new Error("Python subprocess stdin exceeds 16 MiB.");r.stdin.write(s),ai(t,{written:s.byteLength});return}if(t.action==="read"){const s=t.stream==="stdout"?r.stdout:t.stream==="stderr"?r.stderr:void 0;if(!s)throw new Error("Browser subprocess output is not a pipe.");const i=t.maximum??64*1024;if(!Number.isSafeInteger(i)||i<=0||i>X0e)throw new Error("Invalid browser subprocess read size.");const a=await s.read(i);ai(t,{dataBase64:HT(a.bytes),eof:a.eof});return}if(t.action==="close"){r.stdin?.close(),ai(t,{});return}if(t.action==="terminate"){r.stdin?.close(),r.controller.abort(new DOMException("Python subprocess terminated.","AbortError")),ai(t,{});return}if(t.action==="release"){if(!r.finished)throw new Error("Cannot release a running browser subprocess.");this.children.delete(t.childId),ai(t,{});return}t.stdinBase64&&r.stdin?.write(D2(t.stdinBase64)),t.closeStdin&&r.stdin?.close();const n=await r.completion;ai(t,{...n,patch:await this.childChanges()})}catch(r){ai(t,{error:y1(r)})}}requiredBackend(){if(!this.backend)throw new Error("No browser child-process backend is configured.");return this.backend}}class Q0e{chunks=[];readers=[];closed=!1;[Symbol.asyncIterator](){return this}next(){const t=this.chunks.shift();return t?Promise.resolve({value:t,done:!1}):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise(r=>this.readers.push(r))}write(t){if(this.closed)throw new Error("write to closed browser subprocess stdin");const r=t.slice(),n=this.readers.shift();n?n({value:r,done:!1}):this.chunks.push(r)}close(){if(!this.closed){this.closed=!0;for(const t of this.readers.splice(0))t({value:void 0,done:!0})}}}class zT{chunks=[];readers=[];length=0;closed=!1;write(t){if(!(this.closed||t.byteLength===0)){if(this.length+t.byteLength>Y0e)throw new Error("Python subprocess output pipe exceeded 16 MiB without being drained.");this.chunks.push(t.slice()),this.length+=t.byteLength,this.wake()}}close(){this.closed||(this.closed=!0,this.wake())}async read(t){for(;this.length===0&&!this.closed;)await new Promise(i=>this.readers.push(i));if(this.length===0)return{bytes:new Uint8Array,eof:!0};const r=Math.min(t,this.length),n=new Uint8Array(r);let s=0;for(;s<r;){const i=this.chunks[0],a=Math.min(i.byteLength,r-s);n.set(i.subarray(0,a),s),s+=a,this.length-=a,a===i.byteLength?this.chunks.shift():this.chunks[0]=i.subarray(a)}return{bytes:n,eof:this.closed&&this.length===0}}wake(){for(const t of this.readers.splice(0))t()}}function jT(e){return e===UT||e.startsWith(`${UT}/`)}function WT(e,t,r){if(!e||e.length>Z0e||!t.startsWith("/")||t.length>16384||Object.keys(r).length>256)throw new Error("Invalid Python subprocess request.")}function ai(e,t){const r=new Int32Array(e.control),n=new Uint8Array(e.response);let s=new TextEncoder().encode(JSON.stringify(t));s.byteLength>n.byteLength&&(s=new TextEncoder().encode(JSON.stringify({error:"Python subprocess response exceeds 16 MiB."}))),n.set(s),Atomics.store(r,1,s.byteLength),Atomics.store(r,0,1),Atomics.notify(r,0)}function D2(e){const t=atob(e);return Uint8Array.from(t,r=>r.charCodeAt(0))}function HT(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function*J0e(e){yield e}function y1(e){return e instanceof Error?e.message:String(e)}const L2=32,qT=16*1024*1024,GT=32*1024*1024,IF=100,MF=32*1024,Hx=3e4,eye=1024*1024,DF=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;class tye{filesystem;bridge;processHost;webSocketRegistry;nextWebSocketConnection=1;streamingServers=new Map;constructor(t,r,n,s){this.filesystem=t,this.bridge=r,this.processHost=n,this.webSocketRegistry=s}handleStreamingRequest(t,r,n,s,i,a){return this.streamingServers.get(t)?.(r,n,s,i,a)??Promise.resolve(!1)}attach(t,r){const n=new Set,s=new Map,i=new Map;let a=1;const o=new K0e(this.filesystem,r,this.processHost),l=new Map,c=new Map;let u=!1;const d=b=>{u||t.postMessage(b)},p=(b,v,S,x,E)=>{if(u)return Promise.reject(new Error("Python server process exited."));if(s.size+i.size>=L2)return Promise.resolve(Xu(503,"Service Unavailable",`Python server request concurrency exceeded.
|
|
1880
1880
|
`));const A=ZT(E);if(A.byteLength>qT)return Promise.resolve(Xu(413,"Payload Too Large",`Request body exceeds 16 MiB.
|
|
1881
1881
|
`));XT(x);const T=a++;return new Promise((D,I)=>{const U=window.setTimeout(()=>{s.delete(T),I(new Error("Python server request timed out."))},Hx);s.set(T,{resolve:D,reject:I,timeout:U}),d({type:"http-request",requestId:T,application:b,method:v,url:S,headers:x,bodyBase64:QT(A)})})},m=(b,v,S,x,E)=>{if(u)return Promise.reject(new Error("Python server process exited."));if(s.size+i.size>=L2)return Promise.reject(new Error("Python server request concurrency exceeded."));const A=ZT(x);if(A.byteLength>qT)return Promise.reject(new Error("Request body exceeds 16 MiB."));XT(S);const T=a++;return new Promise((D,I)=>{const U=window.setTimeout(()=>{const O=i.get(T);O&&(i.delete(T),O.started?(O.callbacks.end(),O.resolve(!0)):O.reject(new Error("Python streaming response timed out.")))},Hx);i.set(T,{callbacks:E,resolve:D,reject:I,timeout:U,bytes:0,started:!1}),d({type:"http-request",requestId:T,application:"asgi",method:b,url:v,headers:S,bodyBase64:QT(A),streaming:!0})})},g=(b,v,S)=>{if(u)throw new Error("Python server process exited.");if(l.size>=L2)throw new Error("Python WebSocket concurrency exceeded.");const x=this.nextWebSocketConnection++;return l.set(x,{handlers:S,protocols:v}),d({type:"websocket-open",connectionId:x,path:b,protocols:[...v]}),{send:E=>{if(!l.has(x))throw new Error("Python WebSocket is closed.");YT(E),d({type:"websocket-message",connectionId:x,data:E.kind==="text"?E:{kind:"binary",base64:v$(E)}})},close:(E=1e3,A="")=>{l.has(x)&&d({type:"websocket-close",connectionId:x,code:E,reason:A})},abort:()=>{l.delete(x)&&d({type:"websocket-close",connectionId:x,code:1006,reason:""})}}};return t.onmessage=b=>{const v=b.data;if(v.type==="websocket-opened"){const x=l.get(v.connectionId);if(!x)return;v.protocol&&!x.protocols.includes(v.protocol)?(x.handlers.error("Python ASGI app selected an unrequested WebSocket protocol."),x.handlers.close(1002,"Invalid subprotocol",!1),l.delete(v.connectionId)):x.handlers.open(v.protocol);return}if(v.type==="websocket-message"){const x=l.get(v.connectionId);if(!x)return;try{YT(v.data),x.handlers.message(v.data)}catch(E){x.handlers.error(E instanceof Error?E.message:String(E)),x.handlers.close(1009,"Frame too large",!1),l.delete(v.connectionId)}return}if(v.type==="websocket-close"){const x=l.get(v.connectionId);if(!x)return;l.delete(v.connectionId);try{rye(v.code,v.reason),x.handlers.close(v.code,v.reason,v.clean)}catch(E){x.handlers.error(E instanceof Error?E.message:String(E)),x.handlers.close(1002,"Invalid close frame",!1)}return}if(v.type==="websocket-error"){const x=l.get(v.connectionId);if(!x)return;x.handlers.error(v.error);return}if(o.handles(v)){o.handle(v);return}if(v.type==="http-stream-start"){const x=i.get(v.requestId);if(!x)return;try{KT(v.statusCode,v.statusMessage,v.headers),x.callbacks.start(v.statusCode,v.statusMessage,v.headers),x.started=!0,VT(x,v.requestId,i)}catch(E){P2(v.requestId,x,i,E)}return}if(v.type==="http-stream-chunk"){const x=i.get(v.requestId);if(!x)return;try{if(!x.started)throw new Error("Python stream emitted a body before response start.");const E=JT(v.bodyBase64);if(x.bytes+=E.byteLength,x.bytes>GT)throw new Error("Python server response exceeds 32 MiB.");x.callbacks.chunk(E),VT(x,v.requestId,i)}catch(E){P2(v.requestId,x,i,E)}return}if(v.type==="http-stream-end"){const x=i.get(v.requestId);if(!x)return;i.delete(v.requestId),clearTimeout(x.timeout),x.started?(x.callbacks.end(),x.resolve(!0)):x.reject(new Error("Python stream ended before response start."));return}if(v.type==="http-stream-error"){const x=i.get(v.requestId);if(!x)return;P2(v.requestId,x,i,new Error(v.error));return}if(v.type==="http-response"){const x=s.get(v.requestId);if(!x)return;s.delete(v.requestId),clearTimeout(x.timeout);try{if(v.error)throw new Error(v.error);const E=JT(v.bodyBase64);if(E.byteLength>GT)throw new Error("Python server response exceeds 32 MiB.");KT(v.statusCode,v.statusMessage,v.headers),x.resolve({statusCode:v.statusCode,statusMessage:v.statusMessage,headers:v.headers,body:E})}catch(E){x.reject(E)}return}let S=0;if(!aye(v.port)||this.bridge.getServerPorts().includes(v.port))S=-98;else try{const x=v.server==="static"?(A,T)=>Promise.resolve(this.handleStatic(LF(v.root),A,T)):(A,T,D,I)=>p(v.server,A,T,D,I),E={listening:!0,address:()=>({port:v.port,address:"0.0.0.0",family:"IPv4"}),handleRequest:x};this.bridge.registerServer(E,v.port),n.add(v.port),v.server==="asgi"&&(this.streamingServers.set(v.port,m),this.webSocketRegistry&&c.set(v.port,this.webSocketRegistry.register(v.port,{open:(A,T,D)=>g(A,T,D)})))}catch{c.get(v.port)?.(),c.delete(v.port),this.streamingServers.delete(v.port),this.bridge.unregisterServer(v.port),S=-98}d({type:"ack",requestId:v.requestId,result:S})},t.start(),()=>{if(!u){u=!0;for(const b of n)this.bridge.unregisterServer(b);for(const b of n)this.streamingServers.delete(b);for(const b of c.values())b();c.clear(),n.clear();for(const b of s.values())clearTimeout(b.timeout),b.reject(new Error("Python server process exited."));s.clear();for(const b of i.values())clearTimeout(b.timeout),b.started?(b.callbacks.end(),b.resolve(!0)):b.reject(new Error("Python server process exited."));i.clear();for(const b of l.values())b.handlers.error("Python server process exited."),b.handlers.close(1011,"Python server process exited",!1);l.clear(),o.close(),t.close()}}}async handleStatic(t,r,n){if(r!=="GET"&&r!=="HEAD")return Xu(405,"Method Not Allowed",`Method not allowed
|
|
1882
1882
|
`);let s;try{s=nye(t,n)}catch{return Xu(400,"Bad Request",`Bad request
|
|
@@ -1885,8 +1885,8 @@ connection: close\r
|
|
|
1885
1885
|
`);const i=r==="HEAD"?new Uint8Array:await this.filesystem.readFile(s);return{statusCode:200,statusMessage:"OK",headers:{"content-type":iye(s),"content-length":String(this.filesystem.statSync(s).size),"cache-control":"no-store"},body:i}}}function VT(e,t,r){clearTimeout(e.timeout),e.timeout=window.setTimeout(()=>{r.has(t)&&(r.delete(t),e.started?(e.callbacks.end(),e.resolve(!0)):e.reject(new Error("Python streaming response timed out.")))},Hx)}function P2(e,t,r,n){r.delete(e),clearTimeout(t.timeout),t.started?(t.callbacks.end(),t.resolve(!0)):t.reject(n)}function ZT(e){if(e==null)return new Uint8Array;if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return Uint8Array.from(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));throw new Error("Unsupported Python request body.")}function YT(e){if((e.kind==="text"?new TextEncoder().encode(e.text).byteLength:op(e).byteLength)>eye)throw new Error("Python WebSocket frame exceeds 1 MiB.")}function rye(e,t){if(!Number.isInteger(e)||e<1e3||e>4999||[1004,1005,1006,1015].includes(e))throw new Error("Invalid Python WebSocket close code.");if(new TextEncoder().encode(t).byteLength>123)throw new Error("Python WebSocket close reason is too large.")}function XT(e){const t=Object.entries(e);if(t.length>IF)throw new Error("Python request has too many headers.");let r=0;for(const[n,s]of t){if(!DF.test(n)||/[\u0000\r\n]/u.test(s))throw new Error("Malformed Python request header.");r+=n.length+s.length}if(r>MF)throw new Error("Python request headers are too large.")}function KT(e,t,r){if(!Number.isInteger(e)||e<100||e>599||/[\u0000\r\n]/u.test(t))throw new Error("Malformed Python response status.");const n=Object.entries(r);if(n.length>IF)throw new Error("Python response has too many headers.");let s=0;for(const[i,a]of n){const o=Array.isArray(a)?a:[a];if(!DF.test(i)||o.some(l=>/[\u0000\r\n]/u.test(l)))throw new Error("Malformed Python response header.");s+=i.length+o.reduce((l,c)=>l+c.length,0)}if(s>MF)throw new Error("Python response headers are too large.")}function nye(e,t){const r=decodeURIComponent(new URL(t,"http://localhost").pathname);if(r.includes("\0"))throw new Error("Invalid path");const n=LF(`${e}/${r}`);if(n!==e&&!n.startsWith(`${e}/`))throw new Error("Path escapes root");return n}function LF(e){const t=[];for(const r of e.replaceAll("\\","/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function sye(e,t,r){const n=`<!doctype html><title>Directory listing for ${U2(e)}</title><h1>Directory listing for ${U2(e)}</h1><ul>${t.sort().map(i=>`<li><a href="${encodeURIComponent(i)}">${U2(i)}</a></li>`).join("")}</ul>`,s=new TextEncoder().encode(n);return{statusCode:200,statusMessage:"OK",headers:{"content-type":"text/html; charset=utf-8","content-length":String(s.byteLength),"cache-control":"no-store"},body:r?new Uint8Array:s}}function Xu(e,t,r){const n=new TextEncoder().encode(r);return{statusCode:e,statusMessage:t,headers:{"content-type":"text/plain; charset=utf-8","content-length":String(n.byteLength),"cache-control":"no-store"},body:n}}function iye(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".css":"text/css; charset=utf-8",".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain; charset=utf-8",".wasm":"application/wasm"}[t]??"application/octet-stream"}function U2(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function aye(e){return Number.isSafeInteger(e)&&e>0&&e<=65535}function QT(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function JT(e){const t=atob(e);return Uint8Array.from(t,r=>r.charCodeAt(0))}function zg(e){const t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function yc(e){return e==="/"?"":e}async function oye(e,t){try{return await lye(e,t)}catch{return}}async function lye(e,t){if(t.some(m=>m.path!=="/"&&(m.mode===void 0||m.mtimeMs===void 0)))return;const r=t.filter(m=>m.type==="file"&&m.content===void 0);if(r.length===0)return;const n=[],s=[],i=[];let a=0;for(const m of r){if(!e.existsSync(m.path)){s.push(m.path);continue}const g=await e.readFile(m.path);n.push(m),i.push(g),a+=g.byteLength}const o=new SharedArrayBuffer(a),l=new Uint8Array(o),c=new Map,u=new Map,d=m=>{for(let g=m;g!=="/";g=zg(g)){const b=zg(g),v=yc(b),S=u.get(v)??new Set,x=g.slice(v.length+1);if(S.has(x))return;S.add(x),u.set(v,S)}};let p=0;n.forEach((m,g)=>{const b=i[g];l.set(b,p),c.set(m.path,{type:"file",mode:m.mode,mtimeMs:m.mtimeMs,offset:p,length:b.byteLength}),d(m.path),p+=b.byteLength});for(const m of t)m.type!=="directory"||m.path==="/"||(c.set(m.path,{type:"directory",mode:m.mode,mtimeMs:m.mtimeMs,offset:0,length:0}),d(m.path));return{index:_j(c,u),bytes:o,...s.length>0?{vanished:s}:{}}}function PF(e,t){const r=new h$(e.index),n=new Ij(r),s=new p$(r),i={childrenOf:o=>[...s.get(yc(o))??[]].sort(),descendants(o){const l=[],c=u=>{const d=n.get(u);d&&l.push([u,d]);for(const p of s.get(yc(u))??[])c(`${yc(u)}/${p}`)};return c(o),l}};if(e.store!==void 0){const o=e.roots?.[0]??"/",l=e.storeRoot??o,c=d=>l+d.slice(o==="/"?0:o.length),u=d=>{const p=n.get(d);throw!p||p.type==="directory"?new Error(`The shared layer holds no file at ${d}.`):new Error(`${d} is in the store ${e.store}, which this realm did not open.`)};return{entries:n,read:d=>u(d).read(c(d)),readRange:(d,p,m)=>u(d).readRange(c(d),p,m),readsByRange:()=>!0,...i}}if(!e.bytes)throw new Error("A shared layer holds neither its bytes nor a store of them.");const a=new Uint8Array(e.bytes);return{entries:n,read(o){const l=n.get(o);if(!l||l.type==="directory")throw new Error(`The shared layer holds no file at ${o}.`);return a.slice(l.offset,l.offset+l.length)},view(o){const l=n.get(o);if(!l||l.type==="directory")throw new Error(`The shared layer holds no file at ${o}.`);return a.subarray(l.offset,l.offset+l.length)},readRange(o,l,c){const u=n.get(o);if(!u||u.type==="directory")throw new Error(`The shared layer holds no file at ${o}.`);const d=Math.min(Math.max(0,l),u.length);return a.slice(u.offset+d,u.offset+Math.min(u.length,d+Math.max(0,c)))},childrenOf:o=>[...s.get(yc(o))??[]].sort(),descendants(o){const l=[],c=u=>{const d=n.get(u);d&&l.push([u,d]);for(const p of s.get(yc(u))??[])c(`${yc(u)}/${p}`)};return c(o),l}}}function cye(e){const t=[];for(const[r,n]of PF(e).entries)t.push(n.type==="directory"?{path:r,type:"directory",mode:n.mode,mtimeMs:n.mtimeMs}:{path:r,type:"file",size:n.length,mode:n.mode,mtimeMs:n.mtimeMs});return t}function uye(e){if(e.length===1)return e[0];const t=(a,o)=>{if(a===0)return!1;for(let l=zg(o);;l=zg(l)){for(let c=0;c<a;c+=1){const u=e[c].entries.get(l);if(u&&u.type!=="directory")return!0}if(l==="/")return!1}},r=a=>{for(let o=0;o<e.length;o+=1)if(e[o].entries.has(a)&&!t(o,a))return o;return-1},n=a=>e[r(a)],s={get:a=>n(a)?.entries.get(a),has:a=>r(a)>=0,get size(){let a=0;for(const o of s)a+=1;return a},*[Symbol.iterator](){const a=new Set;for(let o=0;o<e.length;o+=1)for(const[l,c]of e[o].entries)a.has(l)||r(l)!==o||(a.add(l),yield[l,c])},*entries(){yield*s[Symbol.iterator]()},*keys(){for(const[a]of s)yield a},*values(){for(const[,a]of s)yield a},forEach(a){for(const[o,l]of s)a(l,o,s)}},i=a=>{const o=n(a)?.entries.get(a);return o&&o.type!=="directory"?[]:e.filter((l,c)=>{const u=l.entries.get(a);return(!u||u.type==="directory")&&!t(c,a)})};return{entries:s,read:a=>{const o=n(a);if(!o)throw new Error(`No lower tree holds ${a}.`);return o.read(a)},view:a=>{const o=n(a);if(!o)throw new Error(`No lower tree holds ${a}.`);return o.view?o.view(a):o.read(a)},readRange:(a,o,l)=>{const c=n(a);if(!c)throw new Error(`No lower tree holds ${a}.`);if(c.readRange)return c.readRange(a,o,l);const u=c.read(a),d=Math.min(Math.max(0,o),u.byteLength);return u.slice(d,Math.min(u.byteLength,d+Math.max(0,l)))},readsByRange:a=>n(a)?.readsByRange?.(a)??!1,childrenOf:a=>[...new Set(i(a).flatMap(o=>o.childrenOf(a)))].sort(),descendants:a=>{const o=[],l=new Set;for(const u of e)for(const[d]of u.descendants(a)){if(l.has(d))continue;l.add(d);const p=s.get(d);p&&o.push([d,p])}const c=o.findIndex(([u])=>u===a);return c>0&&o.unshift(...o.splice(c,1)),o}}}function fye(e,t,r){const n=[...(t??[]).map(s=>PF(s))];return n.length===0?void 0:uye(n)}function dye(e,t){if(t.length===0)return e;const r=n=>t.some(s=>s==="/"||n===s||n.startsWith(`${s}/`));return{...e,files:e.files.filter(n=>!r(n.path)),removed:e.removed.filter(n=>!r(n))}}const F2=0,b1=1,hye=2,eN=3,pye=4,mye=5,w1=6,gye=256*1024;class yye{buffer;control;bytes;constructor(t=gye,r){if(!Number.isSafeInteger(t)||t<2)throw new Error("WALI stdin capacity must be at least two bytes.");if(this.buffer=r??new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*w1+t),this.buffer.byteLength!==Int32Array.BYTES_PER_ELEMENT*w1+t)throw new Error("WALI stdin shared buffer has an invalid size.");this.control=new Int32Array(this.buffer,0,w1),this.bytes=new Uint8Array(this.buffer,Int32Array.BYTES_PER_ELEMENT*w1)}write(t){const r=typeof t=="string"?new TextEncoder().encode(t):t;if(r.byteLength===0)return!0;const n=Atomics.load(this.control,F2),s=Atomics.load(this.control,b1);if(r.byteLength>rN(n,s,this.bytes.byteLength))return!1;for(let i=0;i<r.byteLength;i+=1)this.bytes[(s+i)%this.bytes.byteLength]=r[i];return Atomics.store(this.control,b1,(s+r.byteLength)%this.bytes.byteLength),this.wake(),!0}free(){return rN(Atomics.load(this.control,F2),Atomics.load(this.control,b1),this.bytes.byteLength)}resize(t,r){Atomics.store(this.control,mye,tN(t)),Atomics.store(this.control,pye,tN(r)),this.wake()}close(){Atomics.store(this.control,hye,1),this.wake()}get availableBytes(){return UF(Atomics.load(this.control,F2),Atomics.load(this.control,b1),this.bytes.byteLength)}wake(){Atomics.add(this.control,eN,1),Atomics.notify(this.control,eN)}}function tN(e){return Number.isFinite(e)?Math.min(65535,Math.max(1,Math.floor(e))):0}function UF(e,t,r){return t>=e?t-e:r-e+t}function rN(e,t,r){return r-UF(e,t,r)-1}const nN=24,FF=12,BF=4,jg=e=>1n<<BigInt(e-1);jg(9)|jg(19);const bye=new Set([17,18,19,20,21,22,23,28]),wye=e=>!bye.has(e);function vye(){return new SharedArrayBuffer((BF+64*FF)*4)}class xye{buffer;words;constructor(t){this.buffer=t,this.words=new Int32Array(t)}offset(t){return BF+(t-1)*FF}locked(t){for(;Atomics.compareExchange(this.words,0,0,1)!==0;)Atomics.wait(this.words,0,1);try{return t()}finally{Atomics.store(this.words,0,0),Atomics.notify(this.words,0)}}changed(){Atomics.add(this.words,1,1),Atomics.notify(this.words,1)}action(t,r){return this.locked(()=>{const n=this.offset(t),s=new Uint8Array(this.buffer,(n+1)*4,nN),i=Uint8Array.from(s);return r&&(s.set(r),new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,!0)<=1&&Atomics.exchange(this.words,n,0)!==0&&Atomics.sub(this.words,2,1),this.changed()),i})}raise(t,r=0,n=0){return this.locked(()=>{const s=this.offset(t),i=Atomics.load(this.words,s+1)>>>0;return i<=1?i===1?"ignored":"default":(Atomics.load(this.words,s)!==0||(Atomics.store(this.words,s+7,r),Atomics.store(this.words,s+8,n),Atomics.store(this.words,s,1),Atomics.add(this.words,2,1),this.changed()),"handled")})}anyPending(){return Atomics.load(this.words,2)!==0}pending(){if(Atomics.load(this.words,2)===0)return 0n;let t=0n;for(let r=1;r<=64;r++)Atomics.load(this.words,this.offset(r))&&(t|=jg(r));return t}take(t){if((this.pending()&~t)!==0n)return this.locked(()=>{for(let r=1;r<=64;r++){const n=this.offset(r);if((t&jg(r))!==0n||Atomics.load(this.words,n)===0)continue;Atomics.store(this.words,n,0),Atomics.sub(this.words,2,1);const s=Uint8Array.from(new Uint8Array(this.buffer,(n+1)*4,nN));return(new DataView(s.buffer).getBigUint64(4,!0)&0x80000000n)!==0n&&Atomics.store(this.words,n+1,0),{signal:r,action:s,pid:Atomics.load(this.words,n+7),status:Atomics.load(this.words,n+8)}}})}}const sN=0,iN=1,Fc=2,zF=3,jF=4,WF=5,HF=6;function Sye(e){const t=tE(e),r=e.role==="reader"?zF:jF;Atomics.sub(t,r,1)<=1&&Atomics.store(t,r,0),Atomics.add(t,e.role==="reader"?HF:WF,1),Atomics.notify(t,Fc)}function Eye(e,t){if(e.role!=="reader")return-9n;const r=tE(e),n=qF(e),s=Atomics.load(r,Fc);if(s===0)return Atomics.load(r,jF)===0?new Uint8Array:-11n;const i=Math.min(Math.max(0,t),s),a=Atomics.load(r,sN),o=Math.min(i,n.byteLength-a),l=new Uint8Array(i);return l.set(n.subarray(a,a+o)),o<i&&l.set(n.subarray(0,i-o),o),Atomics.store(r,sN,(a+i)%n.byteLength),Atomics.sub(r,Fc,i),i>0&&Atomics.add(r,HF,1),Atomics.notify(r,Fc),l}async function B2(e,t){if(e.role!=="writer")throw new Error("Cannot write through a shared-pipe reader.");const r=tE(e),n=qF(e);let s=0;for(;s<t.byteLength;){if(Atomics.load(r,zF)===0)return;const i=Atomics.load(r,Fc),a=n.byteLength-i;if(a===0){await new Promise(c=>setTimeout(c,1));continue}const o=Atomics.load(r,iN),l=Math.min(t.byteLength-s,a,n.byteLength-o);n.set(t.subarray(s,s+l),o),Atomics.store(r,iN,(o+l)%n.byteLength),Atomics.add(r,Fc,l),Atomics.add(r,WF,1),Atomics.notify(r,Fc),s+=l}}const aN=new WeakMap;function tE(e){const t=e.controlOffset??0;let r=aN.get(e.control);r||(r=new Map,aN.set(e.control,r));let n=r.get(t);return n||(n=new Int32Array(e.control,t,8),r.set(t,n)),n}function qF(e){const t=e.payloadOffset??0,r=e.payloadLength??e.payload.byteLength-t;return new Uint8Array(e.payload,t,r)}function oN(e,t,r){const n=new TextEncoder().encode(JSON.stringify(t));if(n.byteLength>e.response.byteLength)throw new Error(`Browser child filesystem patch is ${n.byteLength} bytes; limit is ${e.response.byteLength}.`);new Uint8Array(e.response).set(n);const s=new Int32Array(e.control);Atomics.store(s,1,r|0),Atomics.store(s,2,n.byteLength),Atomics.store(s,0,1),Atomics.notify(s,0)}const lN=new WeakMap;let cN,uN;function kye(e,t){if(!Number.isSafeInteger(t)||t<0||t>=65536)return 0;let r=e===cN?uN:lN.get(e);r||(r={table:new Int32Array(e.table),descriptions:new Int32Array(e.descriptions)},lN.set(e,r)),cN=e,uN=r;const n=Atomics.load(r.table,t);return Atomics.load(r.descriptions,n*3)}function Aye(e,t){return kye(e,t)!==0}const fN=new Map,z2=(e,t)=>t?`${e}
|
|
1886
1886
|
${t}`:void 0;async function Cye(e,t){if(!t){await e;return}if(t.aborted)return;let r=()=>{};const n=new Promise(s=>{r=()=>s()});t.addEventListener("abort",r,{once:!0});try{await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}const Tye=new Map;class Nye{filesystem;program;capabilities=Object.freeze({filesystemPolicy:!0});worker;pending;stdin;terminalSize={columns:80,rows:24};nextId=1;forkWorkers=new Map;childControllers=new Map;openUrlHandler;urlScanTail="";openedUrls=new Set;processPorts=[];threadOutputPorts=[];filesystemUpdatePort;traceId=crypto.randomUUID();preparing=!1;applyingFilesystem=!1;constructor(t,r){this.filesystem=t,this.program=r}hostRoots=[];withoutHostTrees(t){return dye(t,this.hostRoots)}async run(t,r={}){if(r.filesystemPolicy!==void 0&&(r={...r,filesystemPolicy:es(r.filesystemPolicy)}),this.pending||this.preparing)throw new Error("The browser WALI program is already running.");if(r.signal?.aborted)throw r.signal.reason;this.worker??=this.createWorker(),this.preparing=!0,console.log("[wali-boot]",JSON.stringify({stage:"prepare",run:this.traceId,argv:t,at:Date.now()}));try{const n=S$(this.filesystem);n&&await this.filesystem.flush?.(),console.log("[wali-boot]",JSON.stringify({stage:"flushed",run:this.traceId,at:Date.now()}));const s=this.unreadRoots();let i=await S1(this.filesystem,"/",n?{metadataRoots:[...Mj,...s]}:{metadataRoots:["/"]});const a=n?void 0:await oye(this.filesystem,i.files.filter(D=>!lc(D.path,s)));if(!n&&!a&&(i=await S1(this.filesystem,"/",s.length>0?{metadataRoots:s}:{})),a?.vanished){const D=new Set(a.vanished);i={files:i.files.filter(I=>!D.has(I.path))},delete a.vanished}const o=this.program.layers??[];if(o.length>0){const D=new Set(i.files.map(I=>I.path));i={files:[...i.files,...o.flatMap(cye).filter(I=>!D.has(I.path))]}}const l=[...a?[a]:[],...o];this.hostRoots=[...o.flatMap(D=>D.roots??[]),...this.program.privateRoots??[]].map(D=>D==="/"?D:D.replace(/\/+$/u,"")||"/");const c={files:i.files.filter(D=>D.type==="directory"||!lc(D.path,s))},u=this.program.prepareFilesystem?await this.program.prepareFilesystem(i):i,d=Tye.get(z2(this.program.url,this.program.integrity)??"");if(d&&await Cye(d.catch(()=>{}),r.signal),r.signal?.aborted)throw r.signal.reason;const p=this.nextId++,m=`wali:${crypto.randomUUID()}`,g=X$(),b=Y$.attach(g.server,m),v=G$(),S=this.program.coherenceFilesystem??this.filesystem,x=q$.attach(v.server,S,()=>this.program.onFilesystemCommit?.(this.filesystem),D=>{const I=this.pending;if(!I||I.id!==p)return;const U=iR(S,D);I.filesystemBase.apply(U?{files:[U],removed:[]}:{files:[],removed:[D]})});this.urlScanTail="",this.openedUrls.clear();const E=new yye,A=r.terminal??this.terminalSize;E.resize(A.columns,A.rows),this.stdin=E;const T=vye();return await new Promise((D,I)=>{const U=()=>r.signal?.reason??new DOMException("The WALI process was interrupted.","AbortError"),O=()=>{const z=r.signal?.reason;z&&typeof z=="object"&&(z.handled=!1),this.resetWorker(),this.finishPending(),I(U())},_=z=>z===9?!1:new xye(T).raise(z)!=="default"||!wye(z),$=()=>{const z=r.signal?.reason;if(!_(Rye(z))){O();return}z&&typeof z=="object"&&(z.handled=!0,z.redeliver=te=>{this.pending&&!_(te)&&O()})};r.signal?.addEventListener("abort",$,{once:!0});let F=()=>{};const P=this.program.loopback?new MessageChannel:void 0;P&&(F=this.program.loopback.attach(P.port1));let W;const K=new Promise(z=>{W=z});this.pending={id:p,filesystemBase:new cX(c,l.some(z=>!z.store)?(z=>te=>z.entries.has(te)?z.read(te):void 0)(fye(void 0,l.filter(z=>!z.store))):void 0),filesystemQueue:Promise.resolve(),resolve:D,reject:I,options:r,removeAbortListener:()=>r.signal?.removeEventListener("abort",$),stdout:"",stderr:"",releaseLoopback:F,releaseFileLocks:b,releaseFileCoherence:x,releaseFilesystemChanges:()=>{},changedPaths:new Set,importSequence:0,importingFilesystem:!1,filesystemFinalized:!1,filesystemFinalization:K,resolveFilesystemFinalization:W};const Y={type:"run",...r[Pd]?{pid:r[Pd].pid,parentPid:r[Pd].parentPid,childPidAllocator:r[Pd].childPidAllocator}:{},id:p,...r.descriptorTable?{descriptorTable:r.descriptorTable}:{},url:this.program.url,...this.program.integrity?{integrity:this.program.integrity}:{},...(()=>{const z=z2(this.program.url,this.program.integrity),te=z?fN.get(z):void 0;return te?{compiled:te}:{}})(),...r.executablePath?{executablePath:r.executablePath}:{},argv:[...t],cwd:r.cwd??this.program.cwd??"/",env:{...r.env,...this.program.env},threadPoolSize:this.program.threadPoolSize??18,...this.program.codec?{codec:this.program.codec}:{},...r.filesystemPolicy?{filesystemPolicy:r.filesystemPolicy}:{},...this.program.spawn?.capabilities?.filesystemPolicy===!0?{childFilesystemPolicyVersion:1}:{},...this.program.network.allowedHosts.length>0||P?{network:{...this.program.network.relayUrl?{relayUrl:this.program.network.relayUrl}:{},allowedHosts:[...this.program.network.allowedHosts],maxConnections:this.program.network.maxConnections,maxBytes:this.program.network.maxBytes}}:{},...P?{loopbackPort:P.port2}:{},stdin:E.buffer,terminal:r.terminal!==void 0,filesystem:u,...n?{store:{projectId:n}}:{},...l.length>0?{layers:l}:{},...this.program.privateRoots?.length?{privateRoots:[...this.program.privateRoots]}:{},fileLocks:{channel:g.client,owner:m},fileCoherence:v.client,signalState:T},V=Array.from({length:Y.threadPoolSize},()=>new MessageChannel);this.processPorts=V.map(z=>z.port1);for(const z of this.processPorts)z.onmessage=te=>{const le=this.pending;!le||le.id!==p||(te.data.type==="spawn"?this.spawnChild({...te.data,id:p,type:"spawn"},le):this.childControllers.get(te.data.pid)?.abort(new DOMException(`Signal ${te.data.signal}`,"AbortError")))},z.start();Y.browserProcessPorts=V.map(z=>z.port2);const L=Array.from({length:Y.threadPoolSize},()=>new MessageChannel);this.threadOutputPorts=L.map(z=>z.port1);for(const z of this.threadOutputPorts)z.onmessage=te=>{try{const le=this.pending;if(!le||le.id!==p)return;if(te.data.type==="error"){this.emitStderr(le,`
|
|
1887
1887
|
WALI pthread ${te.data.tid??"unknown"} error: ${te.data.message}
|
|
1888
|
-
`);return}if(te.data.type==="diagnostic"){le.options.onDiagnostic?.(te.data.message);return}te.data.type==="stdout"?this.emitStdout(le,te.data.bytes):this.emitStderr(le,new TextDecoder().decode(te.data.bytes))}finally{if(te.data.type!=="error"&&te.data.type!=="diagnostic"&&te.data.ack){const le=new Int32Array(te.data.ack);Atomics.store(le,0,1),Atomics.notify(le,0)}}},z.start();Y.threadOutputPorts=L.map(z=>z.port2);const G=new MessageChannel;this.filesystemUpdatePort=G.port1,this.filesystemUpdatePort.onmessage=z=>{const te=this.pending;if(te?.id===p){if(z.data.type==="mailbox"){te.mailbox={control:new Int32Array(z.data.buffer,0,2),buffer:z.data.buffer,doorbell:new Int32Array(z.data.doorbell)};return}if(z.data.type==="port-closed"){const le=te.importOnPort;delete te.importOnPort,le&&(le.sequence??0)>z.data.taken&&te.mailbox&&(te.filesystemQueue=te.filesystemQueue.then(()=>this.sendImport(te,le)).catch(ne=>{this.pending===te&&(this.finishPending(),this.resetWorker(),te.reject(ne))}));return}(z.data.type==="imported"||z.data.type==="import-error")&&delete te.importOnPort,te.filesystemQueue=te.filesystemQueue.then(()=>this.applyLiveFilesystemPatch(p,z.data))}},this.filesystemUpdatePort.start();const q=z=>{const te=this.pending;!te||te.id!==p||this.applyingFilesystem||(te.changedPaths.add(z),this.scheduleFilesystemImport(te))};this.filesystem.on("change",q),this.filesystem.on("delete",q),this.pending.releaseFilesystemChanges=()=>{this.filesystem.off("change",q),this.filesystem.off("delete",q)},Y.filesystemUpdatePort=G.port2,console.log("[wali-boot]",JSON.stringify({stage:"dispatch",run:this.traceId,at:Date.now()})),this.worker.postMessage(Y,[...Y.descriptorTable?[Y.descriptorTable.port]:[],...Y.browserProcessPorts,...Y.threadOutputPorts,Y.filesystemUpdatePort,Y.fileLocks.channel.port,Y.fileCoherence.port,...Y.loopbackPort?[Y.loopbackPort]:[]]);const J=_ye(r.descriptorTable);if(!(J!==void 0&&Aye(J,0)))if(r.stdin!==void 0){const z=r.stdin;this.forwardStdin(p,E,(async function*(){yield z})())}else r.stdinStream&&this.forwardStdin(p,E,r.stdinStream)})}finally{this.preparing=!1}}async forwardStdin(t,r,n){const s=new TextEncoder;try{for await(const i of n){const a=typeof i=="string"?s.encode(i):i;let o=0;for(;this.pending?.id===t&&o<a.byteLength;){const l=r.free();if(l>0){const c=Math.min(l,a.byteLength-o);r.write(a.subarray(o,o+c)),o+=c}else await new Promise(c=>setTimeout(c,1))}if(this.pending?.id!==t)return}this.pending?.id===t&&r.close()}catch(i){const a=this.pending;if(!a||a.id!==t)return;this.resetWorker(),this.finishPending(),a.reject(i)}}get running(){return this.pending!==void 0||this.preparing}sendInput(t){return this.stdin?.write(t)??!1}resize(t,r){this.terminalSize={columns:t,rows:r},this.stdin?.resize(t,r)}setOpenUrlHandler(t){this.openUrlHandler=t}terminate(){this.pending?.reject(new DOMException("The WALI program was terminated.","AbortError")),this.finishPending(),this.worker?.terminate()}createWorker(){const t=bf(new Worker(new URL("/assets/worker-program-worker-
|
|
1889
|
-
${i}`:i))}}forkChild(t){const r=bf(new Worker(new URL("/assets/fork-worker-
|
|
1888
|
+
`);return}if(te.data.type==="diagnostic"){le.options.onDiagnostic?.(te.data.message);return}te.data.type==="stdout"?this.emitStdout(le,te.data.bytes):this.emitStderr(le,new TextDecoder().decode(te.data.bytes))}finally{if(te.data.type!=="error"&&te.data.type!=="diagnostic"&&te.data.ack){const le=new Int32Array(te.data.ack);Atomics.store(le,0,1),Atomics.notify(le,0)}}},z.start();Y.threadOutputPorts=L.map(z=>z.port2);const G=new MessageChannel;this.filesystemUpdatePort=G.port1,this.filesystemUpdatePort.onmessage=z=>{const te=this.pending;if(te?.id===p){if(z.data.type==="mailbox"){te.mailbox={control:new Int32Array(z.data.buffer,0,2),buffer:z.data.buffer,doorbell:new Int32Array(z.data.doorbell)};return}if(z.data.type==="port-closed"){const le=te.importOnPort;delete te.importOnPort,le&&(le.sequence??0)>z.data.taken&&te.mailbox&&(te.filesystemQueue=te.filesystemQueue.then(()=>this.sendImport(te,le)).catch(ne=>{this.pending===te&&(this.finishPending(),this.resetWorker(),te.reject(ne))}));return}(z.data.type==="imported"||z.data.type==="import-error")&&delete te.importOnPort,te.filesystemQueue=te.filesystemQueue.then(()=>this.applyLiveFilesystemPatch(p,z.data))}},this.filesystemUpdatePort.start();const q=z=>{const te=this.pending;!te||te.id!==p||this.applyingFilesystem||(te.changedPaths.add(z),this.scheduleFilesystemImport(te))};this.filesystem.on("change",q),this.filesystem.on("delete",q),this.pending.releaseFilesystemChanges=()=>{this.filesystem.off("change",q),this.filesystem.off("delete",q)},Y.filesystemUpdatePort=G.port2,console.log("[wali-boot]",JSON.stringify({stage:"dispatch",run:this.traceId,at:Date.now()})),this.worker.postMessage(Y,[...Y.descriptorTable?[Y.descriptorTable.port]:[],...Y.browserProcessPorts,...Y.threadOutputPorts,Y.filesystemUpdatePort,Y.fileLocks.channel.port,Y.fileCoherence.port,...Y.loopbackPort?[Y.loopbackPort]:[]]);const J=_ye(r.descriptorTable);if(!(J!==void 0&&Aye(J,0)))if(r.stdin!==void 0){const z=r.stdin;this.forwardStdin(p,E,(async function*(){yield z})())}else r.stdinStream&&this.forwardStdin(p,E,r.stdinStream)})}finally{this.preparing=!1}}async forwardStdin(t,r,n){const s=new TextEncoder;try{for await(const i of n){const a=typeof i=="string"?s.encode(i):i;let o=0;for(;this.pending?.id===t&&o<a.byteLength;){const l=r.free();if(l>0){const c=Math.min(l,a.byteLength-o);r.write(a.subarray(o,o+c)),o+=c}else await new Promise(c=>setTimeout(c,1))}if(this.pending?.id!==t)return}this.pending?.id===t&&r.close()}catch(i){const a=this.pending;if(!a||a.id!==t)return;this.resetWorker(),this.finishPending(),a.reject(i)}}get running(){return this.pending!==void 0||this.preparing}sendInput(t){return this.stdin?.write(t)??!1}resize(t,r){this.terminalSize={columns:t,rows:r},this.stdin?.resize(t,r)}setOpenUrlHandler(t){this.openUrlHandler=t}terminate(){this.pending?.reject(new DOMException("The WALI program was terminated.","AbortError")),this.finishPending(),this.worker?.terminate()}createWorker(){const t=bf(new Worker(new URL("/assets/worker-program-worker-B4OcKVtV.js",import.meta.url),{type:"module",name:"browser-wali-program"}));return t.addEventListener("message",r=>{this.handleMessage(r.data).catch(n=>{this.pending?.id===r.data.id&&(this.pending.reject(n),this.finishPending(),this.resetWorker())})}),t.addEventListener("error",r=>{this.pending?.reject(r.error??new Error(r.message)),this.finishPending(),this.resetWorker()}),t}async handleMessage(t){if(t.type==="compiled"){const i=z2(this.program.url,this.program.integrity);i&&fN.set(i,t.compiled);return}const r=this.pending;if(!r||t.id!==r.id)return;if(t.type==="stdout"){this.emitStdout(r,t.chunk);return}if(t.type==="stderr"){this.emitStderr(r,t.chunk);return}if(t.type==="diagnostic"){r.options.onDiagnostic?.(t.message);return}if(t.type==="fork"){this.forkChild(t);return}if(t.type==="spawn"){this.spawnChild(t,r);return}if(t.type==="kill"){const i=this.childControllers.get(t.pid);if(!i)return;i.signal.aborted?i.signal.reason?.redeliver?.(t.signal):i.abort($ye(t.signal,`Signal ${t.signal}`));return}console.log("[wali-boot]",JSON.stringify({stage:"result-received",run:this.traceId,at:Date.now()}));const n=this.program.sanitizeFilesystem?await this.program.sanitizeFilesystem(t.filesystem):t.filesystem;if(t.filesystemFinalized&&await r.filesystemFinalization,await r.filesystemQueue,console.log("[wali-boot]",JSON.stringify({stage:"filesystem-settled",run:this.traceId,at:Date.now()})),this.pending!==r)return;const s=t.filesystemFinalized?{files:[],removed:[]}:this.withoutHostTrees(N1(r.filesystemBase,n,{written:!0}));t.filesystemFinalized||T1(this.filesystem,s,r.filesystemBase);try{await this.program.onFilesystemCommit?.(this.filesystem,s)}catch(i){this.finishPending(),r.reject(new Error(`WALI filesystem durability barrier failed: ${i instanceof Error?i.message:String(i)}`));return}if(this.finishPending(),console.log("[wali-boot]",JSON.stringify({stage:"done",run:this.traceId,at:Date.now()})),t.result)r.resolve({...t.result,stdout:r.stdout,stderr:r.stderr});else{const i=t.error??"The browser WALI program failed.",a=r.stderr.trimEnd();r.reject(new Error(a?`${a}
|
|
1889
|
+
${i}`:i))}}forkChild(t){const r=bf(new Worker(new URL("/assets/fork-worker-BXY2kfdX.js",import.meta.url),{type:"module",name:`wali-fork-${t.pid}`}));this.forkWorkers.set(t.pid,r);const n=()=>{r.terminate(),this.forkWorkers.delete(t.pid)};r.addEventListener("message",s=>{if(s.data.type==="fork-done"){n();return}this.handleMessage(s.data).catch(i=>{this.pending?.reject(i),this.finishPending(),this.resetWorker()})}),r.addEventListener("error",s=>{this.pending?.reject(s.error??new Error(s.message)),this.finishPending(),this.resetWorker()}),r.postMessage(t,[t.descriptorTable.port,...t.descriptorTable.releasePort?[t.descriptorTable.releasePort]:[],t.forkState.memory])}async spawnChild(t,r){const n=this.program.spawn,s=new AbortController;this.childControllers.set(t.pid,s);const i=A=>console.log("[wali-boot]",JSON.stringify({stage:A,run:this.traceId,child:t.pid,at:Date.now()}));i("spawn-received");const a=t.descriptorTable?.releasePort,o=t.descriptorTable&&{port:t.descriptorTable.port,control:t.descriptorTable.control,payload:t.descriptorTable.payload,...t.descriptorTable.sharedPipes?{sharedPipes:t.descriptorTable.sharedPipes}:{}};let l;const c=()=>l??=a?new Promise(A=>{a.onmessage=()=>{a.close(),A()},a.postMessage(!0)}):Promise.resolve();let u=Promise.resolve(),d=Promise.resolve(),p=!1,m=!1;const g=()=>S1(this.filesystem,"/",{metadataRoots:["/"]}),b=async A=>{const T=N1(A,await g()),D=new Map(A.files.map(_=>[_.path,_])),I=[],U=this.unreadRoots(),O=new Set(T.removed.filter(_=>!lc(_,U)));for(const _ of T.files){if(_.type!=="directory"&&lc(_.path,U))continue;const $=D.get(_.path);if(!(_.type==="file"&&(!$||$.type!=="file"||$.size!==_.size||$.mtimeMs!==_.mtimeMs))){I.push(_);continue}const P=await z8(this.filesystem,_.path);P?I.push(P):$&&O.add(_.path)}return{files:I,removed:[...O]}};let v=await g();i("spawn-snapshot");const S=A=>{p=!0,t.stdout?u=u.then(()=>B2(t.stdout,new TextEncoder().encode(A))):this.emitStdout(r,A)},x=A=>{p=!0,u=u.then(()=>B2(t.stdout,A))},E=A=>{m=!0,t.stderr?d=d.then(()=>B2(t.stderr,new TextEncoder().encode(A))):this.emitStderr(r,A)};try{if(!n)throw new Error("No browser child-process backend is configured.");const A=r.options.filesystemPolicy?Xg(r.options.filesystemPolicy,t.filesystemPolicy):t.filesystemPolicy===void 0?void 0:es(t.filesystemPolicy);Ic(A,n.capabilities);const T=this.withoutHostTrees(this.program.sanitizeFilesystemPatch?await this.program.sanitizeFilesystemPatch(t.filesystemPatch):t.filesystemPatch);T1(this.filesystem,T,r.filesystemBase),r.filesystemBase.apply(T),v=await g(),i("spawn-patched");const D=t.stdin?Iye(t.stdin,s.signal):void 0,I=Oye(t),U=await n.run(I.command,{[Pd]:{pid:t.pid,parentPid:t.parentPid,childPidAllocator:t.childPidAllocator},...A?{filesystemPolicy:A}:{},...o?{descriptorTable:o}:{},cwd:t.cwd,...I.executablePath?{executablePath:I.executablePath}:{},env:t.inheritEnvironment?{...r.options.env,...this.program.env}:t.env,...D?{stdinStream:D}:{},signal:s.signal,...t.stdout?{onStdoutBytes:x}:{},onStdout:S,onStderr:E});U.stdout&&!p&&S(U.stdout),U.stderr&&!m&&E(U.stderr),i("spawn-ran"),await Promise.all([u,d]),await c(),oN(t,await b(v),U.exitCode),i("spawn-returned")}catch(A){const T=`${A instanceof Error?A.message:String(A)}
|
|
1890
1890
|
`;E(T),await d,await c(),oN(t,await b(v),s.signal.aborted?130:127)}finally{s.abort(new DOMException("Browser child process completed.","AbortError")),this.childControllers.delete(t.pid),j2(t.stdin),j2(t.stdout),j2(t.stderr)}}async applyLiveFilesystemPatch(t,r){const n=this.pending;if(!(!n||n.id!==t)){if(r.type==="finalized"){n.filesystemFinalized=!0,n.changedPaths.clear(),n.releaseFilesystemChanges(),n.resolveFilesystemFinalization();return}if(r.type==="checkpoint"){const s=new Int32Array(r.control);Atomics.store(s,0,1),Atomics.notify(s,0);return}if(r.type==="imported"){n.filesystemBase.apply(r.patch),n.importingFilesystem=!1,this.scheduleFilesystemImport(n);return}try{if(r.type==="import-error")throw new Error(r.message);if(r.type==="mailbox"||r.type==="port-closed")return;const s=this.withoutHostTrees(this.program.sanitizeFilesystemPatch?await this.program.sanitizeFilesystemPatch(zm(r.patch)):r.patch);this.applyingFilesystem=!0;try{T1(this.filesystem,s,n.filesystemBase)}finally{this.applyingFilesystem=!1}n.filesystemBase.apply(s)}catch(s){if(this.pending?.id!==t)return;this.finishPending(),this.resetWorker(),n.reject(new Error(`WALI filesystem update could not be applied: ${s instanceof Error?s.message:String(s)}`));return}try{r.type==="filesystem"&&await this.program.onFilesystemCommit?.(this.filesystem,zm(r.patch))}catch(s){if(this.pending?.id!==t)return;this.finishPending(),this.resetWorker(),n.reject(new Error(`WALI filesystem durability barrier failed: ${s instanceof Error?s.message:String(s)}`))}}}unreadRoots(){return[Dj,lg,...this.program.excludedImagePaths?.()??[]]}sendImport(t,r){r={...r,sequence:r.sequence??++t.importSequence};const n=t.mailbox;if(!n){t.importOnPort=r,this.filesystemUpdatePort?.postMessage(r);return}const s=new TextEncoder().encode(JSON.stringify({...r,patch:zm(r.patch),...r.base?{base:zm(r.base)}:{}})),i=8+s.byteLength,a=n.buffer;if(i>n.buffer.byteLength){if(!a.grow||i>(a.maxByteLength??0))throw new Error(`A filesystem import of ${s.byteLength} bytes does not fit the program's mailbox.`);a.grow(i)}new Uint8Array(n.buffer,8,s.byteLength).set(s),Atomics.store(n.control,1,s.byteLength),Atomics.store(n.control,0,1),Atomics.add(n.doorbell,0,1),Atomics.notify(n.doorbell,0)}scheduleFilesystemImport(t){t.filesystemFinalized||t.importingFilesystem||t.changedPaths.size===0||this.pending!==t||(t.importingFilesystem=!0,t.filesystemQueue=t.filesystemQueue.then(async()=>{if(this.pending!==t)return;const r=new Set([...t.changedPaths].filter(o=>!lc(o,this.hostRoots)));t.changedPaths.clear();const n=this.unreadRoots(),s=t.filesystemBase.only([...r].filter(o=>!lc(o,n)||t.filesystemBase.byPath.get(o)?.type==="directory")),i={files:[]};for(const o of r){if(lc(o,n)&&!(this.filesystem.existsSync(o)&&this.filesystem.statSync(o).isDirectory()))continue;const l=await z8(this.filesystem,o);l&&i.files.push(l)}if(this.pending!==t)return;const a=N1(s,i);if(a.files.length===0&&a.removed.length===0){t.importingFilesystem=!1,this.scheduleFilesystemImport(t);return}this.sendImport(t,{type:"import",patch:a,base:s})}).catch(r=>{this.pending===t&&(this.finishPending(),this.resetWorker(),t.reject(r))}))}finishPending(){this.pending?.resolveFilesystemFinalization(),this.pending?.removeAbortListener(),this.pending?.releaseLoopback(),this.pending?.releaseFileLocks(),this.pending?.releaseFileCoherence(),this.pending?.releaseFilesystemChanges(),this.pending=void 0,this.stdin?.close(),this.stdin=void 0;for(const t of this.processPorts)t.close();this.processPorts=[];for(const t of this.threadOutputPorts)t.close();this.threadOutputPorts=[],this.filesystemUpdatePort?.close(),this.filesystemUpdatePort=void 0}emitStdout(t,r){const n=typeof r=="string"?r:new TextDecoder().decode(r);t.stdout+=n,this.scanOpenUrls(n),typeof r!="string"&&t.options.onStdoutBytes?t.options.onStdoutBytes(r):t.options.onStdout?.(n)}emitStderr(t,r){t.stderr+=r,this.scanOpenUrls(r),t.options.onStderr?.(r)}scanOpenUrls(t){if(!this.openUrlHandler)return;const r=`${this.urlScanTail}${t}`;for(const n of r.matchAll(/https?:\/\/[^\s<>'"`]+/gu)){const s=n[0].replace(/[),.;]+$/u,"");this.openedUrls.has(s)||(this.openedUrls.add(s),this.openUrlHandler(s))}this.urlScanTail=r.slice(-2048)}resetWorker(){for(const t of this.forkWorkers.values())t.terminate();this.forkWorkers.clear();for(const t of this.childControllers.values())t.abort();this.childControllers.clear(),this.worker?.terminate(),this.worker=this.createWorker()}}function $ye(e,t){return Object.assign(new DOMException(t,"AbortError"),{signal:e})}function Rye(e){const t=e?.signal;return typeof t=="number"&&Number.isInteger(t)&&t>0&&t<=64?t:9}function Oye(e){const[t="",...r]=e.argv,n=e.executablePath||t,s=n.slice(n.lastIndexOf("/")+1);if(["bash","sh","zsh"].includes(s)){const i=r.findIndex(o=>o==="-c"||o.endsWith("lc")||o.endsWith("ilc"));if((i>=0?r[i+1]:void 0)?.includes("__grok_user_cmd")){const o=r.indexOf("--",i+2);if(o>=0&&r[o+1])return{command:r[o+1]}}return{command:[s,...r].map(dN).join(" ")}}return{command:e.argv.map(dN).join(" "),...e.executablePath?{executablePath:e.executablePath}:{}}}function dN(e){return/^[A-Za-z0-9_./:+,@%=-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}function _ye(e){return e?.sharedPipes}function j2(e){e&&Sye(e)}async function*Iye(e,t){for(;!t.aborted;){const r=Eye(e,65536);if(r instanceof Uint8Array){if(r.byteLength===0)break;yield r;continue}if(r!==-11n)throw new Error(`Browser child stdin failed with ${r}.`);await new Promise(n=>setTimeout(n,1))}if(t.aborted)throw t.reason}function lc(e,t){return t.some(r=>r==="/"||e===r||e.startsWith(`${r}/`))}function Mh(){return typeof performance>"u"?Date.now():performance.timeOrigin+performance.now()}new TextEncoder().encode("\0supercode-wali-symlink-v1\0");new TextDecoder("utf-8",{fatal:!0});const Mye="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",qx=64*1024,_f=1024*1024,Dye=_f*2+qx,Dh=new TextEncoder;class Lye{options;handshake;key=As(GF(16));buffer=new Uint8Array;fragmentedOpcode;fragmentChunks=[];fragmentBytes=0;state="handshake";sentClose=!1;constructor(t){this.options=t;const r=t.protocols.length>0?`Sec-WebSocket-Protocol: ${t.protocols.join(", ")}\r
|
|
1891
1891
|
`:"";this.handshake=Dh.encode(`GET ${t.path} HTTP/1.1\r
|
|
1892
1892
|
Host: localhost:${t.port}\r
|
|
@@ -1911,7 +1911,7 @@ ${Object.entries(a).map(([c,u])=>`${c}: ${u}`).join(`\r
|
|
|
1911
1911
|
`)}\r
|
|
1912
1912
|
\r
|
|
1913
1913
|
`),l=new Uint8Array(o.byteLength+i.byteLength);return l.set(o),l.set(i,o.byteLength),l}function pN(e,t,r,n){const s=rE(t,r),i=ip(s,[13,10,13,10]);if(i<0)return;const o=new TextDecoder("utf-8",{fatal:!0}).decode(s.subarray(0,i)).split(`\r
|
|
1914
|
-
`),l=/^HTTP\/1\.[01] ([1-5][0-9]{2})(?: (.*))?$/u.exec(o.shift()??"");if(!l)throw new Error("WALI loopback server returned an invalid HTTP status line.");const c={};for(const b of o){const v=b.indexOf(":");if(v<=0)throw new Error("WALI loopback server returned an invalid HTTP header.");const S=b.slice(0,v).trim().toLowerCase(),x=b.slice(v+1).trim(),E=c[S];c[S]=E===void 0?x:Array.isArray(E)?[...E,x]:[E,x]}const u=Number(l[1]),d=i+4;if(e==="HEAD"||u<200||u===204||u===304)return{statusCode:u,statusMessage:l[2]||"",headers:c};if(mN(c,"transfer-encoding")?.toLowerCase()?.includes("chunked")){const b=ZF(s.subarray(d));return b?{statusCode:u,statusMessage:l[2]||"",headers:c,body:b}:void 0}const g=mN(c,"content-length");if(g!==void 0){const b=Number(g);if(!Number.isSafeInteger(b)||b<0||b>Ec)throw new Error("Invalid WALI loopback Content-Length.");return s.byteLength-d<b?void 0:{statusCode:u,statusMessage:l[2]||"",headers:c,body:s.slice(d,d+b)}}if(n)return{statusCode:u,statusMessage:l[2]||"",headers:c,body:s.slice(d)}}function ZF(e){const t=[];let r=0,n=0;for(;;){const s=ip(e,[13,10],n);if(s<0)return;const i=new TextDecoder().decode(e.subarray(n,s)).split(";",1)[0]??"",a=Number.parseInt(i,16);if(!Number.isSafeInteger(a)||a<0)throw new Error("Invalid WALI loopback chunk length.");if(n=s+2,a===0)return e.byteLength<n+2?void 0:rE(t,r);if(e.byteLength<n+a+2)return;if(t.push(e.slice(n,n+a)),r+=a,r>Ec||e[n+a]!==13||e[n+a+1]!==10)throw new Error("Invalid WALI loopback chunked response.");n+=a+2}}function rE(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.byteLength;return r}function ip(e,t,r=0){e:for(let n=r;n<=e.byteLength-t.length;n+=1){for(let s=0;s<t.length;s+=1)if(e[n+s]!==t[s])continue e;return n}return-1}function mN(e,t){const r=e[t];return Array.isArray(r)?r[0]:r}function H2(e){return Number.isSafeInteger(e)&&e>0&&e<=65535}var gN;(function(e){e[e.Socket=1]="Socket",e[e.Connect=2]="Connect",e[e.Send=3]="Send",e[e.Receive=4]="Receive",e[e.Close=5]="Close",e[e.Fcntl=6]="Fcntl",e[e.Poll=7]="Poll",e[e.Shutdown=8]="Shutdown",e[e.Duplicate=9]="Duplicate",e[e.SocketName=10]="SocketName",e[e.EpollControl=11]="EpollControl",e[e.EpollWait=12]="EpollWait",e[e.EpollCreate=13]="EpollCreate",e[e.EventFd=14]="EventFd",e[e.SocketPair=15]="SocketPair",e[e.TimerFdCreate=16]="TimerFdCreate",e[e.TimerFdSetTime=17]="TimerFdSetTime",e[e.Bind=18]="Bind",e[e.Listen=19]="Listen",e[e.Accept=20]="Accept",e[e.ChildRegister=21]="ChildRegister",e[e.ChildForget=22]="ChildForget",e[e.ChildWait=23]="ChildWait",e[e.ChildExists=24]="ChildExists",e[e.PidFdOpen=25]="PidFdOpen",e[e.PollMany=26]="PollMany"})(gN||(gN={}));new TextEncoder;var yN;(function(e){e[e.Exists=1]="Exists",e[e.Stat=2]="Stat",e[e.Lstat=3]="Lstat",e[e.ReadFile=4]="ReadFile",e[e.WriteFile=5]="WriteFile",e[e.Mkdir=6]="Mkdir",e[e.Readdir=7]="Readdir",e[e.Unlink=8]="Unlink",e[e.Rmdir=9]="Rmdir",e[e.Rename=10]="Rename",e[e.Snapshot=11]="Snapshot",e[e.ReplaceSnapshot=12]="ReplaceSnapshot",e[e.Syscall=13]="Syscall",e[e.ReadForMapping=14]="ReadForMapping",e[e.SnapshotSize=15]="SnapshotSize",e[e.SnapshotChunk=16]="SnapshotChunk",e[e.ReplaceSnapshotStart=17]="ReplaceSnapshotStart",e[e.ReplaceSnapshotChunk=18]="ReplaceSnapshotChunk",e[e.MappingPath=19]="MappingPath",e[e.WriteForMapping=20]="WriteForMapping",e[e.FinalSnapshotSize=21]="FinalSnapshotSize",e[e.ImportPeerPatch=22]="ImportPeerPatch",e[e.ImportPeerPatchStart=23]="ImportPeerPatchStart",e[e.ImportPeerPatchChunk=24]="ImportPeerPatchChunk",e[e.PrepareSpawn=25]="PrepareSpawn",e[e.ReadRange=26]="ReadRange",e[e.WriteRange=27]="WriteRange",e[e.CopyForExec=28]="CopyForExec",e[e.CloseProcess=29]="CloseProcess",e[e.CopyForFork=30]="CopyForFork",e[e.GetCwd=31]="GetCwd",e[e.SyscallBinary=32]="SyscallBinary",e[e.ReadForMappingBinary=33]="ReadForMappingBinary",e[e.WriteForMappingBinary=34]="WriteForMappingBinary"})(yN||(yN={}));var bN;(function(e){e[e.Query=1]="Query",e[e.Open=2]="Open",e[e.Push=3]="Push",e[e.Pull=4]="Pull",e[e.Flush=5]="Flush",e[e.Close=6]="Close"})(bN||(bN={}));var wN;(function(e){e[e.VideoDecoder=0]="VideoDecoder",e[e.VideoEncoder=1]="VideoEncoder",e[e.AudioDecoder=2]="AudioDecoder",e[e.AudioEncoder=3]="AudioEncoder"})(wN||(wN={}));var vN;(function(e){e[e.State=0]="State",e[e.Operation=1]="Operation",e[e.Result=2]="Result",e[e.Argument0=3]="Argument0",e[e.Argument1=4]="Argument1",e[e.Argument2=5]="Argument2",e[e.Argument3=6]="Argument3",e[e.Argument4=7]="Argument4",e[e.Argument5=8]="Argument5"})(vN||(vN={}));new TextEncoder;new TextDecoder;const xN="/opt/programs/bin",Qye="supercode-browser-credentials",Jye="credentials",YF=1024*1024;class ebe{shared;files;constructor(t,r){this.shared=t,this.files=r}existsSync(t){const r=this.privateFile(t);return r?r.bytes!==void 0:this.shared.existsSync(t)}statSync(t){const r=this.privateFile(t);if(!r)return this.shared.statSync(t);if(!r.bytes)throw new Error(`Private file does not exist: ${t}`);return{isDirectory:()=>!1,mode:r.mode,mtimeMs:r.mtimeMs}}async readFile(t){const r=this.privateFile(t);if(!r)return this.shared.readFile(t);if(!r.bytes)throw new Error(`Private file does not exist: ${t}`);return r.bytes.slice()}writeFileSync(t,r){const n=this.privateFile(t);if(!n){this.shared.writeFileSync(t,r);return}const s=typeof r=="string"?new TextEncoder().encode(r):Uint8Array.from(r);if(s.byteLength===0||s.byteLength>YF)throw new DOMException("Private file exceeds its configured vault bound.","QuotaExceededError");n.bytes=s,n.mode=n.mode||384,n.mtimeMs=Mh()}mkdirSync(t,r){this.shared.mkdirSync(t,r)}unlinkSync(t){const r=this.privateFile(t);if(!r){this.shared.unlinkSync(t);return}if(!r.bytes)throw new Error(`Private file does not exist: ${t}`);r.bytes=void 0,r.mtimeMs=Mh()}rmdirSync(t){this.shared.rmdirSync(t)}chmodSync(t,r){const n=this.privateFile(t);if(!n){this.shared.chmodSync?.(t,r);return}n.mode=r}utimesSync(t,r,n){const s=this.privateFile(t);if(!s){this.shared.utimesSync?.(t,r,n);return}s.mtimeMs=n instanceof Date?n.getTime():n}privateFile(t){return this.files.find(r=>r.path===t)}}class XF{filesystem;processHost;manifest;options;capabilities=Object.freeze({filesystemPolicy:!0});worker;privateFiles;privateOverlay;active=!1;constructor(t,r,n,s={}){if(this.filesystem=t,this.processHost=r,this.manifest=n,this.options=s,n.engine!=="wali")throw new Error(`${n.id} is not a WALI program.`);const i=s.vaultNamespace??"default",a=[...new Set(s.legacyVaultNamespaces??[])].filter(l=>l!==i),o=s.createVault??sbe;this.privateFiles=n.storage.privateFiles.map(l=>({path:this.expand(l.path),vault:o(SN(i,l.vault)),legacyVaults:a.map(c=>o(SN(c,l.vault))),...l.defaultContent!==void 0?{defaultContent:l.defaultContent}:{},clearOnActions:new Set(l.clearOnActions??[]),available:!1,presentAfterRun:void 0,bytes:void 0,mode:384,mtimeMs:Mh()})),this.privateOverlay=new ebe(t,this.privateFiles),this.worker=this.createWorker()}get command(){return this.manifest.executable}get displayName(){return this.manifest.displayName}get running(){return this.worker.running}action(t){const r=this.manifest.actions[t];if(!r)throw new Error(`${this.manifest.id} has no ${t} action.`);return r}hasPrivateState(t){return this.privateFiles.some((r,n)=>r.available&&(t===void 0||this.manifest.storage.privateFiles[n]?.vault===t))}acceptsOpenUrl(t){let r;try{r=t instanceof URL?t:new URL(t)}catch{return!1}return this.manifest.openUrls.some(n=>r.protocol===n.protocol&&r.hostname===n.hostname&&r.pathname===n.pathname)}setOpenUrlHandler(t){this.worker.setOpenUrlHandler(t?r=>{this.acceptsOpenUrl(r)&&t(r)}:void 0)}sendInput(t){return this.worker.sendInput(tbe(this.manifest.terminal.input,t))}resize(t,r){this.worker.resize(t,r)}terminate(){this.worker.terminate()}async restoreState(){for(const t of this.privateFiles){await this.filePresent(t.path)&&await t.vault.save(await this.filesystem.readFile(t.path)),this.unmount(t.path);let r=await this.loadPrivateFile(t);!r&&t.defaultContent!==void 0&&(r=new TextEncoder().encode(t.defaultContent),await t.vault.save(r)),t.available=!!r}this.options.onStateChange?.()}get busy(){return this.active}async run(t,r={}){if(r.filesystemPolicy!==void 0&&(r={...r,filesystemPolicy:es(r.filesystemPolicy)}),this.active)throw new Error(`${this.manifest.displayName} is already running.`);const n=t.length===1&&t[0]===this.manifest.executable?this.action("start"):t,s=this.actionName(n);this.active=!0;let i;try{this.options.onStateChange?.(),await this.installResources(),await this.preparePrivateFiles();const a=await this.worker.run(n,r);return a.exitCode===0&&(i=s),a}finally{await this.finalizePrivateFiles(i),this.active=!1,this.options.onStateChange?.()}}async installResources(){await nX(this.filesystem,this.manifest,{...this.options.resourcesUrl?{url:this.options.resourcesUrl}:{},...this.options.resourcesIntegrity?{integrity:this.options.resourcesIntegrity}:{},...this.options.onResourcesProgress?{onProgress:this.options.onResourcesProgress}:{}})}createWorker(){const t=this.options.policy?.programNetwork(this.manifest.id,this.manifest.network.allowedHosts)??{allowedHosts:this.manifest.network.allowedHosts,maxConnections:16,maxBytes:67108864};return new Nye(this.filesystem,{url:this.options.artifactUrl??this.manifest.artifact.url,integrity:this.options.artifactIntegrity??this.manifest.artifact.integrity,cwd:"/workspace",env:Object.fromEntries(Object.entries(this.manifest.environment).map(([r,n])=>[r,this.expand(n)])),threadPoolSize:this.manifest.requirements.workers??18,...this.manifest.requirements.capabilities.includes("media.webcodecs")?{codec:{version:1}}:{},network:{...this.options.relayUrl?{relayUrl:this.options.relayUrl}:{},...t},...this.options.loopback?{loopback:this.options.loopback}:{},spawn:this.options.spawn??this.processHost,excludedImagePaths:()=>[...this.otherProgramTrees(),...this.options.unreadTrees??[]],prepareFilesystem:r=>this.preparePrivateFilesystem(r),sanitizeFilesystem:r=>this.sanitizePrivateFilesystem(r),sanitizeFilesystemPatch:r=>this.sanitizePrivatePatch(r),coherenceFilesystem:this.privateOverlay,onFilesystemCommit:async()=>{await this.persistPrivateOverlay(),await this.options.onFilesystemCommit?.(),this.options.onStateChange?.()}})}expand(t){return t.replaceAll("${HOME}",this.options.userHome??"/home/browser")}actionName(t){return Object.entries(this.manifest.actions).find(([,r])=>rbe(t,r))?.[0]}async preparePrivateFiles(){for(const t of this.privateFiles){const r=await this.loadPrivateFile(t);t.available=!!r,t.presentAfterRun=void 0,t.bytes=r?.slice(),t.mode=384,t.mtimeMs=Mh(),r&&nbe(this.filesystem,t.path)}}otherProgramTrees(){const r=this.manifest.resources?.root?.split("/").filter(Boolean)??[],n=r.indexOf(this.manifest.id),s=n>0?`/${r.slice(0,n).join("/")}`:xN.slice(0,xN.lastIndexOf("/"));return this.filesystem.existsSync(s)?this.filesystem.readdirSync(s).filter(i=>i!==this.manifest.id&&i!=="bin").map(i=>`${s}/${i}`):[]}async preparePrivateFilesystem(t){const r=t.files.filter(n=>!this.privateFiles.some(s=>s.path===n.path));for(const n of this.privateFiles)n.bytes&&r.push({path:n.path,type:"file",content:As(n.bytes),mode:n.mode,mtimeMs:n.mtimeMs});return{files:r}}async sanitizePrivateFilesystem(t){return await Promise.all(this.privateFiles.map(r=>this.capturePrivateEntry(r,t.files.find(n=>n.path===r.path)))),{files:t.files.filter(r=>!this.privateFiles.some(n=>n.path===r.path))}}async sanitizePrivatePatch(t){return await Promise.all(this.privateFiles.map(async r=>{const n=t.files.find(s=>s.path===r.path);n?await this.capturePrivateEntry(r,n):t.removed.includes(r.path)&&(r.presentAfterRun=!1,r.bytes=void 0)})),{files:t.files.filter(r=>!this.privateFiles.some(n=>n.path===r.path)),removed:t.removed.filter(r=>!this.privateFiles.some(n=>n.path===r))}}async capturePrivateEntry(t,r){if(r?.type!=="file"){t.presentAfterRun=!1,t.bytes=void 0;return}const n=Xa(r.content??"");if(n.byteLength===0){t.presentAfterRun=!1,t.bytes=void 0;return}await t.vault.save(n),t.bytes=n,t.mode=r.mode??384,t.mtimeMs=r.mtimeMs??Mh(),t.available=!0,t.presentAfterRun=!0}async finalizePrivateFiles(t){await Promise.all(this.privateFiles.map(async r=>{r.presentAfterRun===!1&&t!==void 0&&r.clearOnActions.has(t)&&(await Promise.all([r.vault,...r.legacyVaults].map(n=>n.clear())),r.available=!1,r.bytes=void 0),r.presentAfterRun=void 0}))}async persistPrivateOverlay(){await Promise.all(this.privateFiles.map(async t=>{if(!t.bytes||t.bytes.byteLength===0){t.presentAfterRun=!1;return}await t.vault.save(t.bytes),t.available=!0,t.presentAfterRun=!0}))}async loadPrivateFile(t){const r=await t.vault.load();if(r)return r;for(const n of t.legacyVaults){const s=await n.load();if(s)return await t.vault.save(s),s}}async filePresent(t){try{return this.filesystem.existsSync(t)&&this.filesystem.statSync(t).isFile()&&(await this.filesystem.readFile(t)).byteLength>0}catch{return!1}}unmount(t){this.filesystem.existsSync(t)&&this.filesystem.statSync(t).isFile()&&this.filesystem.unlinkSync(t)}}function tbe(e,t){if(e==="canonical-lines")return t.replaceAll("\r",`
|
|
1914
|
+
`),l=/^HTTP\/1\.[01] ([1-5][0-9]{2})(?: (.*))?$/u.exec(o.shift()??"");if(!l)throw new Error("WALI loopback server returned an invalid HTTP status line.");const c={};for(const b of o){const v=b.indexOf(":");if(v<=0)throw new Error("WALI loopback server returned an invalid HTTP header.");const S=b.slice(0,v).trim().toLowerCase(),x=b.slice(v+1).trim(),E=c[S];c[S]=E===void 0?x:Array.isArray(E)?[...E,x]:[E,x]}const u=Number(l[1]),d=i+4;if(e==="HEAD"||u<200||u===204||u===304)return{statusCode:u,statusMessage:l[2]||"",headers:c};if(mN(c,"transfer-encoding")?.toLowerCase()?.includes("chunked")){const b=ZF(s.subarray(d));return b?{statusCode:u,statusMessage:l[2]||"",headers:c,body:b}:void 0}const g=mN(c,"content-length");if(g!==void 0){const b=Number(g);if(!Number.isSafeInteger(b)||b<0||b>Ec)throw new Error("Invalid WALI loopback Content-Length.");return s.byteLength-d<b?void 0:{statusCode:u,statusMessage:l[2]||"",headers:c,body:s.slice(d,d+b)}}if(n)return{statusCode:u,statusMessage:l[2]||"",headers:c,body:s.slice(d)}}function ZF(e){const t=[];let r=0,n=0;for(;;){const s=ip(e,[13,10],n);if(s<0)return;const i=new TextDecoder().decode(e.subarray(n,s)).split(";",1)[0]??"",a=Number.parseInt(i,16);if(!Number.isSafeInteger(a)||a<0)throw new Error("Invalid WALI loopback chunk length.");if(n=s+2,a===0)return e.byteLength<n+2?void 0:rE(t,r);if(e.byteLength<n+a+2)return;if(t.push(e.slice(n,n+a)),r+=a,r>Ec||e[n+a]!==13||e[n+a+1]!==10)throw new Error("Invalid WALI loopback chunked response.");n+=a+2}}function rE(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.byteLength;return r}function ip(e,t,r=0){e:for(let n=r;n<=e.byteLength-t.length;n+=1){for(let s=0;s<t.length;s+=1)if(e[n+s]!==t[s])continue e;return n}return-1}function mN(e,t){const r=e[t];return Array.isArray(r)?r[0]:r}function H2(e){return Number.isSafeInteger(e)&&e>0&&e<=65535}var gN;(function(e){e[e.Socket=1]="Socket",e[e.Connect=2]="Connect",e[e.Send=3]="Send",e[e.Receive=4]="Receive",e[e.Close=5]="Close",e[e.Fcntl=6]="Fcntl",e[e.Poll=7]="Poll",e[e.Shutdown=8]="Shutdown",e[e.Duplicate=9]="Duplicate",e[e.SocketName=10]="SocketName",e[e.EpollControl=11]="EpollControl",e[e.EpollWait=12]="EpollWait",e[e.EpollCreate=13]="EpollCreate",e[e.EventFd=14]="EventFd",e[e.SocketPair=15]="SocketPair",e[e.TimerFdCreate=16]="TimerFdCreate",e[e.TimerFdSetTime=17]="TimerFdSetTime",e[e.Bind=18]="Bind",e[e.Listen=19]="Listen",e[e.Accept=20]="Accept",e[e.ChildRegister=21]="ChildRegister",e[e.ChildForget=22]="ChildForget",e[e.ChildWait=23]="ChildWait",e[e.ChildExists=24]="ChildExists",e[e.PidFdOpen=25]="PidFdOpen",e[e.PollMany=26]="PollMany"})(gN||(gN={}));new TextEncoder;var yN;(function(e){e[e.Exists=1]="Exists",e[e.Stat=2]="Stat",e[e.Lstat=3]="Lstat",e[e.ReadFile=4]="ReadFile",e[e.WriteFile=5]="WriteFile",e[e.Mkdir=6]="Mkdir",e[e.Readdir=7]="Readdir",e[e.Unlink=8]="Unlink",e[e.Rmdir=9]="Rmdir",e[e.Rename=10]="Rename",e[e.Snapshot=11]="Snapshot",e[e.ReplaceSnapshot=12]="ReplaceSnapshot",e[e.Syscall=13]="Syscall",e[e.ReadForMapping=14]="ReadForMapping",e[e.SnapshotSize=15]="SnapshotSize",e[e.SnapshotChunk=16]="SnapshotChunk",e[e.ReplaceSnapshotStart=17]="ReplaceSnapshotStart",e[e.ReplaceSnapshotChunk=18]="ReplaceSnapshotChunk",e[e.MappingPath=19]="MappingPath",e[e.WriteForMapping=20]="WriteForMapping",e[e.FinalSnapshotSize=21]="FinalSnapshotSize",e[e.ImportPeerPatch=22]="ImportPeerPatch",e[e.ImportPeerPatchStart=23]="ImportPeerPatchStart",e[e.ImportPeerPatchChunk=24]="ImportPeerPatchChunk",e[e.PrepareSpawn=25]="PrepareSpawn",e[e.ReadRange=26]="ReadRange",e[e.WriteRange=27]="WriteRange",e[e.CopyForExec=28]="CopyForExec",e[e.CloseProcess=29]="CloseProcess",e[e.CopyForFork=30]="CopyForFork",e[e.GetCwd=31]="GetCwd",e[e.SyscallBinary=32]="SyscallBinary",e[e.ReadForMappingBinary=33]="ReadForMappingBinary",e[e.WriteForMappingBinary=34]="WriteForMappingBinary"})(yN||(yN={}));var bN;(function(e){e[e.Query=1]="Query",e[e.Open=2]="Open",e[e.Push=3]="Push",e[e.Pull=4]="Pull",e[e.Flush=5]="Flush",e[e.Close=6]="Close"})(bN||(bN={}));var wN;(function(e){e[e.VideoDecoder=0]="VideoDecoder",e[e.VideoEncoder=1]="VideoEncoder",e[e.AudioDecoder=2]="AudioDecoder",e[e.AudioEncoder=3]="AudioEncoder"})(wN||(wN={}));var vN;(function(e){e[e.State=0]="State",e[e.Operation=1]="Operation",e[e.Result=2]="Result",e[e.Argument0=3]="Argument0",e[e.Argument1=4]="Argument1",e[e.Argument2=5]="Argument2",e[e.Argument3=6]="Argument3",e[e.Argument4=7]="Argument4",e[e.Argument5=8]="Argument5"})(vN||(vN={}));new TextEncoder;new TextDecoder;const xN="/opt/programs/bin",Qye="supercode-browser-credentials",Jye="credentials",YF=1024*1024;class ebe{shared;files;constructor(t,r){this.shared=t,this.files=r}existsSync(t){const r=this.privateFile(t);return r?r.bytes!==void 0:this.shared.existsSync(t)}statSync(t){const r=this.privateFile(t);if(!r)return this.shared.statSync(t);if(!r.bytes)throw new Error(`Private file does not exist: ${t}`);return{isDirectory:()=>!1,mode:r.mode,mtimeMs:r.mtimeMs}}async readFile(t){const r=this.privateFile(t);if(!r)return this.shared.readFile(t);if(!r.bytes)throw new Error(`Private file does not exist: ${t}`);return r.bytes.slice()}writeFileSync(t,r){const n=this.privateFile(t);if(!n){this.shared.writeFileSync(t,r);return}const s=typeof r=="string"?new TextEncoder().encode(r):Uint8Array.from(r);if(s.byteLength===0||s.byteLength>YF)throw new DOMException("Private file exceeds its configured vault bound.","QuotaExceededError");n.bytes=s,n.mode=n.mode||384,n.mtimeMs=Mh()}mkdirSync(t,r){this.shared.mkdirSync(t,r)}unlinkSync(t){const r=this.privateFile(t);if(!r){this.shared.unlinkSync(t);return}if(!r.bytes)throw new Error(`Private file does not exist: ${t}`);r.bytes=void 0,r.mtimeMs=Mh()}rmdirSync(t){this.shared.rmdirSync(t)}chmodSync(t,r){const n=this.privateFile(t);if(!n){this.shared.chmodSync?.(t,r);return}n.mode=r}utimesSync(t,r,n){const s=this.privateFile(t);if(!s){this.shared.utimesSync?.(t,r,n);return}s.mtimeMs=typeof n=="number"?n:Number(n)}privateFile(t){return this.files.find(r=>r.path===t)}}class XF{filesystem;processHost;manifest;options;capabilities=Object.freeze({filesystemPolicy:!0});worker;privateFiles;privateOverlay;active=!1;constructor(t,r,n,s={}){if(this.filesystem=t,this.processHost=r,this.manifest=n,this.options=s,n.engine!=="wali")throw new Error(`${n.id} is not a WALI program.`);const i=s.vaultNamespace??"default",a=[...new Set(s.legacyVaultNamespaces??[])].filter(l=>l!==i),o=s.createVault??sbe;this.privateFiles=n.storage.privateFiles.map(l=>({path:this.expand(l.path),vault:o(SN(i,l.vault)),legacyVaults:a.map(c=>o(SN(c,l.vault))),...l.defaultContent!==void 0?{defaultContent:l.defaultContent}:{},clearOnActions:new Set(l.clearOnActions??[]),available:!1,presentAfterRun:void 0,bytes:void 0,mode:384,mtimeMs:Mh()})),this.privateOverlay=new ebe(t,this.privateFiles),this.worker=this.createWorker()}get command(){return this.manifest.executable}get displayName(){return this.manifest.displayName}get running(){return this.worker.running}action(t){const r=this.manifest.actions[t];if(!r)throw new Error(`${this.manifest.id} has no ${t} action.`);return r}hasPrivateState(t){return this.privateFiles.some((r,n)=>r.available&&(t===void 0||this.manifest.storage.privateFiles[n]?.vault===t))}acceptsOpenUrl(t){let r;try{r=t instanceof URL?t:new URL(t)}catch{return!1}return this.manifest.openUrls.some(n=>r.protocol===n.protocol&&r.hostname===n.hostname&&r.pathname===n.pathname)}setOpenUrlHandler(t){this.worker.setOpenUrlHandler(t?r=>{this.acceptsOpenUrl(r)&&t(r)}:void 0)}sendInput(t){return this.worker.sendInput(tbe(this.manifest.terminal.input,t))}resize(t,r){this.worker.resize(t,r)}terminate(){this.worker.terminate()}async restoreState(){for(const t of this.privateFiles){await this.filePresent(t.path)&&await t.vault.save(await this.filesystem.readFile(t.path)),this.unmount(t.path);let r=await this.loadPrivateFile(t);!r&&t.defaultContent!==void 0&&(r=new TextEncoder().encode(t.defaultContent),await t.vault.save(r)),t.available=!!r}this.options.onStateChange?.()}get busy(){return this.active}async run(t,r={}){if(r.filesystemPolicy!==void 0&&(r={...r,filesystemPolicy:es(r.filesystemPolicy)}),this.active)throw new Error(`${this.manifest.displayName} is already running.`);const n=t.length===1&&t[0]===this.manifest.executable?this.action("start"):t,s=this.actionName(n);this.active=!0;let i;try{this.options.onStateChange?.(),await this.installResources(),await this.preparePrivateFiles();const a=await this.worker.run(n,r);return a.exitCode===0&&(i=s),a}finally{await this.finalizePrivateFiles(i),this.active=!1,this.options.onStateChange?.()}}async installResources(){await nX(this.filesystem,this.manifest,{...this.options.resourcesUrl?{url:this.options.resourcesUrl}:{},...this.options.resourcesIntegrity?{integrity:this.options.resourcesIntegrity}:{},...this.options.onResourcesProgress?{onProgress:this.options.onResourcesProgress}:{}})}createWorker(){const t=this.options.policy?.programNetwork(this.manifest.id,this.manifest.network.allowedHosts)??{allowedHosts:this.manifest.network.allowedHosts,maxConnections:16,maxBytes:67108864};return new Nye(this.filesystem,{url:this.options.artifactUrl??this.manifest.artifact.url,integrity:this.options.artifactIntegrity??this.manifest.artifact.integrity,cwd:"/workspace",env:Object.fromEntries(Object.entries(this.manifest.environment).map(([r,n])=>[r,this.expand(n)])),threadPoolSize:this.manifest.requirements.workers??18,...this.manifest.requirements.capabilities.includes("media.webcodecs")?{codec:{version:1}}:{},network:{...this.options.relayUrl?{relayUrl:this.options.relayUrl}:{},...t},...this.options.loopback?{loopback:this.options.loopback}:{},spawn:this.options.spawn??this.processHost,excludedImagePaths:()=>[...this.otherProgramTrees(),...this.options.unreadTrees??[]],prepareFilesystem:r=>this.preparePrivateFilesystem(r),sanitizeFilesystem:r=>this.sanitizePrivateFilesystem(r),sanitizeFilesystemPatch:r=>this.sanitizePrivatePatch(r),coherenceFilesystem:this.privateOverlay,onFilesystemCommit:async()=>{await this.persistPrivateOverlay(),await this.options.onFilesystemCommit?.(),this.options.onStateChange?.()}})}expand(t){return t.replaceAll("${HOME}",this.options.userHome??"/home/browser")}actionName(t){return Object.entries(this.manifest.actions).find(([,r])=>rbe(t,r))?.[0]}async preparePrivateFiles(){for(const t of this.privateFiles){const r=await this.loadPrivateFile(t);t.available=!!r,t.presentAfterRun=void 0,t.bytes=r?.slice(),t.mode=384,t.mtimeMs=Mh(),r&&nbe(this.filesystem,t.path)}}otherProgramTrees(){const r=this.manifest.resources?.root?.split("/").filter(Boolean)??[],n=r.indexOf(this.manifest.id),s=n>0?`/${r.slice(0,n).join("/")}`:xN.slice(0,xN.lastIndexOf("/"));return this.filesystem.existsSync(s)?this.filesystem.readdirSync(s).filter(i=>i!==this.manifest.id&&i!=="bin").map(i=>`${s}/${i}`):[]}async preparePrivateFilesystem(t){const r=t.files.filter(n=>!this.privateFiles.some(s=>s.path===n.path));for(const n of this.privateFiles)n.bytes&&r.push({path:n.path,type:"file",content:As(n.bytes),mode:n.mode,mtimeMs:n.mtimeMs});return{files:r}}async sanitizePrivateFilesystem(t){return await Promise.all(this.privateFiles.map(r=>this.capturePrivateEntry(r,t.files.find(n=>n.path===r.path)))),{files:t.files.filter(r=>!this.privateFiles.some(n=>n.path===r.path))}}async sanitizePrivatePatch(t){return await Promise.all(this.privateFiles.map(async r=>{const n=t.files.find(s=>s.path===r.path);n?await this.capturePrivateEntry(r,n):t.removed.includes(r.path)&&(r.presentAfterRun=!1,r.bytes=void 0)})),{files:t.files.filter(r=>!this.privateFiles.some(n=>n.path===r.path)),removed:t.removed.filter(r=>!this.privateFiles.some(n=>n.path===r))}}async capturePrivateEntry(t,r){if(r?.type!=="file"){t.presentAfterRun=!1,t.bytes=void 0;return}const n=Xa(r.content??"");if(n.byteLength===0){t.presentAfterRun=!1,t.bytes=void 0;return}await t.vault.save(n),t.bytes=n,t.mode=r.mode??384,t.mtimeMs=r.mtimeMs??Mh(),t.available=!0,t.presentAfterRun=!0}async finalizePrivateFiles(t){await Promise.all(this.privateFiles.map(async r=>{r.presentAfterRun===!1&&t!==void 0&&r.clearOnActions.has(t)&&(await Promise.all([r.vault,...r.legacyVaults].map(n=>n.clear())),r.available=!1,r.bytes=void 0),r.presentAfterRun=void 0}))}async persistPrivateOverlay(){await Promise.all(this.privateFiles.map(async t=>{if(!t.bytes||t.bytes.byteLength===0){t.presentAfterRun=!1;return}await t.vault.save(t.bytes),t.available=!0,t.presentAfterRun=!0}))}async loadPrivateFile(t){const r=await t.vault.load();if(r)return r;for(const n of t.legacyVaults){const s=await n.load();if(s)return await t.vault.save(s),s}}async filePresent(t){try{return this.filesystem.existsSync(t)&&this.filesystem.statSync(t).isFile()&&(await this.filesystem.readFile(t)).byteLength>0}catch{return!1}}unmount(t){this.filesystem.existsSync(t)&&this.filesystem.statSync(t).isFile()&&this.filesystem.unlinkSync(t)}}function tbe(e,t){if(e==="canonical-lines")return t.replaceAll("\r",`
|
|
1915
1915
|
`);if(e==="kitty-key-events"){if(/^[^\u0000-\u001f\u007f]+$/u.test(t))return[...t].map(r=>`\x1B[${r.codePointAt(0)};1:2u`).join("");if(t==="\r")return"\x1B[13;1:2u";if(t===" ")return"\x1B[9;1:2u"}return t}function rbe(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function nbe(e,t){const r=t.split("/").filter(Boolean);let n="";for(const s of r.slice(0,-1)){if(n+=`/${s}`,e.existsSync(n)){if(!e.statSync(n).isDirectory())throw new Error(`Private file parent is not a directory: ${n}`);continue}e.mkdirSync(n),e.chmodSync?.(n,448)}}function sbe(e){return new c6({databaseName:Qye,storeName:Jye,primaryKey:e,backupKey:`${e}-backup`,minimumBytes:1,maximumBytes:YF})}function SN(e,t){return e==="default"?t:`${e}-${t}`}const EN="browser-substrate-dependency-plan",kN=1;function ibe(e){if(!ma(e)||typeof e.url!="string"||!e.url.startsWith("/")||e.url.startsWith("//"))return!1;const t=e.artifact;return ma(t)&&typeof t.role=="string"&&typeof t.mediaType=="string"&&typeof t.digest=="string"&&/^sha256:[0-9a-f]{64}$/u.test(t.digest)&&(t.archive==="tar"||t.archive==="tar+gzip"||t.archive==="zip")&&[t.bytes,t.expandedBytes,t.files].every(r=>Number.isSafeInteger(r)&&r>=0)}const ih=/^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/u;function AN(e){if(!ma(e)||e.kind!==EN||e.version!==kN)throw new Error("The dependency plan has an unsupported shape or version.");if(typeof e.key!="string"||!e.key)throw new Error("The dependency plan has no key.");if(typeof e.command!="string")throw new Error("The dependency plan names no install command.");if(typeof e.resolver!="string")throw new Error("The dependency plan names no resolver.");const t=e.packages;if(!Array.isArray(t))throw new Error("The dependency plan lists no packages.");for(const a of t)if(!ma(a)||typeof a.name!="string"||!a.name||typeof a.version!="string"||!a.version||typeof a.tarball!="string"||!a.tarball||a.integrity!==void 0&&(typeof a.integrity!="string"||!/^sha(?:1|256|384|512)-[A-Za-z0-9+/=]+$/u.test(a.integrity))||a.placed!==void 0&&typeof a.placed!="boolean"||a.linuxX64!==void 0&&typeof a.linuxX64!="boolean"||a.pack!==void 0&&!ibe(a.pack))throw new Error("The dependency plan lists a malformed package.");const r=e.links;if(!Array.isArray(r))throw new Error("The dependency plan lists no links.");for(const a of r)if(!ma(a)||typeof a.path!="string"||!ih.test(a.path)||!Number.isInteger(a.package)||a.package<0||a.package>=t.length)throw new Error("The dependency plan lists a malformed link.");const n=e.instances??[];if(!Array.isArray(n))throw new Error("The dependency plan lists malformed instances.");const s=new Set;for(const a of n){if(!ma(a)||!Number.isInteger(a.link)||a.link<0||a.link>=r.length||!Array.isArray(a.dependencies))throw new Error("The dependency plan lists a malformed instance.");if(s.has(a.link))throw new Error("The dependency plan lists an instance twice.");s.add(a.link);const o=new Set;for(const l of a.dependencies){if(!ma(l)||typeof l.slot!="string"||!l.slot||typeof l.request!="string"||!l.request||l.kind!=="runtime"&&l.kind!=="peer"||typeof l.optional!="boolean")throw new Error("The dependency plan lists a malformed dependency binding.");if(o.has(l.slot))throw new Error("The dependency plan lists a dependency slot twice.");o.add(l.slot);const c=l.target;if(c!==null&&(!ma(c)||"link"in c=="workspace"in c))throw new Error("The dependency plan lists a malformed dependency target.");if(c!==null&&"link"in c&&(!Number.isInteger(c.link)||c.link<0||c.link>=r.length))throw new Error("The dependency plan points at a missing package instance.");if(c!==null&&"workspace"in c&&(typeof c.workspace!="string"||!ih.test(c.workspace)))throw new Error("The dependency plan points at a malformed workspace.")}}const i=e.entries??[];if(!Array.isArray(i))throw new Error("The dependency plan lists no entries.");for(const a of i)if(!ma(a)||typeof a.path!="string"||!ih.test(a.path)||typeof a.content!="string")throw new Error("The dependency plan lists a malformed entry.");for(const a of["bins","aliases"]){const o=e[a];if(!Array.isArray(o))throw new Error(`The dependency plan lists no ${a}.`);for(const l of o)if(!ma(l)||typeof l.path!="string"||!ih.test(l.path)||typeof l.target!="string"||!ih.test(l.target)||a==="aliases"&&l.coordinate!==void 0&&(typeof l.coordinate!="string"||!l.coordinate))throw new Error(`The dependency plan lists a malformed ${a.slice(0,-1)}.`)}return{kind:EN,version:kN,key:e.key,command:e.command,resolver:e.resolver,packages:t.map(a=>({name:a.name,version:a.version,tarball:a.tarball,...a.integrity!==void 0?{integrity:a.integrity}:{},...a.placed!==void 0?{placed:a.placed}:{},...a.linuxX64!==void 0?{linuxX64:a.linuxX64}:{},...a.pack!==void 0?{pack:{url:a.pack.url,artifact:{...a.pack.artifact}}}:{}})),links:r.map(a=>({path:a.path,package:a.package})),instances:n.map(a=>({link:a.link,dependencies:a.dependencies.map(o=>({slot:o.slot,request:o.request,kind:o.kind,optional:o.optional,target:o.target===null?null:"link"in o.target?{link:o.target.link}:{workspace:o.target.workspace}}))})),bins:e.bins.map(a=>({path:a.path,target:a.target})),aliases:e.aliases.map(a=>({path:a.path,target:a.target,...a.coordinate!==void 0?{coordinate:a.coordinate}:{}})),entries:i.map(a=>({path:a.path,content:a.content}))}}function abe(e){if(!ma(e)||typeof e.url!="string"||typeof e.key!="string"||!e.key||!Number.isInteger(e.packages)||!Number.isInteger(e.links))throw new Error("The image manifest's dependencies block is malformed.");return{url:e.url,key:e.key,packages:e.packages,links:e.links}}function ma(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const CN="browser-substrate-image",TN=1,NN="/_registry",obe=["pids","pids.identity","logs","tls","consumers","instance.json","stopped.json","booting.json","foreground-run.json","last-use.json","proxy.json","proxy-env.json","proxy-starting.json",".locks","world.env"];function $N(e){return`/substrate/${e}.image.json`}function lbe(e){return/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(e)}function RN(e){if(!Gn(e)||e.kind!==CN||e.version!==TN)throw new Error("The image manifest has an unsupported shape or version.");if(typeof e.name!="string"||!lbe(e.name))throw new Error("The image manifest names no valid image.");if(e.project!==void 0&&(typeof e.project!="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(e.project)))throw new Error("The image manifest's project is not a valid project identity.");const t=e.archive;if(!Gn(t)||typeof t.url!="string"||typeof t.blobs!="string"||typeof t.integrity!="string"||!/^sha256-[A-Za-z0-9+/]+=*$/u.test(t.integrity)||typeof t.entries!="number"||typeof t.fileBytes!="number")throw new Error("The image manifest's archive is incomplete.");const r=e.setup;if(!Gn(r)||!["dockerfile","manifests","image","compose"].includes(r.kind)||typeof r.source!="string"||!Array.isArray(r.ports)||!r.ports.every(u=>Number.isInteger(u)&&u>0&&u<65536)||typeof r.playground!="boolean"||r.browserTests!==void 0&&r.browserTests!==!0||r.install!==void 0&&typeof r.install!="string"||r.build!==void 0&&typeof r.build!="string"||r.dev!==void 0&&typeof r.dev!="string"||r.directory!==void 0&&typeof r.directory!="string")throw new Error("The image manifest's setup is incomplete.");const n=r.image;if(r.kind==="image"&&(!Gn(n)||typeof n.command!="string"||typeof n.workdir!="string"||!Gn(n.env)))throw new Error("The image manifest's prebuilt image is incomplete.");const s=Gn(e.settings)?e.settings:{};for(const u of["sandboxOrigin","relayOrigin","artifactBaseUrl"])if(s[u]!==void 0&&typeof s[u]!="string")throw new Error(`The image manifest's ${u} must be a string.`);if(typeof e.builtAt!="string")throw new Error("The image manifest carries no build time.");const i=e.preparation;if(i!==void 0&&(!Gn(i)||!["none","host"].includes(i.location)||i.engine!==void 0&&!["node-host","docker"].includes(i.engine)||i.installObserved!==void 0&&typeof i.installObserved!="boolean"||i.location==="none"&&(i.engine!==void 0||i.installObserved===!0)))throw new Error("The image manifest's execution preparation is malformed.");const a=e.dev;if(a!==void 0&&(!Gn(a)||typeof a.eventsUrl!="string"||a.startupUrl!==void 0&&(typeof a.startupUrl!="string"||!a.startupUrl.startsWith("/substrate/"))))throw new Error("The image manifest's dev block is malformed.");const o=e.rolldown;if(o!==void 0&&(!Gn(o)||typeof o.version!="string"||typeof o.url!="string"||!o.url.startsWith("/substrate/")))throw new Error("The image manifest's rolldown binding is malformed.");const l=e.registry;if(l!==void 0&&(!Gn(l)||l.path!==NN||!Array.isArray(l.scopes)||!l.scopes.every(u=>typeof u=="string"&&/^@[a-z0-9][a-z0-9._-]*$/u.test(u))||!Array.isArray(l.names)||!l.names.every(u=>typeof u=="string"&&/^[a-z0-9][a-z0-9._-]*$/u.test(u))))throw new Error("The image manifest's registry is malformed.");const c=e.dependencies===void 0?void 0:abe(e.dependencies);return{kind:CN,version:TN,name:e.name,...typeof e.project=="string"?{project:e.project}:{},...o!==void 0?{rolldown:{version:String(o.version),url:String(o.url)}}:{},...e.packs!==void 0?{packs:yge(e.packs)}:{},...e.layers!==void 0?{layers:hge(e.layers)}:{},...e.warm!==void 0?{warm:gge(e.warm)}:{},...e.caches!==void 0?{caches:pge(e.caches)}:{},...e.startup!==void 0?{startup:ube(e.startup)}:{},archive:{url:t.url,blobs:t.blobs,integrity:t.integrity,entries:t.entries,fileBytes:t.fileBytes},setup:{kind:r.kind,source:r.source,...r.install!==void 0?{install:r.install}:{},...r.build!==void 0?{build:r.build}:{},...r.dev!==void 0?{dev:r.dev}:{},...typeof r.devScript=="string"?{devScript:r.devScript}:{},...typeof r.directory=="string"?{directory:r.directory}:{},...typeof r.target=="string"?{target:r.target}:{},...typeof r.context=="string"?{context:r.context}:{},...Array.isArray(r.watch)?{watch:r.watch}:{},...Gn(n)?{image:{command:n.command,workdir:n.workdir,env:{...n.env}}}:{},ports:[...r.ports],playground:r.playground,...r.browserTests===!0?{browserTests:!0}:{}},settings:{...s.sandboxOrigin!==void 0?{sandboxOrigin:s.sandboxOrigin}:{},...s.relayOrigin!==void 0?{relayOrigin:s.relayOrigin}:{},...s.artifactBaseUrl!==void 0?{artifactBaseUrl:s.artifactBaseUrl}:{}},builtAt:e.builtAt,...i!==void 0?{preparation:{...i}}:{},...Gn(a)?{dev:{eventsUrl:a.eventsUrl,...typeof a.startupUrl=="string"?{startupUrl:a.startupUrl}:{}}}:{},...Gn(l)?{registry:{path:NN,scopes:[...l.scopes],names:[...l.names]}}:{},...c!==void 0?{dependencies:c}:{},...Gn(e.world)?{world:cbe(e.world)}:{}}}function cbe(e){const t=e.archive;if(typeof e.name!="string"||typeof e.config!="string"||!Gn(t)||typeof t.url!="string"||typeof t.blobs!="string"||typeof t.integrity!="string")throw new Error("The image manifest's world is malformed.");const r=e.dependencies;if(e.environmentOutputFlag!==void 0&&e.environmentOutputFlag!=="--env-file"&&e.environmentOutputFlag!=="--env-out")throw new Error("The image manifest's World environment output flag is unsupported.");return{name:e.name,...e.environmentOutputFlag?{environmentOutputFlag:e.environmentOutputFlag}:{},config:e.config,archive:{url:t.url,blobs:t.blobs,integrity:t.integrity,entries:Number(t.entries??0),fileBytes:Number(t.fileBytes??0)},...Gn(r)&&typeof r.url=="string"&&typeof r.key=="string"?{dependencies:{url:r.url,key:r.key,packages:Number(r.packages??0),links:Number(r.links??0)}}:{}}}function Gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ube(e){if(!Gn(e)||typeof e.url!="string"||!/^\/substrate\/[A-Za-z0-9._-]+\.startup\.json$/u.test(e.url)||!Number.isSafeInteger(e.ranges)||e.ranges<0)throw new Error("The image manifest's startup set is malformed.");const t=e.streams;if(t!==void 0&&(!Array.isArray(t)||t.length>8||!t.every(r=>Gn(r)&&typeof r.url=="string"&&/^\/substrate\/[A-Za-z0-9._-]+\.startup\/[a-f0-9]{64}\.bin$/u.test(r.url)&&Number.isSafeInteger(r.bytes)&&r.bytes>=0&&Number.isSafeInteger(r.ranges)&&r.ranges>=0)))throw new Error("The image manifest's startup streams are malformed.");return{url:e.url,ranges:e.ranges,...t?{streams:t.map(r=>({url:r.url,bytes:r.bytes,ranges:r.ranges}))}:{}}}function fbe(e){return{version:1,preparation:e?.location??"unknown",phases:{install:e?.installObserved?["host"]:[],build:e?.location==="host"?["host"]:[],devServer:[],agentTools:[]}}}function Fa(e,t,r){e.phases[t].includes(r)||e.phases[t].push(r)}function dbe(e,t){t?.location==="host"?(e.preparation="host",Fa(e,"build","host"),t.installObserved&&Fa(e,"install","host")):!t&&e.preparation!=="host"&&(e.preparation="unknown")}function hbe(e){return/(?:^|[;&|]\s*|\s)(?:npm|pnpm|yarn|pip3?|uv)\s+(?:install|ci|sync|pip\s+install)(?:\s|$)/u.test(e)}function pbe(e){const t=n=>n.length===0?"not run yet":n.map(s=>s==="browser"?"in this browser":"on a host").join(" and "),r=e.preparation==="none"?"no host prepared the image":e.preparation==="host"?"a host prepared the image":"the image's preparation is unknown";return`Where it ran: install ${t(e.phases.install)}, build ${t(e.phases.build)}, dev server ${t(e.phases.devServer)}, agent tools ${t(e.phases.agentTools)}; ${r}`}const Gx="valkey-server",mbe=["redis","library/redis","valkey","valkey/valkey","redis/redis-stack-server"],KF="nginx",gbe=["nginx","library/nginx"],ybe="/usr/share/nginx/html",bbe=80,Vx="/etc/nginx/conf.d/default.conf",wbe={html:"text/html; charset=utf-8",htm:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",json:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",map:"application/json",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",wasm:"application/wasm",pdf:"application/pdf",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",webmanifest:"application/manifest+json",rss:"application/rss+xml",atom:"application/atom+xml"};function vbe(e){e.registerProgram(KF,(t,r)=>xbe(e,t,r))}async function xbe(e,t,r){if(t.includes("-v")||t.includes("-V")){const a=`nginx version: nginx/1.27.0 (browser substrate)
|
|
1916
1916
|
`;return r.onStderr?.(a),{stdout:"",stderr:a,exitCode:0}}const n=(r.cwd??"/").replace(/\/+$/u,""),s=await Sbe(e,n);if(t.includes("-t")){const a=`nginx: the configuration file ${n}${Vx} syntax is ok
|
|
1917
1917
|
nginx: configuration file ${n}${Vx} test is successful
|