@jeevanand/agent-browserbox-runtime 0.2.0 → 0.3.0

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.
@@ -1,4 +1,4 @@
1
- import{a as e,c as t,i as n,l as r,n as i,s as a}from"./instance-6eYt0v1_.js";function o(e,t){return globalThis.crossOriginIsolated&&e.setAttribute(`credentialless`,``),e}var s=`https://cdn.jsdelivr.net/pyodide/v0.29.0/full/`,c=[`pyodide.js`,`pyodide.asm.js`,`pyodide.asm.wasm`,`python_stdlib.zip`,`pyodide-lock.json`],l=`bbx-packs`,u=`// BrowserBox sandbox runtime. This file is shipped as text and started as a
1
+ import{d as e,l as t,o as n,r,s as i,u as a}from"./instance-Cu6oky-A.js";function o(e,t){return globalThis.crossOriginIsolated&&e.setAttribute(`credentialless`,``),e}var s=`https://cdn.jsdelivr.net/pyodide/v0.29.0/full/`,c=[`pyodide.js`,`pyodide.asm.js`,`pyodide.asm.wasm`,`python_stdlib.zip`,`pyodide-lock.json`],l=`bbx-packs`,u=`// BrowserBox sandbox runtime. This file is shipped as text and started as a
2
2
  // Worker inside an opaque-origin iframe, so it must stay dependency-free JS.
3
3
  /* eslint-disable */
4
4
  let port;
@@ -319,4 +319,4 @@ async function runWasi(m, out, err) {
319
319
  }
320
320
  return { exitCode };
321
321
  }
322
- `,d=`python.packages`,f=262144,p=class{os;proc;#e;#t;#n=1;#r=!1;#i=new Map;#a=null;constructor(e,t){this.os=e,this.proc=e.procs.spawn({name:t.name,kind:`sandbox`,ppid:t.ppid,detail:t.network?`isolated worker · network allowed`:`isolated worker · no network`,onKill:()=>this.#o()});let n=this.#e=o(document.createElement(`iframe`));n.setAttribute(`sandbox`,`allow-scripts`),n.style.display=`none`,n.src=new URL(t.network?`sandbox-net.html`:`sandbox.html`,a).href,this.#t=new Promise((e,t)=>{let r=setTimeout(()=>t(Error(`sandbox failed to start`)),15e3),i=t=>{if(t.source===n.contentWindow){if(t.data?.type===`hello`){let t=new MessageChannel;t.port1.onmessage=n=>{n.data?.type===`ready`&&(clearTimeout(r),t.port1.onmessage=e=>this.#i.get(e.data.id)?.(e.data),e(t.port1))},n.contentWindow.postMessage({type:`boot`,src:u},`*`,[t.port2])}else t.data?.type===`crash`&&this.#a?.(String(t.data.error))}};addEventListener(`message`,i),this.proc.signal.addEventListener(`abort`,()=>{removeEventListener(`message`,i),clearTimeout(r),t(Error(`sandbox was killed`))})}),this.#t.catch(()=>void 0),document.body.append(n)}get alive(){return!this.#r}#o(){this.#r=!0,this.#e.remove()}dispose(){this.#r||this.os.procs.exit(this.proc.pid)}async run(e,t={}){let n=performance.now(),i=t.cwd??`/`,a=``,o=``,s=e=>{let t=performance.now()-n;return this.os.procs.account(this.proc.pid,t),{ok:!1,stdout:a,stderr:o,ms:t,...e}},c;try{c=await this.#t}catch(e){return s({error:e.message})}let l=this.#n++;return this.os.procs.update(this.proc.pid,{state:`running`}),new Promise(n=>{let u=(e,r=!1)=>{clearTimeout(m),this.#i.delete(l),this.#a=null,t.signal?.removeEventListener(`abort`,d),this.proc.signal.removeEventListener(`abort`,p),r?this.dispose():this.os.procs.update(this.proc.pid,{state:`idle`}),n(s(e))},d=()=>u({error:`aborted`},!0),p=()=>u({error:`sandbox was killed`}),m=setTimeout(()=>u({error:`timed out after ${t.timeoutMs??3e4} ms`,timedOut:!0},!0),t.timeoutMs??3e4);t.signal?.addEventListener(`abort`,d),this.proc.signal.addEventListener(`abort`,p),this.#a=e=>u({error:e},!0),this.#i.set(l,e=>{e.type===`stdout`?(a.length<f&&(a+=e.data),t.onStdout?.(e.data)):e.type===`stderr`?(o.length<f&&(o+=e.data),t.onStderr?.(e.data)):e.type===`progress`?t.onProgress?.({label:e.label,loaded:e.loaded,total:e.total}):e.type===`rpc`?this.#s(i,e.method,e.params).then(t=>c.postMessage({type:`rpc-result`,rid:e.rid,value:t}),t=>c.postMessage({type:`rpc-result`,rid:e.rid,error:t.message})):e.type===`done`&&(async()=>{if(e.error)return u({error:e.error});try{for(let t of e.result?.files??[])await this.os.fs.writeFile(r(i,t.path),t.data)}catch(e){return u({error:`could not write files back: ${e.message}`})}let t=e.result?.exitCode;u({ok:t===void 0||t===0,value:e.result?.value,exitCode:t,response:e.result?.response})})()}),c.postMessage({id:l,...e})})}async#s(e,t,n){let i=this.os.fs,a=(i=0)=>{if(typeof n[i]!=`string`)throw Error(`${t}: path must be a string`);return r(e,n[i])};switch(t){case`fs.readText`:return i.readText(a());case`fs.readFile`:return i.readFile(a());case`fs.writeFile`:return i.writeFile(a(),n[1]);case`fs.appendFile`:return i.appendFile(a(),n[1]);case`fs.readdir`:return i.readdir(a());case`fs.exists`:return i.exists(a());case`fs.mkdir`:return i.mkdir(a());case`fs.rm`:return i.rm(a(),{recursive:!0});case`fs.glob`:return i.glob(String(n[0]),e);default:throw Error(`unknown sandbox call: ${t}`)}}};async function m(e,t,n={}){let r=new p(e,{name:`js`,network:n.network,ppid:n.ppid});try{return await r.run({op:`js`,code:t,args:n.args,env:n.env},n)}finally{r.dispose()}}async function h(e,t,n={}){let r=new p(e,{name:n.name??`wasm`,ppid:n.ppid});try{return await r.run({op:`wasm`,wasm:t,args:n.args,stdin:n.stdin,name:n.name},n)}finally{r.dispose()}}var g=null,_=!1;async function v(){try{let e=await caches.open(l),t=await Promise.all(c.map(async t=>{let n=await e.match(s+t);return n?{path:t,data:new Uint8Array(await n.arrayBuffer())}:null}));return t.every(e=>e!==null)?t:void 0}catch{return}}async function y(e,t){let n=[],r=25165824;for await(let i of e.fs.walk(t,{maxDepth:6}))if(!(i.kind!==`file`||i.size>8388608||i.size>r)&&(r-=i.size,n.push({path:i.path.slice(t===`/`?1:t.length+1),data:await e.fs.readFile(i.path)}),n.length>=400))break;return n}async function b(e,t,n={}){g?.alive||(g=new p(e,{name:`python`,network:!1}),_=!1);let r=n.cwd??`/tmp`,i=await y(e,r),a=!_,o=a?await v():void 0,c=a?e.settings.get(d,[]):[],l=[...new Set([...c,...n.packages??[]])],u=await g.run({op:`python`,code:t,packages:l.length?l:void 0,files:i,pyodideUrl:s,env:n.env,runtime:o},{timeoutMs:18e4,...n,cwd:r});return _=g.alive&&!u.timedOut,u}var x=new Map;async function S(e,t,n,r,i={}){let a=e=>({ok:!e,stdout:``,stderr:``,ms:0,error:e});if(t===`stop`)return x.get(n)?.dispose(),x.delete(n),a();if(t===`load`){x.get(n)?.dispose();let t=new p(e,{name:`backend :${n}`,network:r.network,ppid:r.ppid});x.set(n,t);let a=await t.run({op:`server-load`,code:r.code??``,env:r.env},{...i,timeoutMs:15e3});return a.ok||(t.dispose(),x.delete(n)),a}let o=x.get(n);return!o?.alive||!r.req?a(`backend not loaded`):o.run({op:`server-request`,req:r.req,origin:r.origin??`http://localhost`},{...i,timeoutMs:i.timeoutMs??3e4})}var C=`SharedWorker`in globalThis,w=n(i(location.search)),T=null;function E(){if(C)return new SharedWorker(new URL(new URL(`main-DzFuvDws.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w}).port;T??=new Worker(new URL(new URL(`main-DzFuvDws.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w});let e=new MessageChannel;return T.postMessage({type:`connect`},[e.port2]),e.port1}var D=`bbx-window-${crypto.randomUUID()}`;navigator.locks?.request(D,()=>new Promise(()=>void 0));var O=new t(Promise.resolve({port:E(),lock:D,shared:C}),`host`),k=new Map;O.handle({"host.run":async(e,t,n,r)=>{let i=new AbortController;k.set(e,i);let a=await O.handle({}),o={...r,signal:i.signal,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t}),onProgress:t=>a.emit(`host:progress`,{runId:e,...t}),env:n.env};try{return t===`js`?await m(O,n.code,{...o,args:n.args,network:n.network,ppid:n.ppid}):t===`python`?await b(O,n.code,{...o,packages:n.packages}):await h(O,n.wasm,{...o,args:n.args,stdin:n.stdin,name:n.name,ppid:n.ppid})}finally{k.delete(e)}},"host.backend":async(e,t,n,r,i)=>{let a=await O.handle({});return S(O,t,n,r,{...i,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t})})}}).then(e=>e.on(`host:abort`,e=>k.get(e)?.abort()));var A=new Set([location.origin,...e]),j=!1;addEventListener(`message`,e=>{if(e.source!==parent||e.data?.type!==`bbx:connect`)return;if(!A.has(e.origin))return parent.postMessage({type:`bbx:refused`},e.origin);let t=typeof e.data.req==`number`?e.data.req:null;t===null&&j||(t===null&&(j=!0),parent.postMessage({type:`bbx:port`,req:t,lock:D,shared:C},e.origin,[E()]))}),parent!==window&&parent.postMessage({type:`bbx:ready`},`*`);
322
+ `,d=`python.packages`,f=262144,p=class{os;proc;#e;#t;#n=1;#r=!1;#i=new Map;#a=null;constructor(e,n){this.os=e,this.proc=e.procs.spawn({name:n.name,kind:`sandbox`,ppid:n.ppid,detail:n.network?`isolated worker · network allowed`:`isolated worker · no network`,onKill:()=>this.#o()});let r=this.#e=o(document.createElement(`iframe`));r.setAttribute(`sandbox`,`allow-scripts`),r.style.display=`none`,r.src=new URL(n.network?`sandbox-net.html`:`sandbox.html`,t).href,this.#t=new Promise((e,t)=>{let n=setTimeout(()=>t(Error(`sandbox failed to start`)),15e3),i=t=>{if(t.source===r.contentWindow){if(t.data?.type===`hello`){let t=new MessageChannel;t.port1.onmessage=r=>{r.data?.type===`ready`&&(clearTimeout(n),t.port1.onmessage=e=>this.#i.get(e.data.id)?.(e.data),e(t.port1))},r.contentWindow.postMessage({type:`boot`,src:u},`*`,[t.port2])}else t.data?.type===`crash`&&this.#a?.(String(t.data.error))}};addEventListener(`message`,i),this.proc.signal.addEventListener(`abort`,()=>{removeEventListener(`message`,i),clearTimeout(n),t(Error(`sandbox was killed`))})}),this.#t.catch(()=>void 0),document.body.append(r)}get alive(){return!this.#r}#o(){this.#r=!0,this.#e.remove()}dispose(){this.#r||this.os.procs.exit(this.proc.pid)}async run(t,n={}){let r=performance.now(),i=n.cwd??`/`,a=``,o=``,s=e=>{let t=performance.now()-r;return this.os.procs.account(this.proc.pid,t),{ok:!1,stdout:a,stderr:o,ms:t,...e}},c;try{c=await this.#t}catch(e){return s({error:e.message})}let l=this.#n++;return this.os.procs.update(this.proc.pid,{state:`running`}),new Promise(r=>{let u=(e,t=!1)=>{clearTimeout(m),this.#i.delete(l),this.#a=null,n.signal?.removeEventListener(`abort`,d),this.proc.signal.removeEventListener(`abort`,p),t?this.dispose():this.os.procs.update(this.proc.pid,{state:`idle`}),r(s(e))},d=()=>u({error:`aborted`},!0),p=()=>u({error:`sandbox was killed`}),m=setTimeout(()=>u({error:`timed out after ${n.timeoutMs??3e4} ms`,timedOut:!0},!0),n.timeoutMs??3e4);n.signal?.addEventListener(`abort`,d),this.proc.signal.addEventListener(`abort`,p),this.#a=e=>u({error:e},!0),this.#i.set(l,t=>{t.type===`stdout`?(a.length<f&&(a+=t.data),n.onStdout?.(t.data)):t.type===`stderr`?(o.length<f&&(o+=t.data),n.onStderr?.(t.data)):t.type===`progress`?n.onProgress?.({label:t.label,loaded:t.loaded,total:t.total}):t.type===`rpc`?this.#s(i,t.method,t.params).then(e=>c.postMessage({type:`rpc-result`,rid:t.rid,value:e}),e=>c.postMessage({type:`rpc-result`,rid:t.rid,error:e.message})):t.type===`done`&&(async()=>{if(t.error)return u({error:t.error});try{for(let n of t.result?.files??[])await this.os.fs.writeFile(e(i,n.path),n.data)}catch(e){return u({error:`could not write files back: ${e.message}`})}let n=t.result?.exitCode;u({ok:n===void 0||n===0,value:t.result?.value,exitCode:n,response:t.result?.response})})()}),c.postMessage({id:l,...t})})}async#s(t,n,r){let i=this.os.fs,a=(i=0)=>{if(typeof r[i]!=`string`)throw Error(`${n}: path must be a string`);return e(t,r[i])};switch(n){case`fs.readText`:return i.readText(a());case`fs.readFile`:return i.readFile(a());case`fs.writeFile`:return i.writeFile(a(),r[1]);case`fs.appendFile`:return i.appendFile(a(),r[1]);case`fs.readdir`:return i.readdir(a());case`fs.exists`:return i.exists(a());case`fs.mkdir`:return i.mkdir(a());case`fs.rm`:return i.rm(a(),{recursive:!0});case`fs.glob`:return i.glob(String(r[0]),t);default:throw Error(`unknown sandbox call: ${n}`)}}};async function m(e,t,n={}){let r=new p(e,{name:`js`,network:n.network,ppid:n.ppid});try{return await r.run({op:`js`,code:t,args:n.args,env:n.env},n)}finally{r.dispose()}}async function h(e,t,n={}){let r=new p(e,{name:n.name??`wasm`,ppid:n.ppid});try{return await r.run({op:`wasm`,wasm:t,args:n.args,stdin:n.stdin,name:n.name},n)}finally{r.dispose()}}var g=null,_=!1;async function v(){try{let e=await caches.open(l),t=await Promise.all(c.map(async t=>{let n=await e.match(s+t);return n?{path:t,data:new Uint8Array(await n.arrayBuffer())}:null}));return t.every(e=>e!==null)?t:void 0}catch{return}}async function y(e,t){let n=[],r=25165824;for await(let i of e.fs.walk(t,{maxDepth:6}))if(!(i.kind!==`file`||i.size>8388608||i.size>r)&&(r-=i.size,n.push({path:i.path.slice(t===`/`?1:t.length+1),data:await e.fs.readFile(i.path)}),n.length>=400))break;return n}async function b(e,t,n={}){g?.alive||(g=new p(e,{name:`python`,network:!1}),_=!1);let r=n.cwd??`/tmp`,i=await y(e,r),a=!_,o=a?await v():void 0,c=a?e.settings.get(d,[]):[],l=[...new Set([...c,...n.packages??[]])],u=await g.run({op:`python`,code:t,packages:l.length?l:void 0,files:i,pyodideUrl:s,env:n.env,runtime:o},{timeoutMs:18e4,...n,cwd:r});return _=g.alive&&!u.timedOut,u}var x=new Map;async function S(e,t,n,r,i={}){let a=e=>({ok:!e,stdout:``,stderr:``,ms:0,error:e});if(t===`stop`)return x.get(n)?.dispose(),x.delete(n),a();if(t===`load`){x.get(n)?.dispose();let t=new p(e,{name:`backend :${n}`,network:r.network,ppid:r.ppid});x.set(n,t);let a=await t.run({op:`server-load`,code:r.code??``,env:r.env},{...i,timeoutMs:15e3});return a.ok||(t.dispose(),x.delete(n)),a}let o=x.get(n);return!o?.alive||!r.req?a(`backend not loaded`):o.run({op:`server-request`,req:r.req,origin:r.origin??`http://localhost`},{...i,timeoutMs:i.timeoutMs??3e4})}var C=`SharedWorker`in globalThis,w=n(r(location.search)),T=null;function E(){if(C)return new SharedWorker(new URL(new URL(`main-CQvaEX7y.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w}).port;T??=new Worker(new URL(new URL(`main-CQvaEX7y.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w});let e=new MessageChannel;return T.postMessage({type:`connect`},[e.port2]),e.port1}var D=`bbx-window-${crypto.randomUUID()}`;navigator.locks?.request(D,()=>new Promise(()=>void 0));var O=new a(Promise.resolve({port:E(),lock:D,shared:C}),`host`),k=new Map;O.handle({"host.run":async(e,t,n,r)=>{let i=new AbortController;k.set(e,i);let a=await O.handle({}),o={...r,signal:i.signal,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t}),onProgress:t=>a.emit(`host:progress`,{runId:e,...t}),env:n.env};try{return t===`js`?await m(O,n.code,{...o,args:n.args,network:n.network,ppid:n.ppid}):t===`python`?await b(O,n.code,{...o,packages:n.packages}):await h(O,n.wasm,{...o,args:n.args,stdin:n.stdin,name:n.name,ppid:n.ppid})}finally{k.delete(e)}},"host.backend":async(e,t,n,r,i)=>{let a=await O.handle({});return S(O,t,n,r,{...i,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t})})}}).then(e=>e.on(`host:abort`,e=>k.get(e)?.abort()));var A=new Set([location.origin,...i]),j=!1;addEventListener(`message`,e=>{if(e.source!==parent||e.data?.type!==`bbx:connect`)return;if(!A.has(e.origin))return parent.postMessage({type:`bbx:refused`},e.origin);let t=typeof e.data.req==`number`?e.data.req:null;t===null&&j||(t===null&&(j=!0),parent.postMessage({type:`bbx:port`,req:t,lock:D,shared:C},e.origin,[E()]))}),parent!==window&&parent.postMessage({type:`bbx:ready`},`*`);
@@ -1,2 +1,2 @@
1
- import{o as e,r as t,t as n}from"./path-DGG-Mxbd.js";import{t as r}from"./bundle-qe7w2kMM.js";import{t as i}from"./html-BggiUWIu.js";const a=/\.(tsx?|jsx|mts|cts)$/,o=/* @__PURE__ */ new Set([`package.json`,`package-lock.json`,`tsconfig.json`,`jsconfig.json`,`vite.config.ts`,`vite.config.js`,`AGENTS.md`,`CLAUDE.md`,`README.md`]),s=/* @__PURE__ */ new Set([`node_modules`,`.git`,`dist`,`.bbx`]);async function c(c,l){let u=/* @__PURE__ */ new Map,d=[],f=await c.readText(e(l,`package.json`)).then(e=>JSON.parse(e),()=>null),p=await c.readText(e(l,`tsconfig.json`)).then(e=>JSON.parse(e.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g,``).replace(/,(\s*[}\]])/g,`$1`)),()=>null),m={};for(let t of[`.env`,`.env.production`]){let n=await c.readText(e(l,t)).catch(()=>``);for(let e of n.split(`
1
+ import{o as e,r as t,t as n}from"./path-DGG-Mxbd.js";import{t as r}from"./bundle-CXrJ5BHI.js";import{t as i}from"./html-Bd3_N2aN.js";const a=/\.(tsx?|jsx|mts|cts)$/,o=/* @__PURE__ */ new Set([`package.json`,`package-lock.json`,`tsconfig.json`,`jsconfig.json`,`vite.config.ts`,`vite.config.js`,`AGENTS.md`,`CLAUDE.md`,`README.md`]),s=/* @__PURE__ */ new Set([`node_modules`,`.git`,`dist`,`.bbx`]);async function c(c,l){let u=/* @__PURE__ */ new Map,d=[],f=await c.readText(e(l,`package.json`)).then(e=>JSON.parse(e),()=>null),p=await c.readText(e(l,`tsconfig.json`)).then(e=>JSON.parse(e.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g,``).replace(/,(\s*[}\]])/g,`$1`)),()=>null),m={};for(let t of[`.env`,`.env.production`]){let n=await c.readText(e(l,t)).catch(()=>``);for(let e of n.split(`
2
2
  `)){let t=/^\s*((?:VITE_|PUBLIC_)\w+)\s*=\s*(.*?)\s*$/.exec(e);t&&(m[t[1]]=t[2].replace(/^(['"])(.*)\1$/,`$2`))}}let h=e=>r({fs:c,root:l,entry:e,target:`browser`,production:!0,env:m,pkg:f,tsconfig:p}),g=[],_=async e=>{for(let t of await c.readdir(e).catch(()=>[]))t.name.startsWith(`.`)||s.has(t.name)||(t.kind===`dir`?await _(t.path):g.length<2e3&&g.push(t.path))};await _(l);let v=[`server.ts`,`server.js`,`server.mjs`].find(t=>g.includes(e(l,t)))??null,y=g.filter(e=>/\.html?$/i.test(e)),b=async(e,t)=>{let n=await i(c,{root:l,htmlPath:e,path:`/`,port:0,runtime:!1,bundle:h});d.push(...n.errors),u.set(t,new TextEncoder().encode(n.html))};if(y.length)for(let e of y)await b(e,e.slice(l.length));else await b(null,`/index.html`);for(let e of g){let r=n(e);y.includes(e)||a.test(e)||o.has(r)||r===v||t(e)===`css`&&e.includes(`/src/`)||u.set(e.slice(l.length),await c.readFile(e))}return{files:u,errors:d,backend:v}}export{c as buildSite};
@@ -1 +1 @@
1
- import{a as e,c as t,n,o as r,r as i,s as a}from"./path-DGG-Mxbd.js";import{n as o,t as s}from"./npm-DF8ts_uH.js";import{u as c}from"./main-DzFuvDws.js";const l=[`.tsx`,`.ts`,`.jsx`,`.js`,`.mjs`,`.cjs`,`.json`,`.css`],u=/\.(png|jpe?g|gif|webp|avif|bmp|ico|svg|woff2?|ttf|otf|eot|mp3|wav|ogg|mp4|webm|pdf)$/i,d=/\.(txt|md|html|glsl|wgsl|vert|frag|csv)$/i;function f(e,t){if(t===`raw`)return`text`;if(t===`url`||t===`inline`)return`dataurl`;let n=i(e);return e.endsWith(`.module.css`)?`local-css`:n===`css`?`css`:n===`ts`||n===`mts`||n===`cts`?`ts`:n===`tsx`?`tsx`:n===`js`||n===`jsx`||n===`mjs`||n===`cjs`?`jsx`:n===`json`?`json`:n===`wasm`?`binary`:d.test(e)?`text`:u.test(e)?`dataurl`:`text`}const p=e=>{let t=e.location?`${e.location.file.replace(/^vfs:/,``)}:${e.location.line}:${e.location.column+1}: `:``,n=e.location?.lineText?`\n ${e.location.lineText.trim()}`:``;return`${t}${e.text}${n}`};async function m(i){let{fs:u,root:d}=i,m=new s(i.pkg??null,i.target===`browser`&&!i.production),h=i.fetcher??fetch,g=/* @__PURE__ */ new Set,_=i.tsconfig?.compilerOptions?.paths??{},v=t(d,i.tsconfig?.compilerOptions?.baseUrl??`.`),y=m.versions,b=i.tsconfig?.compilerOptions?.jsxImportSource??(y.preact&&!y.react?`preact`:`react`),x=async e=>(await u.stat(e).catch(()=>null))?.kind===`file`;async function S(e){if(await x(e))return e;for(let t of l)if(await x(e+t))return e+t;if(/\.jsx?$/.test(e)){for(let t of[`.ts`,`.tsx`])if(await x(e.replace(/\.jsx?$/,t)))return e.replace(/\.jsx?$/,t)}for(let t of l)if(await x(`${e}/index${t}`))return`${e}/index${t}`;return null}function C(e){let n=[];for(let[r,i]of Object.entries(_)){let a=r.indexOf(`*`);if(a<0?e!==r:!(e.startsWith(r.slice(0,a))&&e.endsWith(r.slice(a+1))))continue;let o=a<0?``:e.slice(a,e.length-(r.length-a-1));for(let e of i)n.push(t(v,e.replace(`*`,o)))}return!n.length&&e.startsWith(`@/`)&&n.push(r(d,`src`,e.slice(2))),n}let w={name:`bbx`,setup(i){i.onResolve({filter:/.*/},async i=>{let[o,s=``]=i.path.split(`?`);if(i.namespace===`npm`||/^https?:\/\//.test(o)){let e=i.namespace===`npm`?i.importer:void 0;return/^(https?:)?\/\/|^\.{0,2}\//.test(i.path)?{path:m.canonical(new URL(i.path,e).href),namespace:`npm`}:{path:m.url(i.path),namespace:`npm`}}let c,l=i.importer?.startsWith(`/`)?n(i.importer):i.resolveDir||d;if(o.startsWith(`./`)||o.startsWith(`../`)||o===`.`||o===`..`)c=[t(l,o)];else if(o.startsWith(`/`))c=e(d,o)&&d!==`/`?[a(o)]:[r(d,o)];else if(c=C(o),!c.length)return{path:m.url(i.path),namespace:`npm`};for(let t of c){if(!e(d,t))return{errors:[{text:`${i.path} is outside the project folder (${d})`}]};let n=await S(t);if(n)return{path:n,namespace:`vfs`,pluginData:{query:s}}}return{errors:[{text:`Could not find "${i.path}"${i.importer?` (imported by ${i.importer})`:``}`}]}}),i.onLoad({filter:/.*/,namespace:`vfs`},async e=>(g.add(e.path),{contents:await u.readFile(e.path),loader:f(e.path,e.pluginData?.query??``),resolveDir:n(e.path)})),i.onLoad({filter:/.*/,namespace:`npm`},async e=>({contents:await o(e.path,h),loader:/\.css(\?|$)/.test(new URL(e.path).pathname)?`css`:`js`}))}},T={MODE:i.production?`production`:`development`,DEV:!i.production,PROD:!!i.production,SSR:i.target===`server`,BASE_URL:`/`,...i.env},E=i.entry;try{let e=await(await c()).build({...typeof E==`string`?{entryPoints:[E]}:{stdin:{contents:E.contents,resolveDir:E.dir,sourcefile:E.name,loader:`tsx`}},bundle:!0,write:!1,outdir:`/out`,format:i.target===`server`?`iife`:`esm`,globalName:i.target===`server`?`__bbxServer`:void 0,platform:`browser`,target:`es2022`,jsx:`automatic`,jsxImportSource:b,define:{"process.env.NODE_ENV":i.production?`"production"`:`"development"`,"import.meta.env":JSON.stringify(T),...Object.fromEntries(Object.entries(T).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)]))},minify:!!i.production,logLevel:`silent`,charset:`utf8`,plugins:[w]}),t=t=>e.outputFiles?.find(e=>e.path.endsWith(t))?.text??``;return{js:t(`.js`),css:t(`.css`),errors:[],warnings:e.warnings.map(p),inputs:[...g]}}catch(e){let t=e;return{js:``,css:``,errors:t.errors?.length?t.errors.map(p):[e.message??String(e)],warnings:(t.warnings??[]).map(p),inputs:[...g]}}}async function h(e,t){let n=``;for(let t=0;t<e.length;t+=32768)n+=String.fromCharCode(...e.subarray(t,t+32768));return`data:${t};base64,${btoa(n)}`}export{h as n,m as t};
1
+ import{a as e,c as t,n,o as r,r as i,s as a}from"./path-DGG-Mxbd.js";import{n as o,t as s}from"./npm-DF8ts_uH.js";import{u as c}from"./main-CQvaEX7y.js";const l=[`.tsx`,`.ts`,`.jsx`,`.js`,`.mjs`,`.cjs`,`.json`,`.css`],u=/\.(png|jpe?g|gif|webp|avif|bmp|ico|svg|woff2?|ttf|otf|eot|mp3|wav|ogg|mp4|webm|pdf)$/i,d=/\.(txt|md|html|glsl|wgsl|vert|frag|csv)$/i;function f(e,t){if(t===`raw`)return`text`;if(t===`url`||t===`inline`)return`dataurl`;let n=i(e);return e.endsWith(`.module.css`)?`local-css`:n===`css`?`css`:n===`ts`||n===`mts`||n===`cts`?`ts`:n===`tsx`?`tsx`:n===`js`||n===`jsx`||n===`mjs`||n===`cjs`?`jsx`:n===`json`?`json`:n===`wasm`?`binary`:d.test(e)?`text`:u.test(e)?`dataurl`:`text`}const p=e=>{let t=e.location?`${e.location.file.replace(/^vfs:/,``)}:${e.location.line}:${e.location.column+1}: `:``,n=e.location?.lineText?`\n ${e.location.lineText.trim()}`:``;return`${t}${e.text}${n}`};async function m(i){let{fs:u,root:d}=i,m=new s(i.pkg??null,i.target===`browser`&&!i.production),h=i.fetcher??fetch,g=/* @__PURE__ */ new Set,_=i.tsconfig?.compilerOptions?.paths??{},v=t(d,i.tsconfig?.compilerOptions?.baseUrl??`.`),y=m.versions,b=i.tsconfig?.compilerOptions?.jsxImportSource??(y.preact&&!y.react?`preact`:`react`),x=async e=>(await u.stat(e).catch(()=>null))?.kind===`file`;async function S(e){if(await x(e))return e;for(let t of l)if(await x(e+t))return e+t;if(/\.jsx?$/.test(e)){for(let t of[`.ts`,`.tsx`])if(await x(e.replace(/\.jsx?$/,t)))return e.replace(/\.jsx?$/,t)}for(let t of l)if(await x(`${e}/index${t}`))return`${e}/index${t}`;return null}function C(e){let n=[];for(let[r,i]of Object.entries(_)){let a=r.indexOf(`*`);if(a<0?e!==r:!(e.startsWith(r.slice(0,a))&&e.endsWith(r.slice(a+1))))continue;let o=a<0?``:e.slice(a,e.length-(r.length-a-1));for(let e of i)n.push(t(v,e.replace(`*`,o)))}return!n.length&&e.startsWith(`@/`)&&n.push(r(d,`src`,e.slice(2))),n}let w={name:`bbx`,setup(i){i.onResolve({filter:/.*/},async i=>{let[o,s=``]=i.path.split(`?`);if(i.namespace===`npm`||/^https?:\/\//.test(o)){let e=i.namespace===`npm`?i.importer:void 0;return/^(https?:)?\/\/|^\.{0,2}\//.test(i.path)?{path:m.canonical(new URL(i.path,e).href),namespace:`npm`}:{path:m.url(i.path),namespace:`npm`}}let c,l=i.importer?.startsWith(`/`)?n(i.importer):i.resolveDir||d;if(o.startsWith(`./`)||o.startsWith(`../`)||o===`.`||o===`..`)c=[t(l,o)];else if(o.startsWith(`/`))c=e(d,o)&&d!==`/`?[a(o)]:[r(d,o)];else if(c=C(o),!c.length)return{path:m.url(i.path),namespace:`npm`};for(let t of c){if(!e(d,t))return{errors:[{text:`${i.path} is outside the project folder (${d})`}]};let n=await S(t);if(n)return{path:n,namespace:`vfs`,pluginData:{query:s}}}return{errors:[{text:`Could not find "${i.path}"${i.importer?` (imported by ${i.importer})`:``}`}]}}),i.onLoad({filter:/.*/,namespace:`vfs`},async e=>(g.add(e.path),{contents:await u.readFile(e.path),loader:f(e.path,e.pluginData?.query??``),resolveDir:n(e.path)})),i.onLoad({filter:/.*/,namespace:`npm`},async e=>({contents:await o(e.path,h),loader:/\.css(\?|$)/.test(new URL(e.path).pathname)?`css`:`js`}))}},T={MODE:i.production?`production`:`development`,DEV:!i.production,PROD:!!i.production,SSR:i.target===`server`,BASE_URL:`/`,...i.env},E=i.entry;try{let e=await(await c()).build({...typeof E==`string`?{entryPoints:[E]}:{stdin:{contents:E.contents,resolveDir:E.dir,sourcefile:E.name,loader:`tsx`}},bundle:!0,write:!1,outdir:`/out`,format:i.target===`server`?`iife`:`esm`,globalName:i.target===`server`?`__bbxServer`:void 0,platform:`browser`,target:`es2022`,jsx:`automatic`,jsxImportSource:b,define:{"process.env.NODE_ENV":i.production?`"production"`:`"development"`,"import.meta.env":JSON.stringify(T),...Object.fromEntries(Object.entries(T).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)]))},minify:!!i.production,logLevel:`silent`,charset:`utf8`,plugins:[w]}),t=t=>e.outputFiles?.find(e=>e.path.endsWith(t))?.text??``;return{js:t(`.js`),css:t(`.css`),errors:[],warnings:e.warnings.map(p),inputs:[...g]}}catch(e){let t=e;return{js:``,css:``,errors:t.errors?.length?t.errors.map(p):[e.message??String(e)],warnings:(t.warnings??[]).map(p),inputs:[...g]}}}async function h(e,t){let n=``;for(let t=0;t<e.length;t+=32768)n+=String.fromCharCode(...e.subarray(t,t+32768));return`data:${t};base64,${btoa(n)}`}export{h as n,m as t};
@@ -1,4 +1,4 @@
1
- import{i as e,r as t}from"./npm-DF8ts_uH.js";import{o as n,t as r}from"./path-DGG-Mxbd.js";import{c as i,t as a}from"./main-DzFuvDws.js";function o(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=[];for(let i=0;i<e.length;i++){let a=e[i],o=/^--?([\w-]+)(?:=(.*))?$/.exec(a);o?o[2]===void 0?(o[1]===`port`||o[1]===`p`)&&e[i+1]&&/^\d+$/.test(e[i+1])?n.set(`port`,e[++i]):t.add(o[1]):n.set(o[1],o[2]):r.push(a)}return{flags:t,values:n,rest:r}}async function s(e,t){let r=e.os.fs,i=await r.readText(n(t,`index.html`)).catch(()=>null);return i===null||/<script[^>]+type\s*=\s*["']?module/i.test(i)?!0:(await r.glob(`**/*.{ts,tsx,jsx}`,t,1)).length>0||await r.exists(n(t,`package.json`))}const c={error:i.red,warn:i.yellow,info:i.cyan,log:``,debug:i.dim};function l(e){let t=new Date(e.t).toTimeString().slice(0,8);return`${i.dim}${t} ${e.source.padEnd(7)}${i.reset} ${c[e.level]}${e.text}${i.reset}\n`}async function u(e,t,n){let{os:r,out:o}=e;!r.packages.isInstalled(`esbuild`)&&await s(e,t)&&(o(`${i.dim}this project needs the bundler: installing esbuild${i.reset}\n`),await r.packages.install(`esbuild`,a(`esbuild`,o)),o(`
1
+ import{i as e,r as t}from"./npm-DF8ts_uH.js";import{o as n,t as r}from"./path-DGG-Mxbd.js";import{c as i,t as a}from"./main-CQvaEX7y.js";function o(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=[];for(let i=0;i<e.length;i++){let a=e[i],o=/^--?([\w-]+)(?:=(.*))?$/.exec(a);o?o[2]===void 0?(o[1]===`port`||o[1]===`p`)&&e[i+1]&&/^\d+$/.test(e[i+1])?n.set(`port`,e[++i]):t.add(o[1]):n.set(o[1],o[2]):r.push(a)}return{flags:t,values:n,rest:r}}async function s(e,t){let r=e.os.fs,i=await r.readText(n(t,`index.html`)).catch(()=>null);return i===null||/<script[^>]+type\s*=\s*["']?module/i.test(i)?!0:(await r.glob(`**/*.{ts,tsx,jsx}`,t,1)).length>0||await r.exists(n(t,`package.json`))}const c={error:i.red,warn:i.yellow,info:i.cyan,log:``,debug:i.dim};function l(e){let t=new Date(e.t).toTimeString().slice(0,8);return`${i.dim}${t} ${e.source.padEnd(7)}${i.reset} ${c[e.level]}${e.text}${i.reset}\n`}async function u(e,t,n){let{os:r,out:o}=e;!r.packages.isInstalled(`esbuild`)&&await s(e,t)&&(o(`${i.dim}this project needs the bundler: installing esbuild${i.reset}\n`),await r.packages.install(`esbuild`,a(`esbuild`,o)),o(`
2
2
  `));let c=await r.dev.start({root:t,port:n.port,network:n.network});return o(`\n ${i.green}${i.bold}serving${i.reset} ${c.root}\n`),o(` ${i.bold}➜${i.reset} ${i.cyan}${c.url}${i.reset} ${i.dim}opens in Preview${i.reset}\n`),c.backend&&o(` ${i.dim}backend${i.reset} ${c.backend}${c.network?` (network allowed)`:` (no network: serve --net to allow)`}\n`),o(` ${i.dim}npm packages load from esm.sh · files reload on save · serve logs ${c.port} · serve stop ${c.port}${i.reset}\n\n`),n.open!==!1&&r.openApp(`preview`,{dev:c.port}),c.port}const d={name:`serve`,summary:`dev server for a project folder: bundles TS/JSX, reloads on save, runs server.ts`,usage:`serve [dir] [--port N] [--net] [--no-open] | serve list | serve logs [port] | serve stop [port|all]`,async run(e){let{os:t,out:n}=e,{flags:r,values:a,rest:s}=o(e.args),[c]=s,d=await t.dev.list(),f=e=>{let t=e?Number(e):d.length===1?d[0].port:NaN;if(!Number.isFinite(t))throw Error(d.length?`which server? ${d.map(e=>e.port).join(`, `)}`:`nothing is being served`);return t};if(c===`list`||c===`ls`){if(!d.length)return n(`${i.dim}nothing is being served. Start one: serve [dir]${i.reset}\n`);for(let e of d)n(`${i.cyan}${e.url.padEnd(24)}${i.reset} ${e.root}${e.backend?` ${i.dim}backend ${e.backend}${i.reset}`:``}\n`);return}if(c===`stop`){let e=s[1]===`all`?d.map(e=>e.port):[f(s[1])];for(let r of e)n(await t.dev.stop(r)?`stopped :${r}\n`:`nothing on :${r}\n`);return}if(c===`logs`||c===`log`){let e=await t.dev.logs(f(s[1]),{limit:Number(a.get(`n`)??100)});e.length||n(`${i.dim}no output yet${i.reset}\n`);for(let t of e)n(l(t));return}if(c===`open`){t.openApp(`preview`,{dev:f(s[1])});return}let p=a.has(`port`)?Number(a.get(`port`)):void 0;if(p!==void 0&&!(p>0&&p<65536))throw Error(`--port must be a number between 1 and 65535`);await u(e,e.path(c??`.`),{port:p,network:r.has(`net`),open:!r.has(`no-open`)})}};async function f(e){let t=await e.os.fs.readText(n(e.shell.cwd,`package.json`)).catch(()=>null);if(t===null)return null;try{return JSON.parse(t)}catch(e){throw Error(`package.json is not valid JSON: ${e.message}`)}}const p=(e,t)=>e.os.fs.writeFile(n(e.shell.cwd,`package.json`),JSON.stringify(t,null,2)+`
3
3
  `),m=e=>({name:r(e.shell.cwd).toLowerCase().replace(/[^a-z0-9-_.]/g,`-`)||`app`,version:`0.1.0`,private:!0,type:`module`,scripts:{dev:`serve`},dependencies:{}});async function h(e){let t;try{t=await fetch(`https://registry.npmjs.org/${e.replace(`/`,`%2F`)}/latest`)}catch{throw Error(`could not reach the npm registry to look up ${e} (offline?)`)}if(t.status===404)throw Error(`no such package on npm: ${e}`);if(!t.ok)throw Error(`npm registry: HTTP ${t.status} for ${e}`);return(await t.json()).version}const g=/\b(vite|next|webpack|parcel|serve|http-server|live-server|react-scripts|astro|nuxt|svelte-kit)\b/,_={name:`npm`,summary:`manage package.json; npm run dev serves the project (packages load from esm.sh)`,usage:`npm init | npm install <pkg>[@version]… [-D] | npm uninstall <pkg>… | npm ls | npm run dev`,async run(r){let{out:a}=r,{flags:s,rest:c}=o(r.args),[l=`help`,...d]=c;switch(l){case`init`:return await f(r)?a(`package.json already exists
4
4
  `):(await p(r,m(r)),a(`wrote ${n(r.shell.cwd,`package.json`)}\n`));case`install`:case`i`:case`add`:{let n=await f(r)??m(r);if(!d.length)return a(`${i.dim}nothing to download: packages listed in package.json load from esm.sh when the app is bundled, and are cached after that.${i.reset}\n`);let o=s.has(`D`)||s.has(`save-dev`)?`devDependencies`:`dependencies`,c=n[o]??={};for(let n of d){let r=n.lastIndexOf(`@`),[o,s]=r>0?[n.slice(0,r),n.slice(r+1)]:[n,``];if(!e(o)[0])throw Error(`not a package name: ${n}`);let l=t(s)??await h(o);c[o]=`^${l}`,a(`${i.green}+${i.reset} ${o}@${l}\n`)}return await p(r,n),a(`${i.dim}saved to package.json · loaded from esm.sh when the app is bundled${i.reset}\n`)}case`uninstall`:case`remove`:case`rm`:case`un`:{let e=await f(r);if(!e)throw Error(`no package.json here`);for(let t of d){let n=!!(e.dependencies?.[t]??e.devDependencies?.[t]);delete e.dependencies?.[t],delete e.devDependencies?.[t],a(n?`${i.red}-${i.reset} ${t}\n`:`${t} was not a dependency\n`)}return p(r,e)}case`ls`:case`list`:{let e=await f(r),t={...e?.dependencies,...e?.devDependencies};if(!Object.keys(t).length)return a(`${i.dim}no dependencies${i.reset}\n`);for(let[e,n]of Object.entries(t))a(`${e}@${n}\n`);return}case`start`:case`run`:case`run-script`:{let e=l===`start`?`start`:d[0],t=await f(r);if(!e)return a(Object.entries(t?.scripts??{}).map(([e,t])=>` ${e}: ${t}\n`).join(``)||`${i.dim}no scripts${i.reset}\n`);let n=t?.scripts?.[e]??``;if([`dev`,`start`,`serve`,`preview`].includes(e)||g.test(n)){await u(r,r.shell.cwd,{open:!0});return}if(!n)throw Error(`no script "${e}" in package.json`);return a(`${i.dim}> ${n}${i.reset}\n`),r.shell.run(n,{out:r.out,err:r.err,signal:r.signal})}default:return a(`${_.usage}\n${i.dim}There is no node_modules here: dependencies are fetched from esm.sh and bundled by serve.${i.reset}\n`),l===`help`?0:1}}},v={name:`npx`,summary:`npx vite / serve / http-server start the dev server`,usage:`npx vite | npx serve [dir] | npx http-server [dir]`,async run(e){let[t,...n]=e.args;if(t&&/^(vite|serve|http-server|live-server)(@.*)?$/.test(t))await u(e,e.path(n.find(e=>!e.startsWith(`-`))??`.`),{open:!0});else throw Error(`npx ${t??``}: only dev servers are available here (npx vite, npx serve). Packages for your app go in package.json (npm install <pkg>).`)}};export{_ as npmCommand,v as npxCommand,d as serveCommand};
@@ -0,0 +1,3 @@
1
+ import{a as e,c as t,i as n,l as r,n as i,r as a,t as o,u as s}from"./instance-Cu6oky-A.js";function c(t={}){let n=t.kernelUrl??r,i=n.endsWith(`/`)?n:`${n}/`,a=new URL(i).origin;return new Promise((n,r)=>{let s=new URL(`bridge.html${e(t.instance??o)}`,i).href,c=document.getElementById(`bbx-bridge`),l=c?.src===s?c:document.createElement(`iframe`);l!==c&&(l.src=s,l.title=`BrowserBox kernel bridge`,l.setAttribute(`aria-hidden`,`true`),l.hidden=!0);let u=setTimeout(()=>r(Error(`The kernel at ${i} did not respond.`)),2e4),d=1,f=new Map,p=(e,t)=>({port:t,lock:String(e.lock),shared:!!e.shared,more:()=>new Promise(e=>{let t=d++;f.set(t,e),l.contentWindow.postMessage({type:`bbx:connect`,req:t},a)})}),m=!0;addEventListener(`message`,e=>{e.source===l.contentWindow&&e.origin===a&&(e.data?.type===`bbx:ready`&&m?l.contentWindow.postMessage({type:`bbx:connect`},a):e.data?.type===`bbx:port`&&e.ports[0]?typeof e.data.req==`number`?(f.get(e.data.req)?.(p(e.data,e.ports[0])),f.delete(e.data.req)):m&&(m=!1,clearTimeout(u),n(p(e.data,e.ports[0]))):e.data?.type===`bbx:refused`&&m&&(clearTimeout(u),r(Error(`The kernel refused this origin (${location.origin}). Add it to VITE_ALLOWED_ORIGINS.`))))}),l===c?l.contentWindow?.postMessage({type:`bbx:connect`},a):(document.body??document.documentElement).append(l)})}var l=`/home/user`;function u(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}function d(e){return e.replace(/\x1b\[[0-9;]*m/g,``).split(`
2
+ `).map(e=>e.slice(e.lastIndexOf(`\r`)+1)).join(`
3
+ `)}var f=new URLSearchParams(location.search),p=a(location.search),m=f.get(`profile`);if(m!==null&&!i.test(m))throw Error(`invalid profile id: ${m}`);var h=f.get(`site`)===`1`?n(m):{box:p.box??`default`,storage:p.box===null?`opfs`:p.storage},g=c({instance:h}),_=()=>g.then(e=>e.more()),v=h.box??`site`,y=e=>`'${e.replace(/'/g,`'\\''`)}'`,b=({port:e,root:t,url:n,backend:r,network:i})=>({port:e,root:t,url:n,backend:r,network:i}),x=class e{os;#e;#t=1;#n=new Map;#r=1;#i=new Map;#a=new Map;#o=1;constructor(e,t){this.#e=e,this.os=new s(t,`sdk`),this.os.perms.setPrompter((e,t)=>new Promise(n=>{let r=this.#t++;this.#n.set(r,n),t?.addEventListener(`abort`,()=>this.#n.delete(r)&&n(`deny`)),this.send({t:`permission`,id:r,request:{cap:e.cap,actor:e.actor,title:e.title,detail:e.detail}})})),e.onmessage=e=>void this.#f(e.data)}send(e,t=[]){this.#e.postMessage(e,t)}async hello(){return await this.os.ready,await this.os.fs.ready,{t:`hello`,protocol:1,version:this.os.version,id:v,home:l,caps:this.os.caps.filter(e=>e.ok).map(e=>e.id),storage:this.os.rootKind}}async#s(e,t){let n=await this.os.shells.open({cwd:e.cwd,confined:!0});for(let[r,i]of Object.entries(e.env??{})){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw n.close(),Error(`invalid environment variable name: ${r}`);await n.run(`export ${r}=${y(String(i))}`,{out:()=>void 0,err:t})}return n}async#c(e,t,n,r,i){let a=!1,o=n?setTimeout(()=>(a=!0,i.abort()),n):void 0;try{let n=await e.run(t,{...r,signal:i.signal});return a?124:i.signal.aborted?130:n}catch(e){return a?124:i.signal.aborted?130:(r.err(`${e.message}\n`),1)}finally{clearTimeout(o)}}async#l(e,t,n,r){let i;try{i=await this.#s(t,n.err)}catch(e){return n.err(`${e.message}\n`),1}try{return await this.#c(i,e,t.timeoutMs,n,r)}finally{i.close()}}#u(e){return{out:t=>this.send({t:`output`,pid:e,stream:`stdout`,data:u(t)}),err:t=>this.send({t:`output`,pid:e,stream:`stderr`,data:u(t)})}}#d={info:()=>this.hello(),"fs.readFile":e=>this.os.fs.readFile(e),"fs.readTextFile":e=>this.os.fs.readText(e),"fs.writeFile":(e,t)=>this.os.fs.writeFile(e,t),"fs.mkdir":e=>this.os.fs.mkdir(e),"fs.readdir":async e=>(await this.os.fs.readdir(e)).map(({path:e,name:t,kind:n,size:r,mtime:i})=>({path:e,name:t,kind:n,size:r,mtime:i})),"fs.stat":async e=>{let t=await this.os.fs.stat(e);return t&&{path:t.path,name:t.name,kind:t.kind,size:t.size,mtime:t.mtime}},"fs.exists":e=>this.os.fs.exists(e),"fs.rm":(e,t)=>this.os.fs.rm(e,t),"fs.rename":(e,t)=>this.os.fs.mv(e,t),"fs.cp":(e,t)=>this.os.fs.cp(e,t),"fs.appendFile":(e,t)=>this.os.fs.appendFile(e,t),"fs.glob":(e,t,n)=>this.os.fs.glob(e,t??`/home/user`,n),exec:async(e,t={})=>{let n=``,r=``;return{exitCode:await this.#l(e,t,{out:e=>n+=e,err:e=>r+=e},new AbortController),stdout:d(n),stderr:d(r)}},spawn:(e,t={})=>{let n=this.#r++,r=new AbortController;return this.#i.set(n,r),this.#l(e,t,this.#u(n),r).then(e=>{this.#i.delete(n),this.send({t:`exit`,pid:n,exitCode:e})}),n},kill:e=>{let t=this.#i.get(e);return t?.abort(),!!t},"shell.open":async(e={})=>{let t=await this.#s(e,()=>void 0),n=this.#o++;return this.#a.set(n,{shell:t,busy:!1}),{id:n,cwd:t.cwd}},"shell.run":(e,t,n={})=>{let r=this.#a.get(e);if(!r)throw Error(`no such shell session: ${e}`);if(r.busy)throw Error(`this shell session is still running a command`);r.busy=!0;let i=this.#r++,a=new AbortController;return this.#i.set(i,a),this.#c(r.shell,t,n.timeoutMs,this.#u(i),a).then(e=>{r.busy=!1,this.#i.delete(i),this.send({t:`exit`,pid:i,exitCode:e,cwd:r.shell.cwd})}),i},"shell.close":e=>{this.#a.get(e)?.shell.close(),this.#a.delete(e)},"dev.start":({root:e,port:t,network:n})=>this.os.dev.start({root:e,port:t,network:n}).then(b),"dev.stop":e=>this.os.dev.stop(e),"dev.list":async()=>(await this.os.dev.list()).map(b),"dev.logs":async(e,t)=>(await this.os.dev.logs(e,t)).map(({seq:e,t,level:n,source:r,text:i})=>({seq:e,t,level:n,source:r,text:i})),"procs.list":()=>this.os.procs.list().map(e=>({pid:e.pid,ppid:e.ppid,name:e.name,kind:e.kind,state:e.state,detail:e.detail,started:e.started,cpuMs:e.cpuMs,memBytes:e.memBytes})),"procs.kill":e=>this.os.procs.kill(e,`killed through the SDK`),"kernel.connect":async()=>{let e=await _();return{port:e.port,lock:e.lock,shared:e.shared}},share:()=>{let{port1:t,port2:n}=new MessageChannel,r=new e(t,_());return r.hello().then(e=>r.send(e),e=>r.send({t:`refused`,error:`the runtime failed to start: ${e.message}`})),n}};async#f(e){if(e.t===`permission-answer`){this.#n.get(e.id)?.(e.decision),this.#n.delete(e.id);return}if(e.t!==`call`)return;let t=Object.hasOwn(this.#d,e.method)?this.#d[e.method]:null;try{if(!t)throw Error(`unknown method: ${e.method}`);let n=await t(...Array.isArray(e.args)?e.args:[]),r=n instanceof Uint8Array?[n.buffer]:n instanceof MessagePort?[n]:n&&typeof n==`object`&&n.port instanceof MessagePort?[n.port]:[];this.send({t:`result`,id:e.id,ok:!0,value:n},r)}catch(t){let n=t instanceof Error?t.message:String(t);this.send({t:`result`,id:e.id,ok:!1,error:n,code:/^(E[A-Z]+):/.exec(n)?.[1]})}}},S=null,C=e=>t===`*`||t.includes(e)||e===location.origin;addEventListener(`message`,e=>{let t=e.data;if(t?.type!==`bbx:connect`||e.source!==parent||!e.ports[0])return;let n=e.ports[0];if(S)return n.postMessage({t:`refused`,error:`this runtime is already connected; boot another BrowserBox for a second box`});if(!C(e.origin))return n.postMessage({t:`refused`,error:`origin ${e.origin} may not use this runtime (VITE_EMBED_ORIGINS)`});if(t.protocol!==1)return n.postMessage({t:`refused`,error:`protocol mismatch: the SDK speaks ${t.protocol}, this runtime 1. Use matching versions of the SDK and the runtime.`});let r=S=new x(n,g);globalThis.bbx=r.os,r.hello().then(e=>r.send(e),e=>r.send({t:`refused`,error:`the runtime failed to start: ${e.message}`}))}),parent!==window&&parent.postMessage({type:`bbx:embed-ready`,protocol:1},`*`);
@@ -1,4 +1,4 @@
1
- import{a as e,c as t,n,o as r,r as i,s as a,t as o}from"./path-DGG-Mxbd.js";import{n as s}from"./bundle-qe7w2kMM.js";const c={js:`JavaScript`,mjs:`JavaScript`,cjs:`JavaScript`,jsx:`JavaScript (JSX)`,ts:`TypeScript`,mts:`TypeScript`,cts:`TypeScript`,tsx:`TypeScript (TSX)`,py:`Python`,json:`JSON`,jsonl:`JSON Lines`,css:`CSS`,scss:`SCSS`,less:`Less`,html:`HTML`,htm:`HTML`,xml:`XML`,svg:`SVG`,md:`Markdown`,markdown:`Markdown`,sh:`Shell`,bash:`Shell`,zsh:`Shell`,yml:`YAML`,yaml:`YAML`,toml:`TOML`,ini:`INI`,csv:`CSV`,tsv:`TSV`,sql:`SQL`,rs:`Rust`,go:`Go`,c:`C`,h:`C`,cpp:`C++`,cc:`C++`,hpp:`C++`,java:`Java`,kt:`Kotlin`,rb:`Ruby`,php:`PHP`,swift:`Swift`,lua:`Lua`,r:`R`,wat:`WebAssembly Text`,vue:`Vue`,svelte:`Svelte`,txt:`Plain Text`,log:`Log`},l=/* @__PURE__ */ new Set([`txt`,`log`,`csv`,`tsv`,`env`,`conf`,`cfg`,`gitignore`,`gitattributes`,`editorconfig`,`lock`,`properties`,`rst`,`tex`,`diff`,`patch`]),u=/* @__PURE__ */ new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`ico`]),d=/* @__PURE__ */ new Set([`mp3`,`wav`,`ogg`,`oga`,`flac`,`m4a`,`aac`,`opus`]),f=/* @__PURE__ */ new Set([`mp4`,`webm`,`ogv`,`mov`,`m4v`]),p=/* @__PURE__ */ new Set([`zip`,`tar`,`gz`,`tgz`,`bz2`,`xz`,`7z`,`rar`]);function m(e,t=!1){if(t)return`dir`;let n=i(e);return n===`md`||n===`markdown`?`markdown`:n===`html`||n===`htm`?`html`:n===`svg`?`svg`:n===`pdf`?`pdf`:u.has(n)?`image`:d.has(n)?`audio`:f.has(n)?`video`:p.has(n)?`archive`:l.has(n)?`text`:n in c?`code`:!n||o(e).startsWith(`.`)?`text`:`binary`}function h(e){let t=m(e);return t===`text`||t===`code`||t===`markdown`}const g={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,bmp:`image/bmp`,ico:`image/x-icon`,svg:`image/svg+xml`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,oga:`audio/ogg`,flac:`audio/flac`,m4a:`audio/mp4`,aac:`audio/aac`,opus:`audio/ogg`,mp4:`video/mp4`,webm:`video/webm`,ogv:`video/ogg`,mov:`video/quicktime`,m4v:`video/mp4`,pdf:`application/pdf`,html:`text/html`,htm:`text/html`,css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,json:`application/json`,md:`text/markdown`,txt:`text/plain`,csv:`text/csv`,xml:`application/xml`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,wasm:`application/wasm`};function _(e){return g[i(e)]??(h(e)?`text/plain`:`application/octet-stream`)}var v=`// BrowserBox dev runtime. Injected as the first script of every page Preview
1
+ import{a as e,c as t,n,o as r,r as i,s as a,t as o}from"./path-DGG-Mxbd.js";import{n as s}from"./bundle-CXrJ5BHI.js";const c={js:`JavaScript`,mjs:`JavaScript`,cjs:`JavaScript`,jsx:`JavaScript (JSX)`,ts:`TypeScript`,mts:`TypeScript`,cts:`TypeScript`,tsx:`TypeScript (TSX)`,py:`Python`,json:`JSON`,jsonl:`JSON Lines`,css:`CSS`,scss:`SCSS`,less:`Less`,html:`HTML`,htm:`HTML`,xml:`XML`,svg:`SVG`,md:`Markdown`,markdown:`Markdown`,sh:`Shell`,bash:`Shell`,zsh:`Shell`,yml:`YAML`,yaml:`YAML`,toml:`TOML`,ini:`INI`,csv:`CSV`,tsv:`TSV`,sql:`SQL`,rs:`Rust`,go:`Go`,c:`C`,h:`C`,cpp:`C++`,cc:`C++`,hpp:`C++`,java:`Java`,kt:`Kotlin`,rb:`Ruby`,php:`PHP`,swift:`Swift`,lua:`Lua`,r:`R`,wat:`WebAssembly Text`,vue:`Vue`,svelte:`Svelte`,txt:`Plain Text`,log:`Log`},l=/* @__PURE__ */ new Set([`txt`,`log`,`csv`,`tsv`,`env`,`conf`,`cfg`,`gitignore`,`gitattributes`,`editorconfig`,`lock`,`properties`,`rst`,`tex`,`diff`,`patch`]),u=/* @__PURE__ */ new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`ico`]),d=/* @__PURE__ */ new Set([`mp3`,`wav`,`ogg`,`oga`,`flac`,`m4a`,`aac`,`opus`]),f=/* @__PURE__ */ new Set([`mp4`,`webm`,`ogv`,`mov`,`m4v`]),p=/* @__PURE__ */ new Set([`zip`,`tar`,`gz`,`tgz`,`bz2`,`xz`,`7z`,`rar`]);function m(e,t=!1){if(t)return`dir`;let n=i(e);return n===`md`||n===`markdown`?`markdown`:n===`html`||n===`htm`?`html`:n===`svg`?`svg`:n===`pdf`?`pdf`:u.has(n)?`image`:d.has(n)?`audio`:f.has(n)?`video`:p.has(n)?`archive`:l.has(n)?`text`:n in c?`code`:!n||o(e).startsWith(`.`)?`text`:`binary`}function h(e){let t=m(e);return t===`text`||t===`code`||t===`markdown`}const g={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,bmp:`image/bmp`,ico:`image/x-icon`,svg:`image/svg+xml`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,oga:`audio/ogg`,flac:`audio/flac`,m4a:`audio/mp4`,aac:`audio/aac`,opus:`audio/ogg`,mp4:`video/mp4`,webm:`video/webm`,ogv:`video/ogg`,mov:`video/quicktime`,m4v:`video/mp4`,pdf:`application/pdf`,html:`text/html`,htm:`text/html`,css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,json:`application/json`,md:`text/markdown`,txt:`text/plain`,csv:`text/csv`,xml:`application/xml`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,wasm:`application/wasm`};function _(e){return g[i(e)]??(h(e)?`text/plain`:`application/octet-stream`)}var v=`// BrowserBox dev runtime. Injected as the first script of every page Preview
2
2
  // serves from a dev server. The page runs in an opaque-origin frame, so this
3
3
  // connects it to the virtual server through its parent:
4
4
  // - fetch() and XMLHttpRequest to the page's own address are answered by the
@@ -1,2 +1,2 @@
1
1
  var e=class{#e=new Map;on(e,t){let n=this.#e.get(e);return n||this.#e.set(e,n=new Set),n.add(t),()=>n.delete(t)}emit(e,t){let n=this.#e.get(e);if(n)for(let r of[...n])try{r(t)}catch(t){console.error(`[bus] handler for "${String(e)}" threw`,t)}}};function t(){let e=globalThis,t=globalThis.navigator??{},n=(e,t)=>typeof e==`object`&&!!e&&t in e,r=(e,t,n,r,i)=>({id:e,group:t,label:n,ok:!!r,use:i});return[r(`wasm`,`Compute`,`WebAssembly`,n(e,`WebAssembly`),`Rust kernel core, WASI programs, Pyodide`),r(`wasm-streaming`,`Compute`,`WASM streaming compile`,typeof WebAssembly?.instantiateStreaming==`function`,`Fast kernel boot`),r(`workers`,`Compute`,`Web Workers`,n(e,`Worker`),`Sandboxed code execution`),r(`sab`,`Compute`,`SharedArrayBuffer`,n(e,`SharedArrayBuffer`)&&e.crossOriginIsolated===!0,`Threads (needs cross-origin isolation)`),r(`webgpu`,`Compute`,`WebGPU`,n(t,`gpu`),`GPU compute tool, GPU Lab, in-browser LLM`),r(`scheduler`,`Compute`,`Scheduler API`,n(e,`scheduler`),`Prioritised background work`),r(`compression`,`Compute`,`Compression Streams`,n(e,`CompressionStream`),`gzip / gunzip`),r(`crypto`,`Compute`,`Web Crypto`,n(e.crypto,`subtle`),`Secret encryption, hashing`),r(`opfs`,`Storage`,`Origin Private File System`,n(t.storage,`getDirectory`),`Persistent root filesystem`),r(`fsaccess`,`Storage`,`File System Access`,n(e,`showDirectoryPicker`),`Mount real folders at /mnt`),r(`indexeddb`,`Storage`,`IndexedDB`,n(e,`indexedDB`),`Encrypted secrets`),r(`persist`,`Storage`,`Persistent storage`,n(t.storage,`persist`),`Protect data from eviction`),r(`cache`,`Storage`,`Cache Storage`,n(e,`caches`),`Offline boot, model weights`),r(`sw`,`System`,`Service Worker`,n(t,`serviceWorker`),`Instant offline boot`),r(`locks`,`System`,`Web Locks`,n(t,`locks`),`Cross-tab coordination`),r(`broadcast`,`System`,`BroadcastChannel`,n(e,`BroadcastChannel`),`Cross-tab filesystem events`),r(`notifications`,`System`,`Notifications`,n(e,`Notification`),`Agent task alerts`),r(`clipboard`,`System`,`Async Clipboard`,n(t,`clipboard`),`Clipboard tools`),r(`wakelock`,`System`,`Screen Wake Lock`,n(t,`wakeLock`),`Keep awake during long agent runs`),r(`share`,`System`,`Web Share`,n(t,`share`),`Share files`),r(`viewtransitions`,`System`,`View Transitions`,n(globalThis.document,`startViewTransition`),`Window animations`),r(`memory`,`System`,`Memory measurement`,n(globalThis.performance,`memory`)||n(globalThis.performance,`measureUserAgentSpecificMemory`),`Task Manager`),r(`battery`,`System`,`Battery Status`,n(t,`getBattery`),`System monitor`),r(`fetch-stream`,`Network`,`Streaming fetch`,n(e,`ReadableStream`),`LLM token streaming`),r(`websocket`,`Network`,`WebSocket`,n(e,`WebSocket`),`Realtime connections`),r(`webrtc`,`Network`,`WebRTC`,n(e,`RTCPeerConnection`),`Peer-to-peer`),r(`webtransport`,`Network`,`WebTransport`,n(e,`WebTransport`),`Low-latency transport`),r(`netinfo`,`Network`,`Network Information`,n(t,`connection`),`System monitor`),r(`offscreen`,`Graphics & Media`,`OffscreenCanvas`,n(e,`OffscreenCanvas`),`Off-thread rendering`),r(`webgl2`,`Graphics & Media`,`WebGL 2`,n(e,`WebGL2RenderingContext`),`Graphics fallback`),r(`webcodecs`,`Graphics & Media`,`WebCodecs`,n(e,`VideoEncoder`),`Media processing`),r(`webaudio`,`Graphics & Media`,`Web Audio`,n(e,`AudioContext`),`Sound`),r(`speech-tts`,`Graphics & Media`,`Speech synthesis`,n(e,`speechSynthesis`),`Agent speak tool`),r(`speech-stt`,`Graphics & Media`,`Speech recognition`,n(e,`SpeechRecognition`)||n(e,`webkitSpeechRecognition`),`Voice input`),r(`capture`,`Graphics & Media`,`Screen Capture`,n(t.mediaDevices,`getDisplayMedia`),`Screenshots`),r(`usb`,`Devices`,`WebUSB`,n(t,`usb`),`Hardware access`),r(`serial`,`Devices`,`Web Serial`,n(t,`serial`),`Hardware access`),r(`bluetooth`,`Devices`,`Web Bluetooth`,n(t,`bluetooth`),`Hardware access`),r(`hid`,`Devices`,`WebHID`,n(t,`hid`),`Hardware access`),r(`gamepad`,`Devices`,`Gamepad`,n(t,`getGamepads`),`Input`),r(`prompt-api`,`AI`,`Built-in Prompt API`,n(e,`LanguageModel`),`On-device model`),r(`webnn`,`AI`,`WebNN`,n(t,`ml`),`Neural network acceleration`)]}var n=new URL(`kcore-COUztiEr.wasm`,import.meta.url).href,r=new TextEncoder,i=class{#e=null;#t=null;get loaded(){return this.#e!==null}load(){return this.#t??=(async()=>{try{let{instance:e}=await WebAssembly.instantiateStreaming(fetch(n),{});this.#e=e.exports}catch(e){console.warn(`[kcore] wasm unavailable, using JS fallbacks`,e)}})()}#n(e,t){let n=this.#e,r=n.alloc(e.length);try{return new Uint8Array(n.memory.buffer,r,e.length).set(e),t(n,r)}finally{n.dealloc(r,e.length)}}hash(e){if(this.#e)return this.#n(e,(t,n)=>BigInt.asUintN(64,t.fnv1a64(n,e.length)).toString(16).padStart(16,`0`));let t=14695981039346656037n;for(let n of e)t=BigInt.asUintN(64,(t^BigInt(n))*1099511628211n);return t.toString(16).padStart(16,`0`)}searchLines(e,t,n=!1,i=1e3){let a=r.encode(t);if(this.#e)return this.#n(e,(t,r)=>{let o=t.alloc(a.length),s=t.alloc(i*8);try{new Uint8Array(t.memory.buffer,o,a.length).set(a);let c=t.search_lines(r,e.length,o,a.length,+!!n,s,i),l=new DataView(t.memory.buffer,s,i*8),u=[];for(let e=0;e<Math.min(c,i);e++)u.push({line:l.getUint32(e*8,!0),offset:l.getUint32(e*8+4,!0)});return{total:c,matches:u}}finally{t.dealloc(o,a.length),t.dealloc(s,i*8)}});let o=new TextDecoder().decode(e),s=n?t.toLowerCase():t,c=[],l=0,u=0;return o.split(`
2
- `).forEach((e,t)=>{(n?e.toLowerCase():e).includes(s)&&(c.length<i&&c.push({line:t+1,offset:u}),l++),u+=r.encode(e).length+1}),{total:l,matches:c}}wc(e){if(this.#e)return this.#n(e,(t,n)=>{let r=t.alloc(12);try{t.wc(n,e.length,r);let i=new DataView(t.memory.buffer,r,12);return{lines:i.getUint32(0,!0),words:i.getUint32(4,!0),bytes:i.getUint32(8,!0)}}finally{t.dealloc(r,12)}});let t=new TextDecoder().decode(e);return{lines:(t.match(/\n/g)??[]).length,words:(t.match(/\S+/g)??[]).length,bytes:e.length}}estimateTokens(e){if(this.#e){let t=r.encode(e);return this.#n(t,(e,n)=>e.estimate_tokens(n,t.length))}return Math.ceil(e.length/3.6)}},a=class{settings;#e=async()=>`deny`;constructor(e){this.settings=e}setPrompter(e){this.#e=e}prompt(e,t){return this.#e(e,t)}get mode(){return this.settings.get(`perms.mode`,`ask`)}set mode(e){this.settings.set(`perms.mode`,e)}grants(){return this.settings.get(`perms.grants`,[])}revoke(e){this.settings.set(`perms.grants`,this.grants().filter(t=>t!==e))}isGranted(e){return this.mode===`auto`||this.grants().includes(e)}async request(e,t){if(this.isGranted(e.cap))return!0;let n=await(t??this.#e)(e);return n===`always`&&this.settings.set(`perms.grants`,[...new Set([...this.grants(),e.cap])]),n!==`deny`}},o=class{bus;onWrite;#e=new Map;constructor(e,t){this.bus=e,this.onWrite=t}hydrate(e){this.#e=new Map(e);for(let[t,n]of e)this.bus.emit(`settings:change`,{key:t,value:n})}entries(){return[...this.#e]}get(e,t){return this.#e.has(e)?this.#e.get(e):t}set(e,t){this.applyRemote(e,t),this.onWrite?.(e,t)}delete(e){this.set(e,void 0)}applyRemote(e,t){t===void 0?this.#e.delete(e):this.#e.set(e,t),this.bus.emit(`settings:change`,{key:e,value:t})}keys(){return[...this.#e.keys()]}};function s(e){let t=[];for(let n of e.split(`/`))n&&n!==`.`&&(n===`..`?t.pop():t.push(n));return`/`+t.join(`/`)}function c(e,t){return s(t?t.startsWith(`/`)?t:`${e}/${t}`:e)}var l=class{port;#e=1;#t=new Map;#n={};#r=new Map;closed=!1;constructor(e){this.port=e,e.onmessage=e=>void this.#i(e.data)}handle(e){return Object.assign(this.#n,e),this}call(e,...t){return this.closed?Promise.reject(Error(`connection closed`)):new Promise((n,r)=>{let i=this.#e++;this.#t.set(i,{resolve:n,reject:r}),this.port.postMessage({k:`call`,id:i,m:e,a:t})})}emit(e,t){this.closed||this.port.postMessage({k:`evt`,n:e,p:t})}on(e,t){let n=this.#r.get(e);return n||this.#r.set(e,n=new Set),n.add(t),()=>n.delete(t)}close(){if(!this.closed){this.closed=!0,this.port.close();for(let e of this.#t.values())e.reject(Error(`connection closed`));this.#t.clear()}}async#i(e){if(e.k===`call`){let t=Object.hasOwn(this.#n,e.m)?this.#n[e.m]:void 0;try{if(!t)throw Error(`unknown method: ${e.m}`);let n=await t(...e.a);this.closed||this.port.postMessage({k:`ok`,id:e.id,v:n})}catch(t){let n=t;this.closed||this.port.postMessage({k:`err`,id:e.id,e:{name:n?.name??`Error`,message:n?.message??String(t)}})}}else if(e.k===`ok`||e.k===`err`){let t=this.#t.get(e.id);if(this.#t.delete(e.id),!t)return;if(e.k===`ok`)t.resolve(e.v);else{let n=Error(e.e.message);n.name=e.e.name,t.reject(n)}}else if(e.k===`evt`)for(let t of[...this.#r.get(e.n)??[]])try{t(e.p)}catch(t){console.error(`[rpc] listener for "${e.n}" threw`,t)}}},u=new AbortController().signal,d=new TextDecoder,f=class{version=``;rootKind=`opfs`;shared=!0;bootStart=0;bootMarks=[];bus=new e;settings=new o(this.bus,(e,t)=>void this.call(`settings.set`,e,t));perms=new a(this.settings);kcore=new i;caps=t();ready;kernelLog=[];#e;#t=new Map;#n=new Map;#r=0;#i=[];#a=new Map;#o=new Map;#s=1;#c=new Map;constructor(e,t=`ui`){this.#e=e.then(({port:e,lock:t,shared:n})=>{this.shared=n;let r=new l(e);return this.#d(r),r.emit(`alive`,t),r}),this.ready=this.#e.then(async e=>this.#l(await e.call(`hello`,t)))}async call(e,...t){return(await this.#e).call(e,...t)}async handle(e){return(await this.#e).handle(e)}#l(e){this.version=e.version,this.rootKind=e.rootKind,this.#r=e.pidBase+1,this.#i=e.mounts.map(e=>({point:e.point,fs:{label:e.label,readonly:e.readonly}})),this.bootMarks.push(...e.bootMarks.map(e=>({name:`kernel:${e.name}`,at:e.at}))),this.kernelLog.splice(0,this.kernelLog.length,...e.log),this.settings.hydrate(e.settings);for(let t of e.procs)this.bus.emit(`proc:spawn`,this.#u(t));this.mark(`kernel-connected`)}#u(e){let t=this.#t.get(e.pid);if(t)return Object.assign(t,e);let n={...e,signal:u};return this.#t.set(e.pid,n),n}#d(e){e.on(`bus`,({type:t,payload:n})=>{if(t===`settings:change`){let{key:e,value:t}=n;this.settings.applyRemote(e,t)}else if(t===`proc:spawn`||t===`proc:update`)this.bus.emit(t,this.#u(n));else if(t===`proc:exit`){let{proc:e,reason:t}=n,r=this.#u(e);this.#t.delete(e.pid),this.#p(e.pid,t),this.bus.emit(`proc:exit`,{proc:r,reason:t})}else t===`fs:change`&&n.type===`mount`?e.call(`fs.mounts`).then(e=>{this.#i=e.map(e=>({point:e.point,fs:{label:e.label,readonly:e.readonly}})),this.bus.emit(t,n)}):(t===`kmsg`&&!this.kernelLog.some(e=>e.t===n.t&&e.msg===n.msg)&&this.kernelLog.push(n),this.bus.emit(t,n))}),e.on(`proc:kill`,e=>this.#p(e,`killed`)),e.on(`shell:out`,({runId:e,s:t,t:n})=>{let r=this.#o.get(e);(t===`o`?r?.out:r?.err)?.(n)}),e.on(`shell:clear`,e=>this.#a.get(e)?.clear?.()),e.on(`ask`,t=>void this.#f(e,t)),e.on(`ask:done`,e=>{this.#c.get(e)?.abort(),this.#c.delete(e)})}async#f(e,t){let n=new AbortController;this.#c.set(t.askId,n);let r;try{if(t.kind===`perm`)r=await this.perms.prompt(t.payload,n.signal);else if(t.kind===`user`)return;else if(t.kind===`tty`){let e=t.shellId?this.#a.get(t.shellId)?.reader:void 0,{prompt:n,secret:i}=t.payload;r=e?await e(n,i??!1):null}else{let{method:e,args:n}=t.payload;e===`clipboard.write`?r=await navigator.clipboard.writeText(String(n[0])):e===`clipboard.read`?r=await navigator.clipboard.readText():e===`speak`&&speechSynthesis.speak(new SpeechSynthesisUtterance(String(n[0])))}}catch(e){if(n.signal.aborted)return;r=t.kind===`perm`?`deny`:t.kind===`ui`?`failed: ${e.message}`:null}n.signal.aborted||(this.#c.delete(t.askId),e.call(`answer`,t.askId,r))}#p(e,t){let n=this.#n.get(e);if(n){this.#n.delete(e),n.ctl.abort(new DOMException(t,`AbortError`));try{n.onKill?.()}catch(e){console.error(`[procs] onKill threw`,e)}}}procs={spawn:e=>{if(!this.#r)throw Error(`kernel not connected yet`);let t=new AbortController,n={pid:this.#r++,ppid:e.ppid??0,name:e.name,kind:e.kind,started:Date.now(),state:`running`,detail:e.detail??``,cpuMs:0,memBytes:0,signal:t.signal};this.#t.set(n.pid,n),this.#n.set(n.pid,{proc:n,ctl:t,onKill:e.onKill});let{signal:r,...i}=n;return this.call(`procs.spawn`,i),n},update:(e,t)=>{let n=this.#t.get(e);n&&Object.assign(n,t),this.call(`procs.update`,e,t)},account:(e,t)=>{let n=this.#t.get(e);n&&(n.cpuMs+=t),this.call(`procs.account`,e,t)},kill:(e,t=`killed`)=>this.#t.has(e)?(this.#n.has(e)&&this.#t.delete(e),this.#p(e,t),this.call(`procs.kill`,e,t),!0):!1,exit:e=>void this.procs.kill(e,`exit`),get:e=>this.#t.get(e),list:()=>[...this.#t.values()].sort((e,t)=>e.started-t.started||e.pid-t.pid)};fs=(e=>({get ready(){return e.ready},readFile:t=>e.call(`fs.readFile`,t),readText:async t=>d.decode(await e.call(`fs.readFile`,t)),writeFile:(t,n)=>e.call(`fs.writeFile`,t,n),appendFile:(t,n)=>e.call(`fs.appendFile`,t,n),readdir:t=>e.call(`fs.readdir`,t),stat:t=>e.call(`fs.stat`,t),exists:t=>e.call(`fs.stat`,t).then(Boolean,()=>!1),mkdir:t=>e.call(`fs.mkdir`,t),rm:(t,n)=>e.call(`fs.rm`,t,n),cp:(t,n)=>e.call(`fs.cp`,t,n),mv:(t,n)=>e.call(`fs.mv`,t,n),glob:(t,n,r)=>e.call(`fs.glob`,t,n,r),async*walk(t,n={}){let r=[[s(t),0]];for(;r.length;){let[t,i]=r.pop();n.signal?.throwIfAborted();let a=await e.call(`fs.readdir`,t).catch(()=>[]);for(let e of a)yield e,e.kind===`dir`&&i+1<(n.maxDepth??32)&&e.path!==`/proc`&&r.push([e.path,i+1])}},mounts:()=>e.#i,unmount:t=>void e.call(`fs.unmount`,t)}))(this);secrets={has:e=>this.call(`secrets.has`,e),set:(e,t)=>this.call(`secrets.set`,e,t),delete:e=>this.call(`secrets.delete`,e)};dev={start:e=>this.call(`dev.start`,e),stop:e=>this.call(`dev.stop`,e),list:()=>this.call(`dev.list`),page:(e,t)=>this.call(`dev.page`,e,t),request:(e,t)=>this.call(`dev.request`,e,t),log:(e,t)=>void this.call(`dev.log`,e,t).catch(()=>void 0),logs:(e,t)=>this.call(`dev.logs`,e,t)};shells={open:async e=>{let t=await this.call(`shell.open`,e),n={};this.#a.set(t.id,n);let r={id:t.id,cwd:t.cwd,home:t.home,run:async(e,n)=>{let i=this.#s++;this.#o.set(i,n);let a=()=>void this.#e.then(e=>e.emit(`shell:abort`,i));n.signal?.addEventListener(`abort`,a);try{let n=await this.call(`shell.run`,t.id,i,e);return r.cwd=n.cwd,n.code}finally{n.signal?.removeEventListener(`abort`,a),this.#o.delete(i)}},complete:e=>this.call(`shell.complete`,t.id,e),onReadLine:e=>{n.reader=e},onClear:e=>{n.clear=e},close:()=>{this.#a.delete(t.id),this.call(`shell.close`,t.id)}};return r}};mark(e){this.bootMarks.push({name:e,at:Math.round(performance.now()*10)/10})}hasCap(e){return this.caps.find(t=>t.id===e)?.ok??!1}notify(e){let t=typeof e==`string`?{title:e}:e;this.bus.emit(`notify`,t),this.call(`bus.emit`,`notify`,t)}openApp(e,t){this.bus.emit(`app:open`,{id:e,args:t}),this.call(`bus.emit`,`app:open`,{id:e,args:t})}async mountNativeFolder(){let e=globalThis.showDirectoryPicker;if(!e)throw Error(`This browser does not support mounting local folders (File System Access API).`);return this.call(`fs.mountHandle`,await e({mode:`readwrite`}))}},p={BASE_URL:`./`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1},m=p.VITE_KERNEL_URL||(e=>new URL(e,globalThis.location?.href??`http://localhost/`).href)(`../kernel/`),h=(p.VITE_ALLOWED_ORIGINS||``).split(`,`).map(e=>e.trim()).filter(Boolean),g=p.VITE_EMBED_ORIGINS?p.VITE_EMBED_ORIGINS.split(`,`).map(e=>e.trim()).filter(Boolean):h.length?h:`*`,_={box:null,storage:`opfs`},v=/^[A-Za-z0-9_-]{1,64}$/;function y(e){return e.box===null?`bbx-kernel`:`bbx-box:${e.storage}:${e.box}`}function b(e){let t=new URLSearchParams(e),n=t.get(`box`);if(n===null)return _;if(!v.test(n))throw Error(`invalid box id: ${n}`);return{box:n,storage:t.get(`storage`)===`memory`?`memory`:`opfs`}}function x(e){return e.box===null?``:`?box=${encodeURIComponent(e.box)}&storage=${e.storage}`}export{h as a,f as c,y as i,c as l,b as n,g as o,x as r,m as s,_ as t};
2
+ `).forEach((e,t)=>{(n?e.toLowerCase():e).includes(s)&&(c.length<i&&c.push({line:t+1,offset:u}),l++),u+=r.encode(e).length+1}),{total:l,matches:c}}wc(e){if(this.#e)return this.#n(e,(t,n)=>{let r=t.alloc(12);try{t.wc(n,e.length,r);let i=new DataView(t.memory.buffer,r,12);return{lines:i.getUint32(0,!0),words:i.getUint32(4,!0),bytes:i.getUint32(8,!0)}}finally{t.dealloc(r,12)}});let t=new TextDecoder().decode(e);return{lines:(t.match(/\n/g)??[]).length,words:(t.match(/\S+/g)??[]).length,bytes:e.length}}estimateTokens(e){if(this.#e){let t=r.encode(e);return this.#n(t,(e,n)=>e.estimate_tokens(n,t.length))}return Math.ceil(e.length/3.6)}},a=class{settings;#e=async()=>`deny`;constructor(e){this.settings=e}setPrompter(e){this.#e=e}prompt(e,t){return this.#e(e,t)}get mode(){return this.settings.get(`perms.mode`,`ask`)}set mode(e){this.settings.set(`perms.mode`,e)}grants(){return this.settings.get(`perms.grants`,[])}revoke(e){this.settings.set(`perms.grants`,this.grants().filter(t=>t!==e))}isGranted(e){return this.mode===`auto`||this.grants().includes(e)}async request(e,t){if(this.isGranted(e.cap))return!0;let n=await(t??this.#e)(e);return n===`always`&&this.settings.set(`perms.grants`,[...new Set([...this.grants(),e.cap])]),n!==`deny`}},o=class{bus;onWrite;#e=new Map;constructor(e,t){this.bus=e,this.onWrite=t}hydrate(e){this.#e=new Map(e);for(let[t,n]of e)this.bus.emit(`settings:change`,{key:t,value:n})}entries(){return[...this.#e]}get(e,t){return this.#e.has(e)?this.#e.get(e):t}set(e,t){this.applyRemote(e,t),this.onWrite?.(e,t)}delete(e){this.set(e,void 0)}applyRemote(e,t){t===void 0?this.#e.delete(e):this.#e.set(e,t),this.bus.emit(`settings:change`,{key:e,value:t})}keys(){return[...this.#e.keys()]}};function s(e){let t=[];for(let n of e.split(`/`))n&&n!==`.`&&(n===`..`?t.pop():t.push(n));return`/`+t.join(`/`)}function c(e,t){return s(t?t.startsWith(`/`)?t:`${e}/${t}`:e)}var l=class{port;#e=1;#t=new Map;#n={};#r=new Map;closed=!1;constructor(e){this.port=e,e.onmessage=e=>void this.#i(e.data)}handle(e){return Object.assign(this.#n,e),this}call(e,...t){return this.closed?Promise.reject(Error(`connection closed`)):new Promise((n,r)=>{let i=this.#e++;this.#t.set(i,{resolve:n,reject:r}),this.port.postMessage({k:`call`,id:i,m:e,a:t})})}emit(e,t){this.closed||this.port.postMessage({k:`evt`,n:e,p:t})}on(e,t){let n=this.#r.get(e);return n||this.#r.set(e,n=new Set),n.add(t),()=>n.delete(t)}close(){if(!this.closed){this.closed=!0,this.port.close();for(let e of this.#t.values())e.reject(Error(`connection closed`));this.#t.clear()}}async#i(e){if(e.k===`call`){let t=Object.hasOwn(this.#n,e.m)?this.#n[e.m]:void 0;try{if(!t)throw Error(`unknown method: ${e.m}`);let n=await t(...e.a);this.closed||this.port.postMessage({k:`ok`,id:e.id,v:n})}catch(t){let n=t;this.closed||this.port.postMessage({k:`err`,id:e.id,e:{name:n?.name??`Error`,message:n?.message??String(t)}})}}else if(e.k===`ok`||e.k===`err`){let t=this.#t.get(e.id);if(this.#t.delete(e.id),!t)return;if(e.k===`ok`)t.resolve(e.v);else{let n=Error(e.e.message);n.name=e.e.name,t.reject(n)}}else if(e.k===`evt`)for(let t of[...this.#r.get(e.n)??[]])try{t(e.p)}catch(t){console.error(`[rpc] listener for "${e.n}" threw`,t)}}},u=new AbortController().signal,d=new TextDecoder,f=class{version=``;rootKind=`opfs`;shared=!0;bootStart=0;bootMarks=[];bus=new e;settings=new o(this.bus,(e,t)=>void this.call(`settings.set`,e,t));perms=new a(this.settings);kcore=new i;caps=t();ready;kernelLog=[];#e;#t=new Map;#n=new Map;#r=0;#i=[];#a=new Map;#o=new Map;#s=1;#c=new Map;constructor(e,t=`ui`){this.#e=e.then(({port:e,lock:t,shared:n})=>{this.shared=n;let r=new l(e);return this.#d(r),r.emit(`alive`,t),r}),this.ready=this.#e.then(async e=>this.#l(await e.call(`hello`,t)))}async call(e,...t){return(await this.#e).call(e,...t)}async handle(e){return(await this.#e).handle(e)}#l(e){this.version=e.version,this.rootKind=e.rootKind,this.#r=e.pidBase+1,this.#i=e.mounts.map(e=>({point:e.point,fs:{label:e.label,readonly:e.readonly}})),this.bootMarks.push(...e.bootMarks.map(e=>({name:`kernel:${e.name}`,at:e.at}))),this.kernelLog.splice(0,this.kernelLog.length,...e.log),this.settings.hydrate(e.settings);for(let t of e.procs)this.bus.emit(`proc:spawn`,this.#u(t));this.mark(`kernel-connected`)}#u(e){let t=this.#t.get(e.pid);if(t)return Object.assign(t,e);let n={...e,signal:u};return this.#t.set(e.pid,n),n}#d(e){e.on(`bus`,({type:t,payload:n})=>{if(t===`settings:change`){let{key:e,value:t}=n;this.settings.applyRemote(e,t)}else if(t===`proc:spawn`||t===`proc:update`)this.bus.emit(t,this.#u(n));else if(t===`proc:exit`){let{proc:e,reason:t}=n,r=this.#u(e);this.#t.delete(e.pid),this.#p(e.pid,t),this.bus.emit(`proc:exit`,{proc:r,reason:t})}else t===`fs:change`&&n.type===`mount`?e.call(`fs.mounts`).then(e=>{this.#i=e.map(e=>({point:e.point,fs:{label:e.label,readonly:e.readonly}})),this.bus.emit(t,n)}):(t===`kmsg`&&!this.kernelLog.some(e=>e.t===n.t&&e.msg===n.msg)&&this.kernelLog.push(n),this.bus.emit(t,n))}),e.on(`proc:kill`,e=>this.#p(e,`killed`)),e.on(`shell:out`,({runId:e,s:t,t:n})=>{let r=this.#o.get(e);(t===`o`?r?.out:r?.err)?.(n)}),e.on(`shell:clear`,e=>this.#a.get(e)?.clear?.()),e.on(`ask`,t=>void this.#f(e,t)),e.on(`ask:done`,e=>{this.#c.get(e)?.abort(),this.#c.delete(e)})}async#f(e,t){let n=new AbortController;this.#c.set(t.askId,n);let r;try{if(t.kind===`perm`)r=await this.perms.prompt(t.payload,n.signal);else if(t.kind===`user`)return;else if(t.kind===`tty`){let e=t.shellId?this.#a.get(t.shellId)?.reader:void 0,{prompt:n,secret:i}=t.payload;r=e?await e(n,i??!1):null}else{let{method:e,args:n}=t.payload;e===`clipboard.write`?r=await navigator.clipboard.writeText(String(n[0])):e===`clipboard.read`?r=await navigator.clipboard.readText():e===`speak`&&speechSynthesis.speak(new SpeechSynthesisUtterance(String(n[0])))}}catch(e){if(n.signal.aborted)return;r=t.kind===`perm`?`deny`:t.kind===`ui`?`failed: ${e.message}`:null}n.signal.aborted||(this.#c.delete(t.askId),e.call(`answer`,t.askId,r))}#p(e,t){let n=this.#n.get(e);if(n){this.#n.delete(e),n.ctl.abort(new DOMException(t,`AbortError`));try{n.onKill?.()}catch(e){console.error(`[procs] onKill threw`,e)}}}procs={spawn:e=>{if(!this.#r)throw Error(`kernel not connected yet`);let t=new AbortController,n={pid:this.#r++,ppid:e.ppid??0,name:e.name,kind:e.kind,started:Date.now(),state:`running`,detail:e.detail??``,cpuMs:0,memBytes:0,signal:t.signal};this.#t.set(n.pid,n),this.#n.set(n.pid,{proc:n,ctl:t,onKill:e.onKill});let{signal:r,...i}=n;return this.call(`procs.spawn`,i),n},update:(e,t)=>{let n=this.#t.get(e);n&&Object.assign(n,t),this.call(`procs.update`,e,t)},account:(e,t)=>{let n=this.#t.get(e);n&&(n.cpuMs+=t),this.call(`procs.account`,e,t)},kill:(e,t=`killed`)=>this.#t.has(e)?(this.#n.has(e)&&this.#t.delete(e),this.#p(e,t),this.call(`procs.kill`,e,t),!0):!1,exit:e=>void this.procs.kill(e,`exit`),get:e=>this.#t.get(e),list:()=>[...this.#t.values()].sort((e,t)=>e.started-t.started||e.pid-t.pid)};fs=(e=>({get ready(){return e.ready},readFile:t=>e.call(`fs.readFile`,t),readText:async t=>d.decode(await e.call(`fs.readFile`,t)),writeFile:(t,n)=>e.call(`fs.writeFile`,t,n),appendFile:(t,n)=>e.call(`fs.appendFile`,t,n),readdir:t=>e.call(`fs.readdir`,t),stat:t=>e.call(`fs.stat`,t),exists:t=>e.call(`fs.stat`,t).then(Boolean,()=>!1),mkdir:t=>e.call(`fs.mkdir`,t),rm:(t,n)=>e.call(`fs.rm`,t,n),cp:(t,n)=>e.call(`fs.cp`,t,n),mv:(t,n)=>e.call(`fs.mv`,t,n),glob:(t,n,r)=>e.call(`fs.glob`,t,n,r),async*walk(t,n={}){let r=[[s(t),0]];for(;r.length;){let[t,i]=r.pop();n.signal?.throwIfAborted();let a=await e.call(`fs.readdir`,t).catch(()=>[]);for(let e of a)yield e,e.kind===`dir`&&i+1<(n.maxDepth??32)&&e.path!==`/proc`&&r.push([e.path,i+1])}},mounts:()=>e.#i,unmount:t=>void e.call(`fs.unmount`,t)}))(this);secrets={has:e=>this.call(`secrets.has`,e),set:(e,t)=>this.call(`secrets.set`,e,t),delete:e=>this.call(`secrets.delete`,e),status:()=>this.call(`secrets.status`),unlock:e=>this.call(`secrets.unlock`,e),lock:()=>this.call(`secrets.lock`),setPassword:e=>this.call(`secrets.setPassword`,e)};dev={start:e=>this.call(`dev.start`,e),stop:e=>this.call(`dev.stop`,e),list:()=>this.call(`dev.list`),page:(e,t)=>this.call(`dev.page`,e,t),request:(e,t)=>this.call(`dev.request`,e,t),log:(e,t)=>void this.call(`dev.log`,e,t).catch(()=>void 0),logs:(e,t)=>this.call(`dev.logs`,e,t)};shells={open:async e=>{let t=await this.call(`shell.open`,e),n={};this.#a.set(t.id,n);let r={id:t.id,cwd:t.cwd,home:t.home,run:async(e,n)=>{let i=this.#s++;this.#o.set(i,n);let a=()=>void this.#e.then(e=>e.emit(`shell:abort`,i));n.signal?.addEventListener(`abort`,a);try{let n=await this.call(`shell.run`,t.id,i,e);return r.cwd=n.cwd,n.code}finally{n.signal?.removeEventListener(`abort`,a),this.#o.delete(i)}},complete:e=>this.call(`shell.complete`,t.id,e),onReadLine:e=>{n.reader=e},onClear:e=>{n.clear=e},close:()=>{this.#a.delete(t.id),this.call(`shell.close`,t.id)}};return r}};mark(e){this.bootMarks.push({name:e,at:Math.round(performance.now()*10)/10})}hasCap(e){return this.caps.find(t=>t.id===e)?.ok??!1}notify(e){let t=typeof e==`string`?{title:e}:e;this.bus.emit(`notify`,t),this.call(`bus.emit`,`notify`,t)}openApp(e,t){this.bus.emit(`app:open`,{id:e,args:t}),this.call(`bus.emit`,`app:open`,{id:e,args:t})}async mountNativeFolder(){let e=globalThis.showDirectoryPicker;if(!e)throw Error(`This browser does not support mounting local folders (File System Access API).`);return this.call(`fs.mountHandle`,await e({mode:`readwrite`}))}},p={BASE_URL:`./`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1},m=p.VITE_KERNEL_URL||(e=>new URL(e,globalThis.location?.href??`http://localhost/`).href)(`../kernel/`),h=(p.VITE_ALLOWED_ORIGINS||``).split(`,`).map(e=>e.trim()).filter(Boolean),g=p.VITE_EMBED_ORIGINS?p.VITE_EMBED_ORIGINS.split(`,`).map(e=>e.trim()).filter(Boolean):h.length?h:`*`,_={box:null,storage:`opfs`},v=/^[A-Za-z0-9_-]{1,64}$/,y=e=>e?{box:null,storage:`opfs`,profile:e}:_;function b(e){return e.box===null?e.profile?`bbx-kernel:profile:${e.profile}`:`bbx-kernel`:`bbx-box:${e.storage}:${e.box}`}function x(e){let t=new URLSearchParams(e),n=t.get(`box`),r=t.get(`profile`);if(n===null&&r){if(!v.test(r))throw Error(`invalid profile id: ${r}`);return y(r)}if(n===null)return _;if(!v.test(n))throw Error(`invalid box id: ${n}`);return{box:n,storage:t.get(`storage`)===`memory`?`memory`:`opfs`}}function S(e){return e.box===null?e.profile?`?profile=${encodeURIComponent(e.profile)}`:``:`?box=${encodeURIComponent(e.box)}&storage=${e.storage}`}export{S as a,g as c,c as d,y as i,m as l,v as n,b as o,x as r,h as s,_ as t,f as u};
@@ -1,7 +1,7 @@
1
- import{a as e,c as t,i as n,n as r,o as i,s as a,t as o}from"./path-DGG-Mxbd.js";const s={box:null,storage:`opfs`};function c(e){let t=/^bbx-box:(opfs|memory):([A-Za-z0-9_-]{1,64})$/.exec(e);return t?{box:t[2],storage:t[1]}:s}function l(e,t){return t.storage===`memory`?null:t.box===null?e:`${e}:box:${t.box}`}var u=class{#e=/* @__PURE__ */ new Map;on(e,t){let n=this.#e.get(e);return n||this.#e.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}emit(e,t){let n=this.#e.get(e);if(n)for(let r of[...n])try{r(t)}catch(t){console.error(`[bus] handler for "${String(e)}" threw`,t)}}};function d(){let e=globalThis,t=globalThis.navigator??{},n=(e,t)=>typeof e==`object`&&!!e&&t in e,r=(e,t,n,r,i)=>({id:e,group:t,label:n,ok:!!r,use:i});return[r(`wasm`,`Compute`,`WebAssembly`,n(e,`WebAssembly`),`Rust kernel core, WASI programs, Pyodide`),r(`wasm-streaming`,`Compute`,`WASM streaming compile`,typeof WebAssembly?.instantiateStreaming==`function`,`Fast kernel boot`),r(`workers`,`Compute`,`Web Workers`,n(e,`Worker`),`Sandboxed code execution`),r(`sab`,`Compute`,`SharedArrayBuffer`,n(e,`SharedArrayBuffer`)&&e.crossOriginIsolated===!0,`Threads (needs cross-origin isolation)`),r(`webgpu`,`Compute`,`WebGPU`,n(t,`gpu`),`GPU compute tool, GPU Lab, in-browser LLM`),r(`scheduler`,`Compute`,`Scheduler API`,n(e,`scheduler`),`Prioritised background work`),r(`compression`,`Compute`,`Compression Streams`,n(e,`CompressionStream`),`gzip / gunzip`),r(`crypto`,`Compute`,`Web Crypto`,n(e.crypto,`subtle`),`Secret encryption, hashing`),r(`opfs`,`Storage`,`Origin Private File System`,n(t.storage,`getDirectory`),`Persistent root filesystem`),r(`fsaccess`,`Storage`,`File System Access`,n(e,`showDirectoryPicker`),`Mount real folders at /mnt`),r(`indexeddb`,`Storage`,`IndexedDB`,n(e,`indexedDB`),`Encrypted secrets`),r(`persist`,`Storage`,`Persistent storage`,n(t.storage,`persist`),`Protect data from eviction`),r(`cache`,`Storage`,`Cache Storage`,n(e,`caches`),`Offline boot, model weights`),r(`sw`,`System`,`Service Worker`,n(t,`serviceWorker`),`Instant offline boot`),r(`locks`,`System`,`Web Locks`,n(t,`locks`),`Cross-tab coordination`),r(`broadcast`,`System`,`BroadcastChannel`,n(e,`BroadcastChannel`),`Cross-tab filesystem events`),r(`notifications`,`System`,`Notifications`,n(e,`Notification`),`Agent task alerts`),r(`clipboard`,`System`,`Async Clipboard`,n(t,`clipboard`),`Clipboard tools`),r(`wakelock`,`System`,`Screen Wake Lock`,n(t,`wakeLock`),`Keep awake during long agent runs`),r(`share`,`System`,`Web Share`,n(t,`share`),`Share files`),r(`viewtransitions`,`System`,`View Transitions`,n(globalThis.document,`startViewTransition`),`Window animations`),r(`memory`,`System`,`Memory measurement`,n(globalThis.performance,`memory`)||n(globalThis.performance,`measureUserAgentSpecificMemory`),`Task Manager`),r(`battery`,`System`,`Battery Status`,n(t,`getBattery`),`System monitor`),r(`fetch-stream`,`Network`,`Streaming fetch`,n(e,`ReadableStream`),`LLM token streaming`),r(`websocket`,`Network`,`WebSocket`,n(e,`WebSocket`),`Realtime connections`),r(`webrtc`,`Network`,`WebRTC`,n(e,`RTCPeerConnection`),`Peer-to-peer`),r(`webtransport`,`Network`,`WebTransport`,n(e,`WebTransport`),`Low-latency transport`),r(`netinfo`,`Network`,`Network Information`,n(t,`connection`),`System monitor`),r(`offscreen`,`Graphics & Media`,`OffscreenCanvas`,n(e,`OffscreenCanvas`),`Off-thread rendering`),r(`webgl2`,`Graphics & Media`,`WebGL 2`,n(e,`WebGL2RenderingContext`),`Graphics fallback`),r(`webcodecs`,`Graphics & Media`,`WebCodecs`,n(e,`VideoEncoder`),`Media processing`),r(`webaudio`,`Graphics & Media`,`Web Audio`,n(e,`AudioContext`),`Sound`),r(`speech-tts`,`Graphics & Media`,`Speech synthesis`,n(e,`speechSynthesis`),`Agent speak tool`),r(`speech-stt`,`Graphics & Media`,`Speech recognition`,n(e,`SpeechRecognition`)||n(e,`webkitSpeechRecognition`),`Voice input`),r(`capture`,`Graphics & Media`,`Screen Capture`,n(t.mediaDevices,`getDisplayMedia`),`Screenshots`),r(`usb`,`Devices`,`WebUSB`,n(t,`usb`),`Hardware access`),r(`serial`,`Devices`,`Web Serial`,n(t,`serial`),`Hardware access`),r(`bluetooth`,`Devices`,`Web Bluetooth`,n(t,`bluetooth`),`Hardware access`),r(`hid`,`Devices`,`WebHID`,n(t,`hid`),`Hardware access`),r(`gamepad`,`Devices`,`Gamepad`,n(t,`getGamepads`),`Input`),r(`prompt-api`,`AI`,`Built-in Prompt API`,n(e,`LanguageModel`),`On-device model`),r(`webnn`,`AI`,`WebNN`,n(t,`ml`),`Neural network acceleration`)]}var f=new URL(`kcore-COUztiEr.wasm`,import.meta.url).href;const p=new TextEncoder;var m=class{#e=null;#t=null;get loaded(){return this.#e!==null}load(){return this.#t??=(async()=>{try{let{instance:e}=await WebAssembly.instantiateStreaming(fetch(f),{});this.#e=e.exports}catch(e){console.warn(`[kcore] wasm unavailable, using JS fallbacks`,e)}})()}#n(e,t){let n=this.#e,r=n.alloc(e.length);try{return new Uint8Array(n.memory.buffer,r,e.length).set(e),t(n,r)}finally{n.dealloc(r,e.length)}}hash(e){if(this.#e)return this.#n(e,(t,n)=>BigInt.asUintN(64,t.fnv1a64(n,e.length)).toString(16).padStart(16,`0`));let t=14695981039346656037n;for(let n of e)t=BigInt.asUintN(64,(t^BigInt(n))*1099511628211n);return t.toString(16).padStart(16,`0`)}searchLines(e,t,n=!1,r=1e3){let i=p.encode(t);if(this.#e)return this.#n(e,(t,a)=>{let o=t.alloc(i.length),s=t.alloc(r*8);try{new Uint8Array(t.memory.buffer,o,i.length).set(i);let c=t.search_lines(a,e.length,o,i.length,+!!n,s,r),l=new DataView(t.memory.buffer,s,r*8),u=[];for(let e=0;e<Math.min(c,r);e++)u.push({line:l.getUint32(e*8,!0),offset:l.getUint32(e*8+4,!0)});return{total:c,matches:u}}finally{t.dealloc(o,i.length),t.dealloc(s,r*8)}});let a=new TextDecoder().decode(e),o=n?t.toLowerCase():t,s=[],c=0,l=0;return a.split(`
2
- `).forEach((e,t)=>{(n?e.toLowerCase():e).includes(o)&&(s.length<r&&s.push({line:t+1,offset:l}),c++),l+=p.encode(e).length+1}),{total:c,matches:s}}wc(e){if(this.#e)return this.#n(e,(t,n)=>{let r=t.alloc(12);try{t.wc(n,e.length,r);let i=new DataView(t.memory.buffer,r,12);return{lines:i.getUint32(0,!0),words:i.getUint32(4,!0),bytes:i.getUint32(8,!0)}}finally{t.dealloc(r,12)}});let t=new TextDecoder().decode(e);return{lines:(t.match(/\n/g)??[]).length,words:(t.match(/\S+/g)??[]).length,bytes:e.length}}estimateTokens(e){if(this.#e){let t=p.encode(e);return this.#n(t,(e,n)=>e.estimate_tokens(n,t.length))}return Math.ceil(e.length/3.6)}};let h=null,g=null;function _(e){h=e,g=null}function v(){return h?(g??=h().catch(e=>{throw g=null,e}),g):Promise.reject(/* @__PURE__ */ Error(`esbuild is not available here`))}const y=`https://cdn.jsdelivr.net/pyodide/v0.29.0/full/`,ee=[`pyodide.js`,`pyodide.asm.js`,`pyodide.asm.wasm`,`python_stdlib.zip`,`pyodide-lock.json`],b=`bbx-packs`,x=`0.25.5`,te=`https://cdn.jsdelivr.net/npm/esbuild-wasm@${x}/`,S=[`esm/browser.min.js`,`esbuild.wasm`];async function ne(e,t){e.isInstalled(`esbuild`)||(t(`installing the esbuild package for the dev server`),await e.install(`esbuild`));let n=await caches.open(b),r=async e=>await n.match(`https://cdn.jsdelivr.net/npm/esbuild-wasm@0.25.5/`+e)??fetch(`https://cdn.jsdelivr.net/npm/esbuild-wasm@0.25.5/`+e),i=await(await r(S[0])).text(),a=URL.createObjectURL(new Blob([i],{type:`text/javascript`}));try{let e=await import(
1
+ import{a as e,c as t,i as n,n as r,o as i,s as a,t as o}from"./path-DGG-Mxbd.js";const s={box:null,storage:`opfs`},c=[`boxes`,`profiles`],l=e=>e?{box:null,storage:`opfs`,profile:e}:s;function u(e){let t=/^bbx-kernel:profile:([A-Za-z0-9_-]{1,64})$/.exec(e);if(t)return l(t[1]);let n=/^bbx-box:(opfs|memory):([A-Za-z0-9_-]{1,64})$/.exec(e);return n?{box:n[2],storage:n[1]}:s}function d(e,t){return t.storage===`memory`?null:t.box===null?t.profile?`${e}:profile:${t.profile}`:e:`${e}:box:${t.box}`}var f=class{#e=/* @__PURE__ */ new Map;on(e,t){let n=this.#e.get(e);return n||this.#e.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}emit(e,t){let n=this.#e.get(e);if(n)for(let r of[...n])try{r(t)}catch(t){console.error(`[bus] handler for "${String(e)}" threw`,t)}}};function p(){let e=globalThis,t=globalThis.navigator??{},n=(e,t)=>typeof e==`object`&&!!e&&t in e,r=(e,t,n,r,i)=>({id:e,group:t,label:n,ok:!!r,use:i});return[r(`wasm`,`Compute`,`WebAssembly`,n(e,`WebAssembly`),`Rust kernel core, WASI programs, Pyodide`),r(`wasm-streaming`,`Compute`,`WASM streaming compile`,typeof WebAssembly?.instantiateStreaming==`function`,`Fast kernel boot`),r(`workers`,`Compute`,`Web Workers`,n(e,`Worker`),`Sandboxed code execution`),r(`sab`,`Compute`,`SharedArrayBuffer`,n(e,`SharedArrayBuffer`)&&e.crossOriginIsolated===!0,`Threads (needs cross-origin isolation)`),r(`webgpu`,`Compute`,`WebGPU`,n(t,`gpu`),`GPU compute tool, GPU Lab, in-browser LLM`),r(`scheduler`,`Compute`,`Scheduler API`,n(e,`scheduler`),`Prioritised background work`),r(`compression`,`Compute`,`Compression Streams`,n(e,`CompressionStream`),`gzip / gunzip`),r(`crypto`,`Compute`,`Web Crypto`,n(e.crypto,`subtle`),`Secret encryption, hashing`),r(`opfs`,`Storage`,`Origin Private File System`,n(t.storage,`getDirectory`),`Persistent root filesystem`),r(`fsaccess`,`Storage`,`File System Access`,n(e,`showDirectoryPicker`),`Mount real folders at /mnt`),r(`indexeddb`,`Storage`,`IndexedDB`,n(e,`indexedDB`),`Encrypted secrets`),r(`persist`,`Storage`,`Persistent storage`,n(t.storage,`persist`),`Protect data from eviction`),r(`cache`,`Storage`,`Cache Storage`,n(e,`caches`),`Offline boot, model weights`),r(`sw`,`System`,`Service Worker`,n(t,`serviceWorker`),`Instant offline boot`),r(`locks`,`System`,`Web Locks`,n(t,`locks`),`Cross-tab coordination`),r(`broadcast`,`System`,`BroadcastChannel`,n(e,`BroadcastChannel`),`Cross-tab filesystem events`),r(`notifications`,`System`,`Notifications`,n(e,`Notification`),`Agent task alerts`),r(`clipboard`,`System`,`Async Clipboard`,n(t,`clipboard`),`Clipboard tools`),r(`wakelock`,`System`,`Screen Wake Lock`,n(t,`wakeLock`),`Keep awake during long agent runs`),r(`share`,`System`,`Web Share`,n(t,`share`),`Share files`),r(`viewtransitions`,`System`,`View Transitions`,n(globalThis.document,`startViewTransition`),`Window animations`),r(`memory`,`System`,`Memory measurement`,n(globalThis.performance,`memory`)||n(globalThis.performance,`measureUserAgentSpecificMemory`),`Task Manager`),r(`battery`,`System`,`Battery Status`,n(t,`getBattery`),`System monitor`),r(`fetch-stream`,`Network`,`Streaming fetch`,n(e,`ReadableStream`),`LLM token streaming`),r(`websocket`,`Network`,`WebSocket`,n(e,`WebSocket`),`Realtime connections`),r(`webrtc`,`Network`,`WebRTC`,n(e,`RTCPeerConnection`),`Peer-to-peer`),r(`webtransport`,`Network`,`WebTransport`,n(e,`WebTransport`),`Low-latency transport`),r(`netinfo`,`Network`,`Network Information`,n(t,`connection`),`System monitor`),r(`offscreen`,`Graphics & Media`,`OffscreenCanvas`,n(e,`OffscreenCanvas`),`Off-thread rendering`),r(`webgl2`,`Graphics & Media`,`WebGL 2`,n(e,`WebGL2RenderingContext`),`Graphics fallback`),r(`webcodecs`,`Graphics & Media`,`WebCodecs`,n(e,`VideoEncoder`),`Media processing`),r(`webaudio`,`Graphics & Media`,`Web Audio`,n(e,`AudioContext`),`Sound`),r(`speech-tts`,`Graphics & Media`,`Speech synthesis`,n(e,`speechSynthesis`),`Agent speak tool`),r(`speech-stt`,`Graphics & Media`,`Speech recognition`,n(e,`SpeechRecognition`)||n(e,`webkitSpeechRecognition`),`Voice input`),r(`capture`,`Graphics & Media`,`Screen Capture`,n(t.mediaDevices,`getDisplayMedia`),`Screenshots`),r(`usb`,`Devices`,`WebUSB`,n(t,`usb`),`Hardware access`),r(`serial`,`Devices`,`Web Serial`,n(t,`serial`),`Hardware access`),r(`bluetooth`,`Devices`,`Web Bluetooth`,n(t,`bluetooth`),`Hardware access`),r(`hid`,`Devices`,`WebHID`,n(t,`hid`),`Hardware access`),r(`gamepad`,`Devices`,`Gamepad`,n(t,`getGamepads`),`Input`),r(`prompt-api`,`AI`,`Built-in Prompt API`,n(e,`LanguageModel`),`On-device model`),r(`webnn`,`AI`,`WebNN`,n(t,`ml`),`Neural network acceleration`)]}var m=new URL(`kcore-COUztiEr.wasm`,import.meta.url).href;const h=new TextEncoder;var g=class{#e=null;#t=null;get loaded(){return this.#e!==null}load(){return this.#t??=(async()=>{try{let{instance:e}=await WebAssembly.instantiateStreaming(fetch(m),{});this.#e=e.exports}catch(e){console.warn(`[kcore] wasm unavailable, using JS fallbacks`,e)}})()}#n(e,t){let n=this.#e,r=n.alloc(e.length);try{return new Uint8Array(n.memory.buffer,r,e.length).set(e),t(n,r)}finally{n.dealloc(r,e.length)}}hash(e){if(this.#e)return this.#n(e,(t,n)=>BigInt.asUintN(64,t.fnv1a64(n,e.length)).toString(16).padStart(16,`0`));let t=14695981039346656037n;for(let n of e)t=BigInt.asUintN(64,(t^BigInt(n))*1099511628211n);return t.toString(16).padStart(16,`0`)}searchLines(e,t,n=!1,r=1e3){let i=h.encode(t);if(this.#e)return this.#n(e,(t,a)=>{let o=t.alloc(i.length),s=t.alloc(r*8);try{new Uint8Array(t.memory.buffer,o,i.length).set(i);let c=t.search_lines(a,e.length,o,i.length,+!!n,s,r),l=new DataView(t.memory.buffer,s,r*8),u=[];for(let e=0;e<Math.min(c,r);e++)u.push({line:l.getUint32(e*8,!0),offset:l.getUint32(e*8+4,!0)});return{total:c,matches:u}}finally{t.dealloc(o,i.length),t.dealloc(s,r*8)}});let a=new TextDecoder().decode(e),o=n?t.toLowerCase():t,s=[],c=0,l=0;return a.split(`
2
+ `).forEach((e,t)=>{(n?e.toLowerCase():e).includes(o)&&(s.length<r&&s.push({line:t+1,offset:l}),c++),l+=h.encode(e).length+1}),{total:c,matches:s}}wc(e){if(this.#e)return this.#n(e,(t,n)=>{let r=t.alloc(12);try{t.wc(n,e.length,r);let i=new DataView(t.memory.buffer,r,12);return{lines:i.getUint32(0,!0),words:i.getUint32(4,!0),bytes:i.getUint32(8,!0)}}finally{t.dealloc(r,12)}});let t=new TextDecoder().decode(e);return{lines:(t.match(/\n/g)??[]).length,words:(t.match(/\S+/g)??[]).length,bytes:e.length}}estimateTokens(e){if(this.#e){let t=h.encode(e);return this.#n(t,(e,n)=>e.estimate_tokens(n,t.length))}return Math.ceil(e.length/3.6)}};let _=null,v=null;function ee(e){_=e,v=null}function te(){return _?(v??=_().catch(e=>{throw v=null,e}),v):Promise.reject(/* @__PURE__ */ Error(`esbuild is not available here`))}const y=`https://cdn.jsdelivr.net/pyodide/v0.29.0/full/`,ne=[`pyodide.js`,`pyodide.asm.js`,`pyodide.asm.wasm`,`python_stdlib.zip`,`pyodide-lock.json`],b=`bbx-packs`,x=`0.25.5`,re=`https://cdn.jsdelivr.net/npm/esbuild-wasm@${x}/`,S=[`esm/browser.min.js`,`esbuild.wasm`];async function ie(e,t){e.isInstalled(`esbuild`)||(t(`installing the esbuild package for the dev server`),await e.install(`esbuild`));let n=await caches.open(b),r=async e=>await n.match(`https://cdn.jsdelivr.net/npm/esbuild-wasm@0.25.5/`+e)??fetch(`https://cdn.jsdelivr.net/npm/esbuild-wasm@0.25.5/`+e),i=await(await r(S[0])).text(),a=URL.createObjectURL(new Blob([i],{type:`text/javascript`}));try{let e=await import(
3
3
  /* @vite-ignore */
4
- a),n=await WebAssembly.compile(await(await r(S[1])).arrayBuffer());return await e.initialize({wasmModule:n,worker:!1}),t(`esbuild ${x} ready`),e}finally{URL.revokeObjectURL(a)}}var re=class{os;#e=null;constructor(e){this.os=e}#t(){return this.#e??=import(`./server-B0hTONK2.js`).then(e=>new e.DevServers(this.os)),this.#e}start(e){return this.#t().then(t=>t.start(e))}async stop(e){return this.#e?(await this.#e).stop(e):!1}async list(){return this.#e?(await this.#e).list():[]}page(e,t){return this.#t().then(n=>n.page(e,t))}request(e,t){return this.#t().then(n=>n.request(e,t))}log(e,t){this.#e?.then(n=>n.log(e,t))}async logs(e,t){if(!this.#e)throw Error(`nothing is serving on port ${e} (see: serve list)`);return(await this.#e).logs(e,t)}};const C={BASE_URL:`./`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1},w=C.VITE_KERNEL_URL||(e=>new URL(e,globalThis.location?.href??`http://localhost/`).href)(`../kernel/`),ie=(C.VITE_ALLOWED_ORIGINS||``).split(`,`).map(e=>e.trim()).filter(Boolean);C.VITE_EMBED_ORIGINS?C.VITE_EMBED_ORIGINS.split(`,`).map(e=>e.trim()).filter(Boolean):ie.length;const ae={manifests:[],load:e=>Promise.reject(/* @__PURE__ */ Error(`package ${e} has no code`))},T=`pkg.installed`;var oe=class{os;registry;#e=/* @__PURE__ */ new Map;#t=null;constructor(e,t=ae){this.os=e,this.registry=t}manifests(){return this.registry.manifests}#n(e){return this.registry.manifests.find(t=>t.id===e)}#r(e,t){return this.registry.manifests.find(n=>n[t].includes(e))}installed(){return this.os.settings.get(T,[])}isInstalled(e){return this.installed().includes(e)}async#i(e){return this.#t??=fetch(new URL(`packages.json`,w)).then(e=>e.ok?e.json():{}).catch(()=>({})),[...((await this.#t)[e.id]??[]).map(e=>({url:new URL(`../${e.url}`,w).href,bytes:e.bytes})),...(e.remote??[]).map(e=>({url:e,bytes:0}))]}async list(){let e=await caches.open(b).catch(()=>null);return Promise.all(this.registry.manifests.map(async t=>{let n=0,r=!1;for(let i of await this.#i(t)){let t=i.bytes||Number((await e?.match(i.url))?.headers.get(`x-bbx-bytes`))||0;t||(r=!0),n+=t}let i=r&&!!t.remoteBytes;return{...t,installed:this.isInstalled(t.id),bytes:i?n+t.remoteBytes:n,estimated:i}}))}async install(e,t){let n=this.#n(e);if(!n)throw Error(`no such package: ${e} (see pkg list)`);let r=await this.#i(n),i=await caches.open(b),a=r.reduce((e,t)=>e+t.bytes,0),o=0;t?.(0,a);for(let e of r){let n=await i.match(e.url);if(n){o+=e.bytes||Number(n.headers.get(`x-bbx-bytes`))||0,a=Math.max(a,o),t?.(o,a);continue}let r=await fetch(e.url);if(!r.ok||!r.body)throw Error(`download failed (HTTP ${r.status}): ${e.url}`);e.bytes||(a+=Number(r.headers.get(`content-length`))||0);let s=[],c=0;for(let e=r.body.getReader();;){let{value:n,done:r}=await e.read();if(r)break;s.push(n),c+=n.length,o+=n.length,a=Math.max(a,o),t?.(o,a)}let l=new Headers(r.headers);l.set(`x-bbx-bytes`,String(c)),l.delete(`content-encoding`),l.delete(`content-length`),await i.put(e.url,new Response(new Blob(s),{headers:l}))}this.isInstalled(e)||this.os.settings.set(T,[...this.installed(),e].sort()),this.os.log(`pkg`,`installed ${e} ${n.version}`)}async remove(e){let t=this.#n(e);if(!t)throw Error(`no such package: ${e}`);this.os.settings.set(T,this.installed().filter(t=>t!==e)),this.#e.delete(e);let n=await caches.open(b);for(let e of await this.#i(t))await n.delete(e.url);this.os.log(`pkg`,`removed ${e}`)}load(e){if(!this.isInstalled(e))return Promise.reject(/* @__PURE__ */ Error(`package ${e} is not installed. Run: pkg install ${e}`));let t=this.#e.get(e);return t||(t=this.registry.load(e),this.#e.set(e,t),t.catch(()=>this.#e.delete(e))),t}async provided(e,t){let n=this.#r(t,e);if(!n)return null;if(!this.isInstalled(n.id))throw Error(`${t}: provided by the ${n.id} package, which is not installed. Run: pkg install ${n.id}`);return(await this.load(n.id))[e]?.find(e=>e.name===t)??null}async all(e){return(await Promise.all(this.registry.manifests.filter(t=>t[e].length&&this.isInstalled(t.id)).map(e=>this.load(e.id).catch(()=>null)))).flatMap(t=>t?.[e]??[])}},se=class{settings;#e=async()=>`deny`;constructor(e){this.settings=e}setPrompter(e){this.#e=e}prompt(e,t){return this.#e(e,t)}get mode(){return this.settings.get(`perms.mode`,`ask`)}set mode(e){this.settings.set(`perms.mode`,e)}grants(){return this.settings.get(`perms.grants`,[])}revoke(e){this.settings.set(`perms.grants`,this.grants().filter(t=>t!==e))}isGranted(e){return this.mode===`auto`||this.grants().includes(e)}async request(e,t){if(this.isGranted(e.cap))return!0;let n=await(t??this.#e)(e);return n===`always`&&this.settings.set(`perms.grants`,[.../* @__PURE__ */ new Set([...this.grants(),e.cap])]),n!==`deny`}},ce=class{bus;#e=1;#t=/* @__PURE__ */ new Map;constructor(e){this.bus=e}spawn(e){let t=new AbortController,n={pid:e.pid??this.#e++,ppid:e.ppid??0,name:e.name,kind:e.kind,started:Date.now(),state:`running`,detail:e.detail??``,cpuMs:0,memBytes:0,signal:t.signal};return this.#t.set(n.pid,{proc:n,ctl:t,onKill:e.onKill}),this.bus.emit(`proc:spawn`,n),n}update(e,t){let n=this.#t.get(e);n&&(Object.assign(n.proc,t),this.bus.emit(`proc:update`,n.proc))}account(e,t){let n=this.#t.get(e);n&&(n.proc.cpuMs+=t)}kill(e,t=`killed`){let n=this.#t.get(e);if(!n)return!1;this.#t.delete(e);for(let n of this.list())n.ppid===e&&this.kill(n.pid,t);n.ctl.abort(new DOMException(t,`AbortError`));try{n.onKill?.()}catch(e){console.error(`[proc] onKill for ${n.proc.name} threw`,e)}return this.bus.emit(`proc:exit`,{proc:n.proc,reason:t}),!0}exit(e){this.kill(e,`exit`)}get(e){return this.#t.get(e)?.proc}list(){return[...this.#t.values()].map(e=>e.proc)}},E=class e extends Error{code;constructor(t,n,r){super(`${t}: ${r??e.text[t]}, '${n}'`),this.code=t,this.name=`FsError`}static text={ENOENT:`no such file or directory`,EEXIST:`file already exists`,ENOTDIR:`not a directory`,EISDIR:`is a directory`,EACCES:`permission denied`,ENOTEMPTY:`directory not empty`,EIO:`i/o error`}};const le=new TextEncoder;var ue=class{label=`procfs`;readonly=!0;#e;constructor(e){this.#e={ps:()=>e.procs.list().map(e=>`${e.pid}\t${e.ppid}\t${e.kind}\t${e.state}\t${Math.round(e.cpuMs)}ms\t${e.name}\t${e.detail}`).join(`
4
+ a),n=await WebAssembly.compile(await(await r(S[1])).arrayBuffer());return await e.initialize({wasmModule:n,worker:!1}),t(`esbuild ${x} ready`),e}finally{URL.revokeObjectURL(a)}}var ae=class{os;#e=null;constructor(e){this.os=e}#t(){return this.#e??=import(`./server-DPVY2l_9.js`).then(e=>new e.DevServers(this.os)),this.#e}start(e){return this.#t().then(t=>t.start(e))}async stop(e){return this.#e?(await this.#e).stop(e):!1}async list(){return this.#e?(await this.#e).list():[]}page(e,t){return this.#t().then(n=>n.page(e,t))}request(e,t){return this.#t().then(n=>n.request(e,t))}log(e,t){this.#e?.then(n=>n.log(e,t))}async logs(e,t){if(!this.#e)throw Error(`nothing is serving on port ${e} (see: serve list)`);return(await this.#e).logs(e,t)}};const C={BASE_URL:`./`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1},w=C.VITE_KERNEL_URL||(e=>new URL(e,globalThis.location?.href??`http://localhost/`).href)(`../kernel/`),oe=(C.VITE_ALLOWED_ORIGINS||``).split(`,`).map(e=>e.trim()).filter(Boolean);C.VITE_EMBED_ORIGINS?C.VITE_EMBED_ORIGINS.split(`,`).map(e=>e.trim()).filter(Boolean):oe.length;const se={manifests:[],load:e=>Promise.reject(/* @__PURE__ */ Error(`package ${e} has no code`))},T=`pkg.installed`;var ce=class{os;registry;#e=/* @__PURE__ */ new Map;#t=null;constructor(e,t=se){this.os=e,this.registry=t}manifests(){return this.registry.manifests}#n(e){return this.registry.manifests.find(t=>t.id===e)}#r(e,t){return this.registry.manifests.find(n=>n[t].includes(e))}installed(){return this.os.settings.get(T,[])}isInstalled(e){return this.installed().includes(e)}async#i(e){return this.#t??=fetch(new URL(`packages.json`,w)).then(e=>e.ok?e.json():{}).catch(()=>({})),[...((await this.#t)[e.id]??[]).map(e=>({url:new URL(`../${e.url}`,w).href,bytes:e.bytes})),...(e.remote??[]).map(e=>({url:e,bytes:0}))]}async list(){let e=await caches.open(b).catch(()=>null);return Promise.all(this.registry.manifests.map(async t=>{let n=0,r=!1;for(let i of await this.#i(t)){let t=i.bytes||Number((await e?.match(i.url))?.headers.get(`x-bbx-bytes`))||0;t||(r=!0),n+=t}let i=r&&!!t.remoteBytes;return{...t,installed:this.isInstalled(t.id),bytes:i?n+t.remoteBytes:n,estimated:i}}))}async install(e,t){let n=this.#n(e);if(!n)throw Error(`no such package: ${e} (see pkg list)`);let r=await this.#i(n),i=await caches.open(b),a=r.reduce((e,t)=>e+t.bytes,0),o=0;t?.(0,a);for(let e of r){let n=await i.match(e.url);if(n){o+=e.bytes||Number(n.headers.get(`x-bbx-bytes`))||0,a=Math.max(a,o),t?.(o,a);continue}let r=await fetch(e.url);if(!r.ok||!r.body)throw Error(`download failed (HTTP ${r.status}): ${e.url}`);e.bytes||(a+=Number(r.headers.get(`content-length`))||0);let s=[],c=0;for(let e=r.body.getReader();;){let{value:n,done:r}=await e.read();if(r)break;s.push(n),c+=n.length,o+=n.length,a=Math.max(a,o),t?.(o,a)}let l=new Headers(r.headers);l.set(`x-bbx-bytes`,String(c)),l.delete(`content-encoding`),l.delete(`content-length`),await i.put(e.url,new Response(new Blob(s),{headers:l}))}this.isInstalled(e)||this.os.settings.set(T,[...this.installed(),e].sort()),this.os.log(`pkg`,`installed ${e} ${n.version}`)}async remove(e){let t=this.#n(e);if(!t)throw Error(`no such package: ${e}`);this.os.settings.set(T,this.installed().filter(t=>t!==e)),this.#e.delete(e);let n=await caches.open(b);for(let e of await this.#i(t))await n.delete(e.url);this.os.log(`pkg`,`removed ${e}`)}load(e){if(!this.isInstalled(e))return Promise.reject(/* @__PURE__ */ Error(`package ${e} is not installed. Run: pkg install ${e}`));let t=this.#e.get(e);return t||(t=this.registry.load(e),this.#e.set(e,t),t.catch(()=>this.#e.delete(e))),t}async provided(e,t){let n=this.#r(t,e);if(!n)return null;if(!this.isInstalled(n.id))throw Error(`${t}: provided by the ${n.id} package, which is not installed. Run: pkg install ${n.id}`);return(await this.load(n.id))[e]?.find(e=>e.name===t)??null}async all(e){return(await Promise.all(this.registry.manifests.filter(t=>t[e].length&&this.isInstalled(t.id)).map(e=>this.load(e.id).catch(()=>null)))).flatMap(t=>t?.[e]??[])}},le=class{settings;#e=async()=>`deny`;constructor(e){this.settings=e}setPrompter(e){this.#e=e}prompt(e,t){return this.#e(e,t)}get mode(){return this.settings.get(`perms.mode`,`ask`)}set mode(e){this.settings.set(`perms.mode`,e)}grants(){return this.settings.get(`perms.grants`,[])}revoke(e){this.settings.set(`perms.grants`,this.grants().filter(t=>t!==e))}isGranted(e){return this.mode===`auto`||this.grants().includes(e)}async request(e,t){if(this.isGranted(e.cap))return!0;let n=await(t??this.#e)(e);return n===`always`&&this.settings.set(`perms.grants`,[.../* @__PURE__ */ new Set([...this.grants(),e.cap])]),n!==`deny`}},ue=class{bus;#e=1;#t=/* @__PURE__ */ new Map;constructor(e){this.bus=e}spawn(e){let t=new AbortController,n={pid:e.pid??this.#e++,ppid:e.ppid??0,name:e.name,kind:e.kind,started:Date.now(),state:`running`,detail:e.detail??``,cpuMs:0,memBytes:0,signal:t.signal};return this.#t.set(n.pid,{proc:n,ctl:t,onKill:e.onKill}),this.bus.emit(`proc:spawn`,n),n}update(e,t){let n=this.#t.get(e);n&&(Object.assign(n.proc,t),this.bus.emit(`proc:update`,n.proc))}account(e,t){let n=this.#t.get(e);n&&(n.proc.cpuMs+=t)}kill(e,t=`killed`){let n=this.#t.get(e);if(!n)return!1;this.#t.delete(e);for(let n of this.list())n.ppid===e&&this.kill(n.pid,t);n.ctl.abort(new DOMException(t,`AbortError`));try{n.onKill?.()}catch(e){console.error(`[proc] onKill for ${n.proc.name} threw`,e)}return this.bus.emit(`proc:exit`,{proc:n.proc,reason:t}),!0}exit(e){this.kill(e,`exit`)}get(e){return this.#t.get(e)?.proc}list(){return[...this.#t.values()].map(e=>e.proc)}},E=class e extends Error{code;constructor(t,n,r){super(`${t}: ${r??e.text[t]}, '${n}'`),this.code=t,this.name=`FsError`}static text={ENOENT:`no such file or directory`,EEXIST:`file already exists`,ENOTDIR:`not a directory`,EISDIR:`is a directory`,EACCES:`permission denied`,ENOTEMPTY:`directory not empty`,EIO:`i/o error`}};const de=new TextEncoder;var fe=class{label=`procfs`;readonly=!0;#e;constructor(e){this.#e={ps:()=>e.procs.list().map(e=>`${e.pid}\t${e.ppid}\t${e.kind}\t${e.state}\t${Math.round(e.cpuMs)}ms\t${e.name}\t${e.detail}`).join(`
5
5
  `)+`
6
6
  `,mounts:()=>e.fs.mounts().map(e=>`${e.fs.label}\t${e.point}\t${e.fs.readonly?`ro`:`rw`}`).join(`
7
7
  `)+`
@@ -9,7 +9,7 @@ a),n=await WebAssembly.compile(await(await r(S[1])).arrayBuffer());return await
9
9
  `)+`
10
10
  `,uptime:()=>`${((performance.now()-e.bootStart)/1e3).toFixed(1)}\n`,version:()=>`BrowserBox ${e.version} (${navigator.userAgent})\n`,meminfo:async()=>{let e=await navigator.storage?.estimate?.().catch(()=>void 0),t=performance.memory;return[`DeviceMemoryGB:\t${navigator.deviceMemory??`unknown`}`,`JsHeapUsed:\t${t?.usedJSHeapSize??`unknown`}`,`JsHeapLimit:\t${t?.jsHeapSizeLimit??`unknown`}`,`StorageUsed:\t${e?.usage??`unknown`}`,`StorageQuota:\t${e?.quota??`unknown`}`,`Cores:\t${navigator.hardwareConcurrency??`unknown`}`].join(`
11
11
  `)+`
12
- `}}}async readFile(e){let t=this.#e[e.slice(1)];if(!t)throw new E(e===`/`?`EISDIR`:`ENOENT`,e);return le.encode(await t())}async writeFile(e){throw new E(`EACCES`,e)}async readdir(e){if(e!==`/`)throw new E(`ENOTDIR`,e);return Object.keys(this.#e).map(e=>({path:`/`+e,name:e,kind:`file`,size:0,mtime:Date.now()}))}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};let t=e.slice(1);return t in this.#e?{path:e,name:t,kind:`file`,size:0,mtime:Date.now()}:null}async mkdir(e){throw new E(`EACCES`,e)}async remove(e){throw new E(`EACCES`,e)}};const de=`bbx-secrets`;function fe(e){return e===null?Promise.reject(/* @__PURE__ */ Error(`in-memory`)):new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function D(e,t,n){return new Promise((r,i)=>{let a=n(e.transaction(`kv`,t).objectStore(`kv`));a.onsuccess=()=>r(a.result),a.onerror=()=>i(a.error)})}var pe=class{dbName;#e=null;#t=/* @__PURE__ */ new Map;constructor(e=de){this.dbName=e}#n(){return this.#e??=fe(this.dbName)}async#r(e){let t=await D(e,`readonly`,e=>e.get(`#master`));if(t)return t;let n=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return await D(e,`readwrite`,e=>e.put(n,`#master`)),n}async get(e){try{let t=await this.#n(),n=await D(t,`readonly`,t=>t.get(e));if(!n)return this.#t.get(e)??null;let r=await crypto.subtle.decrypt({name:`AES-GCM`,iv:n.iv},await this.#r(t),n.data);return new TextDecoder().decode(r)}catch{return this.#t.get(e)??null}}async set(e,t){if(!t)return this.delete(e);try{let n=await this.#n(),r=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),i=await crypto.subtle.encrypt({name:`AES-GCM`,iv:r},await this.#r(n),new TextEncoder().encode(t));await D(n,`readwrite`,t=>t.put({iv:r,data:i},e))}catch{this.#t.set(e,t)}}async delete(e){this.#t.delete(e);try{await D(await this.#n(),`readwrite`,t=>t.delete(e))}catch{}}async has(e){return await this.get(e)!==null}},me=class{bus;onWrite;#e=/* @__PURE__ */ new Map;constructor(e,t){this.bus=e,this.onWrite=t}hydrate(e){this.#e=new Map(e);for(let[t,n]of e)this.bus.emit(`settings:change`,{key:t,value:n})}entries(){return[...this.#e]}get(e,t){return this.#e.has(e)?this.#e.get(e):t}set(e,t){this.applyRemote(e,t),this.onWrite?.(e,t)}delete(e){this.set(e,void 0)}applyRemote(e,t){t===void 0?this.#e.delete(e):this.#e.set(e,t),this.bus.emit(`settings:change`,{key:e,value:t})}keys(){return[...this.#e.keys()]}};const O=`bbx-settings`;function he(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function ge(e=O){if(e===null)return[];try{let t=await he(e);return await new Promise((e,n)=>{let r=[],i=t.transaction(`kv`,`readonly`).objectStore(`kv`).openCursor();i.onsuccess=()=>{let t=i.result;if(!t)return e(r);r.push([String(t.key),t.value]),t.continue()},i.onerror=()=>n(i.error)})}catch{return[]}}async function _e(e,t,n=O){if(n!==null)try{let r=(await he(n)).transaction(`kv`,`readwrite`).objectStore(`kv`);t===void 0?r.delete(e):r.put(t,e)}catch{}}var ve=class{label;#e=/* @__PURE__ */ new Map;constructor(e,t){this.label=t,this.#e.set(`/`,e)}async#t(e,t=!1){let n=this.#e.get(e);if(n)return n;let i=await this.#t(r(e),t);try{let n=await i.getDirectoryHandle(o(e),{create:t});return this.#e.set(e,n),n}catch(t){throw this.#n(t,e)}}#n(e,t){let n=e?.name;return n===`NotFoundError`?new E(`ENOENT`,t):n===`TypeMismatchError`?new E(`ENOTDIR`,t):n===`NotAllowedError`||n===`SecurityError`?new E(`EACCES`,t):n===`InvalidModificationError`?new E(`ENOTEMPTY`,t):new E(`EIO`,t,e?.message)}async readFile(e){try{let t=await(await this.#t(r(e))).getFileHandle(o(e));for(let e=0;;e++)try{return new Uint8Array(await(await t.getFile()).arrayBuffer())}catch(t){if(e>=4||t?.name!==`NotReadableError`)throw t;await new Promise(t=>setTimeout(t,20*(e+1)))}}catch(t){if(t instanceof E)throw t;let n=this.#n(t,e);throw n.code===`ENOTDIR`?new E(`EISDIR`,e):n}}async writeFile(e,t){try{let n=await(await(await this.#t(r(e))).getFileHandle(o(e),{create:!0})).createWritable();await n.write(t),await n.close()}catch(t){throw t instanceof E?t:this.#n(t,e)}}async readdir(e){let t=await this.#t(e),n=e===`/`?`/`:e+`/`,r=[];for await(let[e,i]of t.entries()){let t=n+e;i.kind===`directory`?r.push(Promise.resolve({path:t,name:e,kind:`dir`,size:0,mtime:0})):r.push(i.getFile().then(n=>({path:t,name:e,kind:`file`,size:n.size,mtime:n.lastModified})).catch(()=>({path:t,name:e,kind:`file`,size:0,mtime:0})))}return Promise.all(r)}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};let t;try{t=await this.#t(r(e))}catch{return null}let n=o(e);try{let r=await(await t.getFileHandle(n)).getFile();return{path:e,name:n,kind:`file`,size:r.size,mtime:r.lastModified}}catch{try{return await t.getDirectoryHandle(n),{path:e,name:n,kind:`dir`,size:0,mtime:0}}catch{return null}}}async mkdir(e){await this.#t(e,!0)}async remove(e,t){if(e===`/`)throw new E(`EACCES`,e);try{await(await this.#t(r(e))).removeEntry(o(e),{recursive:t})}catch(t){throw t instanceof E?t:this.#n(t,e)}for(let t of[...this.#e.keys()])(t===e||t.startsWith(e+`/`))&&this.#e.delete(t)}},ye=class{label=`memfs`;#e=/* @__PURE__ */ new Map([[`/`,{kind:`dir`,mtime:Date.now()}]]);async readFile(e){let t=this.#e.get(e);if(!t)throw new E(`ENOENT`,e);if(t.kind===`dir`)throw new E(`EISDIR`,e);return t.data.slice()}async writeFile(e,t){let n=this.#e.get(r(e));if(!n)throw new E(`ENOENT`,r(e));if(n.kind!==`dir`)throw new E(`ENOTDIR`,r(e));if(this.#e.get(e)?.kind===`dir`)throw new E(`EISDIR`,e);this.#e.set(e,{kind:`file`,data:t.slice(),mtime:Date.now()})}async readdir(e){let t=this.#e.get(e);if(!t)throw new E(`ENOENT`,e);if(t.kind!==`dir`)throw new E(`ENOTDIR`,e);let n=e===`/`?`/`:e+`/`,r=[];for(let[e,t]of this.#e)e!==`/`&&e.startsWith(n)&&!e.slice(n.length).includes(`/`)&&r.push(this.#t(e,t));return r}async stat(e){let t=this.#e.get(e);return t?this.#t(e,t):null}async mkdir(e){if(e===`/`)return;let t=this.#e.get(e);if(t){if(t.kind===`dir`)return;throw new E(`EEXIST`,e)}await this.mkdir(r(e)),this.#e.set(e,{kind:`dir`,mtime:Date.now()})}async remove(e,t){if(!this.#e.get(e))throw new E(`ENOENT`,e);if(e===`/`)throw new E(`EACCES`,e);let n=e+`/`,r=[...this.#e.keys()].filter(e=>e.startsWith(n));if(r.length&&!t)throw new E(`ENOTEMPTY`,e);for(let e of r)this.#e.delete(e);this.#e.delete(e)}#t(e,t){return{path:e,name:o(e),kind:t.kind,size:t.data?.byteLength??0,mtime:t.mtime}}};const be=new TextEncoder,xe=new TextDecoder;var Se=class{bus;#e=[];#t;#n;constructor(e){this.bus=e,this.#t=new Promise(e=>this.#n=e)}get ready(){return this.#t}markReady(){this.#n()}mount(e,t){e=a(e),this.#e=this.#e.filter(t=>t.point!==e),this.#e.push({point:e,fs:t}),this.#e.sort((e,t)=>t.point.length-e.point.length),this.bus.emit(`fs:change`,{path:e,type:`mount`})}unmount(e){e=a(e),this.#e=this.#e.filter(t=>t.point!==e||t.point===`/`),this.bus.emit(`fs:change`,{path:e,type:`mount`})}mounts(){return this.#e}async#r(t){await this.#t;let n=a(t);for(let t of this.#e)if(e(t.point,n))return{fs:t.fs,rel:t.point===`/`?n:n.slice(t.point.length)||`/`,path:n};throw new E(`ENOENT`,n,`no filesystem mounted`)}async readFile(e){let t=await this.#r(e);return t.fs.readFile(t.rel)}async readText(e){return xe.decode(await this.readFile(e))}async writeFile(e,t){let n=await this.#r(e);if(n.fs.readonly)throw new E(`EACCES`,n.path,`read-only filesystem`);let i=typeof t==`string`?be.encode(t):t;await n.fs.mkdir(r(n.rel)),await n.fs.writeFile(n.rel,i),this.bus.emit(`fs:change`,{path:n.path,type:`write`})}async appendFile(e,t){let n=typeof t==`string`?be.encode(t):t,r=/* @__PURE__ */ new Uint8Array;try{r=await this.readFile(e)}catch(e){if(!(e instanceof E&&e.code===`ENOENT`))throw e}let i=new Uint8Array(r.length+n.length);i.set(r),i.set(n,r.length),await this.writeFile(e,i)}async readdir(e){let t=await this.#r(e),n=(await t.fs.readdir(t.rel)).map(e=>({...e,path:i(t.path,e.name)}));for(let e of this.#e)e.point!==`/`&&r(e.point)===t.path&&!n.some(t=>t.name===o(e.point))&&n.push({path:e.point,name:o(e.point),kind:`dir`,size:0,mtime:0});return n.sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`dir`?-1:1)}async stat(e){let t=a(e);if(await this.#t,this.#e.some(e=>e.point===t))return{path:t,name:o(t),kind:`dir`,size:0,mtime:0};let n=await this.#r(t),r=await n.fs.stat(n.rel);return r?{...r,path:n.path,name:o(n.path)}:null}async exists(e){return await this.stat(e).catch(()=>null)!==null}async mkdir(e){let t=await this.#r(e);if(t.fs.readonly)throw new E(`EACCES`,t.path,`read-only filesystem`);await t.fs.mkdir(t.rel),this.bus.emit(`fs:change`,{path:t.path,type:`mkdir`})}async rm(e,t={}){let n=await this.#r(e);if(n.fs.readonly)throw new E(`EACCES`,n.path,`read-only filesystem`);if(this.#e.some(e=>e.point===n.path))throw new E(`EACCES`,n.path,`is a mount point`);await n.fs.remove(n.rel,t.recursive??!1),this.bus.emit(`fs:change`,{path:n.path,type:`remove`})}async cp(t,n){let r=await this.stat(t);if(!r)throw new E(`ENOENT`,t);if(r.kind===`file`)return this.writeFile(n,await this.readFile(t));if(e(t,n))throw new E(`EACCES`,n,`cannot copy a directory into itself`);await this.mkdir(n);for(let e of await this.readdir(t))await this.cp(e.path,i(n,e.name))}async mv(e,t){a(e)!==a(t)&&(await this.cp(e,t),await this.rm(e,{recursive:!0}))}async*walk(e,t={}){let n=[[a(e),0]];for(;n.length;){let[e,r]=n.pop();t.signal?.throwIfAborted();let i;try{i=await this.readdir(e)}catch{continue}for(let e of i)yield e,e.kind===`dir`&&r+1<(t.maxDepth??32)&&e.path!==`/proc`&&n.push([e.path,r+1])}}async glob(e,t=`/`,o=2e3){let s=e.startsWith(`/`)?e:i(t,e).replace(/\/$/,``),c=s.search(/[*?{]/);if(c<0)return await this.exists(s)?[a(s)]:[];let l=r(s.slice(0,c)+`x`),u=n(s),d=[];for await(let e of this.walk(l))if(u.test(e.path)&&d.push(e.path),d.length>=o)break;return d.sort()}};const k=`/home/user`,A=`/home/agent`;var Ce=class{version=`0.2.0`;bootStart=0;bus=new u;settings=new me(this.bus,(e,t)=>{_e(e,t,l(O,this.instance)),this.onSettingWritten?.(e,t)});onSettingWritten;secrets;instance;perms=new se(this.settings);procs=new ce(this.bus);fs=new Se(this.bus);kcore=new m;caps=d();shells;ui=null;packages;dev=new re(this);constructor(e={}){this.instance=e.instance??s,this.secrets=new pe(l(de,this.instance)),this.packages=new oe(this,e.packages),_(()=>ne(this.packages,e=>this.log(`dev`,e)))}kernelLog=[];rootKind=`memory`;bootMarks=[];mark(e){this.bootMarks.push({name:e,at:Math.round(performance.now()*10)/10})}log(e,t){let n={t:Math.round(performance.now()),src:e,msg:t};this.kernelLog.push(n),this.kernelLog.length>500&&this.kernelLog.shift(),this.bus.emit(`kmsg`,n)}hasCap(e){return this.caps.find(t=>t.id===e)?.ok??!1}notify(e){this.bus.emit(`notify`,typeof e==`string`?{title:e}:e)}openApp(e,t){this.bus.emit(`app:open`,{id:e,args:t})}async start(){this.log(`kernel`,`BrowserBox ${this.version}`);let e=this.procs.spawn({name:`kernel`,kind:`service`,detail:`event bus, vfs, process table`});this.procs.update(e.pid,{state:`idle`});let t=this.kcore.load().then(()=>this.log(`kcore`,this.kcore.loaded?`WebAssembly core loaded`:`WebAssembly unavailable, using JavaScript fallbacks`));this.settings.hydrate(await ge(l(O,this.instance))),this.log(`settings`,`${this.settings.keys().length} keys loaded`);let n=this.instance.box;n!==null&&this.log(`kernel`,`box ${n} (${this.instance.storage})`);try{if(this.instance.storage===`memory`)throw Error(`in-memory box`);let e=await navigator.storage.getDirectory();n!==null&&(e=await(await e.getDirectoryHandle(`boxes`,{create:!0})).getDirectoryHandle(n,{create:!0})),this.fs.mount(`/`,new ve(e,`opfs`)),this.rootKind=`opfs`,this.log(`vfs`,`mounted opfs${n===null?``:` boxes/${n}`} on / (persistent)`)}catch(e){this.fs.mount(`/`,new ye),this.log(`vfs`,this.instance.storage===`memory`?`mounted memfs on / (in-memory box)`:`OPFS unavailable (${e.message}): mounted memfs on / (not persistent)`)}this.fs.mount(`/tmp`,new ye),this.fs.mount(`/proc`,new ue(this)),this.fs.markReady(),this.log(`vfs`,`mounted memfs on /tmp, procfs on /proc`);try{await this.#e()}catch(e){this.log(`init`,`seeding the filesystem failed: ${e.message}`)}let r=this.packages.installed();this.log(`pkg`,r.length?`installed: ${r.join(`, `)}`:`no packages installed`);let i=this.hasCap(`webgpu`)?`WebGPU available`:`no WebGPU`;this.log(`caps`,`${this.caps.filter(e=>e.ok).length}/${this.caps.length} platform features · ${i} · ${navigator.hardwareConcurrency??`?`} cores`),navigator.storage?.persist?.().then(e=>this.log(`vfs`,e?`storage marked persistent`:`storage may be evicted under pressure`)).catch(()=>!1),await t,this.log(`kernel`,`ready`)}seeders=[];async#e(){if(this.instance.box!==null)await Promise.all([this.fs.mkdir(k),this.fs.mkdir(`/mnt`)]);else{for(let e of this.seeders)await e();await this.fs.exists(`/home/user/Welcome.md`)||(await Promise.all([this.fs.mkdir(`${k}/Documents`),this.fs.mkdir(A),this.fs.mkdir(`/mnt`)]),await this.fs.writeFile(`${k}/Welcome.md`,`# Welcome to BrowserBox
12
+ `}}}async readFile(e){let t=this.#e[e.slice(1)];if(!t)throw new E(e===`/`?`EISDIR`:`ENOENT`,e);return de.encode(await t())}async writeFile(e){throw new E(`EACCES`,e)}async readdir(e){if(e!==`/`)throw new E(`ENOTDIR`,e);return Object.keys(this.#e).map(e=>({path:`/`+e,name:e,kind:`file`,size:0,mtime:Date.now()}))}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};let t=e.slice(1);return t in this.#e?{path:e,name:t,kind:`file`,size:0,mtime:Date.now()}:null}async mkdir(e){throw new E(`EACCES`,e)}async remove(e){throw new E(`EACCES`,e)}};const pe=`bbx-secrets`;function me(e){return e===null?Promise.reject(/* @__PURE__ */ Error(`in-memory`)):new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function D(e,t,n){return new Promise((r,i)=>{let a=n(e.transaction(`kv`,t).objectStore(`kv`));a.onsuccess=()=>r(a.result),a.onerror=()=>i(a.error)})}var O=class extends Error{constructor(){super(`This profile is signed out: its API keys are locked until you sign in.`),this.name=`SecretsLockedError`}};const he=31e4;async function ge(e,t,n){let r=await crypto.subtle.importKey(`raw`,new TextEncoder().encode(e),`PBKDF2`,!1,[`deriveKey`]);return crypto.subtle.deriveKey({name:`PBKDF2`,salt:t,iterations:n,hash:`SHA-256`},r,{name:`AES-GCM`,length:256},!1,[`wrapKey`,`unwrapKey`])}function _e(e){return new Promise((t,n)=>{let r=[],i=e.transaction(`kv`,`readonly`).objectStore(`kv`).openCursor();i.onsuccess=()=>{let e=i.result;if(!e)return t(r);r.push([String(e.key),e.value]),e.continue()},i.onerror=()=>n(i.error)})}function ve(e,t,n){return new Promise((r,i)=>{let a=e.transaction(`kv`,`readwrite`),o=a.objectStore(`kv`);for(let[e,n]of t)o.put(n,e);for(let e of n)o.delete(e);a.oncomplete=()=>r(),a.onerror=()=>i(a.error),a.onabort=()=>i(a.error)})}var ye=class{dbName;#e=null;#t=/* @__PURE__ */ new Map;constructor(e=pe){this.dbName=e}#n(){return this.#e??=me(this.dbName)}async#r(e){let t=await D(e,`readonly`,e=>e.get(`#session`));if(t)return t;if(await D(e,`readonly`,e=>e.get(`#wrapped`)))throw new O;let n=await D(e,`readonly`,e=>e.get(`#master`));if(n)return n;let r=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return await D(e,`readwrite`,e=>e.put(r,`#master`)),r}async status(){if(this.dbName===null)return`open`;let e=await this.#n();return await D(e,`readonly`,e=>e.get(`#wrapped`))?await D(e,`readonly`,e=>e.get(`#session`))?`unlocked`:`locked`:`open`}async unlock(e){let t=await this.#n(),n=await D(t,`readonly`,e=>e.get(`#wrapped`));if(!n)return!0;try{let r=await crypto.subtle.unwrapKey(`raw`,n.wrapped,await ge(e,n.salt,n.iterations),{name:`AES-GCM`,iv:n.iv},{name:`AES-GCM`},!1,[`encrypt`,`decrypt`]);return await D(t,`readwrite`,e=>e.put(r,`#session`)),!0}catch{return!1}}async lock(){this.dbName!==null&&await D(await this.#n(),`readwrite`,e=>e.delete(`#session`))}async setPassword(e){if(this.dbName===null)throw Error(`an in-memory box has no password`);let t=await this.#n(),n=await this.#r(t),r=[];for(let[e,i]of await _e(t)){if(e.startsWith(`#`))continue;let t=i;r.push([e,new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:t.iv},n,t.data))])}let i,a=[],o;if(e){let t=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!0,[`encrypt`,`decrypt`]),n=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),r=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),s=await ge(e,n,he),c=await crypto.subtle.wrapKey(`raw`,t,s,{name:`AES-GCM`,iv:r});i=await crypto.subtle.unwrapKey(`raw`,c,s,{name:`AES-GCM`,iv:r},{name:`AES-GCM`},!1,[`encrypt`,`decrypt`]),a.push([`#wrapped`,{salt:n,iv:r,iterations:he,wrapped:c}],[`#session`,i]),o=[`#master`]}else i=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]),a.push([`#master`,i]),o=[`#wrapped`,`#session`];for(let[e,t]of r){let n=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));a.push([e,{iv:n,data:await crypto.subtle.encrypt({name:`AES-GCM`,iv:n},i,t)}])}await ve(t,a,o)}async get(e){try{let t=await this.#n(),n=await D(t,`readonly`,t=>t.get(e));if(!n)return this.#t.get(e)??null;let r=await crypto.subtle.decrypt({name:`AES-GCM`,iv:n.iv},await this.#r(t),n.data);return new TextDecoder().decode(r)}catch(t){if(t instanceof O)throw t;return this.#t.get(e)??null}}async set(e,t){if(!t)return this.delete(e);try{let n=await this.#n(),r=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),i=await crypto.subtle.encrypt({name:`AES-GCM`,iv:r},await this.#r(n),new TextEncoder().encode(t));await D(n,`readwrite`,t=>t.put({iv:r,data:i},e))}catch(n){if(n instanceof O)throw n;this.#t.set(e,t)}}async delete(e){this.#t.delete(e);try{await D(await this.#n(),`readwrite`,t=>t.delete(e))}catch{}}async has(e){return await this.get(e)!==null}},be=class{bus;onWrite;#e=/* @__PURE__ */ new Map;constructor(e,t){this.bus=e,this.onWrite=t}hydrate(e){this.#e=new Map(e);for(let[t,n]of e)this.bus.emit(`settings:change`,{key:t,value:n})}entries(){return[...this.#e]}get(e,t){return this.#e.has(e)?this.#e.get(e):t}set(e,t){this.applyRemote(e,t),this.onWrite?.(e,t)}delete(e){this.set(e,void 0)}applyRemote(e,t){t===void 0?this.#e.delete(e):this.#e.set(e,t),this.bus.emit(`settings:change`,{key:e,value:t})}keys(){return[...this.#e.keys()]}};const k=`bbx-settings`;function xe(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function Se(e=k){if(e===null)return[];try{let t=await xe(e);return await new Promise((e,n)=>{let r=[],i=t.transaction(`kv`,`readonly`).objectStore(`kv`).openCursor();i.onsuccess=()=>{let t=i.result;if(!t)return e(r);r.push([String(t.key),t.value]),t.continue()},i.onerror=()=>n(i.error)})}catch{return[]}}async function Ce(e,t,n=k){if(n!==null)try{let r=(await xe(n)).transaction(`kv`,`readwrite`).objectStore(`kv`);t===void 0?r.delete(e):r.put(t,e)}catch{}}var A=class{label;#e=/* @__PURE__ */ new Map;#t;constructor(e,t,n=[]){this.label=t,this.#e.set(`/`,e),this.#t=new Set(n)}#n(e){return this.#t.size>0&&this.#t.has(e.split(`/`)[1]??``)}#r(e){if(this.#n(e))throw new E(`ENOENT`,e)}async#i(e,t=!1){let n=this.#e.get(e);if(n)return n;let i=await this.#i(r(e),t);try{let n=await i.getDirectoryHandle(o(e),{create:t});return this.#e.set(e,n),n}catch(t){throw this.#a(t,e)}}#a(e,t){let n=e?.name;return n===`NotFoundError`?new E(`ENOENT`,t):n===`TypeMismatchError`?new E(`ENOTDIR`,t):n===`NotAllowedError`||n===`SecurityError`?new E(`EACCES`,t):n===`InvalidModificationError`?new E(`ENOTEMPTY`,t):new E(`EIO`,t,e?.message)}async readFile(e){this.#r(e);try{let t=await(await this.#i(r(e))).getFileHandle(o(e));for(let e=0;;e++)try{return new Uint8Array(await(await t.getFile()).arrayBuffer())}catch(t){if(e>=4||t?.name!==`NotReadableError`)throw t;await new Promise(t=>setTimeout(t,20*(e+1)))}}catch(t){if(t instanceof E)throw t;let n=this.#a(t,e);throw n.code===`ENOTDIR`?new E(`EISDIR`,e):n}}async writeFile(e,t){if(this.#n(e))throw new E(`EACCES`,e);try{let n=await(await(await this.#i(r(e))).getFileHandle(o(e),{create:!0})).createWritable();await n.write(t),await n.close()}catch(t){throw t instanceof E?t:this.#a(t,e)}}async readdir(e){this.#r(e);let t=await this.#i(e),n=e===`/`?`/`:e+`/`,r=[];for await(let[i,a]of t.entries()){let t=n+i;e===`/`&&this.#t.has(i)||(a.kind===`directory`?r.push(Promise.resolve({path:t,name:i,kind:`dir`,size:0,mtime:0})):r.push(a.getFile().then(e=>({path:t,name:i,kind:`file`,size:e.size,mtime:e.lastModified})).catch(()=>({path:t,name:i,kind:`file`,size:0,mtime:0}))))}return Promise.all(r)}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};if(this.#n(e))return null;let t;try{t=await this.#i(r(e))}catch{return null}let n=o(e);try{let r=await(await t.getFileHandle(n)).getFile();return{path:e,name:n,kind:`file`,size:r.size,mtime:r.lastModified}}catch{try{return await t.getDirectoryHandle(n),{path:e,name:n,kind:`dir`,size:0,mtime:0}}catch{return null}}}async mkdir(e){if(this.#n(e))throw new E(`EACCES`,e);await this.#i(e,!0)}async remove(e,t){if(e===`/`||this.#n(e))throw new E(`EACCES`,e);try{await(await this.#i(r(e))).removeEntry(o(e),{recursive:t})}catch(t){throw t instanceof E?t:this.#a(t,e)}for(let t of[...this.#e.keys()])(t===e||t.startsWith(e+`/`))&&this.#e.delete(t)}},we=class{label=`memfs`;#e=/* @__PURE__ */ new Map([[`/`,{kind:`dir`,mtime:Date.now()}]]);async readFile(e){let t=this.#e.get(e);if(!t)throw new E(`ENOENT`,e);if(t.kind===`dir`)throw new E(`EISDIR`,e);return t.data.slice()}async writeFile(e,t){let n=this.#e.get(r(e));if(!n)throw new E(`ENOENT`,r(e));if(n.kind!==`dir`)throw new E(`ENOTDIR`,r(e));if(this.#e.get(e)?.kind===`dir`)throw new E(`EISDIR`,e);this.#e.set(e,{kind:`file`,data:t.slice(),mtime:Date.now()})}async readdir(e){let t=this.#e.get(e);if(!t)throw new E(`ENOENT`,e);if(t.kind!==`dir`)throw new E(`ENOTDIR`,e);let n=e===`/`?`/`:e+`/`,r=[];for(let[e,t]of this.#e)e!==`/`&&e.startsWith(n)&&!e.slice(n.length).includes(`/`)&&r.push(this.#t(e,t));return r}async stat(e){let t=this.#e.get(e);return t?this.#t(e,t):null}async mkdir(e){if(e===`/`)return;let t=this.#e.get(e);if(t){if(t.kind===`dir`)return;throw new E(`EEXIST`,e)}await this.mkdir(r(e)),this.#e.set(e,{kind:`dir`,mtime:Date.now()})}async remove(e,t){if(!this.#e.get(e))throw new E(`ENOENT`,e);if(e===`/`)throw new E(`EACCES`,e);let n=e+`/`,r=[...this.#e.keys()].filter(e=>e.startsWith(n));if(r.length&&!t)throw new E(`ENOTEMPTY`,e);for(let e of r)this.#e.delete(e);this.#e.delete(e)}#t(e,t){return{path:e,name:o(e),kind:t.kind,size:t.data?.byteLength??0,mtime:t.mtime}}};const Te=new TextEncoder,Ee=new TextDecoder;var De=class{bus;#e=[];#t;#n;constructor(e){this.bus=e,this.#t=new Promise(e=>this.#n=e)}get ready(){return this.#t}markReady(){this.#n()}mount(e,t){e=a(e),this.#e=this.#e.filter(t=>t.point!==e),this.#e.push({point:e,fs:t}),this.#e.sort((e,t)=>t.point.length-e.point.length),this.bus.emit(`fs:change`,{path:e,type:`mount`})}unmount(e){e=a(e),this.#e=this.#e.filter(t=>t.point!==e||t.point===`/`),this.bus.emit(`fs:change`,{path:e,type:`mount`})}mounts(){return this.#e}async#r(t){await this.#t;let n=a(t);for(let t of this.#e)if(e(t.point,n))return{fs:t.fs,rel:t.point===`/`?n:n.slice(t.point.length)||`/`,path:n};throw new E(`ENOENT`,n,`no filesystem mounted`)}async readFile(e){let t=await this.#r(e);return t.fs.readFile(t.rel)}async readText(e){return Ee.decode(await this.readFile(e))}async writeFile(e,t){let n=await this.#r(e);if(n.fs.readonly)throw new E(`EACCES`,n.path,`read-only filesystem`);let i=typeof t==`string`?Te.encode(t):t;await n.fs.mkdir(r(n.rel)),await n.fs.writeFile(n.rel,i),this.bus.emit(`fs:change`,{path:n.path,type:`write`})}async appendFile(e,t){let n=typeof t==`string`?Te.encode(t):t,r=/* @__PURE__ */ new Uint8Array;try{r=await this.readFile(e)}catch(e){if(!(e instanceof E&&e.code===`ENOENT`))throw e}let i=new Uint8Array(r.length+n.length);i.set(r),i.set(n,r.length),await this.writeFile(e,i)}async readdir(e){let t=await this.#r(e),n=(await t.fs.readdir(t.rel)).map(e=>({...e,path:i(t.path,e.name)}));for(let e of this.#e)e.point!==`/`&&r(e.point)===t.path&&!n.some(t=>t.name===o(e.point))&&n.push({path:e.point,name:o(e.point),kind:`dir`,size:0,mtime:0});return n.sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`dir`?-1:1)}async stat(e){let t=a(e);if(await this.#t,this.#e.some(e=>e.point===t))return{path:t,name:o(t),kind:`dir`,size:0,mtime:0};let n=await this.#r(t),r=await n.fs.stat(n.rel);return r?{...r,path:n.path,name:o(n.path)}:null}async exists(e){return await this.stat(e).catch(()=>null)!==null}async mkdir(e){let t=await this.#r(e);if(t.fs.readonly)throw new E(`EACCES`,t.path,`read-only filesystem`);await t.fs.mkdir(t.rel),this.bus.emit(`fs:change`,{path:t.path,type:`mkdir`})}async rm(e,t={}){let n=await this.#r(e);if(n.fs.readonly)throw new E(`EACCES`,n.path,`read-only filesystem`);if(this.#e.some(e=>e.point===n.path))throw new E(`EACCES`,n.path,`is a mount point`);await n.fs.remove(n.rel,t.recursive??!1),this.bus.emit(`fs:change`,{path:n.path,type:`remove`})}async cp(t,n){let r=await this.stat(t);if(!r)throw new E(`ENOENT`,t);if(r.kind===`file`)return this.writeFile(n,await this.readFile(t));if(e(t,n))throw new E(`EACCES`,n,`cannot copy a directory into itself`);await this.mkdir(n);for(let e of await this.readdir(t))await this.cp(e.path,i(n,e.name))}async mv(e,t){a(e)!==a(t)&&(await this.cp(e,t),await this.rm(e,{recursive:!0}))}async*walk(e,t={}){let n=[[a(e),0]];for(;n.length;){let[e,r]=n.pop();t.signal?.throwIfAborted();let i;try{i=await this.readdir(e)}catch{continue}for(let e of i)yield e,e.kind===`dir`&&r+1<(t.maxDepth??32)&&e.path!==`/proc`&&n.push([e.path,r+1])}}async glob(e,t=`/`,o=2e3){let s=e.startsWith(`/`)?e:i(t,e).replace(/\/$/,``),c=s.search(/[*?{]/);if(c<0)return await this.exists(s)?[a(s)]:[];let l=r(s.slice(0,c)+`x`),u=n(s),d=[];for await(let e of this.walk(l))if(u.test(e.path)&&d.push(e.path),d.length>=o)break;return d.sort()}};const j=`/home/user`,M=`/home/agent`;var Oe=class{version=`0.3.0`;bootStart=0;bus=new f;settings=new be(this.bus,(e,t)=>{Ce(e,t,d(k,this.instance)),this.onSettingWritten?.(e,t)});onSettingWritten;secrets;instance;perms=new le(this.settings);procs=new ue(this.bus);fs=new De(this.bus);kcore=new g;caps=p();shells;ui=null;packages;dev=new ae(this);constructor(e={}){this.instance=e.instance??s,this.secrets=new ye(d(pe,this.instance)),this.packages=new ce(this,e.packages),ee(()=>ie(this.packages,e=>this.log(`dev`,e)))}kernelLog=[];rootKind=`memory`;bootMarks=[];mark(e){this.bootMarks.push({name:e,at:Math.round(performance.now()*10)/10})}log(e,t){let n={t:Math.round(performance.now()),src:e,msg:t};this.kernelLog.push(n),this.kernelLog.length>500&&this.kernelLog.shift(),this.bus.emit(`kmsg`,n)}hasCap(e){return this.caps.find(t=>t.id===e)?.ok??!1}notify(e){this.bus.emit(`notify`,typeof e==`string`?{title:e}:e)}openApp(e,t){this.bus.emit(`app:open`,{id:e,args:t})}async start(){this.log(`kernel`,`BrowserBox ${this.version}`);let e=this.procs.spawn({name:`kernel`,kind:`service`,detail:`event bus, vfs, process table`});this.procs.update(e.pid,{state:`idle`});let t=this.kcore.load().then(()=>this.log(`kcore`,this.kcore.loaded?`WebAssembly core loaded`:`WebAssembly unavailable, using JavaScript fallbacks`));this.settings.hydrate(await Se(d(k,this.instance))),this.log(`settings`,`${this.settings.keys().length} keys loaded`);let n=this.instance.box,r=this.instance.profile??null;n!==null&&this.log(`kernel`,`box ${n} (${this.instance.storage})`),r!==null&&this.log(`kernel`,`profile ${r}`);try{if(this.instance.storage===`memory`)throw Error(`in-memory box`);let e=await navigator.storage.getDirectory(),t=n===null?r===null?null:[`profiles`,r]:[`boxes`,n];t&&(e=await(await e.getDirectoryHandle(t[0],{create:!0})).getDirectoryHandle(t[1],{create:!0})),this.fs.mount(`/`,new A(e,`opfs`,t?[]:c)),this.rootKind=`opfs`,this.log(`vfs`,`mounted opfs${t?` ${t.join(`/`)}`:``} on / (persistent)`)}catch(e){this.fs.mount(`/`,new we),this.log(`vfs`,this.instance.storage===`memory`?`mounted memfs on / (in-memory box)`:`OPFS unavailable (${e.message}): mounted memfs on / (not persistent)`)}this.fs.mount(`/tmp`,new we),this.fs.mount(`/proc`,new fe(this)),this.fs.markReady(),this.log(`vfs`,`mounted memfs on /tmp, procfs on /proc`);try{await this.#e()}catch(e){this.log(`init`,`seeding the filesystem failed: ${e.message}`)}let i=this.packages.installed();this.log(`pkg`,i.length?`installed: ${i.join(`, `)}`:`no packages installed`);let a=this.hasCap(`webgpu`)?`WebGPU available`:`no WebGPU`;this.log(`caps`,`${this.caps.filter(e=>e.ok).length}/${this.caps.length} platform features · ${a} · ${navigator.hardwareConcurrency??`?`} cores`),navigator.storage?.persist?.().then(e=>this.log(`vfs`,e?`storage marked persistent`:`storage may be evicted under pressure`)).catch(()=>!1),await t,this.log(`kernel`,`ready`)}seeders=[];async#e(){if(this.instance.box!==null)await Promise.all([this.fs.mkdir(j),this.fs.mkdir(`/mnt`)]);else{for(let e of this.seeders)await e();await this.fs.exists(`/home/user/Welcome.md`)||(await Promise.all([this.fs.mkdir(`${j}/Documents`),this.fs.mkdir(M),this.fs.mkdir(`/mnt`)]),await this.fs.writeFile(`${j}/Welcome.md`,`# Welcome to BrowserBox
13
13
 
14
14
  BrowserBox is an operating system for AI agents that runs entirely in this
15
15
  browser tab. Nothing leaves your machine except the model requests you configure.
@@ -18,16 +18,17 @@ browser tab. Nothing leaves your machine except the model requests you configure
18
18
  - **Terminal** — a shell. Try \`help\`, \`ls /proc\`, \`agent "summarise this folder"\`.
19
19
  - **Files / Editor** — browse and edit the persistent filesystem (OPFS).
20
20
  - **Task Manager** — watch and kill processes, including running agents.
21
- - **Settings** — pick a model: Claude, a local server (Ollama, LM Studio,
22
- llama.cpp) or a model running in this tab on WebGPU.
21
+ - **Settings** — pick a model: a hosted API (Anthropic, OpenAI, OpenRouter…),
22
+ a local server (Ollama, LM Studio, llama.cpp) or a model running in this tab
23
+ on WebGPU.
23
24
 
24
25
  The agent works in \`/home/agent\`. Files there survive reloads.
25
- `),await this.fs.writeFile(`${A}/MEMORY.md`,`# Agent memory
26
+ `),await this.fs.writeFile(`${M}/MEMORY.md`,`# Agent memory
26
27
 
27
28
  Durable notes the agent keeps across sessions. Edit freely.
28
- `))}}async mountNativeFolder(){throw Error(`Mounting a folder needs a window: use Files → Mount.`)}mountHandle(e){let t=`/mnt/${e.name.replace(/[^\w.-]+/g,`_`)||`folder`}`;return this.fs.mount(t,new ve(e,`native:${e.name}`)),t}},we={id:`esbuild`,version:x,summary:`bundler for TypeScript, JSX and CSS (WebAssembly); used by serve`,commands:[`esbuild`],tools:[],default:!1,remote:S.map(e=>te+e),remoteBytes:4e6},Te={id:`git`,version:`isomorphic-git 1.x`,summary:`Version control for repositories in the virtual filesystem (clone needs a relay; no push)`,commands:[`git`],tools:[],default:!0},Ee={id:`python`,version:`3.13.2 (Pyodide 0.29)`,summary:`CPython compiled to WebAssembly, with the standard library`,commands:[`python`,`python3`,`pip`,`pip3`],tools:[],default:!1,remote:ee.map(e=>y+e),remoteBytes:12e6};const De=/* #__PURE__ */ Object.assign({"./esbuild/manifest.ts":we,"./git/manifest.ts":Te,"./python/manifest.ts":Ee,"./sqlite/manifest.ts":{id:`sqlite`,version:`SQLite 3 (sql.js)`,summary:`SQL database engine for .db files in the workspace`,commands:[`sqlite3`],tools:[],default:!0},"./zip/manifest.ts":{id:`zip`,version:`fflate`,summary:`Create and extract zip archives`,commands:[`zip`,`unzip`],tools:[],default:!0}}),Oe=/* #__PURE__ */ Object.assign({"./esbuild/index.ts":()=>import(`./pkg-esbuild-QrU0ybpL.js`).then(e=>e.default),"./git/index.ts":()=>import(`./pkg-git-BQFdAkWZ.js`).then(e=>e.default),"./python/index.ts":()=>import(`./pkg-python-ytZLbJ8W.js`).then(e=>e.default),"./sqlite/index.ts":()=>import(`./pkg-sqlite-CKGWzcwt.js`).then(e=>e.default),"./zip/index.ts":()=>import(`./pkg-zip-CL-568aV.js`).then(e=>e.default)}),ke=Object.values(De).sort((e,t)=>e.id.localeCompare(t.id));function Ae(e){let t=Oe[`./${e}/index.ts`];return t?t():Promise.reject(/* @__PURE__ */ Error(`package ${e} has no code`))}const je={manifests:ke,load:Ae},j=/* @__PURE__ */ new Map;function Me(e){j.set(e.name,e)}function Ne(e,t){t&&j.get(e)!==t||j.delete(e)}function M(e){return j.get(e)}function N(){return[...j.keys()]}const P={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`},Pe={name:`build`,summary:`production build of a project: bundled, minified, ready for any static host`,usage:`build [dir] [--out dist]`,async run(e){let{buildSite:t}=await import(`./build-DqisMe_5.js`),n=e.args.indexOf(`--out`),r=n>=0?e.args[n+1]:void 0,a=e.args.filter((e,t)=>t!==n&&t!==n+1&&!e.startsWith(`-`)),o=e.path(a[0]??`.`),s=e.path(r??i(o,`dist`)),c=performance.now(),l=await t(e.os.fs,o);if(l.errors.length){for(let t of l.errors)e.err(`error: ${t}\n`);return 1}await e.os.fs.rm(s,{recursive:!0}).catch(()=>void 0);let u=0;for(let[t,n]of l.files)await e.os.fs.writeFile(i(s,t),n),u+=n.length;e.out(`built ${l.files.size} files (${(u/1024).toFixed(1)} KB) into ${s} in ${Math.round(performance.now()-c)} ms\n${l.backend?`${P.yellow}${l.backend} is a backend: static hosts do not run it.${P.reset}\n`:``}`)}};function F(e,t,n,r){return{name:e,summary:t,usage:n,run:async e=>(await r()).run(e)}}const Fe=F(`serve`,`dev server for a project folder: bundles TS/JSX, reloads on save, runs server.ts`,`serve [dir] [--port N] [--net] [--no-open] | serve list | serve logs [port] | serve stop [port|all]`,()=>import(`./dev-impl-DLIrrRxu.js`).then(e=>e.serveCommand)),Ie=F(`npm`,`manage package.json; npm run dev serves the project (packages load from esm.sh)`,`npm init | npm install <pkg>[@version]… [-D] | npm uninstall <pkg>… | npm ls | npm run dev`,()=>import(`./dev-impl-DLIrrRxu.js`).then(e=>e.npmCommand)),Le=F(`npx`,`npx vite / serve / http-server start the dev server`,`npx vite | npx serve [dir] | npx http-server [dir]`,()=>import(`./dev-impl-DLIrrRxu.js`).then(e=>e.npxCommand));let I=null;function Re(){return typeof navigator<`u`&&`gpu`in navigator}function ze(){return I??=(async()=>{if(!Re())throw Error(`WebGPU is not available in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`No WebGPU adapter found`);let t=await e.requestDevice();return t.lost.then(()=>I=null),t})().catch(e=>{throw I=null,e})}const L=16777216;async function Be(e){if(!Number.isInteger(e.outputLength)||e.outputLength<1||e.outputLength>L)throw Error(`outputLength must be 1..${L}`);if(e.input.length>L)throw Error(`input is limited to ${L} elements`);let t=await ze(),n=performance.now();t.pushErrorScope(`validation`);let r=!0,i=t.createShaderModule({code:e.wgsl}),a=(await i.getCompilationInfo()).messages.filter(e=>e.type===`error`);if(a.length)throw t.popErrorScope(),r=!1,Error(`WGSL compile error:
29
+ `))}}async mountNativeFolder(){throw Error(`Mounting a folder needs a window: use Files → Mount.`)}mountHandle(e){let t=`/mnt/${e.name.replace(/[^\w.-]+/g,`_`)||`folder`}`;return this.fs.mount(t,new A(e,`native:${e.name}`)),t}},ke={id:`esbuild`,version:x,summary:`bundler for TypeScript, JSX and CSS (WebAssembly); used by serve`,commands:[`esbuild`],tools:[],default:!1,remote:S.map(e=>re+e),remoteBytes:4e6},Ae={id:`git`,version:`isomorphic-git 1.x`,summary:`Version control for repositories in the virtual filesystem (clone needs a relay; no push)`,commands:[`git`],tools:[],default:!0},je={id:`python`,version:`3.13.2 (Pyodide 0.29)`,summary:`CPython compiled to WebAssembly, with the standard library`,commands:[`python`,`python3`,`pip`,`pip3`],tools:[],default:!1,remote:ne.map(e=>y+e),remoteBytes:12e6};const Me=/* #__PURE__ */ Object.assign({"./esbuild/manifest.ts":ke,"./git/manifest.ts":Ae,"./python/manifest.ts":je,"./sqlite/manifest.ts":{id:`sqlite`,version:`SQLite 3 (sql.js)`,summary:`SQL database engine for .db files in the workspace`,commands:[`sqlite3`],tools:[],default:!0},"./zip/manifest.ts":{id:`zip`,version:`fflate`,summary:`Create and extract zip archives`,commands:[`zip`,`unzip`],tools:[],default:!0}}),Ne=/* #__PURE__ */ Object.assign({"./esbuild/index.ts":()=>import(`./pkg-esbuild-C-EHnLD8.js`).then(e=>e.default),"./git/index.ts":()=>import(`./pkg-git-BCxqHW9a.js`).then(e=>e.default),"./python/index.ts":()=>import(`./pkg-python-B23D6vdG.js`).then(e=>e.default),"./sqlite/index.ts":()=>import(`./pkg-sqlite-CKGWzcwt.js`).then(e=>e.default),"./zip/index.ts":()=>import(`./pkg-zip-CuNUYwRy.js`).then(e=>e.default)}),Pe=Object.values(Me).sort((e,t)=>e.id.localeCompare(t.id));function Fe(e){let t=Ne[`./${e}/index.ts`];return t?t():Promise.reject(/* @__PURE__ */ Error(`package ${e} has no code`))}const Ie={manifests:Pe,load:Fe},N=/* @__PURE__ */ new Map;function Le(e){N.set(e.name,e)}function Re(e,t){t&&N.get(e)!==t||N.delete(e)}function P(e){return N.get(e)}function ze(){return[...N.keys()]}const F={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`},Be={name:`build`,summary:`production build of a project: bundled, minified, ready for any static host`,usage:`build [dir] [--out dist]`,async run(e){let{buildSite:t}=await import(`./build-Bd5qSPS-.js`),n=e.args.indexOf(`--out`),r=n>=0?e.args[n+1]:void 0,a=e.args.filter((e,t)=>t!==n&&t!==n+1&&!e.startsWith(`-`)),o=e.path(a[0]??`.`),s=e.path(r??i(o,`dist`)),c=performance.now(),l=await t(e.os.fs,o);if(l.errors.length){for(let t of l.errors)e.err(`error: ${t}\n`);return 1}await e.os.fs.rm(s,{recursive:!0}).catch(()=>void 0);let u=0;for(let[t,n]of l.files)await e.os.fs.writeFile(i(s,t),n),u+=n.length;e.out(`built ${l.files.size} files (${(u/1024).toFixed(1)} KB) into ${s} in ${Math.round(performance.now()-c)} ms\n${l.backend?`${F.yellow}${l.backend} is a backend: static hosts do not run it.${F.reset}\n`:``}`)}};function I(e,t,n,r){return{name:e,summary:t,usage:n,run:async e=>(await r()).run(e)}}const Ve=I(`serve`,`dev server for a project folder: bundles TS/JSX, reloads on save, runs server.ts`,`serve [dir] [--port N] [--net] [--no-open] | serve list | serve logs [port] | serve stop [port|all]`,()=>import(`./dev-impl-DJx7S2dO.js`).then(e=>e.serveCommand)),He=I(`npm`,`manage package.json; npm run dev serves the project (packages load from esm.sh)`,`npm init | npm install <pkg>[@version]… [-D] | npm uninstall <pkg>… | npm ls | npm run dev`,()=>import(`./dev-impl-DJx7S2dO.js`).then(e=>e.npmCommand)),Ue=I(`npx`,`npx vite / serve / http-server start the dev server`,`npx vite | npx serve [dir] | npx http-server [dir]`,()=>import(`./dev-impl-DJx7S2dO.js`).then(e=>e.npxCommand));let L=null;function We(){return typeof navigator<`u`&&`gpu`in navigator}function Ge(){return L??=(async()=>{if(!We())throw Error(`WebGPU is not available in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`No WebGPU adapter found`);let t=await e.requestDevice();return t.lost.then(()=>L=null),t})().catch(e=>{throw L=null,e})}const R=16777216;async function Ke(e){if(!Number.isInteger(e.outputLength)||e.outputLength<1||e.outputLength>R)throw Error(`outputLength must be 1..${R}`);if(e.input.length>R)throw Error(`input is limited to ${R} elements`);let t=await Ge(),n=performance.now();t.pushErrorScope(`validation`);let r=!0,i=t.createShaderModule({code:e.wgsl}),a=(await i.getCompilationInfo()).messages.filter(e=>e.type===`error`);if(a.length)throw t.popErrorScope(),r=!1,Error(`WGSL compile error:
29
30
  `+a.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join(`
30
- `));let o=new Float32Array(Math.max(1,e.input.length));o.set(e.input);let s=t.createBuffer({size:o.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});t.queue.writeBuffer(s,0,o);let c=e.outputLength*4,l=t.createBuffer({size:c,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),u=t.createBuffer({size:c,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});try{let a=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]}),o=await t.createComputePipelineAsync({layout:t.createPipelineLayout({bindGroupLayouts:[a]}),compute:{module:i,entryPoint:`main`}}),d=t.createBindGroup({layout:a,entries:[{binding:0,resource:{buffer:s}},{binding:1,resource:{buffer:l}}]}),f=t.createCommandEncoder(),p=f.beginComputePass();p.setPipeline(o),p.setBindGroup(0,d);let[m,h=1,g=1]=e.workgroups??[Math.ceil(e.outputLength/64)],_=t.limits.maxComputeWorkgroupsPerDimension;if(Math.max(m,h,g)>_)throw Error(`dispatch of ${Math.max(m,h,g)} workgroups exceeds the device limit of ${_} per dimension; use a larger @workgroup_size or a 2D dispatch via workgroups`);p.dispatchWorkgroups(m,h,g),p.end(),f.copyBufferToBuffer(l,0,u,0,c),t.queue.submit([f.finish()]),r=!1;let v=await t.popErrorScope();if(v)throw Error(`WebGPU validation error: ${v.message}`);await u.mapAsync(GPUMapMode.READ);let y=new Float32Array(u.getMappedRange().slice(0));return u.unmap(),{output:y,ms:performance.now()-n}}finally{r&&t.popErrorScope().catch(()=>null),s.destroy(),l.destroy(),u.destroy()}}function Ve(e,t){return globalThis.crossOriginIsolated&&e.setAttribute(`credentialless`,``),e}var He=`// BrowserBox sandbox runtime. This file is shipped as text and started as a
31
+ `));let o=new Float32Array(Math.max(1,e.input.length));o.set(e.input);let s=t.createBuffer({size:o.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});t.queue.writeBuffer(s,0,o);let c=e.outputLength*4,l=t.createBuffer({size:c,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),u=t.createBuffer({size:c,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});try{let a=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]}),o=await t.createComputePipelineAsync({layout:t.createPipelineLayout({bindGroupLayouts:[a]}),compute:{module:i,entryPoint:`main`}}),d=t.createBindGroup({layout:a,entries:[{binding:0,resource:{buffer:s}},{binding:1,resource:{buffer:l}}]}),f=t.createCommandEncoder(),p=f.beginComputePass();p.setPipeline(o),p.setBindGroup(0,d);let[m,h=1,g=1]=e.workgroups??[Math.ceil(e.outputLength/64)],_=t.limits.maxComputeWorkgroupsPerDimension;if(Math.max(m,h,g)>_)throw Error(`dispatch of ${Math.max(m,h,g)} workgroups exceeds the device limit of ${_} per dimension; use a larger @workgroup_size or a 2D dispatch via workgroups`);p.dispatchWorkgroups(m,h,g),p.end(),f.copyBufferToBuffer(l,0,u,0,c),t.queue.submit([f.finish()]),r=!1;let v=await t.popErrorScope();if(v)throw Error(`WebGPU validation error: ${v.message}`);await u.mapAsync(GPUMapMode.READ);let ee=new Float32Array(u.getMappedRange().slice(0));return u.unmap(),{output:ee,ms:performance.now()-n}}finally{r&&t.popErrorScope().catch(()=>null),s.destroy(),l.destroy(),u.destroy()}}function qe(e,t){return globalThis.crossOriginIsolated&&e.setAttribute(`credentialless`,``),e}var Je=`// BrowserBox sandbox runtime. This file is shipped as text and started as a
31
32
  // Worker inside an opaque-origin iframe, so it must stay dependency-free JS.
32
33
  /* eslint-disable */
33
34
  let port;
@@ -348,24 +349,24 @@ async function runWasi(m, out, err) {
348
349
  }
349
350
  return { exitCode };
350
351
  }
351
- `;const Ue=`python.packages`,We=262144;var R=class{os;proc;#e;#t;#n=1;#r=!1;#i=/* @__PURE__ */ new Map;#a=null;constructor(e,t){this.os=e,this.proc=e.procs.spawn({name:t.name,kind:`sandbox`,ppid:t.ppid,detail:t.network?`isolated worker · network allowed`:`isolated worker · no network`,onKill:()=>this.#o()});let n=this.#e=Ve(document.createElement(`iframe`));n.setAttribute(`sandbox`,`allow-scripts`),n.style.display=`none`,n.src=new URL(t.network?`sandbox-net.html`:`sandbox.html`,w).href,this.#t=new Promise((e,t)=>{let r=setTimeout(()=>t(/* @__PURE__ */ Error(`sandbox failed to start`)),15e3),i=t=>{if(t.source===n.contentWindow){if(t.data?.type===`hello`){let t=new MessageChannel;t.port1.onmessage=n=>{n.data?.type===`ready`&&(clearTimeout(r),t.port1.onmessage=e=>this.#i.get(e.data.id)?.(e.data),e(t.port1))},n.contentWindow.postMessage({type:`boot`,src:He},`*`,[t.port2])}else t.data?.type===`crash`&&this.#a?.(String(t.data.error))}};addEventListener(`message`,i),this.proc.signal.addEventListener(`abort`,()=>{removeEventListener(`message`,i),clearTimeout(r),t(/* @__PURE__ */ Error(`sandbox was killed`))})}),this.#t.catch(()=>void 0),document.body.append(n)}get alive(){return!this.#r}#o(){this.#r=!0,this.#e.remove()}dispose(){this.#r||this.os.procs.exit(this.proc.pid)}async run(e,n={}){let r=performance.now(),i=n.cwd??`/`,a=``,o=``,s=e=>{let t=performance.now()-r;return this.os.procs.account(this.proc.pid,t),{ok:!1,stdout:a,stderr:o,ms:t,...e}},c;try{c=await this.#t}catch(e){return s({error:e.message})}let l=this.#n++;return this.os.procs.update(this.proc.pid,{state:`running`}),new Promise(r=>{let u=(e,t=!1)=>{clearTimeout(p),this.#i.delete(l),this.#a=null,n.signal?.removeEventListener(`abort`,d),this.proc.signal.removeEventListener(`abort`,f),t?this.dispose():this.os.procs.update(this.proc.pid,{state:`idle`}),r(s(e))},d=()=>u({error:`aborted`},!0),f=()=>u({error:`sandbox was killed`}),p=setTimeout(()=>u({error:`timed out after ${n.timeoutMs??3e4} ms`,timedOut:!0},!0),n.timeoutMs??3e4);n.signal?.addEventListener(`abort`,d),this.proc.signal.addEventListener(`abort`,f),this.#a=e=>u({error:e},!0),this.#i.set(l,e=>{e.type===`stdout`?(a.length<We&&(a+=e.data),n.onStdout?.(e.data)):e.type===`stderr`?(o.length<We&&(o+=e.data),n.onStderr?.(e.data)):e.type===`progress`?n.onProgress?.({label:e.label,loaded:e.loaded,total:e.total}):e.type===`rpc`?this.#s(i,e.method,e.params).then(t=>c.postMessage({type:`rpc-result`,rid:e.rid,value:t}),t=>c.postMessage({type:`rpc-result`,rid:e.rid,error:t.message})):e.type===`done`&&(async()=>{if(e.error)return u({error:e.error});try{for(let n of e.result?.files??[])await this.os.fs.writeFile(t(i,n.path),n.data)}catch(e){return u({error:`could not write files back: ${e.message}`})}let n=e.result?.exitCode;u({ok:n===void 0||n===0,value:e.result?.value,exitCode:n,response:e.result?.response})})()}),c.postMessage({id:l,...e})})}async#s(e,n,r){let i=this.os.fs,a=(i=0)=>{if(typeof r[i]!=`string`)throw Error(`${n}: path must be a string`);return t(e,r[i])};switch(n){case`fs.readText`:return i.readText(a());case`fs.readFile`:return i.readFile(a());case`fs.writeFile`:return i.writeFile(a(),r[1]);case`fs.appendFile`:return i.appendFile(a(),r[1]);case`fs.readdir`:return i.readdir(a());case`fs.exists`:return i.exists(a());case`fs.mkdir`:return i.mkdir(a());case`fs.rm`:return i.rm(a(),{recursive:!0});case`fs.glob`:return i.glob(String(r[0]),e);default:throw Error(`unknown sandbox call: ${n}`)}}};let z=null;function Ge(e){z=e}async function Ke(e,t,n={}){if(z)return z.run(`js`,{code:t,args:n.args,network:n.network,ppid:n.ppid,env:n.env},n);let r=new R(e,{name:`js`,network:n.network,ppid:n.ppid});try{return await r.run({op:`js`,code:t,args:n.args,env:n.env},n)}finally{r.dispose()}}async function qe(e,t,n={}){if(z)return z.run(`wasm`,{wasm:t,args:n.args,stdin:n.stdin,name:n.name,ppid:n.ppid},n);let r=new R(e,{name:n.name??`wasm`,ppid:n.ppid});try{return await r.run({op:`wasm`,wasm:t,args:n.args,stdin:n.stdin,name:n.name},n)}finally{r.dispose()}}let B=null,V=!1;async function Je(){try{let e=await caches.open(b),t=await Promise.all(ee.map(async t=>{let n=await e.match(y+t);return n?{path:t,data:new Uint8Array(await n.arrayBuffer())}:null}));return t.every(e=>e!==null)?t:void 0}catch{return}}async function Ye(e,t){let n=[],r=25165824;for await(let i of e.fs.walk(t,{maxDepth:6}))if(!(i.kind!==`file`||i.size>8388608||i.size>r)&&(r-=i.size,n.push({path:i.path.slice(t===`/`?1:t.length+1),data:await e.fs.readFile(i.path)}),n.length>=400))break;return n}async function Xe(e,t,n={}){if(z)return z.run(`python`,{code:t,packages:n.packages,env:n.env},n);B?.alive||(B=new R(e,{name:`python`,network:!1}),V=!1);let r=n.cwd??`/tmp`,i=await Ye(e,r),a=!V,o=a?await Je():void 0,s=a?e.settings.get(Ue,[]):[],c=[.../* @__PURE__ */ new Set([...s,...n.packages??[]])],l=await B.run({op:`python`,code:t,packages:c.length?c:void 0,files:i,pyodideUrl:y,env:n.env,runtime:o},{timeoutMs:18e4,...n,cwd:r});return V=B.alive&&!l.timedOut,l}const H=/* @__PURE__ */ new Map;async function Ze(e,t,n,r,i={}){if(z)return z.backend(t,n,r,i);let a=e=>({ok:!e,stdout:``,stderr:``,ms:0,error:e});if(t===`stop`)return H.get(n)?.dispose(),H.delete(n),a();if(t===`load`){H.get(n)?.dispose();let t=new R(e,{name:`backend :${n}`,network:r.network,ppid:r.ppid});H.set(n,t);let a=await t.run({op:`server-load`,code:r.code??``,env:r.env},{...i,timeoutMs:15e3});return a.ok||(t.dispose(),H.delete(n)),a}let o=H.get(n);return!o?.alive||!r.req?a(`backend not loaded`):o.run({op:`server-request`,req:r.req,origin:r.origin??`http://localhost`},{...i,timeoutMs:i.timeoutMs??3e4})}var U=class extends Error{};function Qe(e,t){let n=[],r=0,i=``,a=!1,o=!0,s=()=>{a&&n.push({kind:`word`,word:{text:i,bare:o}}),i=``,a=!1,o=!0},c=()=>{if(e[r+1]===`{`){let n=e.indexOf(`}`,r);if(n<0)throw new U("unterminated ${");let i=e.slice(r+2,n);return r=n,t[i]??``}let n=/^[A-Za-z_][A-Za-z0-9_]*|^\?/.exec(e.slice(r+1));return n?(r+=n[0].length,t[n[0]]??``):`$`};for(;r<e.length;r++){let l=e[r];if(l===`'`){let t=e.indexOf(`'`,r+1);if(t<0)throw new U(`unterminated '`);i+=e.slice(r+1,t),r=t,a=!0,o=!1}else if(l===`"`)for(a=!0,o=!1,r++;;r++){let t=e[r];if(t===void 0)throw new U(`unterminated "`);if(t===`"`)break;t===`\\`&&'"\\$`'.includes(e[r+1]??``)?i+=e[++r]:i+=t===`$`?c():t}else if(l===`\\`)r+1<e.length&&(i+=e[++r]),a=!0,o=!1;else if(l===`$`)i+=c(),a=!0;else if(l===` `||l===` `||l===`
352
- `)s();else if(l===`#`&&!a)break;else if(`|&;<>`.includes(l)){s();let t=e.slice(r,r+2);if(t===`&&`||t===`||`||t===`>>`)n.push({kind:`op`,op:t}),r++;else if(l===`&`)throw new U(`background jobs (&) are not supported`);else n.push({kind:`op`,op:l})}else l===`~`&&!a&&/^(\/|\s|$)/.test(e.slice(r+1))?i+=t.HOME??`~`:i+=l,a=!0}return s(),n}function $e(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(r)a===`\\`&&r===`"`?i++:a===r&&(r=``);else if(a===`\\`)i++;else if(a===`"`||a===`'`)r=a;else if(a===`#`&&(i===0||/\s/.test(e[i-1]))){e=e.slice(0,i);break}else if(a===`;`||e.startsWith(`&&`,i)||e.startsWith(`||`,i)){let r=a===`;`?`;`:e.slice(i,i+2);t.push({src:e.slice(n,i),next:r}),i+=r.length-1,n=i+1}}return t.push({src:e.slice(n),next:`;`}),t.filter((e,t,n)=>e.src.trim()||e.next!==`;`&&t<n.length-1)}function et(e,t){let n=Qe(e,t),r=[],i=[],a={argv:[]},o=()=>{if(!a.argv.length)throw new U(`syntax error: empty command`);i.push(a),a={argv:[]}};for(let e=0;e<n.length;e++){let t=n[e];if(t.kind===`word`)a.argv.push(t.word);else if(t.op===`>`||t.op===`>>`||t.op===`<`){let r=n[++e];if(r?.kind!==`word`)throw new U(`syntax error: expected a file after ${t.op}`);t.op===`<`?a.stdin=r.word:a.stdout={target:r.word,append:t.op===`>>`}}else if(t.op===`|`)o();else{if(!a.argv.length&&!i.length&&t.op===`;`)continue;o(),r.push({stages:i,next:t.op}),i=[]}}return(a.argv.length||i.length)&&(o(),r.push({stages:i,next:`;`})),r}function W(e){let t=/* @__PURE__ */ new Set,n=[],r=!1;for(let i of e)if(!r&&i===`--`)r=!0;else if(!r&&i.startsWith(`--`)&&i.length>2)t.add(i.slice(2));else if(!r&&i.startsWith(`-`)&&i.length>1&&!/^-\d/.test(i))for(let e of i.slice(1))t.add(e);else n.push(i);return{opts:t,rest:n}}var tt=class{os;cwd;env;history=[];commands=/* @__PURE__ */ new Map;tty;ppid=0;confined;prompter;constructor(e,t={}){this.os=e,this.cwd=t.cwd??`/home/user`,this.confined=t.confined??!1,this.prompter=t.prompter,this.tty=t.tty,this.ppid=t.ppid??0,this.env={...e.settings.get(`env.vars`,{}),HOME:k,USER:`user`,SHELL:`/bin/bbsh`,AGENT_HOME:A,PATH:`/bin`,"?":`0`}}register(...e){for(let t of e)this.commands.set(t.name,t);return this}async#e(e){let t=[];for(let n of e){if(n.bare&&/[*?{]/.test(n.text)){let e=await this.os.fs.glob(n.text,this.cwd).catch(()=>[]);if(e.length){let r=this.cwd===`/`?`/`:this.cwd+`/`;t.push(...e.map(e=>!n.text.startsWith(`/`)&&e.startsWith(r)?e.slice(r.length):e));continue}}t.push(n.text)}return t}async run(e,t){let n=0,r=t.signal??new AbortController().signal;try{let i=!1;for(let a of $e(e)){if(!i){if(!a.src.trim())throw new U(`syntax error: empty command`);for(let e of et(a.src,this.env))n=await this.#t(e.stages,t,r);this.env[`?`]=String(n)}if(r.aborted)break;i=a.next===`&&`?n!==0:a.next===`||`&&n===0}}catch(e){t.err(`${e instanceof U?`bbsh`:`bbsh: error`}: ${e.message}\n`),n=2}return this.env[`?`]=String(n),n}async#t(e,n,r){let i=n.stdin??``,a=0;for(let o=0;o<e.length;o++){let s=e[o],c=o===e.length-1,l=await this.#e(s.argv),u=l[0],d=this.commands.get(u)??M(u);if(!d)try{let e=await this.os.packages.provided(`commands`,u);e&&this.commands.set(u,d=e)}catch(e){return n.err(`bbsh: ${e.message}\n`),127}if(!d)return n.err(`bbsh: ${u}: command not found\n`),127;s.stdin&&(i=await this.os.fs.readText(t(this.cwd,s.stdin.text)));let f=``,p=!c||s.stdout!==void 0;try{a=await d.run({os:this.os,shell:this,args:l.slice(1),stdin:i,out:p?e=>f+=e:n.out,err:n.err,signal:r,tty:c&&!s.stdout?this.tty:void 0,path:e=>t(this.cwd,e)})??0}catch(e){if(r.aborted)return n.err(`^C
353
- `),130;n.err(`${u}: ${e.message}\n`),a=1}if(s.stdout){let e=t(this.cwd,s.stdout.target.text);try{s.stdout.append?await this.os.fs.appendFile(e,f):await this.os.fs.writeFile(e,f)}catch(e){return n.err(`bbsh: ${e.message}\n`),1}f=``}if(i=f,r.aborted)return 130}return a}async complete(e){let n=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`|`),e.lastIndexOf(`;`))+1,r=e.slice(n);if(!/\S/.test(e.slice(0,n).split(/[|;&]/).pop()??``)&&!r.includes(`/`))return{start:n,options:[.../* @__PURE__ */ new Set([...this.commands.keys(),...N()])].filter(e=>e.startsWith(r)).sort()};let i=r.lastIndexOf(`/`),a=i>=0?r.slice(0,i+1):``,o=r.slice(i+1),s=t(this.cwd,a.replace(/^~/,this.env.HOME??`~`)||`.`);return{start:n,options:(await this.os.fs.readdir(s).catch(()=>[])).filter(e=>e.name.startsWith(o)).map(e=>a+e.name+(e.kind===`dir`?`/`:` `))}}};async function nt(e,t,n){if(e.shell.confined&&!await e.os.perms.request({cap:`net`,actor:t,title:`Network access`,detail:n},e.shell.prompter))throw Error(`network access to ${n} was not allowed`)}const rt=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`?`));function it(e,t){return t.value!==void 0&&t.value!==`undefined`&&e.out(t.value+`
352
+ `;const Ye=`python.packages`,Xe=262144;var z=class{os;proc;#e;#t;#n=1;#r=!1;#i=/* @__PURE__ */ new Map;#a=null;constructor(e,t){this.os=e,this.proc=e.procs.spawn({name:t.name,kind:`sandbox`,ppid:t.ppid,detail:t.network?`isolated worker · network allowed`:`isolated worker · no network`,onKill:()=>this.#o()});let n=this.#e=qe(document.createElement(`iframe`));n.setAttribute(`sandbox`,`allow-scripts`),n.style.display=`none`,n.src=new URL(t.network?`sandbox-net.html`:`sandbox.html`,w).href,this.#t=new Promise((e,t)=>{let r=setTimeout(()=>t(/* @__PURE__ */ Error(`sandbox failed to start`)),15e3),i=t=>{if(t.source===n.contentWindow){if(t.data?.type===`hello`){let t=new MessageChannel;t.port1.onmessage=n=>{n.data?.type===`ready`&&(clearTimeout(r),t.port1.onmessage=e=>this.#i.get(e.data.id)?.(e.data),e(t.port1))},n.contentWindow.postMessage({type:`boot`,src:Je},`*`,[t.port2])}else t.data?.type===`crash`&&this.#a?.(String(t.data.error))}};addEventListener(`message`,i),this.proc.signal.addEventListener(`abort`,()=>{removeEventListener(`message`,i),clearTimeout(r),t(/* @__PURE__ */ Error(`sandbox was killed`))})}),this.#t.catch(()=>void 0),document.body.append(n)}get alive(){return!this.#r}#o(){this.#r=!0,this.#e.remove()}dispose(){this.#r||this.os.procs.exit(this.proc.pid)}async run(e,n={}){let r=performance.now(),i=n.cwd??`/`,a=``,o=``,s=e=>{let t=performance.now()-r;return this.os.procs.account(this.proc.pid,t),{ok:!1,stdout:a,stderr:o,ms:t,...e}},c;try{c=await this.#t}catch(e){return s({error:e.message})}let l=this.#n++;return this.os.procs.update(this.proc.pid,{state:`running`}),new Promise(r=>{let u=(e,t=!1)=>{clearTimeout(p),this.#i.delete(l),this.#a=null,n.signal?.removeEventListener(`abort`,d),this.proc.signal.removeEventListener(`abort`,f),t?this.dispose():this.os.procs.update(this.proc.pid,{state:`idle`}),r(s(e))},d=()=>u({error:`aborted`},!0),f=()=>u({error:`sandbox was killed`}),p=setTimeout(()=>u({error:`timed out after ${n.timeoutMs??3e4} ms`,timedOut:!0},!0),n.timeoutMs??3e4);n.signal?.addEventListener(`abort`,d),this.proc.signal.addEventListener(`abort`,f),this.#a=e=>u({error:e},!0),this.#i.set(l,e=>{e.type===`stdout`?(a.length<Xe&&(a+=e.data),n.onStdout?.(e.data)):e.type===`stderr`?(o.length<Xe&&(o+=e.data),n.onStderr?.(e.data)):e.type===`progress`?n.onProgress?.({label:e.label,loaded:e.loaded,total:e.total}):e.type===`rpc`?this.#s(i,e.method,e.params).then(t=>c.postMessage({type:`rpc-result`,rid:e.rid,value:t}),t=>c.postMessage({type:`rpc-result`,rid:e.rid,error:t.message})):e.type===`done`&&(async()=>{if(e.error)return u({error:e.error});try{for(let n of e.result?.files??[])await this.os.fs.writeFile(t(i,n.path),n.data)}catch(e){return u({error:`could not write files back: ${e.message}`})}let n=e.result?.exitCode;u({ok:n===void 0||n===0,value:e.result?.value,exitCode:n,response:e.result?.response})})()}),c.postMessage({id:l,...e})})}async#s(e,n,r){let i=this.os.fs,a=(i=0)=>{if(typeof r[i]!=`string`)throw Error(`${n}: path must be a string`);return t(e,r[i])};switch(n){case`fs.readText`:return i.readText(a());case`fs.readFile`:return i.readFile(a());case`fs.writeFile`:return i.writeFile(a(),r[1]);case`fs.appendFile`:return i.appendFile(a(),r[1]);case`fs.readdir`:return i.readdir(a());case`fs.exists`:return i.exists(a());case`fs.mkdir`:return i.mkdir(a());case`fs.rm`:return i.rm(a(),{recursive:!0});case`fs.glob`:return i.glob(String(r[0]),e);default:throw Error(`unknown sandbox call: ${n}`)}}};let B=null;function Ze(e){B=e}async function Qe(e,t,n={}){if(B)return B.run(`js`,{code:t,args:n.args,network:n.network,ppid:n.ppid,env:n.env},n);let r=new z(e,{name:`js`,network:n.network,ppid:n.ppid});try{return await r.run({op:`js`,code:t,args:n.args,env:n.env},n)}finally{r.dispose()}}async function $e(e,t,n={}){if(B)return B.run(`wasm`,{wasm:t,args:n.args,stdin:n.stdin,name:n.name,ppid:n.ppid},n);let r=new z(e,{name:n.name??`wasm`,ppid:n.ppid});try{return await r.run({op:`wasm`,wasm:t,args:n.args,stdin:n.stdin,name:n.name},n)}finally{r.dispose()}}let V=null,H=!1;async function et(){try{let e=await caches.open(b),t=await Promise.all(ne.map(async t=>{let n=await e.match(y+t);return n?{path:t,data:new Uint8Array(await n.arrayBuffer())}:null}));return t.every(e=>e!==null)?t:void 0}catch{return}}async function tt(e,t){let n=[],r=25165824;for await(let i of e.fs.walk(t,{maxDepth:6}))if(!(i.kind!==`file`||i.size>8388608||i.size>r)&&(r-=i.size,n.push({path:i.path.slice(t===`/`?1:t.length+1),data:await e.fs.readFile(i.path)}),n.length>=400))break;return n}async function nt(e,t,n={}){if(B)return B.run(`python`,{code:t,packages:n.packages,env:n.env},n);V?.alive||(V=new z(e,{name:`python`,network:!1}),H=!1);let r=n.cwd??`/tmp`,i=await tt(e,r),a=!H,o=a?await et():void 0,s=a?e.settings.get(Ye,[]):[],c=[.../* @__PURE__ */ new Set([...s,...n.packages??[]])],l=await V.run({op:`python`,code:t,packages:c.length?c:void 0,files:i,pyodideUrl:y,env:n.env,runtime:o},{timeoutMs:18e4,...n,cwd:r});return H=V.alive&&!l.timedOut,l}const U=/* @__PURE__ */ new Map;async function rt(e,t,n,r,i={}){if(B)return B.backend(t,n,r,i);let a=e=>({ok:!e,stdout:``,stderr:``,ms:0,error:e});if(t===`stop`)return U.get(n)?.dispose(),U.delete(n),a();if(t===`load`){U.get(n)?.dispose();let t=new z(e,{name:`backend :${n}`,network:r.network,ppid:r.ppid});U.set(n,t);let a=await t.run({op:`server-load`,code:r.code??``,env:r.env},{...i,timeoutMs:15e3});return a.ok||(t.dispose(),U.delete(n)),a}let o=U.get(n);return!o?.alive||!r.req?a(`backend not loaded`):o.run({op:`server-request`,req:r.req,origin:r.origin??`http://localhost`},{...i,timeoutMs:i.timeoutMs??3e4})}var W=class extends Error{};function it(e,t){let n=[],r=0,i=``,a=!1,o=!0,s=()=>{a&&n.push({kind:`word`,word:{text:i,bare:o}}),i=``,a=!1,o=!0},c=()=>{if(e[r+1]===`{`){let n=e.indexOf(`}`,r);if(n<0)throw new W("unterminated ${");let i=e.slice(r+2,n);return r=n,t[i]??``}let n=/^[A-Za-z_][A-Za-z0-9_]*|^\?/.exec(e.slice(r+1));return n?(r+=n[0].length,t[n[0]]??``):`$`};for(;r<e.length;r++){let l=e[r];if(l===`'`){let t=e.indexOf(`'`,r+1);if(t<0)throw new W(`unterminated '`);i+=e.slice(r+1,t),r=t,a=!0,o=!1}else if(l===`"`)for(a=!0,o=!1,r++;;r++){let t=e[r];if(t===void 0)throw new W(`unterminated "`);if(t===`"`)break;t===`\\`&&'"\\$`'.includes(e[r+1]??``)?i+=e[++r]:i+=t===`$`?c():t}else if(l===`\\`)r+1<e.length&&(i+=e[++r]),a=!0,o=!1;else if(l===`$`)i+=c(),a=!0;else if(l===` `||l===` `||l===`
353
+ `)s();else if(l===`#`&&!a)break;else if(`|&;<>`.includes(l)){s();let t=e.slice(r,r+2);if(t===`&&`||t===`||`||t===`>>`)n.push({kind:`op`,op:t}),r++;else if(l===`&`)throw new W(`background jobs (&) are not supported`);else n.push({kind:`op`,op:l})}else l===`~`&&!a&&/^(\/|\s|$)/.test(e.slice(r+1))?i+=t.HOME??`~`:i+=l,a=!0}return s(),n}function at(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(r)a===`\\`&&r===`"`?i++:a===r&&(r=``);else if(a===`\\`)i++;else if(a===`"`||a===`'`)r=a;else if(a===`#`&&(i===0||/\s/.test(e[i-1]))){e=e.slice(0,i);break}else if(a===`;`||e.startsWith(`&&`,i)||e.startsWith(`||`,i)){let r=a===`;`?`;`:e.slice(i,i+2);t.push({src:e.slice(n,i),next:r}),i+=r.length-1,n=i+1}}return t.push({src:e.slice(n),next:`;`}),t.filter((e,t,n)=>e.src.trim()||e.next!==`;`&&t<n.length-1)}function ot(e,t){let n=it(e,t),r=[],i=[],a={argv:[]},o=()=>{if(!a.argv.length)throw new W(`syntax error: empty command`);i.push(a),a={argv:[]}};for(let e=0;e<n.length;e++){let t=n[e];if(t.kind===`word`)a.argv.push(t.word);else if(t.op===`>`||t.op===`>>`||t.op===`<`){let r=n[++e];if(r?.kind!==`word`)throw new W(`syntax error: expected a file after ${t.op}`);t.op===`<`?a.stdin=r.word:a.stdout={target:r.word,append:t.op===`>>`}}else if(t.op===`|`)o();else{if(!a.argv.length&&!i.length&&t.op===`;`)continue;o(),r.push({stages:i,next:t.op}),i=[]}}return(a.argv.length||i.length)&&(o(),r.push({stages:i,next:`;`})),r}function G(e){let t=/* @__PURE__ */ new Set,n=[],r=!1;for(let i of e)if(!r&&i===`--`)r=!0;else if(!r&&i.startsWith(`--`)&&i.length>2)t.add(i.slice(2));else if(!r&&i.startsWith(`-`)&&i.length>1&&!/^-\d/.test(i))for(let e of i.slice(1))t.add(e);else n.push(i);return{opts:t,rest:n}}var st=class{os;cwd;env;history=[];commands=/* @__PURE__ */ new Map;tty;ppid=0;confined;prompter;constructor(e,t={}){this.os=e,this.cwd=t.cwd??`/home/user`,this.confined=t.confined??!1,this.prompter=t.prompter,this.tty=t.tty,this.ppid=t.ppid??0,this.env={...e.settings.get(`env.vars`,{}),HOME:j,USER:`user`,SHELL:`/bin/bbsh`,AGENT_HOME:M,PATH:`/bin`,"?":`0`}}register(...e){for(let t of e)this.commands.set(t.name,t);return this}async#e(e){let t=[];for(let n of e){if(n.bare&&/[*?{]/.test(n.text)){let e=await this.os.fs.glob(n.text,this.cwd).catch(()=>[]);if(e.length){let r=this.cwd===`/`?`/`:this.cwd+`/`;t.push(...e.map(e=>!n.text.startsWith(`/`)&&e.startsWith(r)?e.slice(r.length):e));continue}}t.push(n.text)}return t}async run(e,t){let n=0,r=t.signal??new AbortController().signal;try{let i=!1;for(let a of at(e)){if(!i){if(!a.src.trim())throw new W(`syntax error: empty command`);for(let e of ot(a.src,this.env))n=await this.#t(e.stages,t,r);this.env[`?`]=String(n)}if(r.aborted)break;i=a.next===`&&`?n!==0:a.next===`||`&&n===0}}catch(e){t.err(`${e instanceof W?`bbsh`:`bbsh: error`}: ${e.message}\n`),n=2}return this.env[`?`]=String(n),n}async#t(e,n,r){let i=n.stdin??``,a=0;for(let o=0;o<e.length;o++){let s=e[o],c=o===e.length-1,l=await this.#e(s.argv),u=l[0],d=this.commands.get(u)??P(u);if(!d)try{let e=await this.os.packages.provided(`commands`,u);e&&this.commands.set(u,d=e)}catch(e){return n.err(`bbsh: ${e.message}\n`),127}if(!d)return n.err(`bbsh: ${u}: command not found\n`),127;s.stdin&&(i=await this.os.fs.readText(t(this.cwd,s.stdin.text)));let f=``,p=!c||s.stdout!==void 0;try{a=await d.run({os:this.os,shell:this,args:l.slice(1),stdin:i,out:p?e=>f+=e:n.out,err:n.err,signal:r,tty:c&&!s.stdout?this.tty:void 0,path:e=>t(this.cwd,e)})??0}catch(e){if(r.aborted)return n.err(`^C
354
+ `),130;n.err(`${u}: ${e.message}\n`),a=1}if(s.stdout){let e=t(this.cwd,s.stdout.target.text);try{s.stdout.append?await this.os.fs.appendFile(e,f):await this.os.fs.writeFile(e,f)}catch(e){return n.err(`bbsh: ${e.message}\n`),1}f=``}if(i=f,r.aborted)return 130}return a}async complete(e){let n=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`|`),e.lastIndexOf(`;`))+1,r=e.slice(n);if(!/\S/.test(e.slice(0,n).split(/[|;&]/).pop()??``)&&!r.includes(`/`))return{start:n,options:[.../* @__PURE__ */ new Set([...this.commands.keys(),...ze()])].filter(e=>e.startsWith(r)).sort()};let i=r.lastIndexOf(`/`),a=i>=0?r.slice(0,i+1):``,o=r.slice(i+1),s=t(this.cwd,a.replace(/^~/,this.env.HOME??`~`)||`.`);return{start:n,options:(await this.os.fs.readdir(s).catch(()=>[])).filter(e=>e.name.startsWith(o)).map(e=>a+e.name+(e.kind===`dir`?`/`:` `))}}};async function ct(e,t,n){if(e.shell.confined&&!await e.os.perms.request({cap:`net`,actor:t,title:`Network access`,detail:n},e.shell.prompter))throw Error(`network access to ${n} was not allowed`)}const lt=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`?`));function ut(e,t){return t.value!==void 0&&t.value!==`undefined`&&e.out(t.value+`
354
355
  `),t.error&&e.err(t.error+`
355
- `),t.ok?0:t.exitCode??1}async function at(e,t,n){if(n.has(`e`)||n.has(`c`))return{code:t[0]??``,args:t.slice(1)};if(t[0])return{code:await e.os.fs.readText(e.path(t[0])),args:t.slice(1)};if(e.stdin)return{code:e.stdin,args:[]};throw Error(`nothing to run: pass a file, -e "code", or pipe code in`)}const ot=[{name:`js`,summary:`run JavaScript in an isolated sandbox`,usage:`js [--net] file.js [args…] | js -e "code" (globals: fs, print, console, args)`,async run(e){let{opts:t,rest:n}=W(e.args),{code:r,args:i}=await at(e,n,t);return t.has(`net`)&&await nt(e,`js`,`network access for a JavaScript program`),it(e,await Ke(e.os,r,{cwd:e.shell.cwd,env:rt(e.shell.env),args:i,network:t.has(`net`),signal:e.signal,onStdout:e.out,onStderr:e.err,ppid:e.shell.ppid,timeoutMs:12e4}))}},{name:`wasm`,summary:`run a WASI WebAssembly program`,usage:`wasm program.wasm [args…]`,async run(e){let t=e.args[0];if(!t)throw Error(`usage: wasm program.wasm [args…]`);let n=await e.os.fs.readFile(e.path(t));return it(e,await qe(e.os,n,{name:t,args:e.args.slice(1),stdin:e.stdin,signal:e.signal,onStdout:e.out,onStderr:e.err,ppid:e.shell.ppid}))}},{name:`gpu`,summary:`run a WGSL compute shader on WebGPU`,usage:`gpu shader.wgsl <outputLength> [input.json]`,async run(e){let[t,n,r]=e.args;if(!t||!n)throw Error(`usage: gpu shader.wgsl <outputLength> [input.json]`);let i=r?JSON.parse(await e.os.fs.readText(e.path(r))):e.stdin.trim()?JSON.parse(e.stdin):[],a=await Be({wgsl:await e.os.fs.readText(e.path(t)),input:i,outputLength:Number(n)});e.out(JSON.stringify(Array.from(a.output.slice(0,64)))+(a.output.length>64?` … (${a.output.length} values)`:``)+`\n${a.ms.toFixed(1)} ms\n`)}},{name:`curl`,summary:`fetch a URL (subject to browser CORS rules)`,usage:`curl [-i] [-X METHOD] [-H "k: v"] [-d body] [-o file] url`,async run(e){let t=[...e.args],n={headers:{},signal:e.signal},r=``,i,a=!1;for(;t.length;){let e=t.shift();if(e===`-X`)n.method=t.shift();else if(e===`-H`){let e=t.shift()??``,r=e.indexOf(`:`);r>0&&(n.headers[e.slice(0,r).trim()]=e.slice(r+1).trim())}else if(e===`-d`||e===`--data`)n.body=t.shift(),n.method??=`POST`;else if(e===`-o`)i=t.shift();else if(e===`-i`)a=!0;else if(e===`-s`||e===`-L`)continue;else r=e}if(!r)throw Error(`usage: curl [options] url`);/^[a-z]+:\/\//i.test(r)||(r=`https://`+r),await nt(e,`curl`,r);let o;try{o=await fetch(r,n)}catch(t){throw e.signal.aborted?t:Error(`could not fetch ${r} — the server is unreachable or does not allow cross-origin requests (CORS)`)}return a&&(e.out(`HTTP ${o.status} ${o.statusText}\n`),o.headers.forEach((t,n)=>e.out(`${n}: ${t}\n`)),e.out(`
356
- `)),i?await e.os.fs.writeFile(e.path(i),new Uint8Array(await o.arrayBuffer())):e.out(await o.text()),o.ok?0:22}}];function G(e){if(!Number.isFinite(e))return`—`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=0;for(;e>=1024&&n<t.length-1;)e/=1024,n++;return`${n===0?e:e.toFixed(+(e<10))} ${t[n]}`}function st(e){if(e<1e3)return`${Math.round(e)} ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)} s`;let n=Math.floor(t/60);return n<60?`${n}m ${Math.floor(t%60)}s`:`${Math.floor(n/60)}h ${n%60}m`}const ct=e=>e?new Date(e).toISOString().slice(0,16).replace(`T`,` `):` `,K=e=>e.kind===`dir`?`${P.blue}${e.name}/${P.reset}`:e.name,lt=[{name:`pwd`,summary:`print the working directory`,async run({shell:e,out:t}){t(e.cwd+`
357
- `)}},{name:`cd`,summary:`change directory`,usage:`cd [dir]`,async run({args:e,shell:t,os:n,path:r}){let i=r(e[0]??t.env.HOME??`/`),a=await n.fs.stat(i);if(!a)throw Error(`no such directory: ${e[0]}`);if(a.kind!==`dir`)throw Error(`not a directory: ${e[0]}`);t.cwd=i}},{name:`ls`,summary:`list directory contents`,usage:`ls [-la] [path…]`,async run({args:e,os:t,out:n,path:r}){let{opts:i,rest:a}=W(e),o=a.length?a:[`.`],s=0;for(let e of o){let a=r(e),c=await t.fs.stat(a);if(!c){n(`ls: ${e}: no such file or directory\n`),s=1;continue}let l=c.kind===`dir`?await t.fs.readdir(a):[c];if(i.has(`a`)||(l=l.filter(e=>!e.name.startsWith(`.`))),o.length>1&&n(`${e}:\n`),i.has(`l`))for(let e of l)n(`${e.kind===`dir`?`d`:`-`} ${G(e.size).padStart(8)} ${ct(e.mtime)} ${K(e)}\n`);else l.length&&n(l.map(K).join(` `)+`
358
- `)}return s}},{name:`tree`,summary:`show a directory tree`,usage:`tree [path] [-L depth]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=e.indexOf(`-L`),o=a>=0?Number(e[a+1])||3:4,s=r(e.filter((e,t)=>e!==`-L`&&t!==a+1)[0]??`.`),c=0,l=async(e,r,a)=>{if(a>=o)return;let s=await t.fs.readdir(e);for(let[e,t]of s.entries()){if(i.throwIfAborted(),++c>2e3)return;let o=e===s.length-1;n(`${r}${o?`└── `:`├── `}${K(t)}\n`),t.kind===`dir`&&t.path!==`/proc`&&await l(t.path,r+(o?` `:`│ `),a+1)}};n(`${s}\n`),await l(s,``,0),c>2e3&&n(`… (truncated)
359
- `)}},{name:`cat`,summary:`print files`,usage:`cat [file…]`,async run({args:e,os:t,out:n,stdin:r,path:i}){if(!e.length)return void n(r);for(let r of e)n(await t.fs.readText(i(r)))}},{name:`mkdir`,summary:`create directories (parents included)`,usage:`mkdir dir…`,async run({args:e,os:t,path:n}){let{rest:r}=W(e);if(!r.length)throw Error(`missing operand`);for(let e of r)await t.fs.mkdir(n(e))}},{name:`touch`,summary:`create empty files`,usage:`touch file…`,async run({args:e,os:t,path:n}){for(let r of e)await t.fs.exists(n(r))||await t.fs.writeFile(n(r),``)}},{name:`rm`,summary:`remove files or directories`,usage:`rm [-rf] path…`,async run({args:e,os:t,err:n,path:r}){let{opts:i,rest:a}=W(e);if(!a.length)throw Error(`missing operand`);let o=0;for(let e of a){let a=r(e),s=await t.fs.stat(a);s?s.kind===`dir`&&!i.has(`r`)&&!i.has(`R`)?(n(`rm: ${e}: is a directory (use -r)\n`),o=1):await t.fs.rm(a,{recursive:!0}):i.has(`f`)||(n(`rm: ${e}: no such file or directory\n`),o=1)}return o}},{name:`cp`,summary:`copy files or directories`,usage:`cp src… dest`,async run({args:e,os:t,path:n}){let{rest:r}=W(e);if(r.length<2)throw Error(`usage: cp src… dest`);let a=n(r.pop()),s=(await t.fs.stat(a))?.kind===`dir`;if(r.length>1&&!s)throw Error(`target is not a directory: ${a}`);for(let e of r)await t.fs.cp(n(e),s?i(a,o(n(e))):a)}},{name:`mv`,summary:`move or rename`,usage:`mv src… dest`,async run({args:e,os:t,path:n}){let{rest:r}=W(e);if(r.length<2)throw Error(`usage: mv src… dest`);let a=n(r.pop()),s=(await t.fs.stat(a))?.kind===`dir`;if(r.length>1&&!s)throw Error(`target is not a directory: ${a}`);for(let e of r)await t.fs.mv(n(e),s?i(a,o(n(e))):a)}},{name:`find`,summary:`find files by glob`,usage:`find [path] [-name glob] [-type f|d]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=e.indexOf(`-name`),o=e.indexOf(`-type`),s=a>=0?e[a+1]:void 0,c=o>=0?e[o+1]:void 0,l=r(e[0]&&!e[0].startsWith(`-`)?e[0]:`.`),u=s?RegExp(`^`+s.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)+`$`):null;for await(let e of t.fs.walk(l,{signal:i}))u&&!u.test(e.name)||c&&c===`d`!=(e.kind===`dir`)||n(e.path+`
360
- `)}},{name:`stat`,summary:`show file details`,usage:`stat path…`,async run({args:e,os:t,out:n,path:r}){for(let i of e){let e=await t.fs.stat(r(i));if(!e)throw Error(`${i}: no such file or directory`);n(` path: ${e.path}\n kind: ${e.kind}\n size: ${e.size} bytes\n mtime: ${e.mtime?new Date(e.mtime).toISOString():`-`}\n`)}}},{name:`du`,summary:`disk usage of a directory`,usage:`du [path]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=r(e[0]??`.`),o=0,s=0;for await(let e of t.fs.walk(a,{signal:i}))e.kind===`file`&&(o+=e.size,s++);n(`${G(o)}\t${s} files\t${a}\n`)}},{name:`df`,summary:`storage quota and mounts`,async run({os:e,out:t}){let n=await navigator.storage?.estimate?.().catch(()=>void 0);t(`origin storage: ${G(n?.usage??NaN)} used of ${G(n?.quota??NaN)}\n\n`);for(let n of e.fs.mounts())t(`${n.fs.label.padEnd(18)} ${n.fs.readonly?`ro`:`rw`} ${n.point}\n`)}},{name:`mount`,summary:`mount a real folder from this computer under /mnt`,async run({os:e,out:t}){t(`mounted at ${await e.mountNativeFolder()}\n`)}}];function ut(e,t){let n=-1;return(r,i)=>{let a=i?Math.min(100,Math.floor(r/i*100)):0;if(a===n)return;n=a;let o=Math.round(a/100*24);t(`\r${e.padEnd(8)} [${`#`.repeat(o)}${`.`.repeat(24-o)}] ${String(a).padStart(3)}% ${G(r)}${i?` / ${G(i)}`:``}`)}}async function q(e,t){for(let n of t){let t=ut(n,e.out);await e.os.packages.install(n,t),e.out(`\n${P.green}installed${P.reset} ${n}\n`)}}const dt={name:`pkg`,summary:`package manager: list, info, install, remove`,usage:`pkg list | pkg info <name> | pkg install <name>… | pkg install --defaults | pkg remove <name>…`,async run(e){let{os:t,out:n}=e,[r=`list`,...i]=e.args;if(r===`list`){for(let e of await t.packages.list())n(`${e.installed?`${P.green}i${P.reset}`:` `} ${P.bold}${e.id.padEnd(8)}${P.reset} ${(e.bytes?`${e.estimated?`~`:``}${G(e.bytes)}`:``).padStart(9)} ${e.summary}\n`);return n(`${P.dim}i = installed · pkg install <name>${P.reset}\n`)}if(r===`info`){let e=(await t.packages.list()).find(e=>e.id===i[0]);if(!e)throw Error(`no such package: ${i[0]??``}`);n(`${P.bold}${e.id}${P.reset} ${e.version}\n${e.summary}\nstatus: ${e.installed?`installed`:`not installed`}\nsize: ${e.bytes?`${e.estimated?`about `:``}${G(e.bytes)}`:`unknown until downloaded`}\ncommands: ${e.commands.join(`, `)||`—`}\ntools: ${e.tools.join(`, `)||`—`}\n`)}else{if(r===`install`){if(i.includes(`--defaults`))return q(e,pt(t).filter(e=>!t.packages.isInstalled(e)));if(!i.length)throw Error(`usage: pkg install <name>… | pkg install --defaults`);return q(e,i)}if(r===`remove`)for(let e of i)await t.packages.remove(e),n(`removed ${e}\n`);else throw Error(`usage: ${this.usage}`)}}},ft={name:`dmesg`,summary:`print the kernel log`,async run({os:e,out:t}){for(let n of e.kernelLog)t(`${P.dim}[${(n.t/1e3).toFixed(3).padStart(9)}]${P.reset} ${n.src}: ${n.msg}\n`)}},pt=e=>e.packages.manifests().filter(e=>e.default).map(e=>e.id),mt=[];function ht(){return mt}const gt=[{name:`help`,summary:`list commands`,usage:`help [command]`,async run({args:e,shell:t,out:n}){let r=e[0]?t.commands.get(e[0])??M(e[0]):void 0;if(e[0]&&!r)throw Error(`no such command: ${e[0]}`);if(r)return void n(`${P.bold}${r.name}${P.reset} — ${r.summary}\n${r.usage?`usage: ${r.usage}\n`:``}`);n(`${P.bold}BrowserBox shell${P.reset} — pipes (|), redirects (> >> <), && || ;, $VARS, globs, quotes.\n\n`);let i=new Map([...N().map(e=>[e,M(e)]),...t.commands]);for(let e of[...i.values()].sort((e,t)=>e.name.localeCompare(t.name)))n(` ${P.cyan}${e.name.padEnd(10)}${P.reset} ${e.summary}\n`)}},{name:`ps`,summary:`list processes`,async run({os:e,out:t}){t(`${P.dim}${`PID`.padStart(4)} ${`PPID`.padStart(4)} ${`KIND`.padEnd(8)} ${`STATE`.padEnd(8)} ${`CPU`.padStart(8)} NAME${P.reset}\n`);for(let n of e.procs.list())t(`${String(n.pid).padStart(4)} ${String(n.ppid).padStart(4)} ${n.kind.padEnd(8)} ${n.state.padEnd(8)} ${st(n.cpuMs).padStart(8)} ${n.name}${n.detail?` ${P.dim}${n.detail}${P.reset}`:``}\n`)}},{name:`kill`,summary:`terminate a process`,usage:`kill pid…`,async run({args:e,os:t,err:n}){if(!e.length)throw Error(`usage: kill pid…`);let r=0;for(let i of e)t.procs.kill(Number(i))||(n(`kill: ${i}: no such process\n`),r=1);return r}},{name:`open`,summary:`open an app, or a file in the right app`,usage:`open <app | path>`,async run({args:e,os:t,path:n,out:r}){let i=e[0];if(!i)return void r(`apps: ${ht().filter(e=>!e.hidden).map(e=>e.id).join(`, `)}\n`);if(ht().some(e=>e.id===i))return void t.openApp(i,e[1]?{path:n(e[1])}:{});let a=n(i),o=await t.fs.stat(a);if(!o)throw Error(`${i}: no such app or file`);o.kind===`dir`?t.openApp(`files`,{path:a}):/\.(html?|png|jpe?g|gif|webp|svg|avif|pdf|mp3|wav|ogg|mp4|webm)$/i.test(a)?t.openApp(`preview`,{path:a}):t.openApp(`editor`,{path:a})}},{name:`env`,summary:`print environment variables`,async run({shell:e,out:t}){for(let[n,r]of Object.entries(e.env))n!==`?`&&t(`${n}=${r}\n`)}},{name:`export`,summary:`set an environment variable`,usage:`export NAME=value`,async run({args:e,shell:t}){for(let n of e){let e=n.indexOf(`=`);if(e<1)throw Error(`usage: export NAME=value`);t.env[n.slice(0,e)]=n.slice(e+1)}}},{name:`clear`,summary:`clear the terminal`,async run({shell:e}){e.tty?.clear()}},{name:`history`,summary:`show command history`,async run({shell:e,out:t}){e.history.forEach((e,n)=>t(`${String(n+1).padStart(4)} ${e}\n`))}},{name:`date`,summary:`print the date and time`,async run({out:e}){e((/* @__PURE__ */ new Date()).toString()+`
356
+ `),t.ok?0:t.exitCode??1}async function dt(e,t,n){if(n.has(`e`)||n.has(`c`))return{code:t[0]??``,args:t.slice(1)};if(t[0])return{code:await e.os.fs.readText(e.path(t[0])),args:t.slice(1)};if(e.stdin)return{code:e.stdin,args:[]};throw Error(`nothing to run: pass a file, -e "code", or pipe code in`)}const ft=[{name:`js`,summary:`run JavaScript in an isolated sandbox`,usage:`js [--net] file.js [args…] | js -e "code" (globals: fs, print, console, args)`,async run(e){let{opts:t,rest:n}=G(e.args),{code:r,args:i}=await dt(e,n,t);return t.has(`net`)&&await ct(e,`js`,`network access for a JavaScript program`),ut(e,await Qe(e.os,r,{cwd:e.shell.cwd,env:lt(e.shell.env),args:i,network:t.has(`net`),signal:e.signal,onStdout:e.out,onStderr:e.err,ppid:e.shell.ppid,timeoutMs:12e4}))}},{name:`wasm`,summary:`run a WASI WebAssembly program`,usage:`wasm program.wasm [args…]`,async run(e){let t=e.args[0];if(!t)throw Error(`usage: wasm program.wasm [args…]`);let n=await e.os.fs.readFile(e.path(t));return ut(e,await $e(e.os,n,{name:t,args:e.args.slice(1),stdin:e.stdin,signal:e.signal,onStdout:e.out,onStderr:e.err,ppid:e.shell.ppid}))}},{name:`gpu`,summary:`run a WGSL compute shader on WebGPU`,usage:`gpu shader.wgsl <outputLength> [input.json]`,async run(e){let[t,n,r]=e.args;if(!t||!n)throw Error(`usage: gpu shader.wgsl <outputLength> [input.json]`);let i=r?JSON.parse(await e.os.fs.readText(e.path(r))):e.stdin.trim()?JSON.parse(e.stdin):[],a=await Ke({wgsl:await e.os.fs.readText(e.path(t)),input:i,outputLength:Number(n)});e.out(JSON.stringify(Array.from(a.output.slice(0,64)))+(a.output.length>64?` … (${a.output.length} values)`:``)+`\n${a.ms.toFixed(1)} ms\n`)}},{name:`curl`,summary:`fetch a URL (subject to browser CORS rules)`,usage:`curl [-i] [-X METHOD] [-H "k: v"] [-d body] [-o file] url`,async run(e){let t=[...e.args],n={headers:{},signal:e.signal},r=``,i,a=!1;for(;t.length;){let e=t.shift();if(e===`-X`)n.method=t.shift();else if(e===`-H`){let e=t.shift()??``,r=e.indexOf(`:`);r>0&&(n.headers[e.slice(0,r).trim()]=e.slice(r+1).trim())}else if(e===`-d`||e===`--data`)n.body=t.shift(),n.method??=`POST`;else if(e===`-o`)i=t.shift();else if(e===`-i`)a=!0;else if(e===`-s`||e===`-L`)continue;else r=e}if(!r)throw Error(`usage: curl [options] url`);/^[a-z]+:\/\//i.test(r)||(r=`https://`+r),await ct(e,`curl`,r);let o;try{o=await fetch(r,n)}catch(t){throw e.signal.aborted?t:Error(`could not fetch ${r} — the server is unreachable or does not allow cross-origin requests (CORS)`)}return a&&(e.out(`HTTP ${o.status} ${o.statusText}\n`),o.headers.forEach((t,n)=>e.out(`${n}: ${t}\n`)),e.out(`
357
+ `)),i?await e.os.fs.writeFile(e.path(i),new Uint8Array(await o.arrayBuffer())):e.out(await o.text()),o.ok?0:22}}];function K(e){if(!Number.isFinite(e))return`—`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=0;for(;e>=1024&&n<t.length-1;)e/=1024,n++;return`${n===0?e:e.toFixed(+(e<10))} ${t[n]}`}function pt(e){if(e<1e3)return`${Math.round(e)} ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)} s`;let n=Math.floor(t/60);return n<60?`${n}m ${Math.floor(t%60)}s`:`${Math.floor(n/60)}h ${n%60}m`}const mt=e=>e?new Date(e).toISOString().slice(0,16).replace(`T`,` `):` `,q=e=>e.kind===`dir`?`${F.blue}${e.name}/${F.reset}`:e.name,ht=[{name:`pwd`,summary:`print the working directory`,async run({shell:e,out:t}){t(e.cwd+`
358
+ `)}},{name:`cd`,summary:`change directory`,usage:`cd [dir]`,async run({args:e,shell:t,os:n,path:r}){let i=r(e[0]??t.env.HOME??`/`),a=await n.fs.stat(i);if(!a)throw Error(`no such directory: ${e[0]}`);if(a.kind!==`dir`)throw Error(`not a directory: ${e[0]}`);t.cwd=i}},{name:`ls`,summary:`list directory contents`,usage:`ls [-la] [path…]`,async run({args:e,os:t,out:n,path:r}){let{opts:i,rest:a}=G(e),o=a.length?a:[`.`],s=0;for(let e of o){let a=r(e),c=await t.fs.stat(a);if(!c){n(`ls: ${e}: no such file or directory\n`),s=1;continue}let l=c.kind===`dir`?await t.fs.readdir(a):[c];if(i.has(`a`)||(l=l.filter(e=>!e.name.startsWith(`.`))),o.length>1&&n(`${e}:\n`),i.has(`l`))for(let e of l)n(`${e.kind===`dir`?`d`:`-`} ${K(e.size).padStart(8)} ${mt(e.mtime)} ${q(e)}\n`);else l.length&&n(l.map(q).join(` `)+`
359
+ `)}return s}},{name:`tree`,summary:`show a directory tree`,usage:`tree [path] [-L depth]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=e.indexOf(`-L`),o=a>=0?Number(e[a+1])||3:4,s=r(e.filter((e,t)=>e!==`-L`&&t!==a+1)[0]??`.`),c=0,l=async(e,r,a)=>{if(a>=o)return;let s=await t.fs.readdir(e);for(let[e,t]of s.entries()){if(i.throwIfAborted(),++c>2e3)return;let o=e===s.length-1;n(`${r}${o?`└── `:`├── `}${q(t)}\n`),t.kind===`dir`&&t.path!==`/proc`&&await l(t.path,r+(o?` `:`│ `),a+1)}};n(`${s}\n`),await l(s,``,0),c>2e3&&n(`… (truncated)
360
+ `)}},{name:`cat`,summary:`print files`,usage:`cat [file…]`,async run({args:e,os:t,out:n,stdin:r,path:i}){if(!e.length)return void n(r);for(let r of e)n(await t.fs.readText(i(r)))}},{name:`mkdir`,summary:`create directories (parents included)`,usage:`mkdir dir…`,async run({args:e,os:t,path:n}){let{rest:r}=G(e);if(!r.length)throw Error(`missing operand`);for(let e of r)await t.fs.mkdir(n(e))}},{name:`touch`,summary:`create empty files`,usage:`touch file…`,async run({args:e,os:t,path:n}){for(let r of e)await t.fs.exists(n(r))||await t.fs.writeFile(n(r),``)}},{name:`rm`,summary:`remove files or directories`,usage:`rm [-rf] path…`,async run({args:e,os:t,err:n,path:r}){let{opts:i,rest:a}=G(e);if(!a.length)throw Error(`missing operand`);let o=0;for(let e of a){let a=r(e),s=await t.fs.stat(a);s?s.kind===`dir`&&!i.has(`r`)&&!i.has(`R`)?(n(`rm: ${e}: is a directory (use -r)\n`),o=1):await t.fs.rm(a,{recursive:!0}):i.has(`f`)||(n(`rm: ${e}: no such file or directory\n`),o=1)}return o}},{name:`cp`,summary:`copy files or directories`,usage:`cp src… dest`,async run({args:e,os:t,path:n}){let{rest:r}=G(e);if(r.length<2)throw Error(`usage: cp src… dest`);let a=n(r.pop()),s=(await t.fs.stat(a))?.kind===`dir`;if(r.length>1&&!s)throw Error(`target is not a directory: ${a}`);for(let e of r)await t.fs.cp(n(e),s?i(a,o(n(e))):a)}},{name:`mv`,summary:`move or rename`,usage:`mv src… dest`,async run({args:e,os:t,path:n}){let{rest:r}=G(e);if(r.length<2)throw Error(`usage: mv src… dest`);let a=n(r.pop()),s=(await t.fs.stat(a))?.kind===`dir`;if(r.length>1&&!s)throw Error(`target is not a directory: ${a}`);for(let e of r)await t.fs.mv(n(e),s?i(a,o(n(e))):a)}},{name:`find`,summary:`find files by glob`,usage:`find [path] [-name glob] [-type f|d]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=e.indexOf(`-name`),o=e.indexOf(`-type`),s=a>=0?e[a+1]:void 0,c=o>=0?e[o+1]:void 0,l=r(e[0]&&!e[0].startsWith(`-`)?e[0]:`.`),u=s?RegExp(`^`+s.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)+`$`):null;for await(let e of t.fs.walk(l,{signal:i}))u&&!u.test(e.name)||c&&c===`d`!=(e.kind===`dir`)||n(e.path+`
361
+ `)}},{name:`stat`,summary:`show file details`,usage:`stat path…`,async run({args:e,os:t,out:n,path:r}){for(let i of e){let e=await t.fs.stat(r(i));if(!e)throw Error(`${i}: no such file or directory`);n(` path: ${e.path}\n kind: ${e.kind}\n size: ${e.size} bytes\n mtime: ${e.mtime?new Date(e.mtime).toISOString():`-`}\n`)}}},{name:`du`,summary:`disk usage of a directory`,usage:`du [path]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=r(e[0]??`.`),o=0,s=0;for await(let e of t.fs.walk(a,{signal:i}))e.kind===`file`&&(o+=e.size,s++);n(`${K(o)}\t${s} files\t${a}\n`)}},{name:`df`,summary:`storage quota and mounts`,async run({os:e,out:t}){let n=await navigator.storage?.estimate?.().catch(()=>void 0);t(`origin storage: ${K(n?.usage??NaN)} used of ${K(n?.quota??NaN)}\n\n`);for(let n of e.fs.mounts())t(`${n.fs.label.padEnd(18)} ${n.fs.readonly?`ro`:`rw`} ${n.point}\n`)}},{name:`mount`,summary:`mount a real folder from this computer under /mnt`,async run({os:e,out:t}){t(`mounted at ${await e.mountNativeFolder()}\n`)}}];function gt(e,t){let n=-1;return(r,i)=>{let a=i?Math.min(100,Math.floor(r/i*100)):0;if(a===n)return;n=a;let o=Math.round(a/100*24);t(`\r${e.padEnd(8)} [${`#`.repeat(o)}${`.`.repeat(24-o)}] ${String(a).padStart(3)}% ${K(r)}${i?` / ${K(i)}`:``}`)}}async function J(e,t){for(let n of t){let t=gt(n,e.out);await e.os.packages.install(n,t),e.out(`\n${F.green}installed${F.reset} ${n}\n`)}}const _t={name:`pkg`,summary:`package manager: list, info, install, remove`,usage:`pkg list | pkg info <name> | pkg install <name>… | pkg install --defaults | pkg remove <name>…`,async run(e){let{os:t,out:n}=e,[r=`list`,...i]=e.args;if(r===`list`){for(let e of await t.packages.list())n(`${e.installed?`${F.green}i${F.reset}`:` `} ${F.bold}${e.id.padEnd(8)}${F.reset} ${(e.bytes?`${e.estimated?`~`:``}${K(e.bytes)}`:``).padStart(9)} ${e.summary}\n`);return n(`${F.dim}i = installed · pkg install <name>${F.reset}\n`)}if(r===`info`){let e=(await t.packages.list()).find(e=>e.id===i[0]);if(!e)throw Error(`no such package: ${i[0]??``}`);n(`${F.bold}${e.id}${F.reset} ${e.version}\n${e.summary}\nstatus: ${e.installed?`installed`:`not installed`}\nsize: ${e.bytes?`${e.estimated?`about `:``}${K(e.bytes)}`:`unknown until downloaded`}\ncommands: ${e.commands.join(`, `)||`—`}\ntools: ${e.tools.join(`, `)||`—`}\n`)}else{if(r===`install`){if(i.includes(`--defaults`))return J(e,yt(t).filter(e=>!t.packages.isInstalled(e)));if(!i.length)throw Error(`usage: pkg install <name>… | pkg install --defaults`);return J(e,i)}if(r===`remove`)for(let e of i)await t.packages.remove(e),n(`removed ${e}\n`);else throw Error(`usage: ${this.usage}`)}}},vt={name:`dmesg`,summary:`print the kernel log`,async run({os:e,out:t}){for(let n of e.kernelLog)t(`${F.dim}[${(n.t/1e3).toFixed(3).padStart(9)}]${F.reset} ${n.src}: ${n.msg}\n`)}},yt=e=>e.packages.manifests().filter(e=>e.default).map(e=>e.id),bt=[];function xt(){return bt}const St=[{name:`help`,summary:`list commands`,usage:`help [command]`,async run({args:e,shell:t,out:n}){let r=e[0]?t.commands.get(e[0])??P(e[0]):void 0;if(e[0]&&!r)throw Error(`no such command: ${e[0]}`);if(r)return void n(`${F.bold}${r.name}${F.reset} — ${r.summary}\n${r.usage?`usage: ${r.usage}\n`:``}`);n(`${F.bold}BrowserBox shell${F.reset} — pipes (|), redirects (> >> <), && || ;, $VARS, globs, quotes.\n\n`);let i=new Map([...ze().map(e=>[e,P(e)]),...t.commands]);for(let e of[...i.values()].sort((e,t)=>e.name.localeCompare(t.name)))n(` ${F.cyan}${e.name.padEnd(10)}${F.reset} ${e.summary}\n`)}},{name:`ps`,summary:`list processes`,async run({os:e,out:t}){t(`${F.dim}${`PID`.padStart(4)} ${`PPID`.padStart(4)} ${`KIND`.padEnd(8)} ${`STATE`.padEnd(8)} ${`CPU`.padStart(8)} NAME${F.reset}\n`);for(let n of e.procs.list())t(`${String(n.pid).padStart(4)} ${String(n.ppid).padStart(4)} ${n.kind.padEnd(8)} ${n.state.padEnd(8)} ${pt(n.cpuMs).padStart(8)} ${n.name}${n.detail?` ${F.dim}${n.detail}${F.reset}`:``}\n`)}},{name:`kill`,summary:`terminate a process`,usage:`kill pid…`,async run({args:e,os:t,err:n}){if(!e.length)throw Error(`usage: kill pid…`);let r=0;for(let i of e)t.procs.kill(Number(i))||(n(`kill: ${i}: no such process\n`),r=1);return r}},{name:`open`,summary:`open an app, or a file in the right app`,usage:`open <app | path>`,async run({args:e,os:t,path:n,out:r}){let i=e[0];if(!i)return void r(`apps: ${xt().filter(e=>!e.hidden).map(e=>e.id).join(`, `)}\n`);if(xt().some(e=>e.id===i))return void t.openApp(i,e[1]?{path:n(e[1])}:{});let a=n(i),o=await t.fs.stat(a);if(!o)throw Error(`${i}: no such app or file`);o.kind===`dir`?t.openApp(`files`,{path:a}):/\.(html?|png|jpe?g|gif|webp|svg|avif|pdf|mp3|wav|ogg|mp4|webm)$/i.test(a)?t.openApp(`preview`,{path:a}):t.openApp(`editor`,{path:a})}},{name:`env`,summary:`print environment variables`,async run({shell:e,out:t}){for(let[n,r]of Object.entries(e.env))n!==`?`&&t(`${n}=${r}\n`)}},{name:`export`,summary:`set an environment variable`,usage:`export NAME=value`,async run({args:e,shell:t}){for(let n of e){let e=n.indexOf(`=`);if(e<1)throw Error(`usage: export NAME=value`);t.env[n.slice(0,e)]=n.slice(e+1)}}},{name:`clear`,summary:`clear the terminal`,async run({shell:e}){e.tty?.clear()}},{name:`history`,summary:`show command history`,async run({shell:e,out:t}){e.history.forEach((e,n)=>t(`${String(n+1).padStart(4)} ${e}\n`))}},{name:`date`,summary:`print the date and time`,async run({out:e}){e((/* @__PURE__ */ new Date()).toString()+`
361
362
  `)}},{name:`whoami`,summary:`print the user name`,async run({shell:e,out:t}){t((e.env.USER??`user`)+`
362
363
  `)}},{name:`uname`,summary:`print system information`,async run({os:e,out:t,args:n}){t(n.includes(`-a`)?`BrowserBox ${e.version} wasm32 ${navigator.userAgent}\n`:`BrowserBox
363
- `)}},{name:`uptime`,summary:`time since boot`,async run({os:e,out:t}){t(`up ${st(performance.now())}, ${e.procs.list().length} processes\n`)}},{name:`sysinfo`,summary:`platform capabilities and boot timings`,async run({os:e,out:t}){let n=await navigator.storage?.estimate?.().catch(()=>void 0);t(`${P.bold}BrowserBox ${e.version}${P.reset}\n`),t(`root fs ${e.rootKind===`opfs`?`OPFS (persistent)`:`memory (not persistent)`}\n`),t(`storage ${G(n?.usage??NaN)} / ${G(n?.quota??NaN)}\n`),t(`cores ${navigator.hardwareConcurrency??`?`}\n`),t(`boot ${e.bootMarks.map(e=>`${e.name} ${e.at}ms`).join(` → `)}\n\n`);for(let n of e.caps)t(`${n.ok?`${P.green}✓${P.reset}`:`${P.red}✗${P.reset}`} ${n.label.padEnd(26)} ${P.dim}${n.use}${P.reset}\n`)}},{name:`sleep`,summary:`wait N seconds`,usage:`sleep seconds`,async run({args:e,signal:t}){await new Promise((n,r)=>{let i=setTimeout(n,(Number(e[0])||0)*1e3);t.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)})})}},{name:`notify`,summary:`show a notification`,usage:`notify title [body]`,async run({args:e,os:t}){t.notify({title:e[0]??`Notification`,body:e.slice(1).join(` `)||void 0})}},{name:`which`,summary:`locate a command`,async run({args:e,shell:t,out:n}){let r=0;for(let i of e)t.commands.has(i)?n(`/bin/${i}\n`):r=1;return r}},{name:`true`,summary:`succeed`,run:async()=>0},{name:`false`,summary:`fail`,run:async()=>1}];async function J(e,t){if(!t.length)return e.stdin;let n=``;for(let r of t)n+=await e.os.fs.readText(e.path(r));return n}const Y=e=>{let t=e.split(`
364
- `);return t.at(-1)===``&&t.pop(),t};function _t(e,t){let n=e.indexOf(`-n`);if(n>=0)return{n:Number(e[n+1])||t,rest:e.filter((e,t)=>t!==n&&t!==n+1)};let r=e.find(e=>/^-\d+$/.test(e));return{n:r?Number(r.slice(1)):t,rest:e.filter(e=>e!==r)}}async function vt(e,t){let n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}const yt=[{name:`echo`,summary:`print arguments`,async run({args:e,out:t}){let n=e[0]===`-n`;t((n?e.slice(1):e).join(` `)+(n?``:`
365
- `))}},{name:`grep`,summary:`search text with a regular expression`,usage:`grep [-i] [-n] [-v] [-r] [-F] pattern [path…]`,async run(e){let{opts:t,rest:n}=W(e.args),r=n.shift();if(r===void 0)throw Error(`usage: grep [-invrF] pattern [path…]`);let i=new RegExp(t.has(`F`)?r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`):r,t.has(`i`)?`i`:``),a=0,o=(n,r)=>{Y(n).forEach((n,o)=>{if(i.test(n)===t.has(`v`))return;a++;let s=t.has(`v`)?n:n.replace(i,e=>`${P.red}${e}${P.reset}`);e.out(`${r?`${P.magenta}${r}${P.reset}:`:``}${t.has(`n`)?`${P.green}${o+1}${P.reset}:`:``}${s}\n`)})};n.length||o(e.stdin,null);for(let r of n){let i=e.path(r),a=await e.os.fs.stat(i);if(!a)throw Error(`${r}: no such file or directory`);if(a.kind===`file`)o(await e.os.fs.readText(i),n.length>1?r:null);else if(t.has(`r`))for await(let t of e.os.fs.walk(i,{signal:e.signal}))t.kind===`file`&&t.size<2e6&&o(await e.os.fs.readText(t.path).catch(()=>``),t.path);else throw Error(`${r}: is a directory (use -r)`)}return+!a}},{name:`head`,summary:`first lines of input`,usage:`head [-n N] [file…]`,async run(e){let{n:t,rest:n}=_t(e.args,10),r=Y(await J(e,n)).slice(0,t);r.length&&e.out(r.join(`
364
+ `)}},{name:`uptime`,summary:`time since boot`,async run({os:e,out:t}){t(`up ${pt(performance.now())}, ${e.procs.list().length} processes\n`)}},{name:`sysinfo`,summary:`platform capabilities and boot timings`,async run({os:e,out:t}){let n=await navigator.storage?.estimate?.().catch(()=>void 0);t(`${F.bold}BrowserBox ${e.version}${F.reset}\n`),t(`root fs ${e.rootKind===`opfs`?`OPFS (persistent)`:`memory (not persistent)`}\n`),t(`storage ${K(n?.usage??NaN)} / ${K(n?.quota??NaN)}\n`),t(`cores ${navigator.hardwareConcurrency??`?`}\n`),t(`boot ${e.bootMarks.map(e=>`${e.name} ${e.at}ms`).join(` → `)}\n\n`);for(let n of e.caps)t(`${n.ok?`${F.green}✓${F.reset}`:`${F.red}✗${F.reset}`} ${n.label.padEnd(26)} ${F.dim}${n.use}${F.reset}\n`)}},{name:`sleep`,summary:`wait N seconds`,usage:`sleep seconds`,async run({args:e,signal:t}){await new Promise((n,r)=>{let i=setTimeout(n,(Number(e[0])||0)*1e3);t.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)})})}},{name:`notify`,summary:`show a notification`,usage:`notify title [body]`,async run({args:e,os:t}){t.notify({title:e[0]??`Notification`,body:e.slice(1).join(` `)||void 0})}},{name:`which`,summary:`locate a command`,async run({args:e,shell:t,out:n}){let r=0;for(let i of e)t.commands.has(i)?n(`/bin/${i}\n`):r=1;return r}},{name:`true`,summary:`succeed`,run:async()=>0},{name:`false`,summary:`fail`,run:async()=>1}];async function Y(e,t){if(!t.length)return e.stdin;let n=``;for(let r of t)n+=await e.os.fs.readText(e.path(r));return n}const X=e=>{let t=e.split(`
365
+ `);return t.at(-1)===``&&t.pop(),t};function Ct(e,t){let n=e.indexOf(`-n`);if(n>=0)return{n:Number(e[n+1])||t,rest:e.filter((e,t)=>t!==n&&t!==n+1)};let r=e.find(e=>/^-\d+$/.test(e));return{n:r?Number(r.slice(1)):t,rest:e.filter(e=>e!==r)}}async function wt(e,t){let n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}const Tt=[{name:`echo`,summary:`print arguments`,async run({args:e,out:t}){let n=e[0]===`-n`;t((n?e.slice(1):e).join(` `)+(n?``:`
366
+ `))}},{name:`grep`,summary:`search text with a regular expression`,usage:`grep [-i] [-n] [-v] [-r] [-F] pattern [path…]`,async run(e){let{opts:t,rest:n}=G(e.args),r=n.shift();if(r===void 0)throw Error(`usage: grep [-invrF] pattern [path…]`);let i=new RegExp(t.has(`F`)?r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`):r,t.has(`i`)?`i`:``),a=0,o=(n,r)=>{X(n).forEach((n,o)=>{if(i.test(n)===t.has(`v`))return;a++;let s=t.has(`v`)?n:n.replace(i,e=>`${F.red}${e}${F.reset}`);e.out(`${r?`${F.magenta}${r}${F.reset}:`:``}${t.has(`n`)?`${F.green}${o+1}${F.reset}:`:``}${s}\n`)})};n.length||o(e.stdin,null);for(let r of n){let i=e.path(r),a=await e.os.fs.stat(i);if(!a)throw Error(`${r}: no such file or directory`);if(a.kind===`file`)o(await e.os.fs.readText(i),n.length>1?r:null);else if(t.has(`r`))for await(let t of e.os.fs.walk(i,{signal:e.signal}))t.kind===`file`&&t.size<2e6&&o(await e.os.fs.readText(t.path).catch(()=>``),t.path);else throw Error(`${r}: is a directory (use -r)`)}return+!a}},{name:`head`,summary:`first lines of input`,usage:`head [-n N] [file…]`,async run(e){let{n:t,rest:n}=Ct(e.args,10),r=X(await Y(e,n)).slice(0,t);r.length&&e.out(r.join(`
366
367
  `)+`
367
- `)}},{name:`tail`,summary:`last lines of input`,usage:`tail [-n N] [file…]`,async run(e){let{n:t,rest:n}=_t(e.args,10),r=Y(await J(e,n)).slice(-t);r.length&&e.out(r.join(`
368
+ `)}},{name:`tail`,summary:`last lines of input`,usage:`tail [-n N] [file…]`,async run(e){let{n:t,rest:n}=Ct(e.args,10),r=X(await Y(e,n)).slice(-t);r.length&&e.out(r.join(`
368
369
  `)+`
369
- `)}},{name:`wc`,summary:`count lines, words and bytes (Rust/WASM)`,usage:`wc [-l] [file…]`,async run(e){let{opts:t,rest:n}=W(e.args),r=new TextEncoder().encode(await J(e,n)),i=e.os.kcore.wc(r);e.out(t.has(`l`)?`${i.lines}\n`:`${String(i.lines).padStart(7)} ${String(i.words).padStart(7)} ${String(i.bytes).padStart(7)}\n`)}},{name:`sort`,summary:`sort lines`,usage:`sort [-r] [-n] [-u] [file…]`,async run(e){let{opts:t,rest:n}=W(e.args),r=Y(await J(e,n));r.sort(t.has(`n`)?(e,t)=>parseFloat(e)-parseFloat(t):void 0),t.has(`r`)&&r.reverse(),t.has(`u`)&&(r=[...new Set(r)]),r.length&&e.out(r.join(`
370
+ `)}},{name:`wc`,summary:`count lines, words and bytes (Rust/WASM)`,usage:`wc [-l] [file…]`,async run(e){let{opts:t,rest:n}=G(e.args),r=new TextEncoder().encode(await Y(e,n)),i=e.os.kcore.wc(r);e.out(t.has(`l`)?`${i.lines}\n`:`${String(i.lines).padStart(7)} ${String(i.words).padStart(7)} ${String(i.bytes).padStart(7)}\n`)}},{name:`sort`,summary:`sort lines`,usage:`sort [-r] [-n] [-u] [file…]`,async run(e){let{opts:t,rest:n}=G(e.args),r=X(await Y(e,n));r.sort(t.has(`n`)?(e,t)=>parseFloat(e)-parseFloat(t):void 0),t.has(`r`)&&r.reverse(),t.has(`u`)&&(r=[...new Set(r)]),r.length&&e.out(r.join(`
370
371
  `)+`
371
- `)}},{name:`uniq`,summary:`drop adjacent duplicate lines`,usage:`uniq [-c] [file…]`,async run(e){let{opts:t,rest:n}=W(e.args),r=[];for(let t of Y(await J(e,n))){let e=r.at(-1);e&&e[0]===t?e[1]++:r.push([t,1])}for(let[n,i]of r)e.out(t.has(`c`)?`${String(i).padStart(7)} ${n}\n`:`${n}\n`)}},{name:`tee`,summary:`copy stdin to files and stdout`,usage:`tee [-a] file…`,async run(e){let{opts:t,rest:n}=W(e.args);for(let r of n)await(t.has(`a`)?e.os.fs.appendFile(e.path(r),e.stdin):e.os.fs.writeFile(e.path(r),e.stdin));e.out(e.stdin)}},{name:`sha256sum`,summary:`SHA-256 digest (Web Crypto)`,usage:`sha256sum [file…]`,async run(e){let t=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,e))].map(e=>e.toString(16).padStart(2,`0`)).join(``);if(!e.args.length)return void e.out(`${await t(new TextEncoder().encode(e.stdin))} -\n`);for(let n of e.args)e.out(`${await t(await e.os.fs.readFile(e.path(n)))} ${n}\n`)}},{name:`hash`,summary:`fast FNV-1a content hash (Rust/WASM)`,usage:`hash file…`,async run(e){for(let t of e.args)e.out(`${e.os.kcore.hash(await e.os.fs.readFile(e.path(t)))} ${t}\n`)}},{name:`gzip`,summary:`compress a file to file.gz (Compression Streams)`,usage:`gzip file…`,async run(e){if(!(`CompressionStream`in globalThis))throw Error(`Compression Streams are not supported in this browser`);for(let t of e.args){let n=e.path(t);await e.os.fs.writeFile(n+`.gz`,await vt(await e.os.fs.readFile(n),new CompressionStream(`gzip`))),await e.os.fs.rm(n)}}},{name:`gunzip`,summary:`decompress file.gz`,usage:`gunzip file.gz…`,async run(e){if(!(`DecompressionStream`in globalThis))throw Error(`Compression Streams are not supported in this browser`);for(let t of e.args){let n=e.path(t);if(!n.endsWith(`.gz`))throw Error(`${t}: unknown suffix`);await e.os.fs.writeFile(n.slice(0,-3),await vt(await e.os.fs.readFile(n),new DecompressionStream(`gzip`))),await e.os.fs.rm(n)}}}];function bt(e){return e.register(...lt,...yt,...gt,...ot,dt,ft,Fe,Ie,Le,Pe)}var xt=class{os;#e=1;constructor(e){this.os=e}contribute(e){let t={name:e.name,summary:e.summary,usage:e.usage,run:t=>e.run({args:t.args,stdin:t.stdin,cwd:t.shell.cwd,out:t.out,err:t.err,signal:t.signal,readLine:t.tty?(e,n)=>t.tty.readLine(e,{secret:n}):void 0})};return Me(t),()=>Ne(e.name,t)}async open(e={}){let t=this.os,n=null,r=null,i=null,a=t.procs.spawn({name:`bbsh`,kind:`shell`,ppid:e.ppid,onKill:()=>i?.abort()});t.procs.update(a.pid,{state:`idle`});let o=bt(new tt(t,{cwd:e.cwd,ppid:a.pid,confined:e.confined,prompter:e.prompter,tty:{readLine:(e,t)=>n?n(e,t?.secret??!1):Promise.resolve(null),clear:()=>r?.()}})),s={id:`sh${this.#e++}`,cwd:o.cwd,home:o.env.HOME??`/`,async run(e,n){if(a.signal.aborted)throw Error(`this shell has exited`);e.trim()&&o.history.at(-1)!==e&&o.history.push(e),i=new AbortController;let r=()=>i?.abort();n.signal?.addEventListener(`abort`,r),t.procs.update(a.pid,{state:`running`,detail:e.slice(0,60)});let c=performance.now();try{return await o.run(e,{out:n.out,err:n.err,signal:i.signal})}finally{n.signal?.removeEventListener(`abort`,r),i=null,s.cwd=o.cwd,t.procs.account(a.pid,performance.now()-c),t.procs.update(a.pid,{state:`idle`,detail:o.cwd})}},complete:e=>o.complete(e),onReadLine(e){n=e},onClear(e){r=e},close:()=>t.procs.exit(a.pid)};return s}},St=class{port;#e=1;#t=/* @__PURE__ */ new Map;#n={};#r=/* @__PURE__ */ new Map;closed=!1;constructor(e){this.port=e,e.onmessage=e=>void this.#i(e.data)}handle(e){return Object.assign(this.#n,e),this}call(e,...t){return this.closed?Promise.reject(/* @__PURE__ */ Error(`connection closed`)):new Promise((n,r)=>{let i=this.#e++;this.#t.set(i,{resolve:n,reject:r}),this.port.postMessage({k:`call`,id:i,m:e,a:t})})}emit(e,t){this.closed||this.port.postMessage({k:`evt`,n:e,p:t})}on(e,t){let n=this.#r.get(e);return n||this.#r.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}close(){if(!this.closed){this.closed=!0,this.port.close();for(let e of this.#t.values())e.reject(/* @__PURE__ */ Error(`connection closed`));this.#t.clear()}}async#i(e){if(e.k===`call`){let t=Object.hasOwn(this.#n,e.m)?this.#n[e.m]:void 0;try{if(!t)throw Error(`unknown method: ${e.m}`);let n=await t(...e.a);this.closed||this.port.postMessage({k:`ok`,id:e.id,v:n})}catch(t){let n=t;this.closed||this.port.postMessage({k:`err`,id:e.id,e:{name:n?.name??`Error`,message:n?.message??String(t)}})}}else if(e.k===`ok`||e.k===`err`){let t=this.#t.get(e.id);if(this.#t.delete(e.id),!t)return;if(e.k===`ok`)t.resolve(e.v);else{let n=Error(e.e.message);n.name=e.e.name,t.reject(n)}}else if(e.k===`evt`)for(let t of[...this.#r.get(e.n)??[]])try{t(e.p)}catch(t){console.error(`[rpc] listener for "${e.n}" threw`,t)}}};const X=e=>({pid:e.pid,ppid:e.ppid,name:e.name,kind:e.kind,started:e.started,state:e.state,detail:e.detail,cpuMs:e.cpuMs,memBytes:e.memBytes}),Ct=[`fs:change`,`settings:change`,`notify`,`app:open`,`kmsg`,`dev:update`,`dev:log`];var wt=class{os;shared;#e=/* @__PURE__ */ new Map;#t=1;#n=1;#r=1;#i=/* @__PURE__ */ new Map;#a=/* @__PURE__ */ new Map;#o=/* @__PURE__ */ new Map;#s=1;#c=null;#l=[];constructor(e,t){this.os=e,this.shared=t;for(let t of Ct)e.bus.on(t,e=>this.#u(`bus`,{type:t,payload:e},this.#c));e.bus.on(`proc:spawn`,e=>this.#u(`bus`,{type:`proc:spawn`,payload:X(e)})),e.bus.on(`proc:update`,e=>this.#u(`bus`,{type:`proc:update`,payload:X(e)})),e.bus.on(`proc:exit`,({proc:e,reason:t})=>this.#u(`bus`,{type:`proc:exit`,payload:{proc:X(e),reason:t}})),e.perms.setPrompter((e,t)=>this.#d({kind:`perm`,payload:e},t).catch(()=>`deny`)),e.ui={call:(e,...t)=>this.#d({kind:`ui`,payload:{method:e,args:t}},void 0,[...this.#e.values()].find(e=>e.role===`ui`))},Ge({run:(e,t,n)=>this.#f(e,t,n),backend:(e,t,n,r)=>this.#p(e,t,n,r)})}use(e){return this.#l.push(e),this}#u(e,t,n=null){for(let r of this.#e.values())r.id!==n&&(r.role===`ui`||r.role===`sdk`)&&r.peer.emit(e,t)}#d(e,t,n){return new Promise((r,i)=>{let a=this.#n++,o={...e,askId:a},s=n?[n]:[...this.#e.values()].filter(e=>e.role===`ui`);if(!s.length)return i(/* @__PURE__ */ Error(`no window is connected to answer`));this.#i.set(a,{ask:o,resolve:e=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);r(e)}},targets:new Set(s.map(e=>e.id))}),t?.addEventListener(`abort`,()=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);i(t.reason)}});for(let e of s)e.peer.emit(`ask`,o)})}async#f(e,t,n){let r=[...this.#e.values()].find(e=>e.role===`host`);if(!r)return{ok:!1,stdout:``,stderr:``,ms:0,error:`No window is open to host the sandbox. Open the agent window or the desktop.`};let i=this.#r++;this.#a.set(i,n);let a=()=>r.peer.emit(`host:abort`,i);n.signal?.addEventListener(`abort`,a);try{return await r.peer.call(`host.run`,i,e,t,{cwd:n.cwd,timeoutMs:n.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{n.signal?.removeEventListener(`abort`,a),this.#a.delete(i)}}async#p(e,t,n,r){let i=[...this.#e.values()].find(e=>e.role===`host`);if(!i)return{ok:!1,stdout:``,stderr:``,ms:0,error:e===`request`?`backend not loaded`:`No window is open to host the backend. Open the agent window or the desktop.`};let a=this.#r++;this.#a.set(a,r);try{return await i.peer.call(`host.backend`,a,e,t,n,{cwd:r.cwd,timeoutMs:r.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{this.#a.delete(a)}}connect(e){let t=new St(e),n={id:this.#t++,peer:t,role:`new`,shells:/* @__PURE__ */ new Map,drops:[]},r=this.os,i=r.fs,a=this,o=e=>{this.#c=n.id;try{return e()}finally{this.#c=null}},s=e=>{let t=n.shells.get(e);if(!t)throw Error(`no such shell: ${e}`);return t};t.handle({async hello(e){return n.role=e,await i.ready,{clientId:n.id,pidBase:n.id*1e5,version:r.version,rootKind:r.rootKind,shared:a.shared,settings:r.settings.entries(),procs:r.procs.list().map(X),mounts:i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),bootMarks:r.bootMarks,log:r.kernelLog}},"fs.readFile":e=>i.readFile(e),"fs.writeFile":(e,t)=>i.writeFile(e,t),"fs.appendFile":(e,t)=>i.appendFile(e,t),"fs.readdir":e=>i.readdir(e),"fs.stat":e=>i.stat(e),"fs.mkdir":e=>i.mkdir(e),"fs.rm":(e,t)=>i.rm(e,t),"fs.cp":(e,t)=>i.cp(e,t),"fs.mv":(e,t)=>i.mv(e,t),"fs.glob":(e,t,n)=>i.glob(e,t,n),"fs.unmount":e=>i.unmount(e),"fs.mounts":()=>i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),"fs.mountHandle":e=>r.mountHandle(e),"dev.start":e=>r.dev.start(e),"dev.stop":e=>r.dev.stop(e),"dev.list":()=>r.dev.list(),"dev.page":(e,t)=>r.dev.page(e,t),"dev.request":(e,t)=>r.dev.request(e,t),"dev.log":(e,t)=>r.dev.log(e,t),"dev.logs":(e,t)=>r.dev.logs(e,t),"settings.set":(e,t)=>o(()=>r.settings.set(e,t)),"secrets.has":e=>r.secrets.has(e),"secrets.set":(e,t)=>r.secrets.set(e,t),"secrets.delete":e=>r.secrets.delete(e),"procs.spawn":e=>{if(Math.floor(e.pid/1e5)!==n.id)throw Error(`pid outside this client’s range`);r.procs.spawn({pid:e.pid,name:e.name,kind:e.kind,ppid:e.ppid,detail:e.detail,onKill:()=>t.emit(`proc:kill`,e.pid)})},"procs.update":(e,t)=>r.procs.update(e,t),"procs.account":(e,t)=>r.procs.account(e,t),"procs.kill":(e,t)=>r.procs.kill(e,t),"bus.emit":(e,t)=>{if(e!==`notify`&&e!==`app:open`)throw Error(`windows may not emit ${String(e)}`);o(()=>r.bus.emit(e,e===`app:open`?{...t,fromWindow:n.role===`ui`}:t))},"shell.open":async e=>{let i=e?.confined?(e,t)=>this.#d({kind:`perm`,payload:e},t,n).catch(()=>`deny`):void 0,a=await r.shells.open({...e,prompter:i});return n.shells.set(a.id,a),a.onReadLine((e,t)=>this.#d({kind:`tty`,shellId:a.id,payload:{prompt:e,secret:t}},void 0,n)),a.onClear(()=>t.emit(`shell:clear`,a.id)),{id:a.id,cwd:a.cwd,home:a.home}},"shell.run":async(e,n,r)=>{let i=s(e),a=new AbortController,o=t.on(`shell:abort`,e=>e===n&&a.abort());try{let o=await i.run(r,{out:e=>t.emit(`shell:out`,{runId:n,s:`o`,t:e}),err:e=>t.emit(`shell:out`,{runId:n,s:`e`,t:e}),signal:a.signal});for(let t of[...this.#i.values()])t.ask.shellId===e&&t.resolve(null);return{code:o,cwd:i.cwd}}finally{o()}},"shell.complete":(e,t)=>s(e).complete(t),"shell.close":e=>{n.shells.get(e)?.close(),n.shells.delete(e)},"shell.contribute":e=>{for(let i of e){let e=r.shells.contribute?.({name:i.name,summary:i.summary,usage:i.usage,run:async e=>{let n=this.#s++;this.#o.set(n,e);let r=()=>t.emit(`cmd:abort`,n);e.signal.addEventListener(`abort`,r);try{return await t.call(`cmd.run`,n,i.name,{args:e.args,stdin:e.stdin,cwd:e.cwd,tty:!!e.readLine})}finally{e.signal.removeEventListener(`abort`,r),this.#o.delete(n)}}});e&&n.drops.push(e)}},"cmd.readLine":(e,t,n)=>this.#o.get(e)?.readLine?.(t,n)??null,answer:(e,t)=>{let r=this.#i.get(e);r?.targets.has(n.id)&&r.resolve(t)}});let c={id:n.id,peer:t,ask:(e,t,r)=>this.#d(e,t,r?n:void 0)};for(let e of this.#l){let{handlers:r,drop:i}=e.connect(c);t.handle(r),i&&n.drops.push(i)}t.on(`cmd:out`,({runId:e,s:t,t:n})=>{let r=this.#o.get(e);(t===`o`?r?.out:r?.err)?.(n)}),t.on(`host:out`,({runId:e,s:t,t:n})=>{let r=this.#a.get(e);(t===`o`?r?.onStdout:r?.onStderr)?.(n)}),t.on(`host:progress`,({runId:e,...t})=>this.#a.get(e)?.onProgress?.(t)),t.on(`alive`,e=>{navigator.locks?.request(e,()=>this.#m(n))}),t.on(`bye`,()=>this.#m(n)),this.#e.set(n.id,n)}#m(e){if(this.#e.delete(e.id)){e.peer.close();for(let t of e.drops)t();for(let t of e.shells.values())t.close();for(let t of this.os.procs.list())Math.floor(t.pid/1e5)===e.id&&this.os.procs.kill(t.pid,`window closed`);for(let[t,n]of this.#i)n.targets.delete(e.id),n.targets.size||(this.#i.delete(t),n.resolve(n.ask.kind===`perm`?`deny`:null))}}};const Tt=self,Z=`SharedWorkerGlobalScope`in self,Q=new Ce({packages:je,instance:c(self.name)});Q.shells=new xt(Q);const Et=new wt(Q,Z);if(Q.start().then(()=>Q.mark(`kernel-ready`)),!Z){let e=new BroadcastChannel(`bbx-settings:${self.name}`);Q.onSettingWritten=(t,n)=>e.postMessage({key:t,value:n}),e.onmessage=e=>Q.settings.applyRemote(e.data.key,e.data.value)}const $=e=>Et.connect(e);Z?Tt.onconnect=e=>$(e.ports[0]):Tt.onmessage=e=>e.data?.type===`connect`&&$(e.ports[0]);export{Ue as a,P as c,W as i,E as l,G as n,Ze as o,rt as r,Xe as s,ut as t,v as u};
372
+ `)}},{name:`uniq`,summary:`drop adjacent duplicate lines`,usage:`uniq [-c] [file…]`,async run(e){let{opts:t,rest:n}=G(e.args),r=[];for(let t of X(await Y(e,n))){let e=r.at(-1);e&&e[0]===t?e[1]++:r.push([t,1])}for(let[n,i]of r)e.out(t.has(`c`)?`${String(i).padStart(7)} ${n}\n`:`${n}\n`)}},{name:`tee`,summary:`copy stdin to files and stdout`,usage:`tee [-a] file…`,async run(e){let{opts:t,rest:n}=G(e.args);for(let r of n)await(t.has(`a`)?e.os.fs.appendFile(e.path(r),e.stdin):e.os.fs.writeFile(e.path(r),e.stdin));e.out(e.stdin)}},{name:`sha256sum`,summary:`SHA-256 digest (Web Crypto)`,usage:`sha256sum [file…]`,async run(e){let t=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,e))].map(e=>e.toString(16).padStart(2,`0`)).join(``);if(!e.args.length)return void e.out(`${await t(new TextEncoder().encode(e.stdin))} -\n`);for(let n of e.args)e.out(`${await t(await e.os.fs.readFile(e.path(n)))} ${n}\n`)}},{name:`hash`,summary:`fast FNV-1a content hash (Rust/WASM)`,usage:`hash file…`,async run(e){for(let t of e.args)e.out(`${e.os.kcore.hash(await e.os.fs.readFile(e.path(t)))} ${t}\n`)}},{name:`gzip`,summary:`compress a file to file.gz (Compression Streams)`,usage:`gzip file…`,async run(e){if(!(`CompressionStream`in globalThis))throw Error(`Compression Streams are not supported in this browser`);for(let t of e.args){let n=e.path(t);await e.os.fs.writeFile(n+`.gz`,await wt(await e.os.fs.readFile(n),new CompressionStream(`gzip`))),await e.os.fs.rm(n)}}},{name:`gunzip`,summary:`decompress file.gz`,usage:`gunzip file.gz…`,async run(e){if(!(`DecompressionStream`in globalThis))throw Error(`Compression Streams are not supported in this browser`);for(let t of e.args){let n=e.path(t);if(!n.endsWith(`.gz`))throw Error(`${t}: unknown suffix`);await e.os.fs.writeFile(n.slice(0,-3),await wt(await e.os.fs.readFile(n),new DecompressionStream(`gzip`))),await e.os.fs.rm(n)}}}];function Et(e){return e.register(...ht,...Tt,...St,...ft,_t,vt,Ve,He,Ue,Be)}var Dt=class{os;#e=1;constructor(e){this.os=e}contribute(e){let t={name:e.name,summary:e.summary,usage:e.usage,run:t=>e.run({args:t.args,stdin:t.stdin,cwd:t.shell.cwd,out:t.out,err:t.err,signal:t.signal,readLine:t.tty?(e,n)=>t.tty.readLine(e,{secret:n}):void 0})};return Le(t),()=>Re(e.name,t)}async open(e={}){let t=this.os,n=null,r=null,i=null,a=t.procs.spawn({name:`bbsh`,kind:`shell`,ppid:e.ppid,onKill:()=>i?.abort()});t.procs.update(a.pid,{state:`idle`});let o=Et(new st(t,{cwd:e.cwd,ppid:a.pid,confined:e.confined,prompter:e.prompter,tty:{readLine:(e,t)=>n?n(e,t?.secret??!1):Promise.resolve(null),clear:()=>r?.()}})),s={id:`sh${this.#e++}`,cwd:o.cwd,home:o.env.HOME??`/`,async run(e,n){if(a.signal.aborted)throw Error(`this shell has exited`);e.trim()&&o.history.at(-1)!==e&&o.history.push(e),i=new AbortController;let r=()=>i?.abort();n.signal?.addEventListener(`abort`,r),t.procs.update(a.pid,{state:`running`,detail:e.slice(0,60)});let c=performance.now();try{return await o.run(e,{out:n.out,err:n.err,signal:i.signal})}finally{n.signal?.removeEventListener(`abort`,r),i=null,s.cwd=o.cwd,t.procs.account(a.pid,performance.now()-c),t.procs.update(a.pid,{state:`idle`,detail:o.cwd})}},complete:e=>o.complete(e),onReadLine(e){n=e},onClear(e){r=e},close:()=>t.procs.exit(a.pid)};return s}},Ot=class{port;#e=1;#t=/* @__PURE__ */ new Map;#n={};#r=/* @__PURE__ */ new Map;closed=!1;constructor(e){this.port=e,e.onmessage=e=>void this.#i(e.data)}handle(e){return Object.assign(this.#n,e),this}call(e,...t){return this.closed?Promise.reject(/* @__PURE__ */ Error(`connection closed`)):new Promise((n,r)=>{let i=this.#e++;this.#t.set(i,{resolve:n,reject:r}),this.port.postMessage({k:`call`,id:i,m:e,a:t})})}emit(e,t){this.closed||this.port.postMessage({k:`evt`,n:e,p:t})}on(e,t){let n=this.#r.get(e);return n||this.#r.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}close(){if(!this.closed){this.closed=!0,this.port.close();for(let e of this.#t.values())e.reject(/* @__PURE__ */ Error(`connection closed`));this.#t.clear()}}async#i(e){if(e.k===`call`){let t=Object.hasOwn(this.#n,e.m)?this.#n[e.m]:void 0;try{if(!t)throw Error(`unknown method: ${e.m}`);let n=await t(...e.a);this.closed||this.port.postMessage({k:`ok`,id:e.id,v:n})}catch(t){let n=t;this.closed||this.port.postMessage({k:`err`,id:e.id,e:{name:n?.name??`Error`,message:n?.message??String(t)}})}}else if(e.k===`ok`||e.k===`err`){let t=this.#t.get(e.id);if(this.#t.delete(e.id),!t)return;if(e.k===`ok`)t.resolve(e.v);else{let n=Error(e.e.message);n.name=e.e.name,t.reject(n)}}else if(e.k===`evt`)for(let t of[...this.#r.get(e.n)??[]])try{t(e.p)}catch(t){console.error(`[rpc] listener for "${e.n}" threw`,t)}}};const Z=e=>({pid:e.pid,ppid:e.ppid,name:e.name,kind:e.kind,started:e.started,state:e.state,detail:e.detail,cpuMs:e.cpuMs,memBytes:e.memBytes}),kt=[`fs:change`,`settings:change`,`secrets:lock`,`notify`,`app:open`,`kmsg`,`dev:update`,`dev:log`];var At=class{os;shared;#e=/* @__PURE__ */ new Map;#t=1;#n=1;#r=1;#i=/* @__PURE__ */ new Map;#a=/* @__PURE__ */ new Map;#o=/* @__PURE__ */ new Map;#s=1;#c=null;#l=[];constructor(e,t){this.os=e,this.shared=t;for(let t of kt)e.bus.on(t,e=>this.#u(`bus`,{type:t,payload:e},this.#c));e.bus.on(`proc:spawn`,e=>this.#u(`bus`,{type:`proc:spawn`,payload:Z(e)})),e.bus.on(`proc:update`,e=>this.#u(`bus`,{type:`proc:update`,payload:Z(e)})),e.bus.on(`proc:exit`,({proc:e,reason:t})=>this.#u(`bus`,{type:`proc:exit`,payload:{proc:Z(e),reason:t}})),e.perms.setPrompter((e,t)=>this.#d({kind:`perm`,payload:e},t).catch(()=>`deny`)),e.ui={call:(e,...t)=>this.#d({kind:`ui`,payload:{method:e,args:t}},void 0,[...this.#e.values()].find(e=>e.role===`ui`))},Ze({run:(e,t,n)=>this.#f(e,t,n),backend:(e,t,n,r)=>this.#p(e,t,n,r)})}use(e){return this.#l.push(e),this}#u(e,t,n=null){for(let r of this.#e.values())r.id!==n&&(r.role===`ui`||r.role===`sdk`)&&r.peer.emit(e,t)}#d(e,t,n){return new Promise((r,i)=>{let a=this.#n++,o={...e,askId:a},s=n?[n]:[...this.#e.values()].filter(e=>e.role===`ui`);if(!s.length)return i(/* @__PURE__ */ Error(`no window is connected to answer`));this.#i.set(a,{ask:o,resolve:e=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);r(e)}},targets:new Set(s.map(e=>e.id))}),t?.addEventListener(`abort`,()=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);i(t.reason)}});for(let e of s)e.peer.emit(`ask`,o)})}async#f(e,t,n){let r=[...this.#e.values()].find(e=>e.role===`host`);if(!r)return{ok:!1,stdout:``,stderr:``,ms:0,error:`No window is open to host the sandbox. Open the agent window or the desktop.`};let i=this.#r++;this.#a.set(i,n);let a=()=>r.peer.emit(`host:abort`,i);n.signal?.addEventListener(`abort`,a);try{return await r.peer.call(`host.run`,i,e,t,{cwd:n.cwd,timeoutMs:n.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{n.signal?.removeEventListener(`abort`,a),this.#a.delete(i)}}async#p(e,t,n,r){let i=[...this.#e.values()].find(e=>e.role===`host`);if(!i)return{ok:!1,stdout:``,stderr:``,ms:0,error:e===`request`?`backend not loaded`:`No window is open to host the backend. Open the agent window or the desktop.`};let a=this.#r++;this.#a.set(a,r);try{return await i.peer.call(`host.backend`,a,e,t,n,{cwd:r.cwd,timeoutMs:r.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{this.#a.delete(a)}}connect(e){let t=new Ot(e),n={id:this.#t++,peer:t,role:`new`,shells:/* @__PURE__ */ new Map,drops:[]},r=this.os,i=r.fs,a=this,o=e=>{this.#c=n.id;try{return e()}finally{this.#c=null}},s=e=>{let t=n.shells.get(e);if(!t)throw Error(`no such shell: ${e}`);return t};t.handle({async hello(e){return n.role=e,await i.ready,{clientId:n.id,pidBase:n.id*1e5,version:r.version,rootKind:r.rootKind,shared:a.shared,settings:r.settings.entries(),procs:r.procs.list().map(Z),mounts:i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),bootMarks:r.bootMarks,log:r.kernelLog}},"fs.readFile":e=>i.readFile(e),"fs.writeFile":(e,t)=>i.writeFile(e,t),"fs.appendFile":(e,t)=>i.appendFile(e,t),"fs.readdir":e=>i.readdir(e),"fs.stat":e=>i.stat(e),"fs.mkdir":e=>i.mkdir(e),"fs.rm":(e,t)=>i.rm(e,t),"fs.cp":(e,t)=>i.cp(e,t),"fs.mv":(e,t)=>i.mv(e,t),"fs.glob":(e,t,n)=>i.glob(e,t,n),"fs.unmount":e=>i.unmount(e),"fs.mounts":()=>i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),"fs.mountHandle":e=>r.mountHandle(e),"dev.start":e=>r.dev.start(e),"dev.stop":e=>r.dev.stop(e),"dev.list":()=>r.dev.list(),"dev.page":(e,t)=>r.dev.page(e,t),"dev.request":(e,t)=>r.dev.request(e,t),"dev.log":(e,t)=>r.dev.log(e,t),"dev.logs":(e,t)=>r.dev.logs(e,t),"settings.set":(e,t)=>o(()=>r.settings.set(e,t)),"secrets.has":e=>r.secrets.has(e),"secrets.set":(e,t)=>r.secrets.set(e,t),"secrets.delete":e=>r.secrets.delete(e),"secrets.status":()=>r.secrets.status(),"secrets.unlock":async e=>{let t=await r.secrets.unlock(e);return t&&r.bus.emit(`secrets:lock`,{state:await r.secrets.status()}),t},"secrets.lock":async()=>{await r.secrets.lock(),r.bus.emit(`secrets:lock`,{state:await r.secrets.status()})},"secrets.setPassword":async e=>{await r.secrets.setPassword(e),r.bus.emit(`secrets:lock`,{state:await r.secrets.status()})},"procs.spawn":e=>{if(Math.floor(e.pid/1e5)!==n.id)throw Error(`pid outside this client’s range`);r.procs.spawn({pid:e.pid,name:e.name,kind:e.kind,ppid:e.ppid,detail:e.detail,onKill:()=>t.emit(`proc:kill`,e.pid)})},"procs.update":(e,t)=>r.procs.update(e,t),"procs.account":(e,t)=>r.procs.account(e,t),"procs.kill":(e,t)=>r.procs.kill(e,t),"bus.emit":(e,t)=>{if(e!==`notify`&&e!==`app:open`)throw Error(`windows may not emit ${String(e)}`);o(()=>r.bus.emit(e,e===`app:open`?{...t,fromWindow:n.role===`ui`}:t))},"shell.open":async e=>{let i=e?.confined?(e,t)=>this.#d({kind:`perm`,payload:e},t,n).catch(()=>`deny`):void 0,a=await r.shells.open({...e,prompter:i});return n.shells.set(a.id,a),a.onReadLine((e,t)=>this.#d({kind:`tty`,shellId:a.id,payload:{prompt:e,secret:t}},void 0,n)),a.onClear(()=>t.emit(`shell:clear`,a.id)),{id:a.id,cwd:a.cwd,home:a.home}},"shell.run":async(e,n,r)=>{let i=s(e),a=new AbortController,o=t.on(`shell:abort`,e=>e===n&&a.abort());try{let o=await i.run(r,{out:e=>t.emit(`shell:out`,{runId:n,s:`o`,t:e}),err:e=>t.emit(`shell:out`,{runId:n,s:`e`,t:e}),signal:a.signal});for(let t of[...this.#i.values()])t.ask.shellId===e&&t.resolve(null);return{code:o,cwd:i.cwd}}finally{o()}},"shell.complete":(e,t)=>s(e).complete(t),"shell.close":e=>{n.shells.get(e)?.close(),n.shells.delete(e)},"shell.contribute":e=>{for(let i of e){let e=r.shells.contribute?.({name:i.name,summary:i.summary,usage:i.usage,run:async e=>{let n=this.#s++;this.#o.set(n,e);let r=()=>t.emit(`cmd:abort`,n);e.signal.addEventListener(`abort`,r);try{return await t.call(`cmd.run`,n,i.name,{args:e.args,stdin:e.stdin,cwd:e.cwd,tty:!!e.readLine})}finally{e.signal.removeEventListener(`abort`,r),this.#o.delete(n)}}});e&&n.drops.push(e)}},"cmd.readLine":(e,t,n)=>this.#o.get(e)?.readLine?.(t,n)??null,answer:(e,t)=>{let r=this.#i.get(e);r?.targets.has(n.id)&&r.resolve(t)}});let c={id:n.id,peer:t,ask:(e,t,r)=>this.#d(e,t,r?n:void 0)};for(let e of this.#l){let{handlers:r,drop:i}=e.connect(c);t.handle(r),i&&n.drops.push(i)}t.on(`cmd:out`,({runId:e,s:t,t:n})=>{let r=this.#o.get(e);(t===`o`?r?.out:r?.err)?.(n)}),t.on(`host:out`,({runId:e,s:t,t:n})=>{let r=this.#a.get(e);(t===`o`?r?.onStdout:r?.onStderr)?.(n)}),t.on(`host:progress`,({runId:e,...t})=>this.#a.get(e)?.onProgress?.(t)),t.on(`alive`,e=>{navigator.locks?.request(e,()=>this.#m(n))}),t.on(`bye`,()=>this.#m(n)),this.#e.set(n.id,n)}#m(e){if(this.#e.delete(e.id)){e.peer.close();for(let t of e.drops)t();for(let t of e.shells.values())t.close();for(let t of this.os.procs.list())Math.floor(t.pid/1e5)===e.id&&this.os.procs.kill(t.pid,`window closed`);for(let[t,n]of this.#i)n.targets.delete(e.id),n.targets.size||(this.#i.delete(t),n.resolve(n.ask.kind===`perm`?`deny`:null))}}};const jt=self,Q=`SharedWorkerGlobalScope`in self,$=new Oe({packages:Ie,instance:u(self.name)});$.shells=new Dt($);const Mt=new At($,Q);if($.start().then(()=>$.mark(`kernel-ready`)),!Q){let e=new BroadcastChannel(`bbx-settings:${self.name}`);$.onSettingWritten=(t,n)=>e.postMessage({key:t,value:n}),e.onmessage=e=>$.settings.applyRemote(e.data.key,e.data.value)}const Nt=e=>Mt.connect(e);Q?jt.onconnect=e=>Nt(e.ports[0]):jt.onmessage=e=>e.data?.type===`connect`&&Nt(e.ports[0]);export{Ye as a,F as c,G as i,E as l,K as n,rt as o,lt as r,nt as s,gt as t,te as u};
@@ -1 +1 @@
1
- import{t as e}from"./bundle-qe7w2kMM.js";import{n as t,r as n,t as r}from"./path-DGG-Mxbd.js";var i={commands:[{name:`esbuild`,summary:`bundle TypeScript/JSX/CSS into files (npm packages from esm.sh)`,usage:`esbuild src/main.tsx --outfile=dist/app.js (also writes dist/app.css when there is CSS)`,async run(i){let a=i.args.find(e=>!e.startsWith(`-`)),o=i.args.find(e=>e.startsWith(`--outfile=`))?.slice(10);if(!a)throw Error(`usage: esbuild <entry> --outfile=<file>`);let s=i.path(a),c=i.path(o??`dist/${r(s).replace(/\.\w+$/,``)}.js`),l=i.shell.cwd,u=await i.os.fs.readText(`${l}/package.json`).then(e=>JSON.parse(e),()=>null),d=performance.now(),f=await e({fs:i.os.fs,root:l,entry:s,target:`browser`,pkg:u});for(let e of f.warnings)i.err(`warning: ${e}\n`);if(f.errors.length){for(let e of f.errors)i.err(`error: ${e}\n`);return 1}if(await i.os.fs.mkdir(t(c)),await i.os.fs.writeFile(c,f.js),i.out(`${c} ${(f.js.length/1024).toFixed(1)} KB\n`),f.css){let e=c.slice(0,-n(c).length-1)+`.css`;await i.os.fs.writeFile(e,f.css),i.out(`${e} ${(f.css.length/1024).toFixed(1)} KB\n`)}i.out(`done in ${Math.round(performance.now()-d)} ms\n`)}}]};export{i as default};
1
+ import{t as e}from"./bundle-CXrJ5BHI.js";import{n as t,r as n,t as r}from"./path-DGG-Mxbd.js";var i={commands:[{name:`esbuild`,summary:`bundle TypeScript/JSX/CSS into files (npm packages from esm.sh)`,usage:`esbuild src/main.tsx --outfile=dist/app.js (also writes dist/app.css when there is CSS)`,async run(i){let a=i.args.find(e=>!e.startsWith(`-`)),o=i.args.find(e=>e.startsWith(`--outfile=`))?.slice(10);if(!a)throw Error(`usage: esbuild <entry> --outfile=<file>`);let s=i.path(a),c=i.path(o??`dist/${r(s).replace(/\.\w+$/,``)}.js`),l=i.shell.cwd,u=await i.os.fs.readText(`${l}/package.json`).then(e=>JSON.parse(e),()=>null),d=performance.now(),f=await e({fs:i.os.fs,root:l,entry:s,target:`browser`,pkg:u});for(let e of f.warnings)i.err(`warning: ${e}\n`);if(f.errors.length){for(let e of f.errors)i.err(`error: ${e}\n`);return 1}if(await i.os.fs.mkdir(t(c)),await i.os.fs.writeFile(c,f.js),i.out(`${c} ${(f.js.length/1024).toFixed(1)} KB\n`),f.css){let e=c.slice(0,-n(c).length-1)+`.css`;await i.os.fs.writeFile(e,f.css),i.out(`${e} ${(f.css.length/1024).toFixed(1)} KB\n`)}i.out(`done in ${Math.round(performance.now()-d)} ms\n`)}}]};export{i as default};
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./rolldown-runtime-WkwZ5CU-.js";import{c as n,i as r,l as i}from"./main-DzFuvDws.js";var a=/* @__PURE__ */ t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),o=/* @__PURE__ */ t((e=>{
1
+ import{n as e,t}from"./rolldown-runtime-WkwZ5CU-.js";import{c as n,i as r,l as i}from"./main-CQvaEX7y.js";var a=/* @__PURE__ */ t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),o=/* @__PURE__ */ t((e=>{
2
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
3
  e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),s=/* @__PURE__ */ t((e=>{
4
4
  /*!
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,r as n,s as r}from"./main-DzFuvDws.js";function i(e,t){return t.value!==void 0&&t.value!==`None`&&e.out(t.value+`
1
+ import{a as e,i as t,r as n,s as r}from"./main-CQvaEX7y.js";function i(e,t){return t.value!==void 0&&t.value!==`None`&&e.out(t.value+`
2
2
  `),t.error&&e.err(t.error+`
3
3
  `),+!t.ok}const a=(e,t)=>r(e.os,t,{cwd:e.shell.cwd,env:n(e.shell.env),signal:e.signal,onStdout:e.out,onStderr:e.err}),o={name:`python`,summary:`run Python 3.13 (CPython on WebAssembly, via Pyodide)`,usage:`python file.py | python -c "code" | python -m pip install <pkg> | python -V (files in the cwd are visible; changes are written back)`,async run(e){let{opts:n,rest:r}=t(e.args);if(n.has(`V`)||n.has(`version`))return i(e,await a(e,`import sys, pyodide
4
4
  print(f"Python {sys.version.split()[0]} (Pyodide {pyodide.__version__})")`));if(n.has(`m`))return r[0]===`pip`?s.run({...e,args:r.slice(1)}):i(e,await a(e,`import runpy, sys\nsys.argv = ${JSON.stringify(r)}\nrunpy.run_module(${JSON.stringify(r[0]??``)}, run_name="__main__")`));let o=n.has(`c`)?r[0]??``:r[0]?await e.os.fs.readText(e.path(r[0])):e.stdin;if(!o.trim())throw Error(`nothing to run: pass a file, -c "code", or pipe code in`);return i(e,await a(e,o))}},s={name:`pip`,summary:`install Python packages (PyPI pure-Python wheels and Pyodide builds) with micropip`,usage:`pip install <pkg>… | pip install -r requirements.txt | pip uninstall <pkg>… | pip list | pip show <pkg> | pip freeze`,async run(t){let[n=`help`,...r]=t.args,o=()=>t.os.settings.get(e,[]),c=e=>e.split(/[<>=!~\[; ]/)[0].toLowerCase();if(n===`install`){let n=[];for(let e=0;e<r.length;e++){let i=r[e];if(i===`-r`||i===`--requirement`){let i=await t.os.fs.readText(t.path(r[++e]??``));n.push(...i.split(`
@@ -1 +1 @@
1
- import{n as e,o as t}from"./path-DGG-Mxbd.js";import{i as n,n as r}from"./main-DzFuvDws.js";var i=Uint8Array,a=Uint16Array,o=Int32Array,s=new i([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),c=new i([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),l=new i([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),u=function(e,t){for(var n=new a(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new o(n[30]),r=1;r<30;++r)for(var s=n[r];s<n[r+1];++s)i[s]=s-n[r]<<5|r;return{b:n,r:i}},d=u(s,2),f=d.b,p=d.r;f[28]=258,p[258]=28;for(var m=u(c,0),h=m.b,g=m.r,_=new a(32768),v=0;v<32768;++v){var y=(v&43690)>>1|(v&21845)<<1;y=(y&52428)>>2|(y&13107)<<2,y=(y&61680)>>4|(y&3855)<<4,_[v]=((y&65280)>>8|(y&255)<<8)>>1}for(var b=(function(e,t,n){for(var r=e.length,i=0,o=new a(t);i<r;++i)e[i]&&++o[e[i]-1];var s=new a(t);for(i=1;i<t;++i)s[i]=s[i-1]+o[i-1]<<1;var c;if(n){c=new a(1<<t);var l=15-t;for(i=0;i<r;++i)if(e[i])for(var u=i<<4|e[i],d=t-e[i],f=s[e[i]-1]++<<d,p=f|(1<<d)-1;f<=p;++f)c[_[f]>>l]=u}else for(c=new a(r),i=0;i<r;++i)e[i]&&(c[i]=_[s[e[i]-1]++]>>15-e[i]);return c}),x=new i(288),v=0;v<144;++v)x[v]=8;for(var v=144;v<256;++v)x[v]=9;for(var v=256;v<280;++v)x[v]=7;for(var v=280;v<288;++v)x[v]=8;for(var S=new i(32),v=0;v<32;++v)S[v]=5;var C=/*#__PURE__*/ b(x,9,0),w=/*#__PURE__*/ b(x,9,1),T=/*#__PURE__*/ b(S,5,0),ee=/*#__PURE__*/ b(S,5,1),E=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},D=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},O=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},te=function(e){return(e+7)/8|0},ne=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new i(e.subarray(t,n))},k=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],A=function(e,t,n){var r=Error(t||k[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,A),!n)throw r;return r},j=function(e,t,n,r){var a=e.length,o=r?r.length:0;if(!a||t.f&&!t.l)return n||new i(0);var u=!n,d=u||t.i!=2,p=t.i;u&&(n=new i(a*3));var m=function(e){var t=n.length;if(e>t){var r=new i(Math.max(t*2,e));r.set(n),n=r}},g=t.f||0,_=t.p||0,v=t.b||0,y=t.l,x=t.d,S=t.m,C=t.n,T=a*8;do{if(!y){g=D(e,_,1);var k=D(e,_+1,3);if(_+=3,!k){var j=te(_)+4,M=e[j-4]|e[j-3]<<8,N=j+M;if(N>a){p&&A(0);break}d&&m(v+M),n.set(e.subarray(j,N),v),t.b=v+=M,t.p=_=N*8,t.f=g;continue}if(k==1)y=w,x=ee,S=9,C=5;else if(k==2){var P=D(e,_,31)+257,F=D(e,_+10,15)+4,I=P+D(e,_+5,31)+1;_+=14;for(var L=new i(I),re=new i(19),R=0;R<F;++R)re[l[R]]=D(e,_+R*3,7);_+=F*3;for(var z=E(re),B=(1<<z)-1,V=b(re,z,1),R=0;R<I;){var H=V[D(e,_,B)];_+=H&15;var j=H>>4;if(j<16)L[R++]=j;else{var U=0,W=0;for(j==16?(W=3+D(e,_,3),_+=2,U=L[R-1]):j==17?(W=3+D(e,_,7),_+=3):j==18&&(W=11+D(e,_,127),_+=7);W--;)L[R++]=U}}var G=L.subarray(0,P),K=L.subarray(P);S=E(G),C=E(K),y=b(G,S,1),x=b(K,C,1)}else A(1);if(_>T){p&&A(0);break}}d&&m(v+131072);for(var q=(1<<S)-1,ie=(1<<C)-1,J=_;;J=_){var U=y[O(e,_)&q],Y=U>>4;if(_+=U&15,_>T){p&&A(0);break}if(U||A(2),Y<256)n[v++]=Y;else if(Y==256){J=_,y=null;break}else{var X=Y-254;if(Y>264){var R=Y-257,Z=s[R];X=D(e,_,(1<<Z)-1)+f[R],_+=Z}var Q=x[O(e,_)&ie],$=Q>>4;Q||A(3),_+=Q&15;var K=h[$];if($>3){var Z=c[$];K+=O(e,_)&(1<<Z)-1,_+=Z}if(_>T){p&&A(0);break}d&&m(v+131072);var ae=v+X;if(v<K){var oe=o-K,se=Math.min(K,ae);for(oe+v<0&&A(3);v<se;++v)n[v]=r[oe+v]}for(;v<ae;++v)n[v]=n[v-K]}}t.l=y,t.p=J,t.b=v,t.f=g,y&&(g=1,t.m=S,t.d=x,t.n=C)}while(!g);return v!=n.length&&u?ne(n,0,v):n.subarray(0,v)},M=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},N=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},P=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var o=n.length,s=n.slice();if(!o)return{t:B,l:0};if(o==1){var c=new i(n[0].s+1);return c[n[0].s]=1,{t:c,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var l=n[0],u=n[1],d=0,f=1,p=2;for(n[0]={s:-1,f:l.f+u.f,l,r:u};f!=o-1;)l=n[n[d].f<n[p].f?d++:p++],u=n[d!=f&&n[d].f<n[p].f?d++:p++],n[f++]={s:-1,f:l.f+u.f,l,r:u};for(var m=s[0].s,r=1;r<o;++r)s[r].s>m&&(m=s[r].s);var h=new a(m+1),g=F(n[f-1],h,0);if(g>t){var r=0,_=0,v=g-t,y=1<<v;for(s.sort(function(e,t){return h[t.s]-h[e.s]||e.f-t.f});r<o;++r){var b=s[r].s;if(h[b]>t)_+=y-(1<<g-h[b]),h[b]=t;else break}for(_>>=v;_>0;){var x=s[r].s;h[x]<t?_-=1<<t-h[x]++-1:++r}for(;r>=0&&_;--r){var S=s[r].s;h[S]==t&&(--h[S],++_)}g=t}return{t:new i(h),l:g}},F=function(e,t,n){return e.s==-1?Math.max(F(e.l,t,n+1),F(e.r,t,n+1)):t[e.s]=n},I=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new a(++t),r=0,i=e[0],o=1,s=function(e){n[r++]=e},c=1;c<=t;++c)if(e[c]==i&&c!=t)++o;else{if(!i&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(s(i),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0)}for(;o--;)s(i);o=1,i=e[c]}return{c:n.subarray(0,r),n:t}},L=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},re=function(e,t,n){var r=n.length,i=te(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},R=function(e,t,n,r,i,o,u,d,f,p,m){M(t,m++,n),++i[256];for(var h=P(i,15),g=h.t,_=h.l,v=P(o,15),y=v.t,w=v.l,ee=I(g),E=ee.c,D=ee.n,O=I(y),te=O.c,ne=O.n,k=new a(19),A=0;A<E.length;++A)++k[E[A]&31];for(var A=0;A<te.length;++A)++k[te[A]&31];for(var j=P(k,7),F=j.t,R=j.l,z=19;z>4&&!F[l[z-1]];--z);var B=p+5<<3,V=L(i,x)+L(o,S)+u,H=L(i,g)+L(o,y)+u+14+3*z+L(k,F)+2*k[16]+3*k[17]+7*k[18];if(f>=0&&B<=V&&B<=H)return re(t,m,e.subarray(f,f+p));var U,W,G,K;if(M(t,m,1+(H<V)),m+=2,H<V){U=b(g,_,0),W=g,G=b(y,w,0),K=y;var q=b(F,R,0);M(t,m,D-257),M(t,m+5,ne-1),M(t,m+10,z-4),m+=14;for(var A=0;A<z;++A)M(t,m+3*A,F[l[A]]);m+=3*z;for(var ie=[E,te],J=0;J<2;++J)for(var Y=ie[J],A=0;A<Y.length;++A){var X=Y[A]&31;M(t,m,q[X]),m+=F[X],X>15&&(M(t,m,Y[A]>>5&127),m+=Y[A]>>12)}}else U=C,W=x,G=T,K=S;for(var A=0;A<d;++A){var Z=r[A];if(Z>255){var X=Z>>18&31;N(t,m,U[X+257]),m+=W[X+257],X>7&&(M(t,m,Z>>23&31),m+=s[X]);var Q=Z&31;N(t,m,G[Q]),m+=K[Q],Q>3&&(N(t,m,Z>>5&8191),m+=c[Q])}else N(t,m,U[Z]),m+=W[Z]}return N(t,m,U[256]),m+W[256]},z=/*#__PURE__*/ new o([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),B=/*#__PURE__*/ new i(0),V=function(e,t,n,r,l,u){var d=u.z||e.length,f=new i(r+d+5*(1+Math.ceil(d/7e3))+l),m=f.subarray(r,f.length-l),h=u.l,_=(u.r||0)&7;if(t){_&&(m[0]=u.r>>3);for(var v=z[t-1],y=v>>13,b=v&8191,x=(1<<n)-1,S=u.p||new a(32768),C=u.h||new a(x+1),w=Math.ceil(n/3),T=2*w,ee=function(t){return(e[t]^e[t+1]<<w^e[t+2]<<T)&x},E=new o(25e3),D=new a(288),O=new a(32),k=0,A=0,j=u.i||0,M=0,N=u.w||0,P=0;j+2<d;++j){var F=ee(j),I=j&32767,L=C[F];if(S[I]=L,C[F]=I,N<=j){var B=d-j;if((k>7e3||M>24576)&&(B>423||!h)){_=R(e,m,0,E,D,O,A,M,P,j-P,_),M=k=A=0,P=j;for(var V=0;V<286;++V)D[V]=0;for(var V=0;V<30;++V)O[V]=0}var H=2,U=0,W=b,G=I-L&32767;if(B>2&&F==ee(j-G))for(var K=Math.min(y,B)-1,q=Math.min(32767,j),ie=Math.min(258,B);G<=q&&--W&&I!=L;){if(e[j+H]==e[j+H-G]){for(var J=0;J<ie&&e[j+J]==e[j+J-G];++J);if(J>H){if(H=J,U=G,J>K)break;for(var Y=Math.min(G,J-2),X=0,V=0;V<Y;++V){var Z=j-G+V&32767,Q=Z-S[Z]&32767;Q>X&&(X=Q,L=Z)}}}I=L,L=S[I],G+=I-L&32767}if(U){E[M++]=268435456|p[H]<<18|g[U];var $=p[H]&31,ae=g[U]&31;A+=s[$]+c[ae],++D[257+$],++O[ae],N=j+H,++k}else E[M++]=e[j],++D[e[j]]}}for(j=Math.max(j,N);j<d;++j)E[M++]=e[j],++D[e[j]];_=R(e,m,h,E,D,O,A,M,P,j-P,_),h||(u.r=_&7|m[_/8|0]<<3,_-=7,u.h=C,u.p=S,u.i=j,u.w=N)}else{for(var j=u.w||0;j<d+h;j+=65535){var oe=j+65535;oe>=d&&(m[_/8|0]=h,oe=d),_=re(m,_+1,e.subarray(j,oe))}u.i=d}return ne(f,0,r+te(_)+l)},H=/*#__PURE__*/ (function(){for(var e=/* @__PURE__ */ new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),U=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=H[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},W=function(e,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),s=new i(o.length+e.length);s.set(o),s.set(e,o.length),e=s,a.w=o.length}return V(e,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,a)},G=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},K=function(e,t){return e[t]|e[t+1]<<8},q=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},ie=function(e,t){return q(e,t)+q(e,t+4)*4294967296},J=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Y(e,t){return W(e,t||{},0,0)}function X(e,t){return j(e,{i:2},t&&t.out,t&&t.dictionary)}var Z=function(e,t,n,r){for(var a in e){var o=e[a],s=t+a,c=r;Array.isArray(o)&&(c=G(r,o[1]),o=o[0]),ArrayBuffer.isView(o)?n[s]=[o,c]:(n[s+=`/`]=[new i(0),c],Z(o,s,n,r))}},Q=typeof TextEncoder<`u`&&/*#__PURE__*/ new TextEncoder,$=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{$.decode(B,{stream:!0})}catch{}var ae=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:ne(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function oe(e,t){if(t){for(var n=new i(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(Q)return Q.encode(e);for(var a=e.length,o=new i(e.length+(e.length>>1)),s=0,c=function(e){o[s++]=e},r=0;r<a;++r){if(s+5>o.length){var l=new i(s+8+(a-r<<1));l.set(o),o=l}var u=e.charCodeAt(r);u<128||t?c(u):u<2048?(c(192|u>>6),c(128|u&63)):u>55295&&u<57344?(u=65536+(u&1047552)|e.charCodeAt(++r)&1023,c(240|u>>18),c(128|u>>12&63),c(128|u>>6&63),c(128|u&63)):(c(224|u>>12),c(128|u>>6&63),c(128|u&63))}return ne(o,0,s)}function se(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if($)return $.decode(e);var i=ae(e),a=i.s,n=i.r;return n.length&&A(8),a}var ce=function(e,t){return t+30+K(e,t+26)+K(e,t+28)},le=function(e,t,n){var r=K(e,t+28),i=K(e,t+30),a=se(e.subarray(t+46,t+46+r),!(K(e,t+8)&2048)),o=t+46+r,s=ue(e,o,i,n,q(e,t+20),q(e,t+24),q(e,t+42)),c=s[0],l=s[1],u=s[2];return[K(e,t+10),c,l,a,o+i+K(e,t+32),u]},ue=function(e,t,n,r,i,a,o){var s=i==4294967295,c=a==4294967295,l=o==4294967295,u=t+n,d=s+c+l;if(r&&d){for(;t+4<u;t+=4+K(e,t+2))if(K(e,t)==1)return[s?ie(e,t+4+8*c):i,c?ie(e,t+4):a,l?ie(e,t+4+8*(c+s)):o,1];r<2&&A(13)}return[i,a,o,0]},de=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&A(9),t+=r+4}return t},fe=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=de(l);J(e,t,o==null?67324752:33639248),t+=4,o!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(a<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),p=f.getFullYear()-1980;if((p<0||p>119)&&A(10),J(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(J(e,t,n.crc),J(e,t+4,a<0?-a-2:a),J(e,t+8,n.size)),J(e,t+12,c),J(e,t+14,d),t+=16,o!=null&&(J(e,t,u),J(e,t+6,n.attrs),J(e,t+10,o),t+=14),e.set(r,t),t+=c,d)for(var m in l){var h=l[m],g=h.length;J(e,t,+m),J(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},pe=function(e,t,n,r,i){J(e,t,101010256),J(e,t+8,n),J(e,t+10,n),J(e,t+12,r),J(e,t+16,i)};function me(e,t){t||={};var n={},r=[];Z(e,``,n,t);var a=0,o=0;for(var s in n){var c=n[s],l=c[0],u=c[1],d=u.level==0?0:8,f=oe(s),p=f.length,m=u.comment,h=m&&oe(m),g=h&&h.length,_=de(u.extra);p>65535&&A(11);var v=d?Y(l,u):l,y=v.length,b=U();b.p(l),r.push(G(u,{size:l.length,crc:b.d(),c:v,f,m:h,u:p!=s.length||h&&m.length!=g,o:a,compression:d})),a+=30+p+_+y,o+=76+2*(p+_)+(g||0)+y}for(var x=new i(o+22),S=a,C=o-a,w=0;w<r.length;++w){var f=r[w];fe(x,f.o,f,f.f,f.u,f.c.length);var T=30+f.f.length+de(f.extra);x.set(f.c,f.o+T),fe(x,a,f,f.f,f.u,f.c.length,f.o,f.m),a+=16+T+(f.m?f.m.length:0)}return pe(x,a,r.length,C,S),x}function he(e,t){for(var n={},r=e.length-22;q(e,r)!=101010256;--r)(!r||e.length-r>65558)&&A(13);var a=K(e,r+8);if(!a)return{};var o=q(e,r+16),s=q(e,r-20)==117853008;if(s){var c=q(e,r-12);s=q(e,c)==101075792,s&&(a=q(e,c+32),o=q(e,c+48))}for(var l=t&&t.filter,u=0;u<a;++u){var d=le(e,o,s),f=d[0],p=d[1],m=d[2],h=d[3],g=d[4],_=d[5],v=ce(e,_);o=g,(!l||l({name:h,size:p,originalSize:m,compression:f}))&&(f?f==8?n[h]=X(e.subarray(v,v+p),{out:new i(m)}):A(14,`unknown compression type `+f):n[h]=ne(e,v,v+p))}return n}var ge={commands:[{name:`zip`,summary:`create a zip archive`,usage:`zip [-r] archive.zip path…`,async run(t){let{rest:i}=n(t.args),a=i.shift();if(!a||!i.length)throw Error(`usage: zip [-r] archive.zip path…`);let o={};for(let n of i){let r=t.path(n),i=await t.os.fs.stat(r);if(!i)throw Error(`${n}: no such file or directory`);let a=e(r)===`/`?`/`:e(r)+`/`;if(i.kind===`file`)o[r.slice(a.length)]=await t.os.fs.readFile(r);else for await(let e of t.os.fs.walk(r,{signal:t.signal}))e.kind===`file`&&(o[e.path.slice(a.length)]=await t.os.fs.readFile(e.path))}let s=me(o);await t.os.fs.writeFile(t.path(a),s),t.out(`${Object.keys(o).length} files → ${a} (${r(s.length)})\n`)}},{name:`unzip`,summary:`list or extract a zip archive`,usage:`unzip [-l] archive.zip [-d dir]`,async run(e){let n=e.args.indexOf(`-d`),r=e.path(n>=0?e.args[n+1]??`.`:`.`),i=e.args.filter((e,t)=>e!==`-l`&&t!==n&&t!==n+1);if(!i[0])throw Error(`usage: unzip [-l] archive.zip [-d dir]`);let a=he(await e.os.fs.readFile(e.path(i[0]))),o=0;for(let[n,i]of Object.entries(a))n.endsWith(`/`)||(o++,e.args.includes(`-l`)?e.out(`${String(i.length).padStart(10)} ${n}\n`):await e.os.fs.writeFile(t(r,t(`/`,n)),i));e.out(`${o} file${o===1?``:`s`}${e.args.includes(`-l`)?``:` extracted to ${r}`}\n`)}}]};export{ge as default};
1
+ import{n as e,o as t}from"./path-DGG-Mxbd.js";import{i as n,n as r}from"./main-CQvaEX7y.js";var i=Uint8Array,a=Uint16Array,o=Int32Array,s=new i([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),c=new i([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),l=new i([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),u=function(e,t){for(var n=new a(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new o(n[30]),r=1;r<30;++r)for(var s=n[r];s<n[r+1];++s)i[s]=s-n[r]<<5|r;return{b:n,r:i}},d=u(s,2),f=d.b,p=d.r;f[28]=258,p[258]=28;for(var m=u(c,0),h=m.b,g=m.r,_=new a(32768),v=0;v<32768;++v){var y=(v&43690)>>1|(v&21845)<<1;y=(y&52428)>>2|(y&13107)<<2,y=(y&61680)>>4|(y&3855)<<4,_[v]=((y&65280)>>8|(y&255)<<8)>>1}for(var b=(function(e,t,n){for(var r=e.length,i=0,o=new a(t);i<r;++i)e[i]&&++o[e[i]-1];var s=new a(t);for(i=1;i<t;++i)s[i]=s[i-1]+o[i-1]<<1;var c;if(n){c=new a(1<<t);var l=15-t;for(i=0;i<r;++i)if(e[i])for(var u=i<<4|e[i],d=t-e[i],f=s[e[i]-1]++<<d,p=f|(1<<d)-1;f<=p;++f)c[_[f]>>l]=u}else for(c=new a(r),i=0;i<r;++i)e[i]&&(c[i]=_[s[e[i]-1]++]>>15-e[i]);return c}),x=new i(288),v=0;v<144;++v)x[v]=8;for(var v=144;v<256;++v)x[v]=9;for(var v=256;v<280;++v)x[v]=7;for(var v=280;v<288;++v)x[v]=8;for(var S=new i(32),v=0;v<32;++v)S[v]=5;var C=/*#__PURE__*/ b(x,9,0),w=/*#__PURE__*/ b(x,9,1),T=/*#__PURE__*/ b(S,5,0),ee=/*#__PURE__*/ b(S,5,1),E=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},D=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},O=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},te=function(e){return(e+7)/8|0},ne=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new i(e.subarray(t,n))},k=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],A=function(e,t,n){var r=Error(t||k[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,A),!n)throw r;return r},j=function(e,t,n,r){var a=e.length,o=r?r.length:0;if(!a||t.f&&!t.l)return n||new i(0);var u=!n,d=u||t.i!=2,p=t.i;u&&(n=new i(a*3));var m=function(e){var t=n.length;if(e>t){var r=new i(Math.max(t*2,e));r.set(n),n=r}},g=t.f||0,_=t.p||0,v=t.b||0,y=t.l,x=t.d,S=t.m,C=t.n,T=a*8;do{if(!y){g=D(e,_,1);var k=D(e,_+1,3);if(_+=3,!k){var j=te(_)+4,M=e[j-4]|e[j-3]<<8,N=j+M;if(N>a){p&&A(0);break}d&&m(v+M),n.set(e.subarray(j,N),v),t.b=v+=M,t.p=_=N*8,t.f=g;continue}if(k==1)y=w,x=ee,S=9,C=5;else if(k==2){var P=D(e,_,31)+257,F=D(e,_+10,15)+4,I=P+D(e,_+5,31)+1;_+=14;for(var L=new i(I),re=new i(19),R=0;R<F;++R)re[l[R]]=D(e,_+R*3,7);_+=F*3;for(var z=E(re),B=(1<<z)-1,V=b(re,z,1),R=0;R<I;){var H=V[D(e,_,B)];_+=H&15;var j=H>>4;if(j<16)L[R++]=j;else{var U=0,W=0;for(j==16?(W=3+D(e,_,3),_+=2,U=L[R-1]):j==17?(W=3+D(e,_,7),_+=3):j==18&&(W=11+D(e,_,127),_+=7);W--;)L[R++]=U}}var G=L.subarray(0,P),K=L.subarray(P);S=E(G),C=E(K),y=b(G,S,1),x=b(K,C,1)}else A(1);if(_>T){p&&A(0);break}}d&&m(v+131072);for(var q=(1<<S)-1,ie=(1<<C)-1,J=_;;J=_){var U=y[O(e,_)&q],Y=U>>4;if(_+=U&15,_>T){p&&A(0);break}if(U||A(2),Y<256)n[v++]=Y;else if(Y==256){J=_,y=null;break}else{var X=Y-254;if(Y>264){var R=Y-257,Z=s[R];X=D(e,_,(1<<Z)-1)+f[R],_+=Z}var Q=x[O(e,_)&ie],$=Q>>4;Q||A(3),_+=Q&15;var K=h[$];if($>3){var Z=c[$];K+=O(e,_)&(1<<Z)-1,_+=Z}if(_>T){p&&A(0);break}d&&m(v+131072);var ae=v+X;if(v<K){var oe=o-K,se=Math.min(K,ae);for(oe+v<0&&A(3);v<se;++v)n[v]=r[oe+v]}for(;v<ae;++v)n[v]=n[v-K]}}t.l=y,t.p=J,t.b=v,t.f=g,y&&(g=1,t.m=S,t.d=x,t.n=C)}while(!g);return v!=n.length&&u?ne(n,0,v):n.subarray(0,v)},M=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},N=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},P=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var o=n.length,s=n.slice();if(!o)return{t:B,l:0};if(o==1){var c=new i(n[0].s+1);return c[n[0].s]=1,{t:c,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var l=n[0],u=n[1],d=0,f=1,p=2;for(n[0]={s:-1,f:l.f+u.f,l,r:u};f!=o-1;)l=n[n[d].f<n[p].f?d++:p++],u=n[d!=f&&n[d].f<n[p].f?d++:p++],n[f++]={s:-1,f:l.f+u.f,l,r:u};for(var m=s[0].s,r=1;r<o;++r)s[r].s>m&&(m=s[r].s);var h=new a(m+1),g=F(n[f-1],h,0);if(g>t){var r=0,_=0,v=g-t,y=1<<v;for(s.sort(function(e,t){return h[t.s]-h[e.s]||e.f-t.f});r<o;++r){var b=s[r].s;if(h[b]>t)_+=y-(1<<g-h[b]),h[b]=t;else break}for(_>>=v;_>0;){var x=s[r].s;h[x]<t?_-=1<<t-h[x]++-1:++r}for(;r>=0&&_;--r){var S=s[r].s;h[S]==t&&(--h[S],++_)}g=t}return{t:new i(h),l:g}},F=function(e,t,n){return e.s==-1?Math.max(F(e.l,t,n+1),F(e.r,t,n+1)):t[e.s]=n},I=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new a(++t),r=0,i=e[0],o=1,s=function(e){n[r++]=e},c=1;c<=t;++c)if(e[c]==i&&c!=t)++o;else{if(!i&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(s(i),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0)}for(;o--;)s(i);o=1,i=e[c]}return{c:n.subarray(0,r),n:t}},L=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},re=function(e,t,n){var r=n.length,i=te(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},R=function(e,t,n,r,i,o,u,d,f,p,m){M(t,m++,n),++i[256];for(var h=P(i,15),g=h.t,_=h.l,v=P(o,15),y=v.t,w=v.l,ee=I(g),E=ee.c,D=ee.n,O=I(y),te=O.c,ne=O.n,k=new a(19),A=0;A<E.length;++A)++k[E[A]&31];for(var A=0;A<te.length;++A)++k[te[A]&31];for(var j=P(k,7),F=j.t,R=j.l,z=19;z>4&&!F[l[z-1]];--z);var B=p+5<<3,V=L(i,x)+L(o,S)+u,H=L(i,g)+L(o,y)+u+14+3*z+L(k,F)+2*k[16]+3*k[17]+7*k[18];if(f>=0&&B<=V&&B<=H)return re(t,m,e.subarray(f,f+p));var U,W,G,K;if(M(t,m,1+(H<V)),m+=2,H<V){U=b(g,_,0),W=g,G=b(y,w,0),K=y;var q=b(F,R,0);M(t,m,D-257),M(t,m+5,ne-1),M(t,m+10,z-4),m+=14;for(var A=0;A<z;++A)M(t,m+3*A,F[l[A]]);m+=3*z;for(var ie=[E,te],J=0;J<2;++J)for(var Y=ie[J],A=0;A<Y.length;++A){var X=Y[A]&31;M(t,m,q[X]),m+=F[X],X>15&&(M(t,m,Y[A]>>5&127),m+=Y[A]>>12)}}else U=C,W=x,G=T,K=S;for(var A=0;A<d;++A){var Z=r[A];if(Z>255){var X=Z>>18&31;N(t,m,U[X+257]),m+=W[X+257],X>7&&(M(t,m,Z>>23&31),m+=s[X]);var Q=Z&31;N(t,m,G[Q]),m+=K[Q],Q>3&&(N(t,m,Z>>5&8191),m+=c[Q])}else N(t,m,U[Z]),m+=W[Z]}return N(t,m,U[256]),m+W[256]},z=/*#__PURE__*/ new o([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),B=/*#__PURE__*/ new i(0),V=function(e,t,n,r,l,u){var d=u.z||e.length,f=new i(r+d+5*(1+Math.ceil(d/7e3))+l),m=f.subarray(r,f.length-l),h=u.l,_=(u.r||0)&7;if(t){_&&(m[0]=u.r>>3);for(var v=z[t-1],y=v>>13,b=v&8191,x=(1<<n)-1,S=u.p||new a(32768),C=u.h||new a(x+1),w=Math.ceil(n/3),T=2*w,ee=function(t){return(e[t]^e[t+1]<<w^e[t+2]<<T)&x},E=new o(25e3),D=new a(288),O=new a(32),k=0,A=0,j=u.i||0,M=0,N=u.w||0,P=0;j+2<d;++j){var F=ee(j),I=j&32767,L=C[F];if(S[I]=L,C[F]=I,N<=j){var B=d-j;if((k>7e3||M>24576)&&(B>423||!h)){_=R(e,m,0,E,D,O,A,M,P,j-P,_),M=k=A=0,P=j;for(var V=0;V<286;++V)D[V]=0;for(var V=0;V<30;++V)O[V]=0}var H=2,U=0,W=b,G=I-L&32767;if(B>2&&F==ee(j-G))for(var K=Math.min(y,B)-1,q=Math.min(32767,j),ie=Math.min(258,B);G<=q&&--W&&I!=L;){if(e[j+H]==e[j+H-G]){for(var J=0;J<ie&&e[j+J]==e[j+J-G];++J);if(J>H){if(H=J,U=G,J>K)break;for(var Y=Math.min(G,J-2),X=0,V=0;V<Y;++V){var Z=j-G+V&32767,Q=Z-S[Z]&32767;Q>X&&(X=Q,L=Z)}}}I=L,L=S[I],G+=I-L&32767}if(U){E[M++]=268435456|p[H]<<18|g[U];var $=p[H]&31,ae=g[U]&31;A+=s[$]+c[ae],++D[257+$],++O[ae],N=j+H,++k}else E[M++]=e[j],++D[e[j]]}}for(j=Math.max(j,N);j<d;++j)E[M++]=e[j],++D[e[j]];_=R(e,m,h,E,D,O,A,M,P,j-P,_),h||(u.r=_&7|m[_/8|0]<<3,_-=7,u.h=C,u.p=S,u.i=j,u.w=N)}else{for(var j=u.w||0;j<d+h;j+=65535){var oe=j+65535;oe>=d&&(m[_/8|0]=h,oe=d),_=re(m,_+1,e.subarray(j,oe))}u.i=d}return ne(f,0,r+te(_)+l)},H=/*#__PURE__*/ (function(){for(var e=/* @__PURE__ */ new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),U=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=H[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},W=function(e,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),s=new i(o.length+e.length);s.set(o),s.set(e,o.length),e=s,a.w=o.length}return V(e,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,a)},G=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},K=function(e,t){return e[t]|e[t+1]<<8},q=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},ie=function(e,t){return q(e,t)+q(e,t+4)*4294967296},J=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Y(e,t){return W(e,t||{},0,0)}function X(e,t){return j(e,{i:2},t&&t.out,t&&t.dictionary)}var Z=function(e,t,n,r){for(var a in e){var o=e[a],s=t+a,c=r;Array.isArray(o)&&(c=G(r,o[1]),o=o[0]),ArrayBuffer.isView(o)?n[s]=[o,c]:(n[s+=`/`]=[new i(0),c],Z(o,s,n,r))}},Q=typeof TextEncoder<`u`&&/*#__PURE__*/ new TextEncoder,$=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{$.decode(B,{stream:!0})}catch{}var ae=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:ne(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function oe(e,t){if(t){for(var n=new i(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(Q)return Q.encode(e);for(var a=e.length,o=new i(e.length+(e.length>>1)),s=0,c=function(e){o[s++]=e},r=0;r<a;++r){if(s+5>o.length){var l=new i(s+8+(a-r<<1));l.set(o),o=l}var u=e.charCodeAt(r);u<128||t?c(u):u<2048?(c(192|u>>6),c(128|u&63)):u>55295&&u<57344?(u=65536+(u&1047552)|e.charCodeAt(++r)&1023,c(240|u>>18),c(128|u>>12&63),c(128|u>>6&63),c(128|u&63)):(c(224|u>>12),c(128|u>>6&63),c(128|u&63))}return ne(o,0,s)}function se(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if($)return $.decode(e);var i=ae(e),a=i.s,n=i.r;return n.length&&A(8),a}var ce=function(e,t){return t+30+K(e,t+26)+K(e,t+28)},le=function(e,t,n){var r=K(e,t+28),i=K(e,t+30),a=se(e.subarray(t+46,t+46+r),!(K(e,t+8)&2048)),o=t+46+r,s=ue(e,o,i,n,q(e,t+20),q(e,t+24),q(e,t+42)),c=s[0],l=s[1],u=s[2];return[K(e,t+10),c,l,a,o+i+K(e,t+32),u]},ue=function(e,t,n,r,i,a,o){var s=i==4294967295,c=a==4294967295,l=o==4294967295,u=t+n,d=s+c+l;if(r&&d){for(;t+4<u;t+=4+K(e,t+2))if(K(e,t)==1)return[s?ie(e,t+4+8*c):i,c?ie(e,t+4):a,l?ie(e,t+4+8*(c+s)):o,1];r<2&&A(13)}return[i,a,o,0]},de=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&A(9),t+=r+4}return t},fe=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=de(l);J(e,t,o==null?67324752:33639248),t+=4,o!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(a<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),p=f.getFullYear()-1980;if((p<0||p>119)&&A(10),J(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(J(e,t,n.crc),J(e,t+4,a<0?-a-2:a),J(e,t+8,n.size)),J(e,t+12,c),J(e,t+14,d),t+=16,o!=null&&(J(e,t,u),J(e,t+6,n.attrs),J(e,t+10,o),t+=14),e.set(r,t),t+=c,d)for(var m in l){var h=l[m],g=h.length;J(e,t,+m),J(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},pe=function(e,t,n,r,i){J(e,t,101010256),J(e,t+8,n),J(e,t+10,n),J(e,t+12,r),J(e,t+16,i)};function me(e,t){t||={};var n={},r=[];Z(e,``,n,t);var a=0,o=0;for(var s in n){var c=n[s],l=c[0],u=c[1],d=u.level==0?0:8,f=oe(s),p=f.length,m=u.comment,h=m&&oe(m),g=h&&h.length,_=de(u.extra);p>65535&&A(11);var v=d?Y(l,u):l,y=v.length,b=U();b.p(l),r.push(G(u,{size:l.length,crc:b.d(),c:v,f,m:h,u:p!=s.length||h&&m.length!=g,o:a,compression:d})),a+=30+p+_+y,o+=76+2*(p+_)+(g||0)+y}for(var x=new i(o+22),S=a,C=o-a,w=0;w<r.length;++w){var f=r[w];fe(x,f.o,f,f.f,f.u,f.c.length);var T=30+f.f.length+de(f.extra);x.set(f.c,f.o+T),fe(x,a,f,f.f,f.u,f.c.length,f.o,f.m),a+=16+T+(f.m?f.m.length:0)}return pe(x,a,r.length,C,S),x}function he(e,t){for(var n={},r=e.length-22;q(e,r)!=101010256;--r)(!r||e.length-r>65558)&&A(13);var a=K(e,r+8);if(!a)return{};var o=q(e,r+16),s=q(e,r-20)==117853008;if(s){var c=q(e,r-12);s=q(e,c)==101075792,s&&(a=q(e,c+32),o=q(e,c+48))}for(var l=t&&t.filter,u=0;u<a;++u){var d=le(e,o,s),f=d[0],p=d[1],m=d[2],h=d[3],g=d[4],_=d[5],v=ce(e,_);o=g,(!l||l({name:h,size:p,originalSize:m,compression:f}))&&(f?f==8?n[h]=X(e.subarray(v,v+p),{out:new i(m)}):A(14,`unknown compression type `+f):n[h]=ne(e,v,v+p))}return n}var ge={commands:[{name:`zip`,summary:`create a zip archive`,usage:`zip [-r] archive.zip path…`,async run(t){let{rest:i}=n(t.args),a=i.shift();if(!a||!i.length)throw Error(`usage: zip [-r] archive.zip path…`);let o={};for(let n of i){let r=t.path(n),i=await t.os.fs.stat(r);if(!i)throw Error(`${n}: no such file or directory`);let a=e(r)===`/`?`/`:e(r)+`/`;if(i.kind===`file`)o[r.slice(a.length)]=await t.os.fs.readFile(r);else for await(let e of t.os.fs.walk(r,{signal:t.signal}))e.kind===`file`&&(o[e.path.slice(a.length)]=await t.os.fs.readFile(e.path))}let s=me(o);await t.os.fs.writeFile(t.path(a),s),t.out(`${Object.keys(o).length} files → ${a} (${r(s.length)})\n`)}},{name:`unzip`,summary:`list or extract a zip archive`,usage:`unzip [-l] archive.zip [-d dir]`,async run(e){let n=e.args.indexOf(`-d`),r=e.path(n>=0?e.args[n+1]??`.`:`.`),i=e.args.filter((e,t)=>e!==`-l`&&t!==n&&t!==n+1);if(!i[0])throw Error(`usage: unzip [-l] archive.zip [-d dir]`);let a=he(await e.os.fs.readFile(e.path(i[0]))),o=0;for(let[n,i]of Object.entries(a))n.endsWith(`/`)||(o++,e.args.includes(`-l`)?e.out(`${String(i.length).padStart(10)} ${n}\n`):await e.os.fs.writeFile(t(r,t(`/`,n)),i));e.out(`${o} file${o===1?``:`s`}${e.args.includes(`-l`)?``:` extracted to ${r}`}\n`)}}]};export{ge as default};
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./html-BggiUWIu.js";import{o as n}from"./main-DzFuvDws.js";import{a as r,o as i,r as a,s as o,t as s}from"./path-DGG-Mxbd.js";import{t as c}from"./bundle-qe7w2kMM.js";const l=[`server.ts`,`server.js`,`server.mjs`,`api/index.ts`,`api/index.js`];function u(e){let t=e.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(e,t)=>t??``).replace(/,(\s*[}\]])/g,`$1`);return JSON.parse(t)}function d(e){let t={};for(let n of e.split(`
1
+ import{n as e,t}from"./html-Bd3_N2aN.js";import{o as n}from"./main-CQvaEX7y.js";import{a as r,o as i,r as a,s as o,t as s}from"./path-DGG-Mxbd.js";import{t as c}from"./bundle-CXrJ5BHI.js";const l=[`server.ts`,`server.js`,`server.mjs`,`api/index.ts`,`api/index.js`];function u(e){let t=e.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(e,t)=>t??``).replace(/,(\s*[}\]])/g,`$1`);return JSON.parse(t)}function d(e){let t={};for(let n of e.split(`
2
2
  `)){let e=/^\s*(?:export\s+)?([\w.]+)\s*=\s*(.*?)\s*$/.exec(n);e&&!n.trim().startsWith(`#`)&&(t[e[1]]=e[2].replace(/^(['"])(.*)\1$/,`$2`))}return t}const f=(e,t,n=`text/plain; charset=utf-8`)=>({status:e,headers:[[`content-type`,n]],body:new TextEncoder().encode(t)});var p=class{os;#e=/* @__PURE__ */ new Map;constructor(e){this.os=e,e.bus.on(`proc:exit`,({proc:t})=>{for(let[r,i]of this.#e)i.info.pid===t.pid&&(this.#e.delete(r),n(e,`stop`,String(r),{}),this.#t())}),e.bus.on(`fs:change`,({path:e})=>{for(let t of this.#e.values()){if(!r(t.info.root,e))continue;let n=e.slice(t.info.root.length+1);(t.backendInputs.has(e)||l.includes(n)||n===`package.json`||n.startsWith(`.env`))&&(t.backendReady=!1)}})}#t(){this.os.bus.emit(`dev:update`,[...this.#e.values()].map(e=>({...e.info})))}#n(e){let t=this.#e.get(e);if(!t)throw Error(`nothing is serving on port ${e} (see: serve list)`);return t}async start(e){let t=o(e.root);if((await this.os.fs.stat(t))?.kind!==`dir`)throw Error(`${t} is not a folder`);for(let e of this.#e.values())if(e.info.root===t)return{...e.info};let n=e.port??3e3;if(e.port!==void 0&&this.#e.has(n))throw Error(`port ${n} is in use by ${this.#e.get(n).info.root}`);for(;this.#e.has(n);)n++;let r=this.os.procs.spawn({name:`serve :${n}`,kind:`service`,ppid:e.ppid,detail:t});this.os.procs.update(r.pid,{state:`idle`});let i={port:n,root:t,pid:r.pid,url:`http://localhost:${n}/`,backend:await this.#a(t),network:!!e.network};return this.#e.set(n,{info:i,logs:[],seq:0,backendReady:!1,backendInputs:/* @__PURE__ */ new Set,queue:Promise.resolve()}),this.os.log(`dev`,`serving ${t} on :${n}${i.backend?` (backend ${i.backend})`:``}`),this.#t(),{...i}}async stop(e){let t=this.#e.get(e);return t?(this.os.procs.kill(t.info.pid,`stopped`),this.#e.delete(e),n(this.os,`stop`,String(e),{}),this.#t(),!0):!1}async list(){return[...this.#e.values()].map(e=>({...e.info}))}log(e,t){let n=this.#e.get(e);if(n)for(let r of t){let t={seq:++n.seq,t:Date.now(),level:r.level,source:r.source,text:String(r.text).slice(0,8e3)};n.logs.push(t),n.logs.length>500&&n.logs.shift(),this.os.bus.emit(`dev:log`,{port:e,entry:t})}}async logs(e,t={}){let n=this.#n(e).logs.filter(e=>e.seq>(t.after??0));return t.limit?n.slice(-t.limit):n}async#r(e){let t=t=>this.os.fs.readText(i(e,t)).catch(()=>null),[n,r,a,...o]=await Promise.all([t(`package.json`),t(`tsconfig.json`),t(`jsconfig.json`),t(`.env`),t(`.env.development`),t(`.env.local`)]),s=(e,t)=>{if(!e)return null;try{return u(e)}catch(e){throw Error(`${t} is not valid JSON: ${e.message}`)}},c={...this.os.settings.get(`env.vars`,{})};for(let e of o)e&&Object.assign(c,d(e));return{pkg:s(n,`package.json`),tsconfig:s(r??a,r?`tsconfig.json`:`jsconfig.json`),env:c}}async#i(e){return(await this.os.fs.stat(e).catch(()=>null))?.kind===`file`}async#a(e){for(let t of l)if(await this.#i(i(e,t)))return t;return null}async page(n,r=`/`){let a=this.#n(n),l=a.info.root,u=o(decodeURIComponent(r.split(/[?#]/)[0]||`/`)),d=i(l,u),f=null,p=await this.os.fs.stat(d).catch(()=>null);if(p?.kind===`dir`&&await this.#i(i(d,`index.html`)))f=i(d,`index.html`);else if(p?.kind===`file`&&/\.html?$/i.test(d))f=d;else if(await this.#i(`${d}.html`))f=`${d}.html`;else if(p?.kind===`file`){let r=e(d).startsWith(`image/`)?`<img src="${u}" alt="" style="max-width:100%">`:`<pre id="t" style="white-space:pre-wrap;font:13px ui-monospace,monospace"></pre><script>fetch(${JSON.stringify(u)}).then(r=>r.text()).then(t=>document.getElementById('t').textContent=t)<\/script>`,i=`<!doctype html><html><head><meta charset="utf-8"><title>${s(d)}</title></head><body style="margin:0;padding:12px">${r}</body></html>`;return t(this.os.fs,{root:l,htmlPath:null,html:i,path:u,port:n,bundle:async()=>({js:``,css:``,errors:[],warnings:[],inputs:[]})})}!f&&p?.kind!==`file`&&await this.#i(i(l,`index.html`))&&(f=i(l,`index.html`));let m;try{m=await this.#r(l)}catch(e){m={pkg:null,tsconfig:null,env:{}},this.log(n,[{level:`error`,source:`build`,text:e.message}])}let h=Object.fromEntries(Object.entries(m.env).filter(([e])=>/^(VITE_|PUBLIC_)/.test(e))),g=performance.now(),_=await t(this.os.fs,{root:l,htmlPath:f,path:u+(r.includes(`?`)?r.slice(r.indexOf(`?`)):``),port:n,bundle:e=>c({fs:this.os.fs,root:l,entry:e,target:`browser`,env:h,pkg:m.pkg,tsconfig:m.tsconfig})});return this.os.procs.account(a.info.pid,performance.now()-g),_.errors.length&&this.log(n,_.errors.map(e=>({level:`error`,source:`build`,text:e}))),{html:_.html,errors:_.errors}}async request(t,n){let o=this.#n(t),s=o.info.root,c=new URL(n.url,`http://localhost`),l;try{l=decodeURIComponent(c.pathname)}catch{return f(400,`Bad request`)}let u=i(s,l),d=u.slice(s.length).split(`/`).some(e=>e.startsWith(`.`));if(r(s,u)&&!d&&/^(GET|HEAD)$/i.test(n.method)){let t=u;if((await this.os.fs.stat(t).catch(()=>null))?.kind===`dir`&&(t=i(t,`index.html`)),await this.#i(t)){let r=n.method.toUpperCase()===`HEAD`?null:await this.os.fs.readFile(t);return{status:200,headers:[[`content-type`,e(t)+(/^text\/|json|javascript|xml/.test(e(t))?`; charset=utf-8`:``)]],body:r}}}if(o.backendReady||(o.info.backend=await this.#a(s)),o.info.backend){let e=o.queue.then(()=>this.#c(o,n,c));return o.queue=e.catch(()=>void 0),e}return this.log(t,[{level:`warn`,source:`network`,text:`${n.method} ${n.url} → 404 (no such file${a(l)?``:`, and no backend: add server.ts to answer requests`})`}]),f(404,`Not found: ${l}`)}async#o(e){let{root:t,port:r,pid:a,network:o}=e.info,s=await this.#r(t),l=await c({fs:this.os.fs,root:t,entry:i(t,e.info.backend),target:`server`,env:s.env,pkg:s.pkg,tsconfig:s.tsconfig});if(e.backendInputs=new Set(l.inputs),l.errors.length)return`The backend (${e.info.backend}) failed to build:\n\n${l.errors.join(`
3
3
 
4
4
  `)}`;let u=await n(this.os,`load`,String(r),{code:l.js,env:s.env,network:o,ppid:a},{cwd:t,onStdout:e=>this.#s(r,`log`,e),onStderr:e=>this.#s(r,`error`,e)});return u.ok?(e.backendReady=!0,this.os.log(`dev`,`:${r} backend ${e.info.backend} loaded`),null):`The backend (${e.info.backend}) failed to start: ${u.error??u.stderr}`}#s(e,t,n){let r=n.replace(/\n$/,``);r&&this.log(e,[{level:t,source:`server`,text:r}])}async#c(e,t,r){let{port:i,root:a}=e.info,o=e=>(this.log(i,[{level:`error`,source:`server`,text:e}]),f(500,e));for(let s=0;s<2;s++){if(!e.backendReady){let t=await this.#o(e);if(t)return o(t)}let s=performance.now(),c=await n(this.os,`request`,String(i),{req:t,origin:`http://localhost:${i}`},{cwd:a,onStdout:e=>this.#s(i,`log`,e),onStderr:e=>this.#s(i,`error`,e)});if(this.os.procs.account(e.info.pid,performance.now()-s),c.error===`backend not loaded`){e.backendReady=!1;continue}if(c.error)return o(`${t.method} ${r.pathname}: ${c.error}`);let l=c.response;return l?(l.status>=400&&this.log(i,[{level:l.status>=500?`error`:`warn`,source:`network`,text:`${t.method} ${t.url} → ${l.status}`}]),l):(this.log(i,[{level:`warn`,source:`network`,text:`${t.method} ${t.url} → 404 (no file, and the backend did not answer)`}]),f(404,`Not found: ${r.pathname}`))}return o(`the backend could not be started`)}};export{p as DevServers};
@@ -4,11 +4,11 @@
4
4
  <meta charset="utf-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>BrowserBox runtime</title>
7
- <script type="module" crossorigin src="../assets/embed-CqexLx9X.js"></script>
8
- <link rel="modulepreload" crossorigin href="../assets/instance-6eYt0v1_.js">
9
- <link rel="modulepreload" href="../assets/bridge-BEwLXp_5.js" />
10
- <link rel="modulepreload" href="../assets/instance-6eYt0v1_.js" />
11
- <link rel="modulepreload" href="../assets/main-DzFuvDws.js" />
7
+ <script type="module" crossorigin src="../assets/embed-uUqwwabc.js"></script>
8
+ <link rel="modulepreload" crossorigin href="../assets/instance-Cu6oky-A.js">
9
+ <link rel="modulepreload" href="../assets/bridge-DQLuopgW.js" />
10
+ <link rel="modulepreload" href="../assets/instance-Cu6oky-A.js" />
11
+ <link rel="modulepreload" href="../assets/main-CQvaEX7y.js" />
12
12
  </head>
13
13
  <body>
14
14
  </body>
@@ -4,8 +4,8 @@
4
4
  <meta charset="utf-8" />
5
5
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; connect-src *; frame-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'" />
6
6
  <title>BrowserBox kernel bridge</title>
7
- <script type="module" crossorigin src="../assets/bridge-BEwLXp_5.js"></script>
8
- <link rel="modulepreload" crossorigin href="../assets/instance-6eYt0v1_.js">
7
+ <script type="module" crossorigin src="../assets/bridge-DQLuopgW.js"></script>
8
+ <link rel="modulepreload" crossorigin href="../assets/instance-Cu6oky-A.js">
9
9
  </head>
10
10
  <body>
11
11
  <!-- No UI. Embedded as a hidden frame by every BrowserBox window; see src/kernel-host/bridge.ts. -->
@@ -1 +1 @@
1
- {"esbuild":[{"url":"assets/pkg-esbuild-QrU0ybpL.js","bytes":1164},{"url":"assets/bundle-qe7w2kMM.js","bytes":4297},{"url":"assets/npm-DF8ts_uH.js","bytes":1459}],"git":[{"url":"assets/pkg-git-BQFdAkWZ.js","bytes":219526},{"url":"assets/rolldown-runtime-WkwZ5CU-.js","bytes":599}],"python":[{"url":"assets/pkg-python-ytZLbJ8W.js","bytes":3681}],"sqlite":[{"url":"assets/pkg-sqlite-CKGWzcwt.js","bytes":41858},{"url":"assets/sql-wasm-CXIAVl5-.wasm","bytes":688197},{"url":"assets/rolldown-runtime-WkwZ5CU-.js","bytes":599}],"zip":[{"url":"assets/pkg-zip-CL-568aV.js","bytes":13877}]}
1
+ {"esbuild":[{"url":"assets/pkg-esbuild-C-EHnLD8.js","bytes":1164},{"url":"assets/bundle-CXrJ5BHI.js","bytes":4297},{"url":"assets/npm-DF8ts_uH.js","bytes":1459}],"git":[{"url":"assets/pkg-git-BCxqHW9a.js","bytes":219526},{"url":"assets/rolldown-runtime-WkwZ5CU-.js","bytes":599}],"python":[{"url":"assets/pkg-python-B23D6vdG.js","bytes":3681}],"sqlite":[{"url":"assets/pkg-sqlite-CKGWzcwt.js","bytes":41858},{"url":"assets/sql-wasm-CXIAVl5-.wasm","bytes":688197},{"url":"assets/rolldown-runtime-WkwZ5CU-.js","bytes":599}],"zip":[{"url":"assets/pkg-zip-CuNUYwRy.js","bytes":13877}]}
@@ -11,7 +11,8 @@ export { Peer, type Handlers } from '../rpc/peer';
11
11
  export type { Kernel, FsApi, MountInfo, ProcsApi, SecretsApi, SettingsApi, ShellHandle, ShellIo, ShellsApi } from '../kernel/api';
12
12
  export type { Capability, PermDecision, PermMode, PermRequest, Prompter } from '../kernel/perms';
13
13
  export type { Proc, ProcKind, ProcState, SpawnOptions } from '../kernel/proc';
14
- export type { KernelEvents, KernelLogLine, Notice } from '../kernel/types';
14
+ export type { KernelEvents, KernelLogLine, LockState, Notice } from '../kernel/types';
15
+ export { createProfile, DEFAULT_PROFILE, deleteProfile, getProfile, lastProfile, listProfiles, setLastProfile, updateProfile, type Profile } from '../kernel/profiles';
15
16
  export type { Stat } from '../kernel/vfs/types';
16
17
  export type { DevApi, DevInfo, DevLog, DevLogLevel, DevPage, DevStartOptions, WireRequest, WireResponse } from '../kernel/dev/types';
17
18
  export type { PlatformCap } from '../kernel/caps';
@@ -7,6 +7,7 @@
7
7
  */
8
8
  export { RemoteKernel } from './remote-kernel';
9
9
  export { Peer } from '../rpc/peer';
10
+ export { createProfile, DEFAULT_PROFILE, deleteProfile, getProfile, lastProfile, listProfiles, setLastProfile, updateProfile } from '../kernel/profiles';
10
11
  // Small helpers: paths, file kinds, formatting, terminal text, frames.
11
12
  export { basename, dirname, extname, isInside, join, normalize, resolve } from '../kernel/vfs/path';
12
13
  export { AGENT_HOME, HOME } from '../kernel/paths';
@@ -241,6 +241,10 @@ export class RemoteKernel {
241
241
  has: (name) => this.call('secrets.has', name),
242
242
  set: (name, value) => this.call('secrets.set', name, value),
243
243
  delete: (name) => this.call('secrets.delete', name),
244
+ status: () => this.call('secrets.status'),
245
+ unlock: (password) => this.call('secrets.unlock', password),
246
+ lock: () => this.call('secrets.lock'),
247
+ setPassword: (password) => this.call('secrets.setPassword', password),
244
248
  };
245
249
  dev = {
246
250
  start: (o) => this.call('dev.start', o),
@@ -4,7 +4,7 @@ import type { PlatformCap } from './caps';
4
4
  import type { KCore } from './kcore';
5
5
  import type { Permissions, Prompter } from './perms';
6
6
  import type { Proc, SpawnOptions } from './proc';
7
- import type { KernelEvents, Notice } from './types';
7
+ import type { KernelEvents, LockState, Notice } from './types';
8
8
  import type { Stat } from './vfs/types';
9
9
  /**
10
10
  * The kernel's public surface. Two things implement it:
@@ -93,6 +93,14 @@ export interface SecretsApi {
93
93
  has(name: string): Promise<boolean>;
94
94
  set(name: string, value: string): Promise<void>;
95
95
  delete(name: string): Promise<void>;
96
+ /** The profile's password lock: 'open' (no password), 'locked' (signed out) or 'unlocked'. */
97
+ status(): Promise<LockState>;
98
+ /** Signs in; false when the password is wrong. */
99
+ unlock(password: string): Promise<boolean>;
100
+ /** Signs out: the keys stay encrypted until the next unlock. */
101
+ lock(): Promise<void>;
102
+ /** Sets or changes the password (`null` removes it). Needs the keys unlocked. */
103
+ setPassword(password: string | null): Promise<void>;
96
104
  }
97
105
  export interface ShellIo {
98
106
  out(text: string): void;
@@ -9,10 +9,20 @@ export interface KernelInstance {
9
9
  box: string | null;
10
10
  /** 'opfs': files and settings persist. 'memory': nothing outlives the box. */
11
11
  storage: 'opfs' | 'memory';
12
+ /**
13
+ * For the app's kernel: which profile. Each profile is a kernel of its own,
14
+ * with its own files, settings and keys; absent or null is the first
15
+ * profile ("Default"), whose data is where it always was.
16
+ */
17
+ profile?: string | null;
12
18
  }
13
19
  export declare const APP_KERNEL: KernelInstance;
20
+ /** Where boxes and other profiles keep their files, inside the first profile's OPFS root: hidden from it. */
21
+ export declare const HIDDEN_FOLDERS: string[];
14
22
  /** Box ids: letters, digits, '-' and '_', up to 64 characters. */
15
23
  export declare const BOX_ID: RegExp;
24
+ /** A profile of the app's kernel. */
25
+ export declare const profileKernel: (profile: string | null) => KernelInstance;
16
26
  export declare function workerName(k: KernelInstance): string;
17
27
  export declare function fromWorkerName(name: string): KernelInstance;
18
28
  /** Reads a box from URL parameters (`?box=<id>&storage=memory`); the app's kernel when there is none. */
@@ -1,10 +1,19 @@
1
1
  export const APP_KERNEL = { box: null, storage: 'opfs' };
2
+ /** Where boxes and other profiles keep their files, inside the first profile's OPFS root: hidden from it. */
3
+ export const HIDDEN_FOLDERS = ['boxes', 'profiles'];
2
4
  /** Box ids: letters, digits, '-' and '_', up to 64 characters. */
3
5
  export const BOX_ID = /^[A-Za-z0-9_-]{1,64}$/;
6
+ /** A profile of the app's kernel. */
7
+ export const profileKernel = (profile) => (profile ? { box: null, storage: 'opfs', profile } : APP_KERNEL);
4
8
  export function workerName(k) {
5
- return k.box === null ? 'bbx-kernel' : `bbx-box:${k.storage}:${k.box}`;
9
+ if (k.box !== null)
10
+ return `bbx-box:${k.storage}:${k.box}`;
11
+ return k.profile ? `bbx-kernel:profile:${k.profile}` : 'bbx-kernel';
6
12
  }
7
13
  export function fromWorkerName(name) {
14
+ const p = /^bbx-kernel:profile:([A-Za-z0-9_-]{1,64})$/.exec(name);
15
+ if (p)
16
+ return profileKernel(p[1]);
8
17
  const m = /^bbx-box:(opfs|memory):([A-Za-z0-9_-]{1,64})$/.exec(name);
9
18
  return m ? { box: m[2], storage: m[1] } : APP_KERNEL;
10
19
  }
@@ -12,6 +21,12 @@ export function fromWorkerName(name) {
12
21
  export function fromSearch(search) {
13
22
  const q = new URLSearchParams(search);
14
23
  const box = q.get('box');
24
+ const profile = q.get('profile');
25
+ if (box === null && profile) {
26
+ if (!BOX_ID.test(profile))
27
+ throw new Error(`invalid profile id: ${profile}`);
28
+ return profileKernel(profile);
29
+ }
15
30
  if (box === null)
16
31
  return APP_KERNEL;
17
32
  if (!BOX_ID.test(box))
@@ -19,11 +34,15 @@ export function fromSearch(search) {
19
34
  return { box, storage: q.get('storage') === 'memory' ? 'memory' : 'opfs' };
20
35
  }
21
36
  export function toSearch(k) {
22
- return k.box === null ? '' : `?box=${encodeURIComponent(k.box)}&storage=${k.storage}`;
37
+ if (k.box === null)
38
+ return k.profile ? `?profile=${encodeURIComponent(k.profile)}` : '';
39
+ return `?box=${encodeURIComponent(k.box)}&storage=${k.storage}`;
23
40
  }
24
41
  /** IndexedDB database name for this kernel's copy of a store; null when nothing may persist. */
25
42
  export function dbName(base, k) {
26
43
  if (k.storage === 'memory')
27
44
  return null;
28
- return k.box === null ? base : `${base}:box:${k.box}`;
45
+ if (k.box === null)
46
+ return k.profile ? `${base}:profile:${k.profile}` : base;
47
+ return `${base}:box:${k.box}`;
29
48
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The profiles of a BrowserBox site: who uses it, each with a kernel of their
3
+ * own (files, settings, API keys, chats). The list lives in this origin's
4
+ * IndexedDB next to the profiles' own stores, readable by every window of the
5
+ * site before any kernel starts. "default" is the first profile: its data is
6
+ * where it always was, so it can be renamed but not deleted.
7
+ */
8
+ export interface Profile {
9
+ id: string;
10
+ name: string;
11
+ created: number;
12
+ /** Shown as locked until signed in (the key store has the truth). */
13
+ password: boolean;
14
+ }
15
+ export declare const DEFAULT_PROFILE = "default";
16
+ /** Every profile, the first one first. */
17
+ export declare function listProfiles(): Promise<Profile[]>;
18
+ export declare function getProfile(id: string): Promise<Profile | null>;
19
+ export declare function createProfile(name: string): Promise<Profile>;
20
+ /** Changes a profile's name or password flag. */
21
+ export declare function updateProfile(id: string, patch: Partial<Pick<Profile, 'name' | 'password'>>): Promise<Profile>;
22
+ /** The profile this browser opened last. */
23
+ export declare function lastProfile(): Promise<string>;
24
+ export declare function setLastProfile(id: string): Promise<void>;
25
+ /**
26
+ * Deletes a profile with its files, settings and keys. Close its windows
27
+ * first: a kernel still running keeps what it has in memory.
28
+ */
29
+ export declare function deleteProfile(id: string): Promise<void>;
30
+ /** The kernel a profile runs in: the first profile is the site's original kernel. */
31
+ export declare const kernelOf: (id: string) => import("./instance").KernelInstance;
@@ -0,0 +1,93 @@
1
+ import { BOX_ID, dbName, profileKernel } from './instance';
2
+ export const DEFAULT_PROFILE = 'default';
3
+ const DB = 'bbx-profiles';
4
+ const STORE = 'profiles';
5
+ const LAST = '#last';
6
+ function open() {
7
+ return new Promise((resolve, reject) => {
8
+ const req = indexedDB.open(DB, 1);
9
+ req.onupgradeneeded = () => req.result.createObjectStore(STORE);
10
+ req.onsuccess = () => resolve(req.result);
11
+ req.onerror = () => reject(req.error);
12
+ });
13
+ }
14
+ async function run(mode, fn) {
15
+ const db = await open();
16
+ try {
17
+ return await new Promise((resolve, reject) => {
18
+ const req = fn(db.transaction(STORE, mode).objectStore(STORE));
19
+ req.onsuccess = () => resolve(req.result);
20
+ req.onerror = () => reject(req.error);
21
+ });
22
+ }
23
+ finally {
24
+ db.close();
25
+ }
26
+ }
27
+ const fallback = () => ({ id: DEFAULT_PROFILE, name: 'Default', created: 0, password: false });
28
+ /** Every profile, the first one first. */
29
+ export async function listProfiles() {
30
+ const all = (await run('readonly', (s) => s.getAll())).filter((p) => p && typeof p === 'object' && 'id' in p);
31
+ if (!all.some((p) => p.id === DEFAULT_PROFILE))
32
+ all.push(fallback());
33
+ return all.sort((a, b) => (a.id === DEFAULT_PROFILE ? -1 : b.id === DEFAULT_PROFILE ? 1 : a.created - b.created));
34
+ }
35
+ export async function getProfile(id) {
36
+ return (await run('readonly', (s) => s.get(id))) ?? (id === DEFAULT_PROFILE ? fallback() : null);
37
+ }
38
+ const cleanName = (name) => name.trim().replace(/\s+/g, ' ').slice(0, 40);
39
+ export async function createProfile(name) {
40
+ const n = cleanName(name);
41
+ if (!n)
42
+ throw new Error('A profile needs a name');
43
+ const profile = { id: `p${Date.now().toString(36)}${crypto.getRandomValues(new Uint32Array(1))[0].toString(36)}`, name: n, created: Date.now(), password: false };
44
+ await run('readwrite', (s) => s.put(profile, profile.id));
45
+ return profile;
46
+ }
47
+ /** Changes a profile's name or password flag. */
48
+ export async function updateProfile(id, patch) {
49
+ const current = await getProfile(id);
50
+ if (!current)
51
+ throw new Error(`No profile ${id}`);
52
+ const next = { ...current, ...patch, ...(patch.name !== undefined ? { name: cleanName(patch.name) || current.name } : {}) };
53
+ await run('readwrite', (s) => s.put(next, id));
54
+ return next;
55
+ }
56
+ /** The profile this browser opened last. */
57
+ export async function lastProfile() {
58
+ const id = await run('readonly', (s) => s.get(LAST)).catch(() => undefined);
59
+ return id && (await getProfile(id)) ? id : DEFAULT_PROFILE;
60
+ }
61
+ export async function setLastProfile(id) {
62
+ await run('readwrite', (s) => s.put(id, LAST));
63
+ }
64
+ const deleteDb = (name) => new Promise((resolve) => {
65
+ if (!name)
66
+ return resolve();
67
+ const req = indexedDB.deleteDatabase(name);
68
+ req.onsuccess = req.onerror = req.onblocked = () => resolve();
69
+ });
70
+ /**
71
+ * Deletes a profile with its files, settings and keys. Close its windows
72
+ * first: a kernel still running keeps what it has in memory.
73
+ */
74
+ export async function deleteProfile(id) {
75
+ if (id === DEFAULT_PROFILE)
76
+ throw new Error('The first profile cannot be deleted');
77
+ if (!BOX_ID.test(id))
78
+ throw new Error(`invalid profile id: ${id}`);
79
+ const k = profileKernel(id);
80
+ try {
81
+ const profiles = await (await navigator.storage.getDirectory()).getDirectoryHandle('profiles');
82
+ await profiles.removeEntry(id, { recursive: true });
83
+ }
84
+ catch {
85
+ /* no files yet */
86
+ }
87
+ await Promise.all([deleteDb(dbName('bbx-settings', k)), deleteDb(dbName('bbx-secrets', k))]);
88
+ await run('readwrite', (s) => s.delete(id));
89
+ if ((await run('readonly', (s) => s.get(LAST)).catch(() => undefined)) === id)
90
+ await setLastProfile(DEFAULT_PROFILE);
91
+ }
92
+ /** The kernel a profile runs in: the first profile is the site's original kernel. */
93
+ export const kernelOf = (id) => profileKernel(id === DEFAULT_PROFILE ? null : id);
@@ -16,6 +16,8 @@ export interface Notice {
16
16
  level?: 'info' | 'ok' | 'warn' | 'error';
17
17
  }
18
18
  /** Every event that can cross module boundaries. */
19
+ /** A profile's password lock: 'open' (no password), 'locked' (signed out) or 'unlocked' (signed in). */
20
+ export type LockState = 'open' | 'locked' | 'unlocked';
19
21
  export interface KernelEvents extends Record<string, unknown> {
20
22
  'fs:change': FsChange;
21
23
  'proc:spawn': Proc;
@@ -28,6 +30,10 @@ export interface KernelEvents extends Record<string, unknown> {
28
30
  key: string;
29
31
  value: unknown;
30
32
  };
33
+ /** The profile was signed in or out, or its password changed. */
34
+ 'secrets:lock': {
35
+ state: LockState;
36
+ };
31
37
  notify: Notice;
32
38
  /** A line was added to the kernel log. */
33
39
  kmsg: KernelLogLine;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jeevanand/agent-browserbox-runtime",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "The runtime for @jeevanand/agent-browserbox-sdk: static files to serve (kernel, filesystem, shell, sandboxes), and a client library for app UIs that drive its kernel (/client).",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -1,3 +0,0 @@
1
- import{c as e,n as t,o as n,r,s as i,t as a}from"./instance-6eYt0v1_.js";function o(e={}){let t=e.kernelUrl??i,n=t.endsWith(`/`)?t:`${t}/`,o=new URL(n).origin;return new Promise((t,i)=>{let s=new URL(`bridge.html${r(e.instance??a)}`,n).href,c=document.getElementById(`bbx-bridge`),l=c?.src===s?c:document.createElement(`iframe`);l!==c&&(l.src=s,l.title=`BrowserBox kernel bridge`,l.setAttribute(`aria-hidden`,`true`),l.hidden=!0);let u=setTimeout(()=>i(Error(`The kernel at ${n} did not respond.`)),2e4),d=1,f=new Map,p=(e,t)=>({port:t,lock:String(e.lock),shared:!!e.shared,more:()=>new Promise(e=>{let t=d++;f.set(t,e),l.contentWindow.postMessage({type:`bbx:connect`,req:t},o)})}),m=!0;addEventListener(`message`,e=>{e.source===l.contentWindow&&e.origin===o&&(e.data?.type===`bbx:ready`&&m?l.contentWindow.postMessage({type:`bbx:connect`},o):e.data?.type===`bbx:port`&&e.ports[0]?typeof e.data.req==`number`?(f.get(e.data.req)?.(p(e.data,e.ports[0])),f.delete(e.data.req)):m&&(m=!1,clearTimeout(u),t(p(e.data,e.ports[0]))):e.data?.type===`bbx:refused`&&m&&(clearTimeout(u),i(Error(`The kernel refused this origin (${location.origin}). Add it to VITE_ALLOWED_ORIGINS.`))))}),l===c?l.contentWindow?.postMessage({type:`bbx:connect`},o):(document.body??document.documentElement).append(l)})}var s=`/home/user`;function c(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}function l(e){return e.replace(/\x1b\[[0-9;]*m/g,``).split(`
2
- `).map(e=>e.slice(e.lastIndexOf(`\r`)+1)).join(`
3
- `)}var u=new URLSearchParams(location.search),d=t(location.search),f=u.get(`site`)===`1`?a:{box:d.box??`default`,storage:d.box===null?`opfs`:d.storage},p=o({instance:f}),m=()=>p.then(e=>e.more()),h=f.box??`site`,g=e=>`'${e.replace(/'/g,`'\\''`)}'`,_=({port:e,root:t,url:n,backend:r,network:i})=>({port:e,root:t,url:n,backend:r,network:i}),v=class t{os;#e;#t=1;#n=new Map;#r=1;#i=new Map;#a=new Map;#o=1;constructor(t,n){this.#e=t,this.os=new e(n,`sdk`),this.os.perms.setPrompter((e,t)=>new Promise(n=>{let r=this.#t++;this.#n.set(r,n),t?.addEventListener(`abort`,()=>this.#n.delete(r)&&n(`deny`)),this.send({t:`permission`,id:r,request:{cap:e.cap,actor:e.actor,title:e.title,detail:e.detail}})})),t.onmessage=e=>void this.#f(e.data)}send(e,t=[]){this.#e.postMessage(e,t)}async hello(){return await this.os.ready,await this.os.fs.ready,{t:`hello`,protocol:1,version:this.os.version,id:h,home:s,caps:this.os.caps.filter(e=>e.ok).map(e=>e.id),storage:this.os.rootKind}}async#s(e,t){let n=await this.os.shells.open({cwd:e.cwd,confined:!0});for(let[r,i]of Object.entries(e.env??{})){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw n.close(),Error(`invalid environment variable name: ${r}`);await n.run(`export ${r}=${g(String(i))}`,{out:()=>void 0,err:t})}return n}async#c(e,t,n,r,i){let a=!1,o=n?setTimeout(()=>(a=!0,i.abort()),n):void 0;try{let n=await e.run(t,{...r,signal:i.signal});return a?124:i.signal.aborted?130:n}catch(e){return a?124:i.signal.aborted?130:(r.err(`${e.message}\n`),1)}finally{clearTimeout(o)}}async#l(e,t,n,r){let i;try{i=await this.#s(t,n.err)}catch(e){return n.err(`${e.message}\n`),1}try{return await this.#c(i,e,t.timeoutMs,n,r)}finally{i.close()}}#u(e){return{out:t=>this.send({t:`output`,pid:e,stream:`stdout`,data:c(t)}),err:t=>this.send({t:`output`,pid:e,stream:`stderr`,data:c(t)})}}#d={info:()=>this.hello(),"fs.readFile":e=>this.os.fs.readFile(e),"fs.readTextFile":e=>this.os.fs.readText(e),"fs.writeFile":(e,t)=>this.os.fs.writeFile(e,t),"fs.mkdir":e=>this.os.fs.mkdir(e),"fs.readdir":async e=>(await this.os.fs.readdir(e)).map(({path:e,name:t,kind:n,size:r,mtime:i})=>({path:e,name:t,kind:n,size:r,mtime:i})),"fs.stat":async e=>{let t=await this.os.fs.stat(e);return t&&{path:t.path,name:t.name,kind:t.kind,size:t.size,mtime:t.mtime}},"fs.exists":e=>this.os.fs.exists(e),"fs.rm":(e,t)=>this.os.fs.rm(e,t),"fs.rename":(e,t)=>this.os.fs.mv(e,t),"fs.cp":(e,t)=>this.os.fs.cp(e,t),"fs.appendFile":(e,t)=>this.os.fs.appendFile(e,t),"fs.glob":(e,t,n)=>this.os.fs.glob(e,t??`/home/user`,n),exec:async(e,t={})=>{let n=``,r=``;return{exitCode:await this.#l(e,t,{out:e=>n+=e,err:e=>r+=e},new AbortController),stdout:l(n),stderr:l(r)}},spawn:(e,t={})=>{let n=this.#r++,r=new AbortController;return this.#i.set(n,r),this.#l(e,t,this.#u(n),r).then(e=>{this.#i.delete(n),this.send({t:`exit`,pid:n,exitCode:e})}),n},kill:e=>{let t=this.#i.get(e);return t?.abort(),!!t},"shell.open":async(e={})=>{let t=await this.#s(e,()=>void 0),n=this.#o++;return this.#a.set(n,{shell:t,busy:!1}),{id:n,cwd:t.cwd}},"shell.run":(e,t,n={})=>{let r=this.#a.get(e);if(!r)throw Error(`no such shell session: ${e}`);if(r.busy)throw Error(`this shell session is still running a command`);r.busy=!0;let i=this.#r++,a=new AbortController;return this.#i.set(i,a),this.#c(r.shell,t,n.timeoutMs,this.#u(i),a).then(e=>{r.busy=!1,this.#i.delete(i),this.send({t:`exit`,pid:i,exitCode:e,cwd:r.shell.cwd})}),i},"shell.close":e=>{this.#a.get(e)?.shell.close(),this.#a.delete(e)},"dev.start":({root:e,port:t,network:n})=>this.os.dev.start({root:e,port:t,network:n}).then(_),"dev.stop":e=>this.os.dev.stop(e),"dev.list":async()=>(await this.os.dev.list()).map(_),"dev.logs":async(e,t)=>(await this.os.dev.logs(e,t)).map(({seq:e,t,level:n,source:r,text:i})=>({seq:e,t,level:n,source:r,text:i})),"procs.list":()=>this.os.procs.list().map(e=>({pid:e.pid,ppid:e.ppid,name:e.name,kind:e.kind,state:e.state,detail:e.detail,started:e.started,cpuMs:e.cpuMs,memBytes:e.memBytes})),"procs.kill":e=>this.os.procs.kill(e,`killed through the SDK`),"kernel.connect":async()=>{let e=await m();return{port:e.port,lock:e.lock,shared:e.shared}},share:()=>{let{port1:e,port2:n}=new MessageChannel,r=new t(e,m());return r.hello().then(e=>r.send(e),e=>r.send({t:`refused`,error:`the runtime failed to start: ${e.message}`})),n}};async#f(e){if(e.t===`permission-answer`){this.#n.get(e.id)?.(e.decision),this.#n.delete(e.id);return}if(e.t!==`call`)return;let t=Object.hasOwn(this.#d,e.method)?this.#d[e.method]:null;try{if(!t)throw Error(`unknown method: ${e.method}`);let n=await t(...Array.isArray(e.args)?e.args:[]),r=n instanceof Uint8Array?[n.buffer]:n instanceof MessagePort?[n]:n&&typeof n==`object`&&n.port instanceof MessagePort?[n.port]:[];this.send({t:`result`,id:e.id,ok:!0,value:n},r)}catch(t){let n=t instanceof Error?t.message:String(t);this.send({t:`result`,id:e.id,ok:!1,error:n,code:/^(E[A-Z]+):/.exec(n)?.[1]})}}},y=null,b=e=>n===`*`||n.includes(e)||e===location.origin;addEventListener(`message`,e=>{let t=e.data;if(t?.type!==`bbx:connect`||e.source!==parent||!e.ports[0])return;let n=e.ports[0];if(y)return n.postMessage({t:`refused`,error:`this runtime is already connected; boot another BrowserBox for a second box`});if(!b(e.origin))return n.postMessage({t:`refused`,error:`origin ${e.origin} may not use this runtime (VITE_EMBED_ORIGINS)`});if(t.protocol!==1)return n.postMessage({t:`refused`,error:`protocol mismatch: the SDK speaks ${t.protocol}, this runtime 1. Use matching versions of the SDK and the runtime.`});let r=y=new v(n,p);globalThis.bbx=r.os,r.hello().then(e=>r.send(e),e=>r.send({t:`refused`,error:`the runtime failed to start: ${e.message}`}))}),parent!==window&&parent.postMessage({type:`bbx:embed-ready`,protocol:1},`*`);