typescript-virtual-container 1.3.2 → 1.3.4

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,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  import{basename as Ti}from"node:path";import{stdin as Oi,stdout as Lt}from"node:process";import{createInterface as zi}from"node:readline";var Fe={name:"adduser",description:"Add a new user",category:"users",params:["<username> <password>"],run:async({authUser:r,shell:t,args:e})=>{if(r!=="root")return{stderr:"adduser: permission denied",exitCode:1};let[n,i]=e;return!n||!i?{stderr:"adduser: usage: adduser <username> <password>",exitCode:1}:(await t.users.addUser(n,i),{stdout:`adduser: user '${n}' created`,exitCode:0})}};function Ne(r){return Array.isArray(r)?r:[r]}function zt(r,t){if(r===t)return{matched:!0,inlineValue:null};let e=`${t}=`;return r.startsWith(e)?{matched:!0,inlineValue:r.slice(e.length)}:{matched:!1,inlineValue:null}}function ds(r,t={}){let e=new Set(t.flags??[]),n=new Set(t.flagsWithValue??[]),i=[],s=!1;for(let o=0;o<r.length;o+=1){let a=r[o];if(s){i.push(a);continue}if(a==="--"){s=!0;continue}let l=!1;for(let c of e){let{matched:u}=zt(a,c);if(u){l=!0;break}}if(!l){for(let c of n){let u=zt(a,c);if(u.matched){l=!0,u.inlineValue===null&&o+1<r.length&&(o+=1);break}}l||i.push(a)}}return i}function h(r,t){let e=Ne(t);for(let n of r)for(let i of e)if(zt(n,i).matched)return!0;return!1}function rt(r,t){let e=Ne(t);for(let n=0;n<r.length;n+=1){let i=r[n];for(let s of e){let o=zt(i,s);if(!o.matched)continue;if(o.inlineValue!==null)return o.inlineValue;let a=r[n+1];return a!==void 0&&a!=="--"?a:!0}}}function it(r,t,e={}){return ds(r,e)[t]}function et(r,t={}){let e=new Set,n=new Map,i=[],s=new Set(t.flags??[]),o=new Set(t.flagsWithValue??[]),a=!1;for(let l=0;l<r.length;l+=1){let c=r[l];if(a){i.push(c);continue}if(c==="--"){a=!0;continue}if(s.has(c)){e.add(c);continue}if(o.has(c)){let d=r[l+1];d&&!d.startsWith("-")?(n.set(c,d),l+=1):n.set(c,"");continue}let u=Array.from(o).find(d=>c.startsWith(`${d}=`));if(u){n.set(u,c.slice(u.length+1));continue}i.push(c)}return{flags:e,flagsWithValues:n,positionals:i}}var Ie={name:"alias",description:"Define or display aliases",category:"shell",params:["[name[=value] ...]"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};if(r.length===0)return{stdout:Object.entries(t.vars).filter(([i])=>i.startsWith("__alias_")).map(([i,s])=>`alias ${i.slice(8)}='${s}'`).join(`
2
3
  `)||"",exitCode:0};let e=[];for(let n of r){let i=n.indexOf("=");if(i===-1){let s=t.vars[`__alias_${n}`];if(s)e.push(`alias ${n}='${s}'`);else return{stderr:`alias: ${n}: not found`,exitCode:1}}else{let s=n.slice(0,i),o=n.slice(i+1).replace(/^['"]|['"]$/g,"");t.vars[`__alias_${s}`]=o}}return{stdout:e.join(`
3
4
  `)||void 0,exitCode:0}}},Ve={name:"unalias",description:"Remove alias definitions",category:"shell",params:["<name...> | -a"],run:({args:r,env:t})=>{if(!t)return{exitCode:0};if(h(r,["-a"])){for(let e of Object.keys(t.vars))e.startsWith("__alias_")&&delete t.vars[e];return{exitCode:0}}for(let e of r)delete t.vars[`__alias_${e}`];return{exitCode:0}}};import*as lt from"node:path";var ms=["/virtual-env-js/.auth"];function S(r,t){return!t||t.trim()===""?r:t.startsWith("/")?lt.posix.normalize(t):lt.posix.normalize(lt.posix.join(r,t))}function ps(r){let t=r.startsWith("/")?lt.posix.normalize(r):lt.posix.normalize(`/${r}`);return ms.some(e=>t===e||t.startsWith(`${e}/`))}function N(r,t,e){if(r!=="root"&&ps(t))throw new Error(`${e}: permission denied: ${t}`)}function Re(r){let e=(r.split("?")[0]?.split("#")[0]??r).split("/").filter(Boolean).pop();return e&&e.length>0?e:"index.html"}function fs(r,t){let e=Array.from({length:r.length+1},()=>Array(t.length+1).fill(0));for(let n=0;n<=r.length;n+=1)e[n][0]=n;for(let n=0;n<=t.length;n+=1)e[0][n]=n;for(let n=1;n<=r.length;n+=1)for(let i=1;i<=t.length;i+=1){let s=r[n-1]===t[i-1]?0:1;e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+s)}return e[r.length][t.length]}function De(r,t,e){let n=S(t,e);if(r.exists(n))return n;let i=lt.posix.dirname(n),s=lt.posix.basename(n),o=r.list(i),a=o.filter(c=>c.toLowerCase()===s.toLowerCase());if(a.length===1)return lt.posix.join(i,a[0]);let l=o.filter(c=>fs(c.toLowerCase(),s.toLowerCase())<=1);return l.length===1?lt.posix.join(i,l[0]):n}function _e(r,t,e){return t.map(n=>{let i=S(r,n);return e(i).type==="directory"?`${n}/`:n}).join(" ")}function vt(r){return r.packageManager}var Le={name:"apt",aliases:["apt-get"],description:"Package manager",category:"package",params:["<install|remove|update|upgrade|search|show|list> [pkg...]"],run:({args:r,shell:t,authUser:e})=>{let n=vt(t);if(!n)return{stderr:"apt: package manager not initialised",exitCode:1};let i=r[0]?.toLowerCase(),s=r.slice(1),o=h(s,["-q","--quiet","-qq"]),a=h(s,["--purge"]),l=s.filter(u=>!u.startsWith("-"));if(["install","remove","purge","upgrade","update"].includes(i??"")&&e!=="root")return{stderr:`E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
@@ -21,7 +22,7 @@ ${n.listAvailable().map(f=>`${f.name}/${f.section??"misc"} ${f.version} amd64`).
21
22
  `).filter(Boolean).map(l=>{let c=l.split(e===" "?/\s+/:e);return s.map(u=>{if(u==="$0")return l;let d=parseInt(u.replace("$",""),10);return Number.isNaN(d)?u.replace(/"/g,""):c[d-1]??""}).join(e===" "?" ":e)}).join(`
22
23
  `),exitCode:0}}};var ze={name:"base64",description:"Encode/decode base64",category:"text",params:["[-d] [file]"],run:({args:r,stdin:t})=>{let e=h(r,["-d","--decode"]),n=t??"";if(e)try{return{stdout:Buffer.from(n.trim(),"base64").toString("utf8"),exitCode:0}}catch{return{stderr:"base64: invalid input",exitCode:1}}return{stdout:Buffer.from(n).toString("base64"),exitCode:0}}};var Be={name:"cat",description:"Concatenate and print files",category:"files",params:["[-n] [-b] <file...>"],run:({authUser:r,shell:t,cwd:e,args:n,stdin:i})=>{let s=h(n,["-n","--number"]),o=h(n,["-b","--number-nonblank"]),a=n.filter(m=>!m.startsWith("-"));if(a.length===0&&i!==void 0)return{stdout:i,exitCode:0};if(a.length===0)return{stderr:"cat: missing file operand",exitCode:1};let l=[];for(let m of a){let f=De(t.vfs,e,m);N(r,f,"cat"),l.push(t.vfs.readFile(f))}let c=l.join("");if(!s&&!o)return{stdout:c,exitCode:0};let u=1;return{stdout:c.split(`
23
24
  `).map(m=>o&&m.trim()===""?m:`${String(u++).padStart(6)} ${m}`).join(`
24
- `),exitCode:0}}};var Ue={name:"cd",description:"Change directory",category:"navigation",params:["[path]"],run:({authUser:r,shell:t,cwd:e,args:n,mode:i})=>{let s=S(e,n[0]??"/virtual-env-js");return N(r,s,"cd"),t.vfs.stat(s).type!=="directory"?{stderr:`cd: not a directory: ${s}`,exitCode:1}:i==="exec"?{exitCode:0}:{nextCwd:s,exitCode:0}}};function hs(r,t){let e=/^([ugoa]*)([+\-=])([rwx]*)$/,n=t.split(","),i=r;for(let s of n){let o=s.trim().match(e);if(!o)return null;let[,a="a",l,c=""]=o,u=a===""||a==="a"?["u","g","o"]:a.split(""),d={u:{r:256,w:128,x:64},g:{r:32,w:16,x:8},o:{r:4,w:2,x:1}};for(let m of u)for(let f of c.split("")){let x=d[m]?.[f];if(x!==void 0){if(l==="+")i|=x;else if(l==="-")i&=~x;else if(l==="="){let g=Object.values(d[m]??{}).reduce((y,$)=>y|$,0);i=i&~g|x}}}}return i}var je={name:"chmod",description:"Change file permissions",category:"files",params:["<mode> <file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let[i,s]=n;if(!i||!s)return{stderr:"chmod: missing operand",exitCode:1};let o=S(e,s);try{if(N(r,o,"chmod"),!t.vfs.exists(o))return{stderr:`chmod: ${s}: No such file or directory`,exitCode:1};let a,l=parseInt(i,8);if(!Number.isNaN(l)&&/^[0-7]+$/.test(i))a=l;else{let c=t.vfs.stat(o).mode,u=hs(c,i);if(u===null)return{stderr:`chmod: invalid mode: ${i}`,exitCode:1};a=u}return t.vfs.chmod(o,a),{exitCode:0}}catch(a){return{stderr:`chmod: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}}};var We={name:"clear",description:"Clear the terminal screen",category:"shell",params:[],run:()=>({clearScreen:!0,stdout:"",exitCode:0})};var He={name:"cp",description:"Copy files or directories",category:"files",params:["[-r] <source> <dest>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=h(n,["-r","-R","--recursive"]),s=n.filter(u=>!u.startsWith("-")),[o,a]=s;if(!o||!a)return{stderr:"cp: missing operand",exitCode:1};let l=S(e,o),c=S(e,a);try{if(N(r,l,"cp"),N(r,c,"cp"),!t.vfs.exists(l))return{stderr:`cp: ${o}: No such file or directory`,exitCode:1};if(t.vfs.stat(l).type==="directory"){if(!i)return{stderr:`cp: ${o}: is a directory (use -r)`,exitCode:1};let d=(f,x)=>{t.vfs.mkdir(x,493);for(let g of t.vfs.list(f)){let y=`${f}/${g}`,$=`${x}/${g}`;if(t.vfs.stat(y).type==="directory")d(y,$);else{let k=t.vfs.readFileRaw(y);t.writeFileAsUser(r,$,k)}}},m=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c;d(l,m)}else{let d=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c,m=t.vfs.readFileRaw(l);t.writeFileAsUser(r,d,m)}return{exitCode:0}}catch(u){return{stderr:`cp: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}};var qe={name:"curl",description:"Transfer data from or to a server (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:r,cwd:t,args:e,shell:n})=>{let{flagsWithValues:i,positionals:s}=et(e,{flagsWithValue:["-o","--output","-X","--request","-d","--data","-H","--header","-u","--user"]});if(h(e,["--help","-h"]))return{stdout:["Usage: curl [options] <url>"," -o, --output <file> Write to file"," -X, --request <method> HTTP method"," -d, --data <data> POST data"," -H, --header <hdr> Extra header"," -s, --silent Silent mode"," -I, --head Fetch headers only"," -L, --location Follow redirects"," -v, --verbose Verbose"].join(`
25
+ `),exitCode:0}}};var Ue={name:"cd",description:"Change directory",category:"navigation",params:["[path]"],run:({authUser:r,shell:t,cwd:e,args:n,mode:i})=>{let s=S(e,n[0]??"/virtual-env-js");return N(r,s,"cd"),t.vfs.stat(s).type!=="directory"?{stderr:`cd: not a directory: ${s}`,exitCode:1}:i==="exec"?{exitCode:0}:{nextCwd:s,exitCode:0}}};function hs(r,t){let e=/^([ugoa]*)([+\-=])([rwx]*)$/,n=t.split(","),i=r;for(let s of n){let o=s.trim().match(e);if(!o)return null;let[,a="a",l,c=""]=o,u=a===""||a==="a"?["u","g","o"]:a.split(""),d={u:{r:256,w:128,x:64},g:{r:32,w:16,x:8},o:{r:4,w:2,x:1}};for(let m of u)for(let f of c.split("")){let x=d[m]?.[f];if(x!==void 0){if(l==="+")i|=x;else if(l==="-")i&=~x;else if(l==="="){let g=Object.values(d[m]??{}).reduce((y,$)=>y|$,0);i=i&~g|x}}}}return i}var We={name:"chmod",description:"Change file permissions",category:"files",params:["<mode> <file>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let[i,s]=n;if(!i||!s)return{stderr:"chmod: missing operand",exitCode:1};let o=S(e,s);try{if(N(r,o,"chmod"),!t.vfs.exists(o))return{stderr:`chmod: ${s}: No such file or directory`,exitCode:1};let a,l=parseInt(i,8);if(!Number.isNaN(l)&&/^[0-7]+$/.test(i))a=l;else{let c=t.vfs.stat(o).mode,u=hs(c,i);if(u===null)return{stderr:`chmod: invalid mode: ${i}`,exitCode:1};a=u}return t.vfs.chmod(o,a),{exitCode:0}}catch(a){return{stderr:`chmod: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}}};var je={name:"clear",description:"Clear the terminal screen",category:"shell",params:[],run:()=>({clearScreen:!0,stdout:"",exitCode:0})};var He={name:"cp",description:"Copy files or directories",category:"files",params:["[-r] <source> <dest>"],run:({authUser:r,shell:t,cwd:e,args:n})=>{let i=h(n,["-r","-R","--recursive"]),s=n.filter(u=>!u.startsWith("-")),[o,a]=s;if(!o||!a)return{stderr:"cp: missing operand",exitCode:1};let l=S(e,o),c=S(e,a);try{if(N(r,l,"cp"),N(r,c,"cp"),!t.vfs.exists(l))return{stderr:`cp: ${o}: No such file or directory`,exitCode:1};if(t.vfs.stat(l).type==="directory"){if(!i)return{stderr:`cp: ${o}: is a directory (use -r)`,exitCode:1};let d=(f,x)=>{t.vfs.mkdir(x,493);for(let g of t.vfs.list(f)){let y=`${f}/${g}`,$=`${x}/${g}`;if(t.vfs.stat(y).type==="directory")d(y,$);else{let k=t.vfs.readFileRaw(y);t.writeFileAsUser(r,$,k)}}},m=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c;d(l,m)}else{let d=t.vfs.exists(c)&&t.vfs.stat(c).type==="directory"?`${c}/${o.split("/").pop()}`:c,m=t.vfs.readFileRaw(l);t.writeFileAsUser(r,d,m)}return{exitCode:0}}catch(u){return{stderr:`cp: ${u instanceof Error?u.message:String(u)}`,exitCode:1}}}};var qe={name:"curl",description:"Transfer data from or to a server (pure fetch)",category:"network",params:["[options] <url>"],run:async({authUser:r,cwd:t,args:e,shell:n})=>{let{flagsWithValues:i,positionals:s}=et(e,{flagsWithValue:["-o","--output","-X","--request","-d","--data","-H","--header","-u","--user"]});if(h(e,["--help","-h"]))return{stdout:["Usage: curl [options] <url>"," -o, --output <file> Write to file"," -X, --request <method> HTTP method"," -d, --data <data> POST data"," -H, --header <hdr> Extra header"," -s, --silent Silent mode"," -I, --head Fetch headers only"," -L, --location Follow redirects"," -v, --verbose Verbose"].join(`
25
26
  `),exitCode:0};let o=s[0];if(!o)return{stderr:"curl: no URL specified",exitCode:1};let a=i.get("-o")??i.get("--output")??null,l=(i.get("-X")??i.get("--request")??"GET").toUpperCase(),c=i.get("-d")??i.get("--data")??null,u=i.get("-H")??i.get("--header")??null,d=h(e,["-s","--silent"]),m=h(e,["-I","--head"]),f=h(e,["-L","--location"]),x=h(e,["-v","--verbose"]),g={"User-Agent":"curl/7.88.1"};if(u){let D=u.indexOf(":");D!==-1&&(g[u.slice(0,D).trim()]=u.slice(D+1).trim())}let y=c&&l==="GET"?"POST":l,$={method:y,headers:g,redirect:f?"follow":"manual"};c&&(g["Content-Type"]??="application/x-www-form-urlencoded",$.body=c);let V=[];x&&(V.push(`* Trying ${o}...`,"* Connected"),V.push(`> ${y} / HTTP/1.1`,`> Host: ${new URL(o).host}`));let k;try{k=await fetch(o,$)}catch(D){return{stderr:`curl: (6) Could not resolve host: ${D instanceof Error?D.message:String(D)}`,exitCode:6}}if(x&&V.push(`< HTTP/1.1 ${k.status} ${k.statusText}`),m){let D=[`HTTP/1.1 ${k.status} ${k.statusText}`];for(let[tt,w]of k.headers.entries())D.push(`${tt}: ${w}`);return{stdout:`${D.join(`\r
26
27
  `)}\r
27
28
  `,exitCode:0}}let R;try{R=await k.text()}catch{return{stderr:"curl: failed to read response body",exitCode:1}}if(a){let D=S(t,a);return N(r,D,"curl"),n.writeFileAsUser(r,D,R),d||V.push(` % Total % Received
@@ -189,21 +190,21 @@ OPTIONS
189
190
  `)){if(!t.startsWith("PRETTY_NAME="))continue;return t.slice(12).trim().replace(/^"|"$/g,"")}}catch{return}}function _r(r){try{let t=ce(r,"utf8").split(`
190
191
  `)[0]?.trim();return!t||t.length===0?void 0:t}catch{return}}function Is(r){let t=_r("/sys/devices/virtual/dmi/id/sys_vendor"),e=_r("/sys/devices/virtual/dmi/id/product_name");return t&&e?`${t} ${e}`:e||r}function Vs(){let r=["/var/lib/dpkg/status","/usr/local/var/lib/dpkg/status"];for(let t of r)if(Lr(t))try{return ce(t,"utf8").match(/^Package:\s+/gm)?.length??0}catch{}}function Rs(){let r=["/snap","/var/lib/snapd/snaps"];for(let t of r)if(Lr(t))try{return Es(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).length}catch{}}function Ds(){let r=Vs(),t=Rs();return r!==void 0&&t!==void 0?`${r} (dpkg), ${t} (snap)`:r!==void 0?`${r} (dpkg)`:t!==void 0?`${t} (snap)`:"n/a"}function _s(){let r=Q.cpus();if(r.length===0)return"unknown";let t=r[0];if(!t)return"unknown";let e=(t.speed/1e3).toFixed(2);return`${t.model} (${r.length}) @ ${e}GHz`}function Ls(r){return!r||r.trim().length===0?"unknown":Tr.posix.basename(r.trim())}function Ts(r){let t=Q.totalmem(),e=Q.freemem(),n=Math.max(0,t-e),i=r.shellProps,s=process.uptime();return r.uptimeSeconds===void 0&&(r.uptimeSeconds=Math.round(s)),{user:r.user,host:r.host,osName:i?.os??r.osName??`${Dr()??Q.type()} ${Q.arch()}`,kernel:i?.kernel??r.kernel??Q.release(),uptimeSeconds:r.uptimeSeconds??Q.uptime(),packages:r.packages??Ds(),shell:Ls(r.shell),shellProps:r.shellProps??{kernel:r.kernel??Q.release(),os:r.osName??`${Dr()??Q.type()} ${Q.arch()}`,arch:Q.arch()},resolution:r.resolution??"n/a (ssh)",terminal:r.terminal??"unknown",cpu:r.cpu??_s(),gpu:r.gpu??"n/a",memoryUsedMiB:r.memoryUsedMiB??Rr(n),memoryTotalMiB:r.memoryTotalMiB??Rr(t)}}function Or(r){let t=Ts(r),e=As(t.uptimeSeconds),n=Fs(),i=[" .. .:. "," .::.. .. .. ",". .... ... .. ",": .... .:. .. ",": .:.:........:. .. ",": .. ",". : ",". : ",".. : "," :. .. "," .. .. "," :-. :: "," .:. :. "," ..: ... "," ..: :.. "," :... :...."," .. ...."," . .. "," .:. .: "," :. .. "," ::. .. ","..... ..:... ","...:. .. ",".:...:. ::. .. "," ... ..:::::.. ..:::::::.. "],s=[`${t.user}@${t.host}`,"-------------------------",`OS: ${t.osName}`,`Host: ${Is(t.host)}`,`Kernel: ${t.kernel}`,`Uptime: ${e}`,`Packages: ${t.packages}`,`Shell: ${t.shell}`,`Resolution: ${t.resolution}`,`Terminal: ${t.terminal}`,`CPU: ${t.cpu}`,`GPU: ${t.gpu}`,`Memory: ${t.memoryUsedMiB}MiB / ${t.memoryTotalMiB}MiB`,"",n[0],n[1]],o=Math.max(i.length,s.length),a=[];for(let l=0;l<o;l+=1){let c=i[l]??"",u=s[l]??"";if(u.length>0){let d=Ir(c.padEnd(31," "),l,i.length),m=Ns(u);a.push(`${d} ${m}`);continue}a.push(Ir(c,l,i.length))}return a.join(`
191
192
  `)}var ue={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/home/user",SHELL:"/bin/sh",TERM:"xterm-256color",USER:"user"};function zr(r){return ue.USER=r,ue.HOME=`/home/${r}`,{...ue}}var Br={name:"set",description:"Display or set shell variables",category:"shell",params:["[VAR=value]"],run:({args:r,env:t})=>{if(r.length===0)return{stdout:Object.entries(t.vars).map(([n,i])=>`${n}=${i}`).join(`
192
- `),exitCode:0};for(let e of r)if(e.includes("=")){let n=e.indexOf("=");t.vars[e.slice(0,n)]=e.slice(n+1)}return{exitCode:0}}};var Ur={name:"neofetch",description:"System info display",category:"system",params:["[--off]"],run:({args:r,authUser:t,hostname:e,shell:n})=>{let i=zr(t);return h(r,"--help")?{stdout:"Usage: neofetch [--off]",exitCode:0}:h(r,"--off")?{stdout:`${t}@${e}`,exitCode:0}:{stdout:Or({user:t,host:e,shell:i.SHELL,shellProps:n.properties,terminal:i.TERM,uptimeSeconds:Math.floor((Date.now()-n.startTime)/1e3),packages:`${n.packageManager?.installedCount()??0} (dpkg)`}),exitCode:0}}};import jr from"node:vm";var jt="v18.19.0",Wr={node:jt,npm:"9.2.0",v8:"10.2.154.26-node.22"};function Os(r,t){let e={version:jt,versions:Wr,platform:"linux",arch:"x64",env:{NODE_ENV:"production",HOME:"/root",PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["node"],stdout:{write:s=>(r.push(s),!0)},stderr:{write:s=>(t.push(s),!0)},exit:(s=0)=>{throw new Wt(s)},cwd:()=>"/root",hrtime:()=>[0,0]},n={log:(...s)=>r.push(s.map(ut).join(" ")),error:(...s)=>t.push(s.map(ut).join(" ")),warn:(...s)=>t.push(s.map(ut).join(" ")),info:(...s)=>r.push(s.map(ut).join(" ")),dir:s=>r.push(ut(s))},i=s=>{switch(s){case"path":return{join:(...o)=>o.join("/").replace(/\/+/g,"/"),resolve:(...o)=>`/${o.join("/").replace(/^\/+/,"")}`,dirname:o=>o.split("/").slice(0,-1).join("/")||"/",basename:o=>o.split("/").pop()??"",extname:o=>{let a=o.split("/").pop()??"",l=a.lastIndexOf(".");return l>0?a.slice(l):""},sep:"/",delimiter:":"};case"os":return{platform:()=>"linux",arch:()=>"x64",type:()=>"Linux",hostname:()=>"fortune-vm",homedir:()=>"/root",tmpdir:()=>"/tmp",EOL:`
193
- `};case"util":return{format:(...o)=>o.map(ut).join(" "),inspect:o=>ut(o)};case"fs":case"fs/promises":throw new Error(`Cannot require '${s}': filesystem access not available in virtual runtime`);case"child_process":case"net":case"http":case"https":throw new Error(`Cannot require '${s}': not available in virtual runtime`);default:throw new Error(`Cannot find module '${s}'`)}};return i.resolve=s=>{throw new Error(`Cannot resolve '${s}'`)},i.cache={},i.extensions={},jr.createContext({console:n,process:e,require:i,Math,JSON,Object,Array,String,Number,Boolean,Symbol,Date,RegExp,Error,TypeError,RangeError,SyntaxError,Promise,Map,Set,WeakMap,WeakSet,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,setTimeout:()=>{},clearTimeout:()=>{},setInterval:()=>{},clearInterval:()=>{},queueMicrotask:()=>{},globalThis:void 0,undefined:void 0,Infinity:1/0,NaN:NaN})}var Wt=class{constructor(t){this.code=t}code};function ut(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="function")return`[Function: ${r.name||"(anonymous)"}]`;if(Array.isArray(r))return`[ ${r.map(ut).join(", ")} ]`;if(r instanceof Error)return`${r.name}: ${r.message}`;if(typeof r=="object")try{return`{ ${Object.entries(r).map(([e,n])=>`${e}: ${ut(n)}`).join(", ")} }`}catch{return"[Object]"}return String(r)}function Ht(r){let t=[],e=[],n=Os(t,e),i=0;try{let s=jr.runInContext(r,n,{timeout:5e3});s!==void 0&&t.length===0&&t.push(ut(s))}catch(s){s instanceof Wt?i=s.code:s instanceof Error?(e.push(`${s.name}: ${s.message}`),i=1):(e.push(String(s)),i=1)}return{stdout:t.length?`${t.join(`
193
+ `),exitCode:0};for(let e of r)if(e.includes("=")){let n=e.indexOf("=");t.vars[e.slice(0,n)]=e.slice(n+1)}return{exitCode:0}}};var Ur={name:"neofetch",description:"System info display",category:"system",params:["[--off]"],run:({args:r,authUser:t,hostname:e,shell:n})=>{let i=zr(t);return h(r,"--help")?{stdout:"Usage: neofetch [--off]",exitCode:0}:h(r,"--off")?{stdout:`${t}@${e}`,exitCode:0}:{stdout:Or({user:t,host:e,shell:i.SHELL,shellProps:n.properties,terminal:i.TERM,uptimeSeconds:Math.floor((Date.now()-n.startTime)/1e3),packages:`${n.packageManager?.installedCount()??0} (dpkg)`}),exitCode:0}}};import Wr from"node:vm";var Wt="v18.19.0",jr={node:Wt,npm:"9.2.0",v8:"10.2.154.26-node.22"};function Os(r,t){let e={version:Wt,versions:jr,platform:"linux",arch:"x64",env:{NODE_ENV:"production",HOME:"/root",PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["node"],stdout:{write:s=>(r.push(s),!0)},stderr:{write:s=>(t.push(s),!0)},exit:(s=0)=>{throw new jt(s)},cwd:()=>"/root",hrtime:()=>[0,0]},n={log:(...s)=>r.push(s.map(ut).join(" ")),error:(...s)=>t.push(s.map(ut).join(" ")),warn:(...s)=>t.push(s.map(ut).join(" ")),info:(...s)=>r.push(s.map(ut).join(" ")),dir:s=>r.push(ut(s))},i=s=>{switch(s){case"path":return{join:(...o)=>o.join("/").replace(/\/+/g,"/"),resolve:(...o)=>`/${o.join("/").replace(/^\/+/,"")}`,dirname:o=>o.split("/").slice(0,-1).join("/")||"/",basename:o=>o.split("/").pop()??"",extname:o=>{let a=o.split("/").pop()??"",l=a.lastIndexOf(".");return l>0?a.slice(l):""},sep:"/",delimiter:":"};case"os":return{platform:()=>"linux",arch:()=>"x64",type:()=>"Linux",hostname:()=>"fortune-vm",homedir:()=>"/root",tmpdir:()=>"/tmp",EOL:`
194
+ `};case"util":return{format:(...o)=>o.map(ut).join(" "),inspect:o=>ut(o)};case"fs":case"fs/promises":throw new Error(`Cannot require '${s}': filesystem access not available in virtual runtime`);case"child_process":case"net":case"http":case"https":throw new Error(`Cannot require '${s}': not available in virtual runtime`);default:throw new Error(`Cannot find module '${s}'`)}};return i.resolve=s=>{throw new Error(`Cannot resolve '${s}'`)},i.cache={},i.extensions={},Wr.createContext({console:n,process:e,require:i,Math,JSON,Object,Array,String,Number,Boolean,Symbol,Date,RegExp,Error,TypeError,RangeError,SyntaxError,Promise,Map,Set,WeakMap,WeakSet,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,setTimeout:()=>{},clearTimeout:()=>{},setInterval:()=>{},clearInterval:()=>{},queueMicrotask:()=>{},globalThis:void 0,undefined:void 0,Infinity:1/0,NaN:NaN})}var jt=class{constructor(t){this.code=t}code};function ut(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="function")return`[Function: ${r.name||"(anonymous)"}]`;if(Array.isArray(r))return`[ ${r.map(ut).join(", ")} ]`;if(r instanceof Error)return`${r.name}: ${r.message}`;if(typeof r=="object")try{return`{ ${Object.entries(r).map(([e,n])=>`${e}: ${ut(n)}`).join(", ")} }`}catch{return"[Object]"}return String(r)}function Ht(r){let t=[],e=[],n=Os(t,e),i=0;try{let s=Wr.runInContext(r,n,{timeout:5e3});s!==void 0&&t.length===0&&t.push(ut(s))}catch(s){s instanceof jt?i=s.code:s instanceof Error?(e.push(`${s.name}: ${s.message}`),i=1):(e.push(String(s)),i=1)}return{stdout:t.length?`${t.join(`
194
195
  `)}
195
196
  `:"",stderr:e.length?`${e.join(`
196
197
  `)}
197
198
  `:"",exitCode:i}}function zs(r){let t=r.trim();return!t.includes(`
198
199
  `)&&!t.startsWith("const ")&&!t.startsWith("let ")&&!t.startsWith("var ")&&!t.startsWith("function ")&&!t.startsWith("class ")&&!t.startsWith("if ")&&!t.startsWith("for ")&&!t.startsWith("while ")&&!t.startsWith("import ")&&!t.startsWith("//")?Ht(t):Ht(`(async () => { ${r} })()`)}var Hr={name:"node",description:"JavaScript runtime (virtual)",category:"system",params:["[--version] [-e <expr>] [-p <expr>] [file]"],run:({args:r,shell:t,cwd:e})=>{if(!t.packageManager.isInstalled("nodejs"))return{stderr:`bash: node: command not found
199
200
  Hint: install it with: apt install nodejs
200
- `,exitCode:127};if(h(r,["--version","-v"]))return{stdout:`${jt}
201
- `,exitCode:0};if(h(r,["--versions"]))return{stdout:`${JSON.stringify(Wr,null,2)}
201
+ `,exitCode:127};if(h(r,["--version","-v"]))return{stdout:`${Wt}
202
+ `,exitCode:0};if(h(r,["--versions"]))return{stdout:`${JSON.stringify(jr,null,2)}
202
203
  `,exitCode:0};let n=r.findIndex(o=>o==="-e"||o==="--eval");if(n!==-1){let o=r[n+1];if(!o)return{stderr:`node: -e requires an argument
203
204
  `,exitCode:1};let{stdout:a,stderr:l,exitCode:c}=Ht(o);return{stdout:a||void 0,stderr:l||void 0,exitCode:c}}let i=r.findIndex(o=>o==="-p"||o==="--print");if(i!==-1){let o=r[i+1];if(!o)return{stderr:`node: -p requires an argument
204
205
  `,exitCode:1};let{stdout:a,stderr:l,exitCode:c}=Ht(o);return{stdout:a||(c===0?`
205
206
  `:void 0),stderr:l||void 0,exitCode:c}}let s=r.find(o=>!o.startsWith("-"));if(s){let o=S(e,s);if(!t.vfs.exists(o))return{stderr:`node: cannot open file '${s}': No such file or directory
206
- `,exitCode:1};let a=t.vfs.readFile(o),{stdout:l,stderr:c,exitCode:u}=zs(a);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}return{stdout:[`Welcome to Node.js ${jt}.`,'Type ".exit" to exit the REPL.',"> "].join(`
207
+ `,exitCode:1};let a=t.vfs.readFile(o),{stdout:l,stderr:c,exitCode:u}=zs(a);return{stdout:l||void 0,stderr:c||void 0,exitCode:u}}return{stdout:[`Welcome to Node.js ${Wt}.`,'Type ".exit" to exit the REPL.',"> "].join(`
207
208
  `),exitCode:0}}};var qt="9.2.0",Bs="18.19.0",qr={name:"npm",description:"Node.js package manager (virtual)",category:"system",params:["<command> [args]"],run:({args:r,shell:t})=>{if(!t.packageManager.isInstalled("npm"))return{stderr:`bash: npm: command not found
208
209
  Hint: install it with: apt install npm
209
210
  `,exitCode:127};if(h(r,["--version","-v"]))return{stdout:`${qt}
@@ -225,19 +226,19 @@ Hint: install it with: apt install npm
225
226
  `),exitCode:0}}};function Us(r,t){let e=0,n="",i=0;for(;i<r.length;){if(r[i]==="\\"&&i+1<r.length)switch(r[i+1]){case"n":n+=`
226
227
  `,i+=2;continue;case"t":n+=" ",i+=2;continue;case"r":n+="\r",i+=2;continue;case"\\":n+="\\",i+=2;continue;case"a":n+="\x07",i+=2;continue;case"b":n+="\b",i+=2;continue;case"f":n+="\f",i+=2;continue;case"v":n+="\v",i+=2;continue;default:n+=r[i],i++;continue}if(r[i]==="%"&&i+1<r.length){let s=i+1;for(r[s]==="-"&&s++;s<r.length&&/\d/.test(r[s]);)s++;if(r[s]===".")for(s++;s<r.length&&/\d/.test(r[s]);)s++;let o=r[s],a=t[e++]??"";switch(o){case"s":n+=a;break;case"d":case"i":n+=String(parseInt(a,10)||0);break;case"f":n+=String(parseFloat(a)||0);break;case"o":n+=(parseInt(a,10)||0).toString(8);break;case"x":n+=(parseInt(a,10)||0).toString(16);break;case"X":n+=(parseInt(a,10)||0).toString(16).toUpperCase();break;case"%":n+="%",e--;break;default:n+=r[i],i++;continue}i=s+1;continue}n+=r[i],i++}return n}var Jr={name:"printf",description:"Format and print data",category:"shell",params:["<format> [args...]"],run:({args:r})=>{let t=r[0];return t?{stdout:Us(t,r.slice(1)),exitCode:0}:{stderr:"printf: missing format string",exitCode:1}}};var Yr={name:"ps",description:"Report process status",category:"system",params:["[-a] [-u] [-x] [aux]"],run:({authUser:r,shell:t,args:e})=>{let n=t.users.listActiveSessions(),i=h(e,["-u"])||e.includes("u")||e.includes("aux")||e.includes("au"),s=h(e,["-a","-x"])||e.includes("a")||e.includes("aux");if(i){let u=["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND"],d=1e3;for(let m of n){let f=m.username.padEnd(10).slice(0,10),x=(Math.random()*.5).toFixed(1),g=Math.floor(Math.random()*2e4+5e3),y=Math.floor(Math.random()*5e3+1e3);u.push(`${f} ${String(d).padStart(6)} 0.0 ${x.padStart(4)} ${String(g).padStart(6)} ${String(y).padStart(5)} ${m.tty.padEnd(8)} Ss 00:00 0:00 bash`),d++}return u.push(`root ${String(d).padStart(6)} 0.0 0.0 0 0 ? S 00:00 0:00 ps`),{stdout:u.join(`
227
228
  `),exitCode:0}}let a=[" PID TTY TIME CMD"],l=1e3;for(let c of n)!s&&c.username!==r||(a.push(`${String(l).padStart(5)} ${c.tty.padEnd(12)} 00:00:00 ${c.username===r?"bash":`bash (${c.username})`}`),l++);return a.push(`${String(l).padStart(5)} pts/0 00:00:00 ps`),{stdout:a.join(`
228
- `),exitCode:0}}};var Qr={name:"pwd",description:"Print working directory",category:"navigation",params:[],run:({cwd:r})=>({stdout:r,exitCode:0})};var js="Python 3.11.2";var Kt="3.11.2 (default, Mar 13 2023, 12:18:29) [GCC 12.2.0]",p={__pytype__:"none"};function j(r=[]){return{__pytype__:"dict",data:new Map(r)}}function de(r,t,e=1){return{__pytype__:"range",start:r,stop:t,step:e}}function B(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="dict"}function $t(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="range"}function dt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="func"}function me(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="class"}function Ft(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="instance"}function gt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="none"}function G(r){return r===null||gt(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?`'${r.replace(/'/g,"\\'")}'`:Array.isArray(r)?`[${r.map(G).join(", ")}]`:B(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${G(e)}`).join(", ")}}`:$t(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:dt(r)?`<function ${r.name} at 0x...>`:me(r)?`<class '${r.name}'>`:Ft(r)?`<${r.cls.name} object at 0x...>`:String(r)}function M(r){return r===null||gt(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?r:Array.isArray(r)?`[${r.map(G).join(", ")}]`:B(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${G(e)}`).join(", ")}}`:$t(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:G(r)}function nt(r){return r===null||gt(r)?!1:typeof r=="boolean"?r:typeof r=="number"?r!==0:typeof r=="string"||Array.isArray(r)?r.length>0:B(r)?r.data.size>0:$t(r)?tn(r)>0:!0}function tn(r){if(r.step===0)return 0;let t=Math.ceil((r.stop-r.start)/r.step);return Math.max(0,t)}function Ws(r){let t=[];for(let e=r.start;(r.step>0?e<r.stop:e>r.stop)&&(t.push(e),!(t.length>1e4));e+=r.step);return t}function K(r){if(Array.isArray(r))return r;if(typeof r=="string")return[...r];if($t(r))return Ws(r);if(B(r))return[...r.data.keys()];throw new U("TypeError",`'${St(r)}' object is not iterable`)}function St(r){return r===null||gt(r)?"NoneType":typeof r=="boolean"?"bool":typeof r=="number"?Number.isInteger(r)?"int":"float":typeof r=="string"?"str":Array.isArray(r)?"list":B(r)?"dict":$t(r)?"range":dt(r)?"function":me(r)?"type":Ft(r)?r.cls.name:"object"}var U=class{constructor(t,e){this.type=t;this.message=e}type;message;toString(){return`${this.type}: ${this.message}`}},Ct=class{constructor(t){this.value=t}value},Nt=class{},It=class{},Vt=class{constructor(t){this.code=t}code};function Hs(r){let t=new Map,e=j([["sep","/"],["linesep",`
229
- `],["curdir","."],["pardir",".."]]);return e.__methods__={getcwd:()=>r,getenv:n=>typeof n=="string"?process.env[n]??p:p,path:j([["join",p],["exists",p],["dirname",p],["basename",p]]),listdir:()=>[]},t.set("__builtins__",p),t.set("__name__","__main__"),t.set("__cwd__",r),t}function qs(r){let t=j([["sep","/"],["curdir","."]]),e=j([["sep","/"],["linesep",`
230
- `],["name","posix"]]);return e._cwd=r,t._cwd=r,e.path=t,e}function Ks(){return j([["version",Kt],["version_info",j([["major",3],["minor",11],["micro",2]].map(([r,t])=>[r,t]))],["platform","linux"],["executable","/usr/bin/python3"],["prefix","/usr"],["path",["/usr/lib/python3.11","/usr/lib/python3.11/lib-dynload"]],["argv",[""]],["maxsize",9007199254740991]])}function Gs(){return j([["pi",Math.PI],["e",Math.E],["tau",Math.PI*2],["inf",1/0],["nan",NaN],["sqrt",p],["floor",p],["ceil",p],["log",p],["pow",p],["sin",p],["cos",p],["tan",p],["fabs",p],["factorial",p]])}function Zs(){return j([["dumps",p],["loads",p]])}function Js(){return j([["match",p],["search",p],["findall",p],["sub",p],["split",p],["compile",p]])}var Xr={os:qs,sys:()=>Ks(),math:()=>Gs(),json:()=>Zs(),re:()=>Js(),random:()=>j([["random",p],["randint",p],["choice",p],["shuffle",p]]),time:()=>j([["time",p],["sleep",p],["ctime",p]]),datetime:()=>j([["datetime",p],["date",p],["timedelta",p]]),collections:()=>j([["Counter",p],["defaultdict",p],["OrderedDict",p]]),itertools:()=>j([["chain",p],["product",p],["combinations",p],["permutations",p]]),functools:()=>j([["reduce",p],["partial",p],["lru_cache",p]]),string:()=>j([["ascii_letters","abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"],["digits","0123456789"],["punctuation","!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"]])},Gt=class{constructor(t){this.cwd=t}cwd;output=[];stderr=[];modules=new Map;getOutput(){return this.output.join(`
229
+ `),exitCode:0}}};var Qr={name:"pwd",description:"Print working directory",category:"navigation",params:[],run:({cwd:r})=>({stdout:r,exitCode:0})};var Ws="Python 3.11.2";var Kt="3.11.2 (default, Mar 13 2023, 12:18:29) [GCC 12.2.0]",p={__pytype__:"none"};function W(r=[]){return{__pytype__:"dict",data:new Map(r)}}function de(r,t,e=1){return{__pytype__:"range",start:r,stop:t,step:e}}function B(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="dict"}function $t(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="range"}function dt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="func"}function me(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="class"}function Ft(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="instance"}function gt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&r.__pytype__==="none"}function G(r){return r===null||gt(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?`'${r.replace(/'/g,"\\'")}'`:Array.isArray(r)?`[${r.map(G).join(", ")}]`:B(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${G(e)}`).join(", ")}}`:$t(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:dt(r)?`<function ${r.name} at 0x...>`:me(r)?`<class '${r.name}'>`:Ft(r)?`<${r.cls.name} object at 0x...>`:String(r)}function M(r){return r===null||gt(r)?"None":r===!0?"True":r===!1?"False":typeof r=="number"?Number.isInteger(r)?String(r):r.toPrecision(12).replace(/\.?0+$/,""):typeof r=="string"?r:Array.isArray(r)?`[${r.map(G).join(", ")}]`:B(r)?`{${[...r.data.entries()].map(([t,e])=>`'${t}': ${G(e)}`).join(", ")}}`:$t(r)?`range(${r.start}, ${r.stop}${r.step!==1?`, ${r.step}`:""})`:G(r)}function nt(r){return r===null||gt(r)?!1:typeof r=="boolean"?r:typeof r=="number"?r!==0:typeof r=="string"||Array.isArray(r)?r.length>0:B(r)?r.data.size>0:$t(r)?tn(r)>0:!0}function tn(r){if(r.step===0)return 0;let t=Math.ceil((r.stop-r.start)/r.step);return Math.max(0,t)}function js(r){let t=[];for(let e=r.start;(r.step>0?e<r.stop:e>r.stop)&&(t.push(e),!(t.length>1e4));e+=r.step);return t}function K(r){if(Array.isArray(r))return r;if(typeof r=="string")return[...r];if($t(r))return js(r);if(B(r))return[...r.data.keys()];throw new U("TypeError",`'${St(r)}' object is not iterable`)}function St(r){return r===null||gt(r)?"NoneType":typeof r=="boolean"?"bool":typeof r=="number"?Number.isInteger(r)?"int":"float":typeof r=="string"?"str":Array.isArray(r)?"list":B(r)?"dict":$t(r)?"range":dt(r)?"function":me(r)?"type":Ft(r)?r.cls.name:"object"}var U=class{constructor(t,e){this.type=t;this.message=e}type;message;toString(){return`${this.type}: ${this.message}`}},Ct=class{constructor(t){this.value=t}value},Nt=class{},It=class{},Vt=class{constructor(t){this.code=t}code};function Hs(r){let t=new Map,e=W([["sep","/"],["linesep",`
230
+ `],["curdir","."],["pardir",".."]]);return e.__methods__={getcwd:()=>r,getenv:n=>typeof n=="string"?process.env[n]??p:p,path:W([["join",p],["exists",p],["dirname",p],["basename",p]]),listdir:()=>[]},t.set("__builtins__",p),t.set("__name__","__main__"),t.set("__cwd__",r),t}function qs(r){let t=W([["sep","/"],["curdir","."]]),e=W([["sep","/"],["linesep",`
231
+ `],["name","posix"]]);return e._cwd=r,t._cwd=r,e.path=t,e}function Ks(){return W([["version",Kt],["version_info",W([["major",3],["minor",11],["micro",2]].map(([r,t])=>[r,t]))],["platform","linux"],["executable","/usr/bin/python3"],["prefix","/usr"],["path",["/usr/lib/python3.11","/usr/lib/python3.11/lib-dynload"]],["argv",[""]],["maxsize",9007199254740991]])}function Gs(){return W([["pi",Math.PI],["e",Math.E],["tau",Math.PI*2],["inf",1/0],["nan",NaN],["sqrt",p],["floor",p],["ceil",p],["log",p],["pow",p],["sin",p],["cos",p],["tan",p],["fabs",p],["factorial",p]])}function Zs(){return W([["dumps",p],["loads",p]])}function Js(){return W([["match",p],["search",p],["findall",p],["sub",p],["split",p],["compile",p]])}var Xr={os:qs,sys:()=>Ks(),math:()=>Gs(),json:()=>Zs(),re:()=>Js(),random:()=>W([["random",p],["randint",p],["choice",p],["shuffle",p]]),time:()=>W([["time",p],["sleep",p],["ctime",p]]),datetime:()=>W([["datetime",p],["date",p],["timedelta",p]]),collections:()=>W([["Counter",p],["defaultdict",p],["OrderedDict",p]]),itertools:()=>W([["chain",p],["product",p],["combinations",p],["permutations",p]]),functools:()=>W([["reduce",p],["partial",p],["lru_cache",p]]),string:()=>W([["ascii_letters","abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"],["digits","0123456789"],["punctuation","!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"]])},Gt=class{constructor(t){this.cwd=t}cwd;output=[];stderr=[];modules=new Map;getOutput(){return this.output.join(`
231
232
  `)+(this.output.length?`
232
233
  `:"")}getStderr(){return this.stderr.join(`
233
234
  `)+(this.stderr.length?`
234
235
  `:"")}splitArgs(t){let e=[],n=0,i="",s=!1,o="";for(let a=0;a<t.length;a++){let l=t[a];s?(i+=l,l===o&&t[a-1]!=="\\"&&(s=!1)):l==='"'||l==="'"?(s=!0,o=l,i+=l):"([{".includes(l)?(n++,i+=l):")]}".includes(l)?(n--,i+=l):l===","&&n===0?(e.push(i.trim()),i=""):i+=l}return i.trim()&&e.push(i.trim()),e}pyEval(t,e){if(t=t.trim(),!t||t==="None")return p;if(t==="True")return!0;if(t==="False")return!1;if(t==="...")return p;if(/^-?\d+$/.test(t))return parseInt(t,10);if(/^-?\d+\.\d*$/.test(t))return parseFloat(t);if(/^0x[0-9a-fA-F]+$/.test(t))return parseInt(t,16);if(/^0o[0-7]+$/.test(t))return parseInt(t.slice(2),8);if(/^('''[\s\S]*'''|"""[\s\S]*""")$/.test(t))return t.slice(3,-3);if(/^(['"])(.*)\1$/s.test(t))return t.slice(1,-1).replace(/\\n/g,`
235
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\").replace(/\\'/g,"'").replace(/\\"/g,'"');let n=t.match(/^f(['"])([\s\S]*)\1$/);if(n){let c=n[2];return c=c.replace(/\{([^{}]+)\}/g,(u,d)=>{try{return M(this.pyEval(d.trim(),e))}catch{return`{${d}}`}}),c}let i=t.match(/^b(['"])(.*)\1$/s);if(i)return i[2];if(t.startsWith("[")&&t.endsWith("]")){let c=t.slice(1,-1).trim();if(!c)return[];let u=c.match(/^(.+?)\s+for\s+(\w+)\s+in\s+(.+?)(?:\s+if\s+(.+))?$/);if(u){let[,d,m,f,x]=u,g=K(this.pyEval(f.trim(),e)),y=[];for(let $ of g){let V=new Map(e);V.set(m,$),!(x&&!nt(this.pyEval(x,V)))&&y.push(this.pyEval(d.trim(),V))}return y}return this.splitArgs(c).map(d=>this.pyEval(d,e))}if(t.startsWith("(")&&t.endsWith(")")){let c=t.slice(1,-1).trim();if(!c)return[];let u=this.splitArgs(c);return u.length===1&&!c.endsWith(",")?this.pyEval(u[0],e):u.map(d=>this.pyEval(d,e))}if(t.startsWith("{")&&t.endsWith("}")){let c=t.slice(1,-1).trim();if(!c)return j();let u=j();for(let d of this.splitArgs(c)){let m=d.indexOf(":");if(m===-1)continue;let f=M(this.pyEval(d.slice(0,m).trim(),e)),x=this.pyEval(d.slice(m+1).trim(),e);u.data.set(f,x)}return u}let s=t.match(/^not\s+(.+)$/);if(s)return!nt(this.pyEval(s[1],e));let o=[["or"],["and"],["in","not in","is not","is","==","!=","<=",">=","<",">"],["+","-"],["**"],["*","//","/","%"]];for(let c of o){let u=this.tryBinaryOp(t,c,e);if(u!==void 0)return u}if(t.startsWith("-")){let c=this.pyEval(t.slice(1),e);if(typeof c=="number")return-c}if(process.env.PY_DEBUG&&console.error("eval:",JSON.stringify(t)),t.endsWith("]")&&!t.startsWith("[")){let c=this.findMatchingBracket(t,"[");if(c!==-1){let u=this.pyEval(t.slice(0,c),e),d=t.slice(c+1,-1);return this.subscript(u,d,e)}}let a=t.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*\(([\s\S]*)\)$/);if(a){let[,c,u]=a,d=(u?.trim()?this.splitArgs(u):[]).map(m=>this.pyEval(m,e));return this.callBuiltin(c,d,e)}let l=this.findDotAccess(t);if(l){let{objExpr:c,attr:u,callPart:d}=l,m=this.pyEval(c,e);if(d!==void 0){let f=d.slice(1,-1),x=f.trim()?this.splitArgs(f).map(g=>this.pyEval(g,e)):[];return this.callMethod(m,u,x,e)}return this.getAttr(m,u,e)}if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)){if(e.has(t))return e.get(t);throw new U("NameError",`name '${t}' is not defined`)}if(/^[A-Za-z_][A-Za-z0-9_.]+$/.test(t)){let c=t.split("."),u=e.get(c[0])??(()=>{throw new U("NameError",`name '${c[0]}' is not defined`)})();for(let d of c.slice(1))u=this.getAttr(u,d,e);return u}return p}findMatchingBracket(t,e){let n=e==="["?"]":e==="("?")":"}",i=0;for(let s=t.length-1;s>=0;s--)if(t[s]===n&&i++,t[s]===e&&(i--,i===0))return s;return-1}findDotAccess(t){let e=0,n=!1,i="";for(let s=t.length-1;s>0;s--){let o=t[s];if(n){o===i&&t[s-1]!=="\\"&&(n=!1);continue}if(o==='"'||o==="'"){n=!0,i=o;continue}if(")]}".includes(o)){e++;continue}if("([{".includes(o)){e--;continue}if(e!==0||o!==".")continue;let a=t.slice(0,s).trim(),c=t.slice(s+1).match(/^(\w+)(\([\s\S]*\))?$/);if(c&&!/^-?\d+$/.test(a))return{objExpr:a,attr:c[1],callPart:c[2]}}return null}tryBinaryOp(t,e,n){let i=0,s=!1,o="";for(let a=t.length-1;a>=0;a--){let l=t[a];if(s){l===o&&t[a-1]!=="\\"&&(s=!1);continue}if(l==='"'||l==="'"){s=!0,o=l;continue}if(")]}".includes(l)){i++;continue}if("([{".includes(l)){i--;continue}if(i===0){for(let c of e)if(t.slice(a,a+c.length)===c){if(c==="*"&&(t[a+1]==="*"||t[a-1]==="*"))continue;let u=t[a-1],d=t[a+c.length];if(/^[a-z]/.test(c)&&(u&&/\w/.test(u)||d&&/\w/.test(d)))continue;let f=t.slice(0,a).trim(),x=t.slice(a+c.length).trim();if(!f||!x)continue;return this.applyBinaryOp(c,f,x,n)}}}}applyBinaryOp(t,e,n,i){if(t==="and"){let a=this.pyEval(e,i);return nt(a)?this.pyEval(n,i):a}if(t==="or"){let a=this.pyEval(e,i);return nt(a)?a:this.pyEval(n,i)}let s=this.pyEval(e,i),o=this.pyEval(n,i);switch(t){case"+":return typeof s=="string"&&typeof o=="string"?s+o:Array.isArray(s)&&Array.isArray(o)?[...s,...o]:s+o;case"-":return s-o;case"*":if(typeof s=="string"&&typeof o=="number")return s.repeat(o);if(Array.isArray(s)&&typeof o=="number"){let a=[];for(let l=0;l<o;l++)a.push(...s);return a}return s*o;case"/":{if(o===0)throw new U("ZeroDivisionError","division by zero");return s/o}case"//":{if(o===0)throw new U("ZeroDivisionError","integer division or modulo by zero");return Math.floor(s/o)}case"%":{if(typeof s=="string")return this.pyStringFormat(s,Array.isArray(o)?o:[o]);if(o===0)throw new U("ZeroDivisionError","integer division or modulo by zero");return s%o}case"**":return s**o;case"==":return G(s)===G(o)||s===o;case"!=":return G(s)!==G(o)&&s!==o;case"<":return s<o;case"<=":return s<=o;case">":return s>o;case">=":return s>=o;case"in":return this.pyIn(o,s);case"not in":return!this.pyIn(o,s);case"is":return s===o||gt(s)&&gt(o);case"is not":return!(s===o||gt(s)&&gt(o))}return p}pyIn(t,e){return typeof t=="string"?typeof e=="string"&&t.includes(e):Array.isArray(t)?t.some(n=>G(n)===G(e)):B(t)?t.data.has(M(e)):!1}subscript(t,e,n){if(e.includes(":")){let s=e.split(":").map(l=>l.trim()),o=s[0]?this.pyEval(s[0],n):void 0,a=s[1]?this.pyEval(s[1],n):void 0;return typeof t=="string"||Array.isArray(t)?t.slice(o,a):p}let i=this.pyEval(e,n);if(Array.isArray(t)){let s=i;return s<0&&(s=t.length+s),t[s]??p}if(typeof t=="string"){let s=i;return s<0&&(s=t.length+s),t[s]??p}if(B(t))return t.data.get(M(i))??p;throw new U("TypeError",`'${St(t)}' is not subscriptable`)}getAttr(t,e,n){return B(t)?t.data.has(e)?t.data.get(e):e==="path"&&t.path?t.path:p:Ft(t)?t.attrs.get(e)??p:typeof t=="string"?{__class__:{__pytype__:"class",name:"str"}}[e]??p:p}callMethod(t,e,n,i){if(typeof t=="string")switch(e){case"upper":return t.toUpperCase();case"lower":return t.toLowerCase();case"strip":return(n[0]?t.replace(new RegExp(`[${n[0]}]+`,"g"),""):t).trim();case"lstrip":return t.trimStart();case"rstrip":return t.trimEnd();case"split":return t.split(typeof n[0]=="string"?n[0]:/\s+/).filter((s,o)=>o>0||s!=="");case"splitlines":return t.split(`
236
- `);case"join":return K(n[0]??[]).map(M).join(t);case"replace":return t.replaceAll(M(n[0]??""),M(n[1]??""));case"startswith":return t.startsWith(M(n[0]??""));case"endswith":return t.endsWith(M(n[0]??""));case"find":return t.indexOf(M(n[0]??""));case"index":{let s=t.indexOf(M(n[0]??""));if(s===-1)throw new U("ValueError","substring not found");return s}case"count":return t.split(M(n[0]??"")).length-1;case"format":return this.pyStringFormat(t,n);case"encode":return t;case"decode":return t;case"isdigit":return/^\d+$/.test(t);case"isalpha":return/^[a-zA-Z]+$/.test(t);case"isalnum":return/^[a-zA-Z0-9]+$/.test(t);case"isspace":return/^\s+$/.test(t);case"isupper":return t===t.toUpperCase()&&t!==t.toLowerCase();case"islower":return t===t.toLowerCase()&&t!==t.toUpperCase();case"center":{let s=n[0]??0,o=M(n[1]??" ");return t.padStart(Math.floor((s+t.length)/2),o).padEnd(s,o)}case"ljust":return t.padEnd(n[0]??0,M(n[1]??" "));case"rjust":return t.padStart(n[0]??0,M(n[1]??" "));case"zfill":return t.padStart(n[0]??0,"0");case"title":return t.replace(/\b\w/g,s=>s.toUpperCase());case"capitalize":return t[0]?.toUpperCase()+t.slice(1).toLowerCase();case"swapcase":return[...t].map(s=>s===s.toUpperCase()?s.toLowerCase():s.toUpperCase()).join("")}if(Array.isArray(t))switch(e){case"append":return t.push(n[0]??p),p;case"extend":for(let s of K(n[0]??[]))t.push(s);return p;case"insert":return t.splice(n[0]??0,0,n[1]??p),p;case"pop":{let s=n[0]!==void 0?n[0]:-1,o=s<0?t.length+s:s;return t.splice(o,1)[0]??p}case"remove":{let s=t.findIndex(o=>G(o)===G(n[0]??p));return s!==-1&&t.splice(s,1),p}case"index":{let s=t.findIndex(o=>G(o)===G(n[0]??p));if(s===-1)throw new U("ValueError","is not in list");return s}case"count":return t.filter(s=>G(s)===G(n[0]??p)).length;case"sort":return t.sort((s,o)=>typeof s=="number"&&typeof o=="number"?s-o:M(s).localeCompare(M(o))),p;case"reverse":return t.reverse(),p;case"copy":return[...t];case"clear":return t.splice(0),p}if(B(t))switch(e){case"keys":return[...t.data.keys()];case"values":return[...t.data.values()];case"items":return[...t.data.entries()].map(([s,o])=>[s,o]);case"get":return t.data.get(M(n[0]??""))??n[1]??p;case"update":{if(B(n[0]??p))for(let[s,o]of n[0].data)t.data.set(s,o);return p}case"pop":{let s=M(n[0]??""),o=t.data.get(s)??n[1]??p;return t.data.delete(s),o}case"clear":return t.data.clear(),p;case"copy":return j([...t.data.entries()]);case"setdefault":{let s=M(n[0]??"");return t.data.has(s)||t.data.set(s,n[1]??p),t.data.get(s)??p}}if(B(t)&&t.data.has("name")&&t.data.get("name")==="posix")switch(e){case"getcwd":return this.cwd;case"getenv":return typeof n[0]=="string"?process.env[n[0]]??n[1]??p:p;case"listdir":return[];case"path":return t}if(B(t))switch(e){case"join":return n.map(M).join("/").replace(/\/+/g,"/");case"exists":return!1;case"dirname":return M(n[0]??"").split("/").slice(0,-1).join("/")||"/";case"basename":return M(n[0]??"").split("/").pop()??"";case"abspath":return M(n[0]??"");case"splitext":{let s=M(n[0]??""),o=s.lastIndexOf(".");return o>0?[s.slice(0,o),s.slice(o)]:[s,""]}case"isfile":return!1;case"isdir":return!1}if(B(t)&&t.data.has("version")&&t.data.get("version")===Kt&&e==="exit")throw new Vt(n[0]??0);if(B(t)){let s={sqrt:Math.sqrt,floor:Math.floor,ceil:Math.ceil,fabs:Math.abs,log:Math.log,log2:Math.log2,log10:Math.log10,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,pow:Math.pow,exp:Math.exp,hypot:Math.hypot};if(e in s){let o=s[e];return o(...n.map(a=>a))}if(e==="factorial"){let o=n[0]??0,a=1;for(;o>1;)a*=o--;return a}if(e==="gcd"){let o=Math.abs(n[0]??0),a=Math.abs(n[1]??0);for(;a;)[o,a]=[a,o%a];return o}}if(B(t)){if(e==="dumps"){let s=B(n[1]??p)?n[1]:void 0,o=s?s.data.get("indent"):void 0;return JSON.stringify(this.pyToJs(n[0]??p),null,o)}if(e==="loads")return this.jsToPy(JSON.parse(M(n[0]??"")))}if(Ft(t)){let s=t.attrs.get(e)??t.cls.methods.get(e)??p;if(dt(s)){let o=new Map(s.closure);return o.set("self",t),s.params.slice(1).forEach((a,l)=>o.set(a,n[l]??p)),this.execBlock(s.body,o)}}throw new U("AttributeError",`'${St(t)}' object has no attribute '${e}'`)}pyStringFormat(t,e){let n=0;return t.replace(/%([diouxXeEfFgGcrs%])/g,(i,s)=>{if(s==="%")return"%";let o=e[n++];switch(s){case"d":case"i":return String(Math.trunc(o));case"f":return o.toFixed(6);case"s":return M(o??p);case"r":return G(o??p);default:return String(o)}})}pyToJs(t){return gt(t)?null:B(t)?Object.fromEntries([...t.data.entries()].map(([e,n])=>[e,this.pyToJs(n)])):Array.isArray(t)?t.map(e=>this.pyToJs(e)):t}jsToPy(t){return t==null?p:typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:Array.isArray(t)?t.map(e=>this.jsToPy(e)):typeof t=="object"?j(Object.entries(t).map(([e,n])=>[e,this.jsToPy(n)])):p}callBuiltin(t,e,n){if(n.has(t)){let i=n.get(t)??p;return dt(i)?this.callFunc(i,e,n):me(i)?this.instantiate(i,e,n):i}switch(t){case"print":return this.output.push(e.map(M).join(" ")+`
237
- `.replace(/\\n/g,"")),p;case"input":return this.output.push(M(e[0]??"")),"";case"int":{if(e.length===0)return 0;let i=e[1]??10,s=parseInt(M(e[0]??0),i);return Number.isNaN(s)?(()=>{throw new U("ValueError","invalid literal for int()")})():s}case"float":{if(e.length===0)return 0;let i=parseFloat(M(e[0]??0));return Number.isNaN(i)?(()=>{throw new U("ValueError","could not convert to float")})():i}case"str":return e.length===0?"":M(e[0]??p);case"bool":return e.length===0?!1:nt(e[0]??p);case"list":return e.length===0?[]:K(e[0]??[]);case"tuple":return e.length===0?[]:K(e[0]??[]);case"set":return e.length===0?[]:[...new Set(K(e[0]??[]).map(G))].map(i=>K(e[0]??[]).find(o=>G(o)===i)??p);case"dict":return e.length===0?j():B(e[0]??p)?e[0]:j();case"bytes":return typeof e[0]=="string"?e[0]:M(e[0]??"");case"bytearray":return e.length===0?"":M(e[0]??"");case"type":return e.length===1?`<class '${St(e[0]??p)}'>`:p;case"isinstance":return St(e[0]??p)===M(e[1]??"");case"issubclass":return!1;case"callable":return dt(e[0]??p);case"hasattr":return B(e[0]??p)?e[0].data.has(M(e[1]??"")):!1;case"getattr":return B(e[0]??p)?e[0].data.get(M(e[1]??""))??e[2]??p:e[2]??p;case"setattr":return B(e[0]??p)&&e[0].data.set(M(e[1]??""),e[2]??p),p;case"len":{let i=e[0]??p;if(typeof i=="string"||Array.isArray(i))return i.length;if(B(i))return i.data.size;if($t(i))return tn(i);throw new U("TypeError",`object of type '${St(i)}' has no len()`)}case"range":return e.length===1?de(0,e[0]):e.length===2?de(e[0],e[1]):de(e[0],e[1],e[2]);case"enumerate":{let i=e[1]??0;return K(e[0]??[]).map((s,o)=>[o+i,s])}case"zip":{let i=e.map(K),s=Math.min(...i.map(o=>o.length));return Array.from({length:s},(o,a)=>i.map(l=>l[a]??p))}case"map":{let i=e[0]??p;return K(e[1]??[]).map(s=>dt(i)?this.callFunc(i,[s],n):p)}case"filter":{let i=e[0]??p;return K(e[1]??[]).filter(s=>dt(i)?nt(this.callFunc(i,[s],n)):nt(s))}case"reduce":{let i=e[0]??p,s=K(e[1]??[]);if(s.length===0)return e[2]??p;let o=e[2]!==void 0?e[2]:s[0];for(let a of e[2]!==void 0?s:s.slice(1))o=dt(i)?this.callFunc(i,[o,a],n):p;return o}case"sorted":{let i=[...K(e[0]??[])],s=e[1]??p,o=B(s)?s.data.get("key")??p:s;return i.sort((a,l)=>{let c=dt(o)?this.callFunc(o,[a],n):a,u=dt(o)?this.callFunc(o,[l],n):l;return typeof c=="number"&&typeof u=="number"?c-u:M(c).localeCompare(M(u))}),i}case"reversed":return[...K(e[0]??[])].reverse();case"any":return K(e[0]??[]).some(nt);case"all":return K(e[0]??[]).every(nt);case"sum":return K(e[0]??[]).reduce((i,s)=>i+s,e[1]??0);case"max":return(e.length===1?K(e[0]??[]):e).reduce((s,o)=>s>=o?s:o);case"min":return(e.length===1?K(e[0]??[]):e).reduce((s,o)=>s<=o?s:o);case"abs":return Math.abs(e[0]??0);case"round":return e[1]!==void 0?parseFloat(e[0].toFixed(e[1])):Math.round(e[0]??0);case"divmod":{let i=e[0],s=e[1];return[Math.floor(i/s),i%s]}case"pow":return e[0]**e[1];case"hex":return`0x${e[0].toString(16)}`;case"oct":return`0o${e[0].toString(8)}`;case"bin":return`0b${e[0].toString(2)}`;case"ord":return M(e[0]??"").charCodeAt(0);case"chr":return String.fromCharCode(e[0]??0);case"id":return Math.floor(Math.random()*4294967295);case"hash":return typeof e[0]=="number"?e[0]:M(e[0]??"").split("").reduce((i,s)=>i*31+s.charCodeAt(0)|0,0);case"open":throw new U("PermissionError","open() not available in virtual runtime");case"repr":return G(e[0]??p);case"iter":return e[0]??p;case"next":return Array.isArray(e[0])&&e[0].length>0?e[0].shift():e[1]??(()=>{throw new U("StopIteration","")})();case"vars":return j([...n.entries()].map(([i,s])=>[i,s]));case"globals":return j([...n.entries()].map(([i,s])=>[i,s]));case"locals":return j([...n.entries()].map(([i,s])=>[i,s]));case"dir":{if(e.length===0)return[...n.keys()];let i=e[0]??p;return typeof i=="string"?["upper","lower","strip","split","join","replace","find","format","encode","startswith","endswith","count","isdigit","isalpha","title","capitalize"]:Array.isArray(i)?["append","extend","insert","pop","remove","index","count","sort","reverse","copy","clear"]:B(i)?["keys","values","items","get","update","pop","clear","copy","setdefault"]:[]}case"Exception":case"ValueError":case"TypeError":case"KeyError":case"IndexError":case"AttributeError":case"NameError":case"RuntimeError":case"StopIteration":case"NotImplementedError":case"OSError":case"IOError":throw new U(t,M(e[0]??""));case"exec":return this.execScript(M(e[0]??""),n),p;case"eval":return this.pyEval(M(e[0]??""),n);default:throw new U("NameError",`name '${t}' is not defined`)}}callFunc(t,e,n){let i=new Map(t.closure);t.params.forEach((s,o)=>{if(s.startsWith("*")){i.set(s.slice(1),e.slice(o));return}i.set(s,e[o]??p)});try{return this.execBlock(t.body,i)}catch(s){if(s instanceof Ct)return s.value;throw s}}instantiate(t,e,n){let i={__pytype__:"instance",cls:t,attrs:new Map};return t.methods.get("__init__")&&this.callMethod(i,"__init__",e,n),i}execScript(t,e){let n=t.split(`
236
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\").replace(/\\'/g,"'").replace(/\\"/g,'"');let n=t.match(/^f(['"])([\s\S]*)\1$/);if(n){let c=n[2];return c=c.replace(/\{([^{}]+)\}/g,(u,d)=>{try{return M(this.pyEval(d.trim(),e))}catch{return`{${d}}`}}),c}let i=t.match(/^b(['"])(.*)\1$/s);if(i)return i[2];if(t.startsWith("[")&&t.endsWith("]")){let c=t.slice(1,-1).trim();if(!c)return[];let u=c.match(/^(.+?)\s+for\s+(\w+)\s+in\s+(.+?)(?:\s+if\s+(.+))?$/);if(u){let[,d,m,f,x]=u,g=K(this.pyEval(f.trim(),e)),y=[];for(let $ of g){let V=new Map(e);V.set(m,$),!(x&&!nt(this.pyEval(x,V)))&&y.push(this.pyEval(d.trim(),V))}return y}return this.splitArgs(c).map(d=>this.pyEval(d,e))}if(t.startsWith("(")&&t.endsWith(")")){let c=t.slice(1,-1).trim();if(!c)return[];let u=this.splitArgs(c);return u.length===1&&!c.endsWith(",")?this.pyEval(u[0],e):u.map(d=>this.pyEval(d,e))}if(t.startsWith("{")&&t.endsWith("}")){let c=t.slice(1,-1).trim();if(!c)return W();let u=W();for(let d of this.splitArgs(c)){let m=d.indexOf(":");if(m===-1)continue;let f=M(this.pyEval(d.slice(0,m).trim(),e)),x=this.pyEval(d.slice(m+1).trim(),e);u.data.set(f,x)}return u}let s=t.match(/^not\s+(.+)$/);if(s)return!nt(this.pyEval(s[1],e));let o=[["or"],["and"],["in","not in","is not","is","==","!=","<=",">=","<",">"],["+","-"],["**"],["*","//","/","%"]];for(let c of o){let u=this.tryBinaryOp(t,c,e);if(u!==void 0)return u}if(t.startsWith("-")){let c=this.pyEval(t.slice(1),e);if(typeof c=="number")return-c}if(process.env.PY_DEBUG&&console.error("eval:",JSON.stringify(t)),t.endsWith("]")&&!t.startsWith("[")){let c=this.findMatchingBracket(t,"[");if(c!==-1){let u=this.pyEval(t.slice(0,c),e),d=t.slice(c+1,-1);return this.subscript(u,d,e)}}let a=t.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*\(([\s\S]*)\)$/);if(a){let[,c,u]=a,d=(u?.trim()?this.splitArgs(u):[]).map(m=>this.pyEval(m,e));return this.callBuiltin(c,d,e)}let l=this.findDotAccess(t);if(l){let{objExpr:c,attr:u,callPart:d}=l,m=this.pyEval(c,e);if(d!==void 0){let f=d.slice(1,-1),x=f.trim()?this.splitArgs(f).map(g=>this.pyEval(g,e)):[];return this.callMethod(m,u,x,e)}return this.getAttr(m,u,e)}if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)){if(e.has(t))return e.get(t);throw new U("NameError",`name '${t}' is not defined`)}if(/^[A-Za-z_][A-Za-z0-9_.]+$/.test(t)){let c=t.split("."),u=e.get(c[0])??(()=>{throw new U("NameError",`name '${c[0]}' is not defined`)})();for(let d of c.slice(1))u=this.getAttr(u,d,e);return u}return p}findMatchingBracket(t,e){let n=e==="["?"]":e==="("?")":"}",i=0;for(let s=t.length-1;s>=0;s--)if(t[s]===n&&i++,t[s]===e&&(i--,i===0))return s;return-1}findDotAccess(t){let e=0,n=!1,i="";for(let s=t.length-1;s>0;s--){let o=t[s];if(n){o===i&&t[s-1]!=="\\"&&(n=!1);continue}if(o==='"'||o==="'"){n=!0,i=o;continue}if(")]}".includes(o)){e++;continue}if("([{".includes(o)){e--;continue}if(e!==0||o!==".")continue;let a=t.slice(0,s).trim(),c=t.slice(s+1).match(/^(\w+)(\([\s\S]*\))?$/);if(c&&!/^-?\d+$/.test(a))return{objExpr:a,attr:c[1],callPart:c[2]}}return null}tryBinaryOp(t,e,n){let i=0,s=!1,o="";for(let a=t.length-1;a>=0;a--){let l=t[a];if(s){l===o&&t[a-1]!=="\\"&&(s=!1);continue}if(l==='"'||l==="'"){s=!0,o=l;continue}if(")]}".includes(l)){i++;continue}if("([{".includes(l)){i--;continue}if(i===0){for(let c of e)if(t.slice(a,a+c.length)===c){if(c==="*"&&(t[a+1]==="*"||t[a-1]==="*"))continue;let u=t[a-1],d=t[a+c.length];if(/^[a-z]/.test(c)&&(u&&/\w/.test(u)||d&&/\w/.test(d)))continue;let f=t.slice(0,a).trim(),x=t.slice(a+c.length).trim();if(!f||!x)continue;return this.applyBinaryOp(c,f,x,n)}}}}applyBinaryOp(t,e,n,i){if(t==="and"){let a=this.pyEval(e,i);return nt(a)?this.pyEval(n,i):a}if(t==="or"){let a=this.pyEval(e,i);return nt(a)?a:this.pyEval(n,i)}let s=this.pyEval(e,i),o=this.pyEval(n,i);switch(t){case"+":return typeof s=="string"&&typeof o=="string"?s+o:Array.isArray(s)&&Array.isArray(o)?[...s,...o]:s+o;case"-":return s-o;case"*":if(typeof s=="string"&&typeof o=="number")return s.repeat(o);if(Array.isArray(s)&&typeof o=="number"){let a=[];for(let l=0;l<o;l++)a.push(...s);return a}return s*o;case"/":{if(o===0)throw new U("ZeroDivisionError","division by zero");return s/o}case"//":{if(o===0)throw new U("ZeroDivisionError","integer division or modulo by zero");return Math.floor(s/o)}case"%":{if(typeof s=="string")return this.pyStringFormat(s,Array.isArray(o)?o:[o]);if(o===0)throw new U("ZeroDivisionError","integer division or modulo by zero");return s%o}case"**":return s**o;case"==":return G(s)===G(o)||s===o;case"!=":return G(s)!==G(o)&&s!==o;case"<":return s<o;case"<=":return s<=o;case">":return s>o;case">=":return s>=o;case"in":return this.pyIn(o,s);case"not in":return!this.pyIn(o,s);case"is":return s===o||gt(s)&&gt(o);case"is not":return!(s===o||gt(s)&&gt(o))}return p}pyIn(t,e){return typeof t=="string"?typeof e=="string"&&t.includes(e):Array.isArray(t)?t.some(n=>G(n)===G(e)):B(t)?t.data.has(M(e)):!1}subscript(t,e,n){if(e.includes(":")){let s=e.split(":").map(l=>l.trim()),o=s[0]?this.pyEval(s[0],n):void 0,a=s[1]?this.pyEval(s[1],n):void 0;return typeof t=="string"||Array.isArray(t)?t.slice(o,a):p}let i=this.pyEval(e,n);if(Array.isArray(t)){let s=i;return s<0&&(s=t.length+s),t[s]??p}if(typeof t=="string"){let s=i;return s<0&&(s=t.length+s),t[s]??p}if(B(t))return t.data.get(M(i))??p;throw new U("TypeError",`'${St(t)}' is not subscriptable`)}getAttr(t,e,n){return B(t)?t.data.has(e)?t.data.get(e):e==="path"&&t.path?t.path:p:Ft(t)?t.attrs.get(e)??p:typeof t=="string"?{__class__:{__pytype__:"class",name:"str"}}[e]??p:p}callMethod(t,e,n,i){if(typeof t=="string")switch(e){case"upper":return t.toUpperCase();case"lower":return t.toLowerCase();case"strip":return(n[0]?t.replace(new RegExp(`[${n[0]}]+`,"g"),""):t).trim();case"lstrip":return t.trimStart();case"rstrip":return t.trimEnd();case"split":return t.split(typeof n[0]=="string"?n[0]:/\s+/).filter((s,o)=>o>0||s!=="");case"splitlines":return t.split(`
237
+ `);case"join":return K(n[0]??[]).map(M).join(t);case"replace":return t.replaceAll(M(n[0]??""),M(n[1]??""));case"startswith":return t.startsWith(M(n[0]??""));case"endswith":return t.endsWith(M(n[0]??""));case"find":return t.indexOf(M(n[0]??""));case"index":{let s=t.indexOf(M(n[0]??""));if(s===-1)throw new U("ValueError","substring not found");return s}case"count":return t.split(M(n[0]??"")).length-1;case"format":return this.pyStringFormat(t,n);case"encode":return t;case"decode":return t;case"isdigit":return/^\d+$/.test(t);case"isalpha":return/^[a-zA-Z]+$/.test(t);case"isalnum":return/^[a-zA-Z0-9]+$/.test(t);case"isspace":return/^\s+$/.test(t);case"isupper":return t===t.toUpperCase()&&t!==t.toLowerCase();case"islower":return t===t.toLowerCase()&&t!==t.toUpperCase();case"center":{let s=n[0]??0,o=M(n[1]??" ");return t.padStart(Math.floor((s+t.length)/2),o).padEnd(s,o)}case"ljust":return t.padEnd(n[0]??0,M(n[1]??" "));case"rjust":return t.padStart(n[0]??0,M(n[1]??" "));case"zfill":return t.padStart(n[0]??0,"0");case"title":return t.replace(/\b\w/g,s=>s.toUpperCase());case"capitalize":return t[0]?.toUpperCase()+t.slice(1).toLowerCase();case"swapcase":return[...t].map(s=>s===s.toUpperCase()?s.toLowerCase():s.toUpperCase()).join("")}if(Array.isArray(t))switch(e){case"append":return t.push(n[0]??p),p;case"extend":for(let s of K(n[0]??[]))t.push(s);return p;case"insert":return t.splice(n[0]??0,0,n[1]??p),p;case"pop":{let s=n[0]!==void 0?n[0]:-1,o=s<0?t.length+s:s;return t.splice(o,1)[0]??p}case"remove":{let s=t.findIndex(o=>G(o)===G(n[0]??p));return s!==-1&&t.splice(s,1),p}case"index":{let s=t.findIndex(o=>G(o)===G(n[0]??p));if(s===-1)throw new U("ValueError","is not in list");return s}case"count":return t.filter(s=>G(s)===G(n[0]??p)).length;case"sort":return t.sort((s,o)=>typeof s=="number"&&typeof o=="number"?s-o:M(s).localeCompare(M(o))),p;case"reverse":return t.reverse(),p;case"copy":return[...t];case"clear":return t.splice(0),p}if(B(t))switch(e){case"keys":return[...t.data.keys()];case"values":return[...t.data.values()];case"items":return[...t.data.entries()].map(([s,o])=>[s,o]);case"get":return t.data.get(M(n[0]??""))??n[1]??p;case"update":{if(B(n[0]??p))for(let[s,o]of n[0].data)t.data.set(s,o);return p}case"pop":{let s=M(n[0]??""),o=t.data.get(s)??n[1]??p;return t.data.delete(s),o}case"clear":return t.data.clear(),p;case"copy":return W([...t.data.entries()]);case"setdefault":{let s=M(n[0]??"");return t.data.has(s)||t.data.set(s,n[1]??p),t.data.get(s)??p}}if(B(t)&&t.data.has("name")&&t.data.get("name")==="posix")switch(e){case"getcwd":return this.cwd;case"getenv":return typeof n[0]=="string"?process.env[n[0]]??n[1]??p:p;case"listdir":return[];case"path":return t}if(B(t))switch(e){case"join":return n.map(M).join("/").replace(/\/+/g,"/");case"exists":return!1;case"dirname":return M(n[0]??"").split("/").slice(0,-1).join("/")||"/";case"basename":return M(n[0]??"").split("/").pop()??"";case"abspath":return M(n[0]??"");case"splitext":{let s=M(n[0]??""),o=s.lastIndexOf(".");return o>0?[s.slice(0,o),s.slice(o)]:[s,""]}case"isfile":return!1;case"isdir":return!1}if(B(t)&&t.data.has("version")&&t.data.get("version")===Kt&&e==="exit")throw new Vt(n[0]??0);if(B(t)){let s={sqrt:Math.sqrt,floor:Math.floor,ceil:Math.ceil,fabs:Math.abs,log:Math.log,log2:Math.log2,log10:Math.log10,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,pow:Math.pow,exp:Math.exp,hypot:Math.hypot};if(e in s){let o=s[e];return o(...n.map(a=>a))}if(e==="factorial"){let o=n[0]??0,a=1;for(;o>1;)a*=o--;return a}if(e==="gcd"){let o=Math.abs(n[0]??0),a=Math.abs(n[1]??0);for(;a;)[o,a]=[a,o%a];return o}}if(B(t)){if(e==="dumps"){let s=B(n[1]??p)?n[1]:void 0,o=s?s.data.get("indent"):void 0;return JSON.stringify(this.pyToJs(n[0]??p),null,o)}if(e==="loads")return this.jsToPy(JSON.parse(M(n[0]??"")))}if(Ft(t)){let s=t.attrs.get(e)??t.cls.methods.get(e)??p;if(dt(s)){let o=new Map(s.closure);return o.set("self",t),s.params.slice(1).forEach((a,l)=>o.set(a,n[l]??p)),this.execBlock(s.body,o)}}throw new U("AttributeError",`'${St(t)}' object has no attribute '${e}'`)}pyStringFormat(t,e){let n=0;return t.replace(/%([diouxXeEfFgGcrs%])/g,(i,s)=>{if(s==="%")return"%";let o=e[n++];switch(s){case"d":case"i":return String(Math.trunc(o));case"f":return o.toFixed(6);case"s":return M(o??p);case"r":return G(o??p);default:return String(o)}})}pyToJs(t){return gt(t)?null:B(t)?Object.fromEntries([...t.data.entries()].map(([e,n])=>[e,this.pyToJs(n)])):Array.isArray(t)?t.map(e=>this.pyToJs(e)):t}jsToPy(t){return t==null?p:typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:Array.isArray(t)?t.map(e=>this.jsToPy(e)):typeof t=="object"?W(Object.entries(t).map(([e,n])=>[e,this.jsToPy(n)])):p}callBuiltin(t,e,n){if(n.has(t)){let i=n.get(t)??p;return dt(i)?this.callFunc(i,e,n):me(i)?this.instantiate(i,e,n):i}switch(t){case"print":return this.output.push(e.map(M).join(" ")+`
238
+ `.replace(/\\n/g,"")),p;case"input":return this.output.push(M(e[0]??"")),"";case"int":{if(e.length===0)return 0;let i=e[1]??10,s=parseInt(M(e[0]??0),i);return Number.isNaN(s)?(()=>{throw new U("ValueError","invalid literal for int()")})():s}case"float":{if(e.length===0)return 0;let i=parseFloat(M(e[0]??0));return Number.isNaN(i)?(()=>{throw new U("ValueError","could not convert to float")})():i}case"str":return e.length===0?"":M(e[0]??p);case"bool":return e.length===0?!1:nt(e[0]??p);case"list":return e.length===0?[]:K(e[0]??[]);case"tuple":return e.length===0?[]:K(e[0]??[]);case"set":return e.length===0?[]:[...new Set(K(e[0]??[]).map(G))].map(i=>K(e[0]??[]).find(o=>G(o)===i)??p);case"dict":return e.length===0?W():B(e[0]??p)?e[0]:W();case"bytes":return typeof e[0]=="string"?e[0]:M(e[0]??"");case"bytearray":return e.length===0?"":M(e[0]??"");case"type":return e.length===1?`<class '${St(e[0]??p)}'>`:p;case"isinstance":return St(e[0]??p)===M(e[1]??"");case"issubclass":return!1;case"callable":return dt(e[0]??p);case"hasattr":return B(e[0]??p)?e[0].data.has(M(e[1]??"")):!1;case"getattr":return B(e[0]??p)?e[0].data.get(M(e[1]??""))??e[2]??p:e[2]??p;case"setattr":return B(e[0]??p)&&e[0].data.set(M(e[1]??""),e[2]??p),p;case"len":{let i=e[0]??p;if(typeof i=="string"||Array.isArray(i))return i.length;if(B(i))return i.data.size;if($t(i))return tn(i);throw new U("TypeError",`object of type '${St(i)}' has no len()`)}case"range":return e.length===1?de(0,e[0]):e.length===2?de(e[0],e[1]):de(e[0],e[1],e[2]);case"enumerate":{let i=e[1]??0;return K(e[0]??[]).map((s,o)=>[o+i,s])}case"zip":{let i=e.map(K),s=Math.min(...i.map(o=>o.length));return Array.from({length:s},(o,a)=>i.map(l=>l[a]??p))}case"map":{let i=e[0]??p;return K(e[1]??[]).map(s=>dt(i)?this.callFunc(i,[s],n):p)}case"filter":{let i=e[0]??p;return K(e[1]??[]).filter(s=>dt(i)?nt(this.callFunc(i,[s],n)):nt(s))}case"reduce":{let i=e[0]??p,s=K(e[1]??[]);if(s.length===0)return e[2]??p;let o=e[2]!==void 0?e[2]:s[0];for(let a of e[2]!==void 0?s:s.slice(1))o=dt(i)?this.callFunc(i,[o,a],n):p;return o}case"sorted":{let i=[...K(e[0]??[])],s=e[1]??p,o=B(s)?s.data.get("key")??p:s;return i.sort((a,l)=>{let c=dt(o)?this.callFunc(o,[a],n):a,u=dt(o)?this.callFunc(o,[l],n):l;return typeof c=="number"&&typeof u=="number"?c-u:M(c).localeCompare(M(u))}),i}case"reversed":return[...K(e[0]??[])].reverse();case"any":return K(e[0]??[]).some(nt);case"all":return K(e[0]??[]).every(nt);case"sum":return K(e[0]??[]).reduce((i,s)=>i+s,e[1]??0);case"max":return(e.length===1?K(e[0]??[]):e).reduce((s,o)=>s>=o?s:o);case"min":return(e.length===1?K(e[0]??[]):e).reduce((s,o)=>s<=o?s:o);case"abs":return Math.abs(e[0]??0);case"round":return e[1]!==void 0?parseFloat(e[0].toFixed(e[1])):Math.round(e[0]??0);case"divmod":{let i=e[0],s=e[1];return[Math.floor(i/s),i%s]}case"pow":return e[0]**e[1];case"hex":return`0x${e[0].toString(16)}`;case"oct":return`0o${e[0].toString(8)}`;case"bin":return`0b${e[0].toString(2)}`;case"ord":return M(e[0]??"").charCodeAt(0);case"chr":return String.fromCharCode(e[0]??0);case"id":return Math.floor(Math.random()*4294967295);case"hash":return typeof e[0]=="number"?e[0]:M(e[0]??"").split("").reduce((i,s)=>i*31+s.charCodeAt(0)|0,0);case"open":throw new U("PermissionError","open() not available in virtual runtime");case"repr":return G(e[0]??p);case"iter":return e[0]??p;case"next":return Array.isArray(e[0])&&e[0].length>0?e[0].shift():e[1]??(()=>{throw new U("StopIteration","")})();case"vars":return W([...n.entries()].map(([i,s])=>[i,s]));case"globals":return W([...n.entries()].map(([i,s])=>[i,s]));case"locals":return W([...n.entries()].map(([i,s])=>[i,s]));case"dir":{if(e.length===0)return[...n.keys()];let i=e[0]??p;return typeof i=="string"?["upper","lower","strip","split","join","replace","find","format","encode","startswith","endswith","count","isdigit","isalpha","title","capitalize"]:Array.isArray(i)?["append","extend","insert","pop","remove","index","count","sort","reverse","copy","clear"]:B(i)?["keys","values","items","get","update","pop","clear","copy","setdefault"]:[]}case"Exception":case"ValueError":case"TypeError":case"KeyError":case"IndexError":case"AttributeError":case"NameError":case"RuntimeError":case"StopIteration":case"NotImplementedError":case"OSError":case"IOError":throw new U(t,M(e[0]??""));case"exec":return this.execScript(M(e[0]??""),n),p;case"eval":return this.pyEval(M(e[0]??""),n);default:throw new U("NameError",`name '${t}' is not defined`)}}callFunc(t,e,n){let i=new Map(t.closure);t.params.forEach((s,o)=>{if(s.startsWith("*")){i.set(s.slice(1),e.slice(o));return}i.set(s,e[o]??p)});try{return this.execBlock(t.body,i)}catch(s){if(s instanceof Ct)return s.value;throw s}}instantiate(t,e,n){let i={__pytype__:"instance",cls:t,attrs:new Map};return t.methods.get("__init__")&&this.callMethod(i,"__init__",e,n),i}execScript(t,e){let n=t.split(`
238
239
  `);this.execLines(n,0,e)}execLines(t,e,n){let i=e;for(;i<t.length;){let s=t[i];if(!s.trim()||s.trim().startsWith("#")){i++;continue}i=this.execStatement(t,i,n)}return i}execBlock(t,e){try{this.execLines(t,0,e)}catch(n){if(n instanceof Ct)return n.value;throw n}return p}getIndent(t){let e=0;for(let n of t)if(n===" ")e++;else if(n===" ")e+=4;else break;return e}collectBlock(t,e,n){let i=[];for(let s=e;s<t.length;s++){let o=t[s];if(!o.trim()){i.push("");continue}if(this.getIndent(o)<=n)break;i.push(o.slice(n+4))}return i}execStatement(t,e,n){let i=t[e],s=i.trim(),o=this.getIndent(i);if(s==="pass")return e+1;if(s==="break")throw new Nt;if(s==="continue")throw new It;let a=s.match(/^return(?:\s+(.+))?$/);if(a)throw new Ct(a[1]?this.pyEval(a[1],n):p);let l=s.match(/^raise(?:\s+(.+))?$/);if(l){if(l[1]){let w=this.pyEval(l[1],n);throw new U(typeof w=="string"?w:St(w),M(w))}throw new U("RuntimeError","")}let c=s.match(/^assert\s+(.+?)(?:,\s*(.+))?$/);if(c){if(!nt(this.pyEval(c[1],n)))throw new U("AssertionError",c[2]?M(this.pyEval(c[2],n)):"");return e+1}let u=s.match(/^del\s+(.+)$/);if(u)return n.delete(u[1].trim()),e+1;let d=s.match(/^import\s+(\w+)(?:\s+as\s+(\w+))?$/);if(d){let[,w,E]=d,T=Xr[w];if(T){let b=T(this.cwd);this.modules.set(w,b),n.set(E??w,b)}return e+1}let m=s.match(/^from\s+(\w+)\s+import\s+(.+)$/);if(m){let[,w,E]=m,T=Xr[w];if(T){let b=T(this.cwd);if(E?.trim()==="*")for(let[P,I]of b.data)n.set(P,I);else for(let P of E.split(",").map(I=>I.trim()))n.set(P,b.data.get(P)??p)}return e+1}let f=s.match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(f){let[,w,E]=f,T=E.split(",").map(I=>I.trim()).filter(Boolean),b=this.collectBlock(t,e+1,o),P={__pytype__:"func",name:w,params:T,body:b,closure:new Map(n)};return n.set(w,P),e+1+b.length}let x=s.match(/^class\s+(\w+)(?:\(([^)]*)\))?\s*:$/);if(x){let[,w,E]=x,T=E?E.split(",").map(H=>H.trim()):[],b=this.collectBlock(t,e+1,o),P={__pytype__:"class",name:w,methods:new Map,bases:T},I=0;for(;I<b.length;){let z=b[I].trim().match(/^def\s+(\w+)\s*\(([^)]*)\)\s*:$/);if(z){let[,q,ft]=z,ot=ft.split(",").map(C=>C.trim()).filter(Boolean),ht=this.collectBlock(b,I+1,0);P.methods.set(q,{__pytype__:"func",name:q,params:ot,body:ht,closure:new Map(n)}),I+=1+ht.length}else I++}return n.set(w,P),e+1+b.length}if(s.startsWith("if ")&&s.endsWith(":")){let w=s.slice(3,-1).trim(),E=this.collectBlock(t,e+1,o),T=E.length+1;if(nt(this.pyEval(w,n))){this.execBlock(E,new Map(n).also?.(I=>{for(let[H,z]of n)I.set(H,z)})??n),this.runBlockInScope(E,n);let P=e+1+E.length;for(;P<t.length;){let I=t[P].trim();if(this.getIndent(t[P])<o||!I.startsWith("elif")&&!I.startsWith("else"))break;let H=this.collectBlock(t,P+1,o);P+=1+H.length}return P}let b=e+1+E.length;for(;b<t.length;){let P=t[b],I=P.trim();if(this.getIndent(P)!==o)break;let H=I.match(/^elif\s+(.+):$/);if(H){let z=this.collectBlock(t,b+1,o);if(nt(this.pyEval(H[1],n))){for(this.runBlockInScope(z,n),b+=1+z.length;b<t.length;){let q=t[b].trim();if(this.getIndent(t[b])!==o||!q.startsWith("elif")&&!q.startsWith("else"))break;let ft=this.collectBlock(t,b+1,o);b+=1+ft.length}return b}b+=1+z.length;continue}if(I==="else:"){let z=this.collectBlock(t,b+1,o);return this.runBlockInScope(z,n),b+1+z.length}break}return b}let g=s.match(/^for\s+(.+?)\s+in\s+(.+?)\s*:$/);if(g){let[,w,E]=g,T=K(this.pyEval(E.trim(),n)),b=this.collectBlock(t,e+1,o),P=[],I=e+1+b.length;I<t.length&&t[I]?.trim()==="else:"&&(P=this.collectBlock(t,I+1,o),I+=1+P.length);let H=!1;for(let z of T){if(w.includes(",")){let q=w.split(",").map(ot=>ot.trim()),ft=Array.isArray(z)?z:[z];q.forEach((ot,ht)=>n.set(ot,ft[ht]??p))}else n.set(w.trim(),z);try{this.runBlockInScope(b,n)}catch(q){if(q instanceof Nt){H=!0;break}if(q instanceof It)continue;throw q}}return!H&&P.length&&this.runBlockInScope(P,n),I}let y=s.match(/^while\s+(.+?)\s*:$/);if(y){let w=y[1],E=this.collectBlock(t,e+1,o),T=0;for(;nt(this.pyEval(w,n))&&T++<1e5;)try{this.runBlockInScope(E,n)}catch(b){if(b instanceof Nt)break;if(b instanceof It)continue;throw b}return e+1+E.length}if(s==="try:"){let w=this.collectBlock(t,e+1,o),E=e+1+w.length,T=[],b=[],P=[];for(;E<t.length;){let H=t[E],z=H.trim();if(this.getIndent(H)!==o)break;if(z.startsWith("except")){let q=z.match(/^except(?:\s+(\w+)(?:\s+as\s+(\w+))?)?\s*:$/),ft=q?.[1]??null,ot=q?.[2],ht=this.collectBlock(t,E+1,o);T.push({exc:ft,body:ht}),ot&&n.set(ot,""),E+=1+ht.length}else if(z==="else:")P=this.collectBlock(t,E+1,o),E+=1+P.length;else if(z==="finally:")b=this.collectBlock(t,E+1,o),E+=1+b.length;else break}let I=null;try{this.runBlockInScope(w,n),P.length&&this.runBlockInScope(P,n)}catch(H){if(H instanceof U){I=H;let z=!1;for(let q of T)if(q.exc===null||q.exc===H.type||q.exc==="Exception"){this.runBlockInScope(q.body,n),z=!0;break}if(!z)throw H}else throw H}finally{b.length&&this.runBlockInScope(b,n)}return E}let $=s.match(/^with\s+(.+?)\s+as\s+(\w+)\s*:$/);if($){let w=this.collectBlock(t,e+1,o);return n.set($[2],p),this.runBlockInScope(w,n),e+1+w.length}let V=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(\+=|-=|\*=|\/\/=|\/=|%=|\*\*=|&=|\|=)\s*(.+)$/);if(V){let[,w,E,T]=V,b=n.get(w)??0,P=this.pyEval(T,n),I;switch(E){case"+=":I=typeof b=="string"?b+M(P):b+P;break;case"-=":I=b-P;break;case"*=":I=b*P;break;case"/=":I=b/P;break;case"//=":I=Math.floor(b/P);break;case"%=":I=b%P;break;case"**=":I=b**P;break;default:I=P}return n.set(w,I),e+1}let k=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\[(.+)\]\s*=\s*(.+)$/);if(k){let[,w,E,T]=k,b=n.get(w)??p,P=this.pyEval(T,n)??p,I=this.pyEval(E,n)??p;return Array.isArray(b)?b[I]=P:B(b)&&b.data.set(M(I),P),e+1}let R=s.match(/^([A-Za-z_][A-Za-z0-9_.]+)\s*=\s*(.+)$/);if(R){let w=R[1].lastIndexOf(".");if(w!==-1){let E=R[1].slice(0,w),T=R[1].slice(w+1),b=this.pyEval(R[2],n),P=this.pyEval(E,n);return B(P)?P.data.set(T,b):Ft(P)&&P.attrs.set(T,b),e+1}}let D=s.match(/^([A-Za-z_][A-Za-z0-9_,\s]*),\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$/);if(D){let w=this.pyEval(D[3],n),E=s.split("=")[0].split(",").map(b=>b.trim()),T=K(w);return E.forEach((b,P)=>n.set(b,T[P]??p)),e+1}let tt=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=]+)?\s*=\s*(.+)$/);if(tt){let[,w,E]=tt;return n.set(w,this.pyEval(E,n)),e+1}try{this.pyEval(s,n)}catch(w){if(w instanceof U||w instanceof Vt)throw w}return e+1}runBlockInScope(t,e){this.execLines(t,0,e)}run(t){let e=Hs(this.cwd);try{this.execScript(t,e)}catch(n){return n instanceof Vt?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:n.code}:n instanceof U?(this.stderr.push(n.toString()),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1}):n instanceof Ct?{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}:(this.stderr.push(`RuntimeError: ${n}`),{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:1})}return{stdout:this.getOutput(),stderr:this.getStderr(),exitCode:0}}},en={name:"python3",aliases:["python"],description:"Python 3 interpreter (virtual)",category:"system",params:["[--version] [-c <code>] [-V] [file]"],run:({args:r,shell:t,cwd:e})=>{if(!t.packageManager.isInstalled("python3"))return{stderr:`bash: python3: command not found
239
240
  Hint: install it with: apt install python3
240
- `,exitCode:127};if(h(r,["--version","-V"]))return{stdout:`${js}
241
+ `,exitCode:127};if(h(r,["--version","-V"]))return{stdout:`${Ws}
241
242
  `,exitCode:0};if(h(r,["--version-full"]))return{stdout:`${Kt}
242
243
  `,exitCode:0};let n=r.indexOf("-c");if(n!==-1){let s=r[n+1];if(!s)return{stderr:`python3: -c requires a code argument
243
244
  `,exitCode:1};let o=s.replace(/\\n/g,`
@@ -276,7 +277,7 @@ Usage: wget [OPTION]... [URL]...`,exitCode:1};let a=i.get("-O")??i.get("--output
276
277
  ${d} 100%[==================>] ${x.length} B`),{stderr:m.join(`
277
278
  `)||void 0,exitCode:0}):{stdout:x,exitCode:0}}};var Nn={name:"which",description:"Locate a command in PATH",category:"shell",params:["<command...>"],run:({args:r,shell:t,env:e})=>{if(r.length===0)return{stderr:"which: missing argument",exitCode:1};let n=(e?.vars?.PATH??"/usr/local/bin:/usr/bin:/bin").split(":"),i=[],s=!1;for(let o of r){let a=!1;for(let l of n){let c=`${l}/${o}`;if(t.vfs.exists(c)&&t.vfs.stat(c).type==="file"){i.push(c),a=!0;break}}a||(s=!0)}return i.length===0?{exitCode:1}:{stdout:i.join(`
278
279
  `),exitCode:s?1:0}}};function Zt(r){let t=r.toLocaleString("en-US",{weekday:"short"}),e=r.toLocaleString("en-US",{month:"short"}),n=r.getDate().toString().padStart(2,"0"),i=r.getHours().toString().padStart(2,"0"),s=r.getMinutes().toString().padStart(2,"0"),o=r.getSeconds().toString().padStart(2,"0"),a=r.getFullYear();return`${t} ${e} ${n} ${i}:${s}:${o} ${a}`}var In={name:"who",description:"Show active sessions",category:"system",params:[],run:({shell:r})=>({stdout:r.users.listActiveSessions().map(e=>{let n=new Date(e.startedAt),i=Number.isNaN(n.getTime())?e.startedAt:Zt(n);return`${e.username} ${e.tty} ${i} (${e.remoteAddress||"unknown"})`}).join(`
279
- `),exitCode:0})};var Vn={name:"whoami",description:"Print current user",category:"system",params:[],run:({authUser:r})=>({stdout:r,exitCode:0})};var Rn={name:"xargs",description:"Build and execute command lines from stdin",category:"text",params:["[command] [args...]"],run:async({authUser:r,hostname:t,mode:e,cwd:n,args:i,stdin:s,shell:o,env:a})=>{let l=i[0]??"echo",c=i.slice(1),u=(s??"").trim().split(/\s+/).filter(Boolean);if(u.length===0)return{exitCode:0};let d=[l,...c,...u].join(" ");return Z(d,r,t,e,n,o,void 0,a)}};var Qs=[Qr,Ue,$r,wn,Be,xn,nn,Mr,He,Er,Cr,je,or,lr,sn,Oe,dn,kn,An,mr,hn,Ke,bn,yn,Rn,Qe,gn,ur,dr,ze,Vn,In,xr,wr,cr,Pn,Yr,vr,Ye,er,Ge,un,Zr,rr,nr,ir,Br,Mn,on,We,sr,Fr,br,qe,Fn,Fe,Gr,Je,fn,pn,Ur,Le,Te,Xe,tr,Nn,$n,kr,Ie,Ve,Sn,mn,Sr,Jr,rn,Ze,an,ln,cn,vn,Cn,qr,Kr,Hr,en,En,ar,Pr],Dn=[],Rt=new Map,Jt=null,Xs=yr(()=>ge().map(r=>r.name));function he(){Rt.clear();for(let r of ge()){Rt.set(r.name,r);for(let t of r.aliases??[])Rt.set(t,r)}Jt=Array.from(Rt.keys()).sort()}function ge(){return[...Qs,...Dn,Xs]}function ye(r){let t={...r,name:r.name.trim().toLowerCase(),aliases:r.aliases?.map(n=>n.trim().toLowerCase())};if([t.name,...t.aliases??[]].some(n=>n.length===0||/\s/.test(n)))throw new Error("Command names must be non-empty and contain no spaces");Dn.push(t),he()}function Se(r,t,e){return{name:r,params:t,run:e}}function xe(){return Jt||he(),Jt}function le(){return ge()}function mt(r){return Jt||he(),Rt.get(r.toLowerCase())}async function _n(r,t,e,n,i,s,o){let a={exitCode:0},l=0;for(;l<r.length;){let c=r[l];if(a=await ti(c.pipeline,t,e,n,i,s,o),o.lastExitCode=a.exitCode??0,a.closeSession||a.switchUser)return a;let u=c.op;if(!(!u||u===";")){if(u==="&&"){if((a.exitCode??0)!==0)for(;l<r.length&&r[l]?.op==="&&";)l++}else if(u==="||"&&(a.exitCode??0)===0)for(;l<r.length&&r[l]?.op==="||";)l++}l++}return a}async function ti(r,t,e,n,i,s,o){if(!r.isValid)return{stderr:r.error||"Syntax error",exitCode:1};if(r.commands.length===0)return{exitCode:0};let a=o??{vars:{},lastExitCode:0};return r.commands.length===1?ei(r.commands[0],t,e,n,i,s,a):ri(r.commands,t,e,n,i,s,a)}async function ei(r,t,e,n,i,s,o){let a;if(r.inputFile){let c=S(i,r.inputFile);try{a=s.vfs.readFile(c)}catch{return{stderr:`${r.inputFile}: No such file or directory`,exitCode:1}}}let l=await Yt(r.name,r.args,t,e,n,i,s,a,o);if(r.outputFile){let c=S(i,r.outputFile),u=l.stdout||"";try{if(r.appendOutput){let d=(()=>{try{return s.vfs.readFile(c)}catch{return""}})();s.writeFileAsUser(t,c,d+u)}else s.writeFileAsUser(t,c,u);return{...l,stdout:""}}catch{return{...l,stderr:`Failed to write to ${r.outputFile}`,exitCode:1}}}return l}async function ri(r,t,e,n,i,s,o){let a="",l=0;for(let c=0;c<r.length;c++){let u=r[c];if(c===0&&u.inputFile){let m=S(i,u.inputFile);try{a=s.vfs.readFile(m)}catch{return{stderr:`${u.inputFile}: No such file or directory`,exitCode:1}}}let d=await Yt(u.name,u.args,t,e,n,i,s,a,o);if(l=d.exitCode??0,c===r.length-1&&u.outputFile){let m=S(i,u.outputFile),f=d.stdout||"";try{if(u.appendOutput){let x=(()=>{try{return s.vfs.readFile(m)}catch{return""}})();s.writeFileAsUser(t,m,x+f)}else s.writeFileAsUser(t,m,f);a=""}catch{return{stderr:`Failed to write to ${u.outputFile}`,exitCode:1}}}else a=d.stdout||"";if(d.stderr&&l!==0)return{stderr:d.stderr,exitCode:l};if(d.closeSession||d.switchUser)return d}return{stdout:a,exitCode:l}}function Ln(r){let t=r.trim();if(!t)return{statements:[],isValid:!0};try{return{statements:ni(t),isValid:!0}}catch(e){return{statements:[],isValid:!1,error:e.message}}}function ni(r){let t=si(r),e=[];for(let n of t){let s={pipeline:{commands:ii(n.text.trim()),isValid:!0}};n.op&&(s.op=n.op),e.push(s)}return e}function si(r){let t=[],e="",n=0,i=!1,s="",o=0,a=l=>{e.trim()&&t.push({text:e,op:l}),e=""};for(;o<r.length;){let l=r[o],c=r.slice(o,o+2);if((l==='"'||l==="'")&&!i){i=!0,s=l,e+=l,o++;continue}if(i&&l===s){i=!1,e+=l,o++;continue}if(i){e+=l,o++;continue}if(l==="("){n++,e+=l,o++;continue}if(l===")"){n--,e+=l,o++;continue}if(n>0){e+=l,o++;continue}if(c==="&&"){a("&&"),o+=2;continue}if(c==="||"){a("||"),o+=2;continue}if(l===";"){a(";"),o++;continue}e+=l,o++}return a(),t}function ii(r){return oi(r).map(ai)}function oi(r){let t=[],e="",n=!1,i="";for(let o=0;o<r.length;o++){let a=r[o];if((a==='"'||a==="'")&&!n){n=!0,i=a,e+=a;continue}if(n&&a===i){n=!1,e+=a;continue}if(n){e+=a;continue}if(a==="|"&&r[o+1]!=="|"){if(!e.trim())throw new Error("Syntax error near unexpected token '|'");t.push(e.trim()),e=""}else e+=a}let s=e.trim();if(!s&&t.length>0)throw new Error("Syntax error near unexpected token '|'");return s&&t.push(s),t}function ai(r){let t=li(r);if(t.length===0)return{name:"",args:[]};let e=[],n,i,s=!1,o=0;for(;o<t.length;){let l=t[o];if(l==="<"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after <");n=t[o],o++}else if(l===">>"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >>");i=t[o],s=!0,o++}else if(l===">"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >");i=t[o],s=!1,o++}else e.push(l),o++}return{name:(e[0]??"").toLowerCase(),args:e.slice(1),inputFile:n,outputFile:i,appendOutput:s}}function li(r){let t=[],e="",n=!1,i="",s=0;for(;s<r.length;){let o=r[s],a=r[s+1];if((o==='"'||o==="'")&&!n){n=!0,i=o,s++;continue}if(n&&o===i){n=!1,i="",s++;continue}if(n){e+=o,s++;continue}if(o===" "){e&&(t.push(e),e=""),s++;continue}if((o===">"||o==="<")&&!n){e&&(t.push(e),e=""),o===">"&&a===">"?(t.push(">>"),s+=2):(t.push(o),s++);continue}e+=o,s++}return e&&t.push(e),t}function Tn(r){let t=[],e="",n=!1,i="",s=0;for(;s<r.length;){let o=r[s],a=r[s+1];if((o==='"'||o==="'")&&!n){n=!0,i=o,s++;continue}if(n&&o===i){n=!1,i="",s++;continue}if(n){e+=o,s++;continue}if(o===" "){e&&(t.push(e),e=""),s++;continue}if((o===">"||o==="<")&&!n){e&&(t.push(e),e=""),o===">"&&a===">"?(t.push(">>"),s+=2):(t.push(o),s++);continue}e+=o,s++}return e&&t.push(e),t}function kt(r,t){return{vars:{PATH:"/usr/local/bin:/usr/bin:/bin",HOME:`/home/${r}`,USER:r,LOGNAME:r,SHELL:"/bin/sh",TERM:"xterm-256color",HOSTNAME:t,PS1:"\\u@\\h:\\w\\$ "},lastExitCode:0}}function On(r,t,e,n){if(r.startsWith("/")){if(!e.vfs.exists(r))return null;try{let s=e.vfs.stat(r);return s.type!=="file"||!(s.mode&73)||(r.startsWith("/sbin/")||r.startsWith("/usr/sbin/"))&&n!=="root"?null:r}catch{return null}}let i=(t.vars.PATH??"/usr/local/bin:/usr/bin:/bin").split(":");for(let s of i){if((s==="/sbin"||s==="/usr/sbin")&&n!=="root")continue;let o=`${s}/${r}`;if(e.vfs.exists(o))try{let a=e.vfs.stat(o);if(a.type!=="file"||!(a.mode&73))continue;return o}catch{}}return null}async function Yt(r,t,e,n,i,s,o,a,l){let c=l.vars[`__alias_${r}`];if(c)return Z(`${c} ${t.join(" ")}`,e,n,i,s,o,a,l);let u=mt(r);if(!u){let d=On(r,l,o,e);if(d){let m=o.vfs.readFile(d),f=m.match(/exec\s+builtin\s+(\S+)/);if(f){let g=mt(f[1]);if(g)return await g.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}let x=mt("sh");if(x)return await x.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(m)}`,mode:i,args:["-c",m,"--",...t],stdin:a,cwd:s,shell:o,env:l})}return{stderr:`${r}: command not found`,exitCode:127}}try{return await u.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}catch(d){return{stderr:d instanceof Error?d.message:"Command failed",exitCode:1}}}async function Z(r,t,e,n,i,s,o,a){let l=r.trim();if(l.length===0)return{exitCode:0};let c=a??kt(t,e),d=Tn(l)[0]?.toLowerCase()??"",m=c.vars[`__alias_${d}`],f=m?l.replace(d,m):l;if(/(?<![|&])[|](?![|])/.test(f)||f.includes(">")||f.includes("<")||f.includes("&&")||f.includes("||")||f.includes(";")){let R=Ln(f);if(!R.isValid)return{stderr:R.error||"Syntax error",exitCode:1};try{return await _n(R.statements,t,e,n,i,s,c)}catch(D){return{stderr:D instanceof Error?D.message:"Execution failed",exitCode:1}}}let g=await Bt(f,c.vars,c.lastExitCode,R=>Z(R,t,e,n,i,s,void 0,c).then(D=>D.stdout??"")),y=Tn(g.trim()),$=y[0]?.toLowerCase()??"",V=y.slice(1),k=mt($);if(!k){let R=On($,c,s,t);if(R){let D=s.vfs.readFile(R),tt=D.match(/exec\s+builtin\s+(\S+)/);if(tt){let E=tt[1],T=mt(E);if(T)return await T.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:[$,...V].join(" "),mode:n,args:V,stdin:o,cwd:i,shell:s,env:c})}let w=mt("sh");if(w)return await w.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(D)}`,mode:n,args:["-c",D,"--",...V],stdin:o,cwd:i,shell:s,env:c})}return{stderr:`${$}: command not found`,exitCode:127}}try{return await k.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:g,mode:n,args:V,stdin:o,cwd:i,shell:s,env:c})}catch(R){return{stderr:R instanceof Error?R.message:"Command failed",exitCode:1}}}function Qt(r,t,e){let n=[`Linux ${r} ${t.kernel} ${t.arch}`,"","The programs included with the Fortune GNU/Linux system are free software;","the exact distribution terms for each program are described in the","individual files in /usr/share/doc/*/copyright.","","Fortune GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent","permitted by applicable law."];if(e){let i=new Date(e.at),s=Number.isNaN(i.getTime())?e.at:Zt(i);n.push(`Last login: ${s} from ${e.from||"unknown"}`)}return n.push(""),`${n.map(i=>`${i}\r
280
+ `),exitCode:0})};var Vn={name:"whoami",description:"Print current user",category:"system",params:[],run:({authUser:r})=>({stdout:r,exitCode:0})};var Rn={name:"xargs",description:"Build and execute command lines from stdin",category:"text",params:["[command] [args...]"],run:async({authUser:r,hostname:t,mode:e,cwd:n,args:i,stdin:s,shell:o,env:a})=>{let l=i[0]??"echo",c=i.slice(1),u=(s??"").trim().split(/\s+/).filter(Boolean);if(u.length===0)return{exitCode:0};let d=[l,...c,...u].join(" ");return Z(d,r,t,e,n,o,void 0,a)}};var Qs=[Qr,Ue,$r,wn,Be,xn,nn,Mr,He,Er,Cr,We,or,lr,sn,Oe,dn,kn,An,mr,hn,Ke,bn,yn,Rn,Qe,gn,ur,dr,ze,Vn,In,xr,wr,cr,Pn,Yr,vr,Ye,er,Ge,un,Zr,rr,nr,ir,Br,Mn,on,je,sr,Fr,br,qe,Fn,Fe,Gr,Je,fn,pn,Ur,Le,Te,Xe,tr,Nn,$n,kr,Ie,Ve,Sn,mn,Sr,Jr,rn,Ze,an,ln,cn,vn,Cn,qr,Kr,Hr,en,En,ar,Pr],Dn=[],Rt=new Map,Jt=null,Xs=yr(()=>ge().map(r=>r.name));function he(){Rt.clear();for(let r of ge()){Rt.set(r.name,r);for(let t of r.aliases??[])Rt.set(t,r)}Jt=Array.from(Rt.keys()).sort()}function ge(){return[...Qs,...Dn,Xs]}function ye(r){let t={...r,name:r.name.trim().toLowerCase(),aliases:r.aliases?.map(n=>n.trim().toLowerCase())};if([t.name,...t.aliases??[]].some(n=>n.length===0||/\s/.test(n)))throw new Error("Command names must be non-empty and contain no spaces");Dn.push(t),he()}function Se(r,t,e){return{name:r,params:t,run:e}}function xe(){return Jt||he(),Jt}function le(){return ge()}function mt(r){return Jt||he(),Rt.get(r.toLowerCase())}async function _n(r,t,e,n,i,s,o){let a={exitCode:0},l=0;for(;l<r.length;){let c=r[l];if(a=await ti(c.pipeline,t,e,n,i,s,o),o.lastExitCode=a.exitCode??0,a.closeSession||a.switchUser)return a;let u=c.op;if(!(!u||u===";")){if(u==="&&"){if((a.exitCode??0)!==0)for(;l<r.length&&r[l]?.op==="&&";)l++}else if(u==="||"&&(a.exitCode??0)===0)for(;l<r.length&&r[l]?.op==="||";)l++}l++}return a}async function ti(r,t,e,n,i,s,o){if(!r.isValid)return{stderr:r.error||"Syntax error",exitCode:1};if(r.commands.length===0)return{exitCode:0};let a=o??{vars:{},lastExitCode:0};return r.commands.length===1?ei(r.commands[0],t,e,n,i,s,a):ri(r.commands,t,e,n,i,s,a)}async function ei(r,t,e,n,i,s,o){let a;if(r.inputFile){let c=S(i,r.inputFile);try{a=s.vfs.readFile(c)}catch{return{stderr:`${r.inputFile}: No such file or directory`,exitCode:1}}}let l=await Yt(r.name,r.args,t,e,n,i,s,a,o);if(r.outputFile){let c=S(i,r.outputFile),u=l.stdout||"";try{if(r.appendOutput){let d=(()=>{try{return s.vfs.readFile(c)}catch{return""}})();s.writeFileAsUser(t,c,d+u)}else s.writeFileAsUser(t,c,u);return{...l,stdout:""}}catch{return{...l,stderr:`Failed to write to ${r.outputFile}`,exitCode:1}}}return l}async function ri(r,t,e,n,i,s,o){let a="",l=0;for(let c=0;c<r.length;c++){let u=r[c];if(c===0&&u.inputFile){let m=S(i,u.inputFile);try{a=s.vfs.readFile(m)}catch{return{stderr:`${u.inputFile}: No such file or directory`,exitCode:1}}}let d=await Yt(u.name,u.args,t,e,n,i,s,a,o);if(l=d.exitCode??0,c===r.length-1&&u.outputFile){let m=S(i,u.outputFile),f=d.stdout||"";try{if(u.appendOutput){let x=(()=>{try{return s.vfs.readFile(m)}catch{return""}})();s.writeFileAsUser(t,m,x+f)}else s.writeFileAsUser(t,m,f);a=""}catch{return{stderr:`Failed to write to ${u.outputFile}`,exitCode:1}}}else a=d.stdout||"";if(d.stderr&&l!==0)return{stderr:d.stderr,exitCode:l};if(d.closeSession||d.switchUser)return d}return{stdout:a,exitCode:l}}function Ln(r){let t=r.trim();if(!t)return{statements:[],isValid:!0};try{return{statements:ni(t),isValid:!0}}catch(e){return{statements:[],isValid:!1,error:e.message}}}function ni(r){let t=si(r),e=[];for(let n of t){let s={pipeline:{commands:ii(n.text.trim()),isValid:!0}};n.op&&(s.op=n.op),e.push(s)}return e}function si(r){let t=[],e="",n=0,i=!1,s="",o=0,a=l=>{e.trim()&&t.push({text:e,op:l}),e=""};for(;o<r.length;){let l=r[o],c=r.slice(o,o+2);if((l==='"'||l==="'")&&!i){i=!0,s=l,e+=l,o++;continue}if(i&&l===s){i=!1,e+=l,o++;continue}if(i){e+=l,o++;continue}if(l==="("){n++,e+=l,o++;continue}if(l===")"){n--,e+=l,o++;continue}if(n>0){e+=l,o++;continue}if(c==="&&"){a("&&"),o+=2;continue}if(c==="||"){a("||"),o+=2;continue}if(l===";"){a(";"),o++;continue}e+=l,o++}return a(),t}function ii(r){return oi(r).map(ai)}function oi(r){let t=[],e="",n=!1,i="";for(let o=0;o<r.length;o++){let a=r[o];if((a==='"'||a==="'")&&!n){n=!0,i=a,e+=a;continue}if(n&&a===i){n=!1,e+=a;continue}if(n){e+=a;continue}if(a==="|"&&r[o+1]!=="|"){if(!e.trim())throw new Error("Syntax error near unexpected token '|'");t.push(e.trim()),e=""}else e+=a}let s=e.trim();if(!s&&t.length>0)throw new Error("Syntax error near unexpected token '|'");return s&&t.push(s),t}function ai(r){let t=li(r);if(t.length===0)return{name:"",args:[]};let e=[],n,i,s=!1,o=0;for(;o<t.length;){let l=t[o];if(l==="<"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after <");n=t[o],o++}else if(l===">>"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >>");i=t[o],s=!0,o++}else if(l===">"){if(o++,o>=t.length)throw new Error("Syntax error: expected filename after >");i=t[o],s=!1,o++}else e.push(l),o++}return{name:(e[0]??"").toLowerCase(),args:e.slice(1),inputFile:n,outputFile:i,appendOutput:s}}function li(r){let t=[],e="",n=!1,i="",s=0;for(;s<r.length;){let o=r[s],a=r[s+1];if((o==='"'||o==="'")&&!n){n=!0,i=o,s++;continue}if(n&&o===i){n=!1,i="",s++;continue}if(n){e+=o,s++;continue}if(o===" "){e&&(t.push(e),e=""),s++;continue}if((o===">"||o==="<")&&!n){e&&(t.push(e),e=""),o===">"&&a===">"?(t.push(">>"),s+=2):(t.push(o),s++);continue}e+=o,s++}return e&&t.push(e),t}function Tn(r){let t=[],e="",n=!1,i="",s=0;for(;s<r.length;){let o=r[s],a=r[s+1];if((o==='"'||o==="'")&&!n){n=!0,i=o,s++;continue}if(n&&o===i){n=!1,i="",s++;continue}if(n){e+=o,s++;continue}if(o===" "){e&&(t.push(e),e=""),s++;continue}if((o===">"||o==="<")&&!n){e&&(t.push(e),e=""),o===">"&&a===">"?(t.push(">>"),s+=2):(t.push(o),s++);continue}e+=o,s++}return e&&t.push(e),t}function kt(r,t){return{vars:{PATH:"/usr/local/bin:/usr/bin:/bin",HOME:`/home/${r}`,USER:r,LOGNAME:r,SHELL:"/bin/sh",TERM:"xterm-256color",HOSTNAME:t,PS1:"\\u@\\h:\\w\\$ "},lastExitCode:0}}function On(r,t,e,n){if(r.startsWith("/")){if(!e.vfs.exists(r))return null;try{let s=e.vfs.stat(r);return s.type!=="file"||!(s.mode&73)||(r.startsWith("/sbin/")||r.startsWith("/usr/sbin/"))&&n!=="root"?null:r}catch{return null}}let i=(t.vars.PATH??"/usr/local/bin:/usr/bin:/bin").split(":");for(let s of i){if((s==="/sbin"||s==="/usr/sbin")&&n!=="root")continue;let o=`${s}/${r}`;if(e.vfs.exists(o))try{let a=e.vfs.stat(o);if(a.type!=="file"||!(a.mode&73))continue;return o}catch{}}return null}async function Yt(r,t,e,n,i,s,o,a,l){let c=l.vars[`__alias_${r}`];if(c)return Z(`${c} ${t.join(" ")}`,e,n,i,s,o,a,l);let u=mt(r);if(!u){let d=On(r,l,o,e);if(d){let m=o.vfs.readFile(d),f=m.match(/exec\s+builtin\s+(\S+)/);if(f){let g=mt(f[1]);if(g)return await g.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}let x=mt("sh");if(x)return await x.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(m)}`,mode:i,args:["-c",m,"--",...t],stdin:a,cwd:s,shell:o,env:l})}return{stderr:`${r}: command not found`,exitCode:127}}try{return await u.run({authUser:e,hostname:n,activeSessions:o.users.listActiveSessions(),rawInput:[r,...t].join(" "),mode:i,args:t,stdin:a,cwd:s,shell:o,env:l})}catch(d){return{stderr:d instanceof Error?d.message:"Command failed",exitCode:1}}}async function Z(r,t,e,n,i,s,o,a){let l=r.trim();if(l.length===0)return{exitCode:0};let c=a??kt(t,e),d=Tn(l)[0]?.toLowerCase()??"",m=c.vars[`__alias_${d}`],f=m?l.replace(d,m):l;if(/(?<![|&])[|](?![|])/.test(f)||f.includes(">")||f.includes("<")||f.includes("&&")||f.includes("||")||f.includes(";")){let R=Ln(f);if(!R.isValid)return{stderr:R.error||"Syntax error",exitCode:1};try{return await _n(R.statements,t,e,n,i,s,c)}catch(D){return{stderr:D instanceof Error?D.message:"Execution failed",exitCode:1}}}let g=await Bt(f,c.vars,c.lastExitCode,R=>Z(R,t,e,n,i,s,void 0,c).then(D=>D.stdout??"")),y=Tn(g.trim()),$=y[0]?.toLowerCase()??"",V=y.slice(1),k=mt($);if(!k){let R=On($,c,s,t);if(R){let D=s.vfs.readFile(R),tt=D.match(/exec\s+builtin\s+(\S+)/);if(tt){let E=tt[1],T=mt(E);if(T)return await T.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:[$,...V].join(" "),mode:n,args:V,stdin:o,cwd:i,shell:s,env:c})}let w=mt("sh");if(w)return await w.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:`sh -c ${JSON.stringify(D)}`,mode:n,args:["-c",D,"--",...V],stdin:o,cwd:i,shell:s,env:c})}return{stderr:`${$}: command not found`,exitCode:127}}try{return await k.run({authUser:t,hostname:e,activeSessions:s.users.listActiveSessions(),rawInput:g,mode:n,args:V,stdin:o,cwd:i,shell:s,env:c})}catch(R){return{stderr:R instanceof Error?R.message:"Command failed",exitCode:1}}}function Qt(r,t,e){let n=[`Linux ${r} ${t.kernel} ${t.arch}`,"","The programs included with the Fortune GNU/Linux system are free software;","the exact distribution terms for each program are described in the","individual files in /usr/share/doc/*/copyright.","","Fortune GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent","permitted by applicable law."];if(e){let i=new Date(e.at),s=Number.isNaN(i.getTime())?e.at:Zt(i);n.push(`Last login: ${s} from ${e.from||"unknown"}`)}return n.push(""),`${n.map(i=>`${i}\r
280
281
  `).join("")}`}function Xt(r,t,e){let n=r==="root",i=n?"\x1B[31;1m":"\x1B[35;1m",s="\x1B[37;1m",o="\x1B[34;1m",a="\x1B[0m";return`${s}[${i}${r}${s}@${o}${t}${a} ${e}${s}]${a}${n?"#":"$"} `}import{EventEmitter as Ri}from"node:events";import*as Mt from"node:os";function v(r,t,e=493){r.exists(t)||r.mkdir(t,e)}function O(r,t,e,n=420){r.exists(t)||r.writeFile(t,e,{mode:n})}function ci(r,t,e){v(r,"/etc"),O(r,"/etc/os-release",`${['NAME="Fortune GNU/Linux"',`PRETTY_NAME="${e.os}"`,"ID=fortune","ID_LIKE=debian",'HOME_URL="https://github.com/itsrealfortune/typescript-virtual-container"',"VERSION_CODENAME=aurora",'VERSION_ID="1.0"'].join(`
281
282
  `)}
282
283
  `),O(r,"/etc/debian_version",`12.0
@@ -333,9 +334,9 @@ exec lsb_release "$@"
333
334
  `),O(r,"/var/log/auth.log",""),O(r,"/var/log/dpkg.log",""),O(r,"/var/log/apt/history.log",""),O(r,"/var/log/apt/term.log","")}function fi(r){r.exists("/bin")||r.symlink("/usr/bin","/bin"),r.exists("/sbin")||r.symlink("/usr/sbin","/sbin"),r.exists("/lib")||v(r,"/lib"),r.exists("/lib64")||v(r,"/lib64")}function hi(r){v(r,"/tmp",1023)}function gi(r){v(r,"/root",448),O(r,"/root/.bashrc",`${["# root .bashrc","export PS1='\\[\\033[0;31m\\]\\u@\\h\\[\\033[0m\\]:\\[\\033[0;34m\\]\\w\\[\\033[0m\\]# '","export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","alias ll='ls -la'","alias la='ls -A'"].join(`
334
335
  `)}
335
336
  `),O(r,"/root/.profile",`[ -f ~/.bashrc ] && . ~/.bashrc
336
- `),r.exists("/home/root")||r.symlink("/root","/home/root")}function yi(r){v(r,"/opt"),v(r,"/srv"),v(r,"/mnt"),v(r,"/media")}function Un(r,t,e,n,i){ci(r,e,n),ui(r,n),di(r),mi(r),pi(r),fi(r),hi(r),gi(r),yi(r),te(r,n,e,i,[]),be(r,t)}function jn(r){return r==="1"||r==="true"}function Wn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Si(){return jn(process.env.DEV_MODE)||jn(process.env.RENDER_PERF)}function ee(r){let t=Si();if(!t)return{enabled:t,mark:()=>{},done:()=>{}};let e=Wn(),n=s=>{let o=Wn()-e;console.log(`[perf][${r}] ${s}: ${o.toFixed(1)}ms`)};return{enabled:t,mark:n,done:(s="done")=>{n(s)}}}import{EventEmitter as wi}from"node:events";import*as yt from"node:fs";import*as pt from"node:path";import{gunzipSync as $e,gzipSync as Qn}from"node:zlib";var Ce=Buffer.from([86,70,83,33]),xi=1,Hn=1,qn=2,we=class{chunks=[];write(t){this.chunks.push(t)}writeUint8(t){let e=Buffer.allocUnsafe(1);e.writeUInt8(t,0),this.chunks.push(e)}writeUint16(t){let e=Buffer.allocUnsafe(2);e.writeUInt16LE(t,0),this.chunks.push(e)}writeUint32(t){let e=Buffer.allocUnsafe(4);e.writeUInt32LE(t,0),this.chunks.push(e)}writeFloat64(t){let e=Buffer.allocUnsafe(8);e.writeDoubleBE(t,0),this.chunks.push(e)}writeString(t){let e=Buffer.from(t,"utf8");this.writeUint16(e.length),this.chunks.push(e)}writeBytes(t){this.writeUint32(t.length),this.chunks.push(t)}toBuffer(){return Buffer.concat(this.chunks)}};function Kn(r,t){if(t.type==="file"){let e=t;r.writeUint8(Hn),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime()),r.writeUint8(e.compressed?1:0),r.writeBytes(e.content)}else{let e=t;r.writeUint8(qn),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime());let n=Array.from(e.children.values());r.writeUint32(n.length);for(let i of n)Kn(r,i)}}function Gn(r){let t=new we;return t.write(Ce),t.writeUint8(xi),Kn(t,r),t.toBuffer()}var ve=class{constructor(t){this.buf=t}buf;pos=0;readUint8(){return this.buf.readUInt8(this.pos++)}readUint16(){let t=this.buf.readUInt16LE(this.pos);return this.pos+=2,t}readUint32(){let t=this.buf.readUInt32LE(this.pos);return this.pos+=4,t}readFloat64(){let t=this.buf.readDoubleBE(this.pos);return this.pos+=8,t}readString(){let t=this.readUint16(),e=this.buf.toString("utf8",this.pos,this.pos+t);return this.pos+=t,e}readBytes(){let t=this.readUint32(),e=this.buf.slice(this.pos,this.pos+t);return this.pos+=t,e}remaining(){return this.buf.length-this.pos}};function Zn(r){let t=r.readUint8(),e=r.readString(),n=r.readUint32(),i=new Date(r.readFloat64()),s=new Date(r.readFloat64());if(t===Hn){let o=r.readUint8()===1,a=r.readBytes();return{type:"file",name:e,mode:n,createdAt:i,updatedAt:s,compressed:o,content:a}}if(t===qn){let o=r.readUint32(),a=new Map;for(let l=0;l<o;l++){let c=Zn(r);a.set(c.name,c)}return{type:"directory",name:e,mode:n,createdAt:i,updatedAt:s,children:a}}throw new Error(`[VFS binary] Unknown node type: 0x${t.toString(16)}`)}function Jn(r){if(r.length<5)throw new Error("[VFS binary] Buffer too short");if(!r.slice(0,4).equals(Ce))throw new Error("[VFS binary] Invalid magic \u2014 not a VFS binary snapshot");let e=new ve(r);for(let i=0;i<5;i++)e.readUint8();let n=Zn(e);if(n.type!=="directory")throw new Error("[VFS binary] Root node must be a directory");return n}function Yn(r){return r.length>=4&&r.slice(0,4).equals(Ce)}import*as re from"node:path";function W(r){if(!r||r.trim()==="")return"/";let t=re.posix.normalize(r.startsWith("/")?r:`/${r}`);return t===""?"/":t}function bi(r){return r.split("/").filter(Boolean)}function X(r,t){let e=W(t);if(e==="/")return r;let n=bi(e),i=r;for(let s of n){if(i.type!=="directory")throw new Error(`Path '${e}' does not exist.`);let o=i.children.get(s);if(!o)throw new Error(`Path '${e}' does not exist.`);i=o}return i}function Et(r,t,e,n){let i=W(t);if(i==="/")throw new Error("Root path has no parent directory.");let s=re.posix.dirname(i),o=re.posix.basename(i);if(!o)throw new Error(`Invalid path '${t}'.`);e&&n(s);let a=X(r,s);if(a.type!=="directory")throw new Error(`Parent path '${s}' is not a directory.`);return{parent:a,name:o}}var Pe=class r extends wi{root;mode;snapshotFile;constructor(t={}){if(super(),this.mode=t.mode??"memory",this.mode==="fs"){if(!t.snapshotPath)throw new Error('VirtualFileSystem: "snapshotPath" is required when mode is "fs".');this.snapshotFile=pt.resolve(t.snapshotPath,"vfs-snapshot.vfsb")}else this.snapshotFile=null;this.root=this.makeDir("",493)}makeDir(t,e){let n=new Date;return{type:"directory",name:t,mode:e,createdAt:n,updatedAt:n,children:new Map}}makeFile(t,e,n,i){let s=new Date;return{type:"file",name:t,content:e,mode:n,compressed:i,createdAt:s,updatedAt:s}}mkdirRecursive(t,e){let n=W(t);if(n==="/")return;let i=n.split("/").filter(Boolean),s=this.root,o="";for(let a of i){o+=`/${a}`;let l=s.children.get(a);if(!l)l=this.makeDir(a,e),s.children.set(a,l),this.emit("dir:create",{path:o,mode:e});else if(l.type!=="directory")throw new Error(`Cannot create directory '${o}': path is a file.`);s=l}}async restoreMirror(){if(!(this.mode!=="fs"||!this.snapshotFile)&&yt.existsSync(this.snapshotFile))try{let t=yt.readFileSync(this.snapshotFile);if(Yn(t))this.root=Jn(t);else{let e=JSON.parse(t.toString("utf8"));this.root=this.deserializeDir(e.root,""),console.info("[VirtualFileSystem] Migrating legacy JSON snapshot to binary format.")}this.emit("snapshot:restore",{path:this.snapshotFile})}catch(t){console.warn(`[VirtualFileSystem] Could not restore snapshot from ${this.snapshotFile}:`,t instanceof Error?t.message:String(t))}}async flushMirror(){if(this.mode!=="fs"||!this.snapshotFile){this.emit("mirror:flush");return}let t=pt.dirname(this.snapshotFile);yt.mkdirSync(t,{recursive:!0});let e=Gn(this.root);yt.writeFileSync(this.snapshotFile,e),this.emit("mirror:flush",{path:this.snapshotFile})}getMode(){return this.mode}getSnapshotPath(){return this.snapshotFile}mkdir(t,e=493){let n=W(t),i=(()=>{try{return X(this.root,n)}catch{return null}})();if(i&&i.type!=="directory")throw new Error(`Cannot create directory '${n}': path is a file.`);this.mkdirRecursive(n,e)}writeFile(t,e,n={}){let i=W(t),{parent:s,name:o}=Et(this.root,i,!0,m=>this.mkdirRecursive(m,493)),a=s.children.get(o);if(a?.type==="directory")throw new Error(`Cannot write file '${i}': path is a directory.`);let l=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),c=n.compress??!1,u=c?Qn(l):l,d=n.mode??420;if(a){let m=a;m.content=u,m.compressed=c,m.mode=d,m.updatedAt=new Date}else s.children.set(o,this.makeFile(o,u,d,c));this.emit("file:write",{path:i,size:u.length})}readFile(t){let e=W(t),n=X(this.root,e);if(n.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let i=n,s=i.compressed?$e(i.content):i.content;return this.emit("file:read",{path:e,size:s.length}),s.toString("utf8")}readFileRaw(t){let e=W(t),n=X(this.root,e);if(n.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let i=n,s=i.compressed?$e(i.content):i.content;return this.emit("file:read",{path:e,size:s.length}),s}exists(t){try{return X(this.root,W(t)),!0}catch{return!1}}chmod(t,e){X(this.root,W(t)).mode=e}stat(t){let e=W(t),n=X(this.root,e),i=e==="/"?"":pt.posix.basename(e);if(n.type==="file"){let o=n;return{type:"file",name:i,path:e,mode:o.mode,createdAt:o.createdAt,updatedAt:o.updatedAt,compressed:o.compressed,size:o.content.length}}let s=n;return{type:"directory",name:i,path:e,mode:s.mode,createdAt:s.createdAt,updatedAt:s.updatedAt,childrenCount:s.children.size}}list(t="/"){let e=W(t),n=X(this.root,e);if(n.type!=="directory")throw new Error(`Cannot list '${t}': not a directory.`);return Array.from(n.children.keys()).sort()}tree(t="/"){let e=W(t),n=X(this.root,e);if(n.type!=="directory")throw new Error(`Cannot render tree for '${t}': not a directory.`);let i=t==="/"?"/":pt.posix.basename(e);return this.renderTreeLines(n,i)}renderTreeLines(t,e){let n=[e],i=Array.from(t.children.keys()).sort();for(let s=0;s<i.length;s++){let o=i[s],a=t.children.get(o),l=s===i.length-1,c=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=l?" ":"\u2502 ";if(n.push(`${c}${o}`),a.type==="directory"){let d=this.renderTreeLines(a,"").split(`
337
+ `),r.exists("/home/root")||r.symlink("/root","/home/root")}function yi(r){v(r,"/opt"),v(r,"/srv"),v(r,"/mnt"),v(r,"/media")}function Un(r,t,e,n,i){ci(r,e,n),ui(r,n),di(r),mi(r),pi(r),fi(r),hi(r),gi(r),yi(r),te(r,n,e,i,[]),be(r,t)}function Wn(r){return r==="1"||r==="true"}function jn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Si(){return Wn(process.env.DEV_MODE)||Wn(process.env.RENDER_PERF)}function ee(r){let t=Si();if(!t)return{enabled:t,mark:()=>{},done:()=>{}};let e=jn(),n=s=>{let o=jn()-e;console.log(`[perf][${r}] ${s}: ${o.toFixed(1)}ms`)};return{enabled:t,mark:n,done:(s="done")=>{n(s)}}}import{EventEmitter as wi}from"node:events";import*as yt from"node:fs";import*as pt from"node:path";import{gunzipSync as $e,gzipSync as Qn}from"node:zlib";var Ce=Buffer.from([86,70,83,33]),xi=1,Hn=1,qn=2,we=class{chunks=[];write(t){this.chunks.push(t)}writeUint8(t){let e=Buffer.allocUnsafe(1);e.writeUInt8(t,0),this.chunks.push(e)}writeUint16(t){let e=Buffer.allocUnsafe(2);e.writeUInt16LE(t,0),this.chunks.push(e)}writeUint32(t){let e=Buffer.allocUnsafe(4);e.writeUInt32LE(t,0),this.chunks.push(e)}writeFloat64(t){let e=Buffer.allocUnsafe(8);e.writeDoubleBE(t,0),this.chunks.push(e)}writeString(t){let e=Buffer.from(t,"utf8");this.writeUint16(e.length),this.chunks.push(e)}writeBytes(t){this.writeUint32(t.length),this.chunks.push(t)}toBuffer(){return Buffer.concat(this.chunks)}};function Kn(r,t){if(t.type==="file"){let e=t;r.writeUint8(Hn),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime()),r.writeUint8(e.compressed?1:0),r.writeBytes(e.content)}else{let e=t;r.writeUint8(qn),r.writeString(e.name),r.writeUint32(e.mode),r.writeFloat64(e.createdAt.getTime()),r.writeFloat64(e.updatedAt.getTime());let n=Array.from(e.children.values());r.writeUint32(n.length);for(let i of n)Kn(r,i)}}function Gn(r){let t=new we;return t.write(Ce),t.writeUint8(xi),Kn(t,r),t.toBuffer()}var ve=class{constructor(t){this.buf=t}buf;pos=0;readUint8(){return this.buf.readUInt8(this.pos++)}readUint16(){let t=this.buf.readUInt16LE(this.pos);return this.pos+=2,t}readUint32(){let t=this.buf.readUInt32LE(this.pos);return this.pos+=4,t}readFloat64(){let t=this.buf.readDoubleBE(this.pos);return this.pos+=8,t}readString(){let t=this.readUint16(),e=this.buf.toString("utf8",this.pos,this.pos+t);return this.pos+=t,e}readBytes(){let t=this.readUint32(),e=this.buf.slice(this.pos,this.pos+t);return this.pos+=t,e}remaining(){return this.buf.length-this.pos}};function Zn(r){let t=r.readUint8(),e=r.readString(),n=r.readUint32(),i=new Date(r.readFloat64()),s=new Date(r.readFloat64());if(t===Hn){let o=r.readUint8()===1,a=r.readBytes();return{type:"file",name:e,mode:n,createdAt:i,updatedAt:s,compressed:o,content:a}}if(t===qn){let o=r.readUint32(),a=new Map;for(let l=0;l<o;l++){let c=Zn(r);a.set(c.name,c)}return{type:"directory",name:e,mode:n,createdAt:i,updatedAt:s,children:a}}throw new Error(`[VFS binary] Unknown node type: 0x${t.toString(16)}`)}function Jn(r){if(r.length<5)throw new Error("[VFS binary] Buffer too short");if(!r.slice(0,4).equals(Ce))throw new Error("[VFS binary] Invalid magic \u2014 not a VFS binary snapshot");let e=new ve(r);for(let i=0;i<5;i++)e.readUint8();let n=Zn(e);if(n.type!=="directory")throw new Error("[VFS binary] Root node must be a directory");return n}function Yn(r){return r.length>=4&&r.slice(0,4).equals(Ce)}import*as re from"node:path";function j(r){if(!r||r.trim()==="")return"/";let t=re.posix.normalize(r.startsWith("/")?r:`/${r}`);return t===""?"/":t}function bi(r){return r.split("/").filter(Boolean)}function X(r,t){let e=j(t);if(e==="/")return r;let n=bi(e),i=r;for(let s of n){if(i.type!=="directory")throw new Error(`Path '${e}' does not exist.`);let o=i.children.get(s);if(!o)throw new Error(`Path '${e}' does not exist.`);i=o}return i}function Et(r,t,e,n){let i=j(t);if(i==="/")throw new Error("Root path has no parent directory.");let s=re.posix.dirname(i),o=re.posix.basename(i);if(!o)throw new Error(`Invalid path '${t}'.`);e&&n(s);let a=X(r,s);if(a.type!=="directory")throw new Error(`Parent path '${s}' is not a directory.`);return{parent:a,name:o}}var Pe=class r extends wi{root;mode;snapshotFile;constructor(t={}){if(super(),this.mode=t.mode??"memory",this.mode==="fs"){if(!t.snapshotPath)throw new Error('VirtualFileSystem: "snapshotPath" is required when mode is "fs".');this.snapshotFile=pt.resolve(t.snapshotPath,"vfs-snapshot.vfsb")}else this.snapshotFile=null;this.root=this.makeDir("",493)}makeDir(t,e){let n=new Date;return{type:"directory",name:t,mode:e,createdAt:n,updatedAt:n,children:new Map}}makeFile(t,e,n,i){let s=new Date;return{type:"file",name:t,content:e,mode:n,compressed:i,createdAt:s,updatedAt:s}}mkdirRecursive(t,e){let n=j(t);if(n==="/")return;let i=n.split("/").filter(Boolean),s=this.root,o="";for(let a of i){o+=`/${a}`;let l=s.children.get(a);if(!l)l=this.makeDir(a,e),s.children.set(a,l),this.emit("dir:create",{path:o,mode:e});else if(l.type!=="directory")throw new Error(`Cannot create directory '${o}': path is a file.`);s=l}}async restoreMirror(){if(!(this.mode!=="fs"||!this.snapshotFile)&&yt.existsSync(this.snapshotFile))try{let t=yt.readFileSync(this.snapshotFile);if(Yn(t))this.root=Jn(t);else{let e=JSON.parse(t.toString("utf8"));this.root=this.deserializeDir(e.root,""),console.info("[VirtualFileSystem] Migrating legacy JSON snapshot to binary format.")}this.emit("snapshot:restore",{path:this.snapshotFile})}catch(t){console.warn(`[VirtualFileSystem] Could not restore snapshot from ${this.snapshotFile}:`,t instanceof Error?t.message:String(t))}}async flushMirror(){if(this.mode!=="fs"||!this.snapshotFile){this.emit("mirror:flush");return}let t=pt.dirname(this.snapshotFile);yt.mkdirSync(t,{recursive:!0});let e=Gn(this.root);yt.writeFileSync(this.snapshotFile,e),this.emit("mirror:flush",{path:this.snapshotFile})}getMode(){return this.mode}getSnapshotPath(){return this.snapshotFile}mkdir(t,e=493){let n=j(t),i=(()=>{try{return X(this.root,n)}catch{return null}})();if(i&&i.type!=="directory")throw new Error(`Cannot create directory '${n}': path is a file.`);this.mkdirRecursive(n,e)}writeFile(t,e,n={}){let i=j(t),{parent:s,name:o}=Et(this.root,i,!0,m=>this.mkdirRecursive(m,493)),a=s.children.get(o);if(a?.type==="directory")throw new Error(`Cannot write file '${i}': path is a directory.`);let l=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),c=n.compress??!1,u=c?Qn(l):l,d=n.mode??420;if(a){let m=a;m.content=u,m.compressed=c,m.mode=d,m.updatedAt=new Date}else s.children.set(o,this.makeFile(o,u,d,c));this.emit("file:write",{path:i,size:u.length})}readFile(t){let e=j(t),n=X(this.root,e);if(n.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let i=n,s=i.compressed?$e(i.content):i.content;return this.emit("file:read",{path:e,size:s.length}),s.toString("utf8")}readFileRaw(t){let e=j(t),n=X(this.root,e);if(n.type!=="file")throw new Error(`Cannot read '${t}': not a file.`);let i=n,s=i.compressed?$e(i.content):i.content;return this.emit("file:read",{path:e,size:s.length}),s}exists(t){try{return X(this.root,j(t)),!0}catch{return!1}}chmod(t,e){X(this.root,j(t)).mode=e}stat(t){let e=j(t),n=X(this.root,e),i=e==="/"?"":pt.posix.basename(e);if(n.type==="file"){let o=n;return{type:"file",name:i,path:e,mode:o.mode,createdAt:o.createdAt,updatedAt:o.updatedAt,compressed:o.compressed,size:o.content.length}}let s=n;return{type:"directory",name:i,path:e,mode:s.mode,createdAt:s.createdAt,updatedAt:s.updatedAt,childrenCount:s.children.size}}list(t="/"){let e=j(t),n=X(this.root,e);if(n.type!=="directory")throw new Error(`Cannot list '${t}': not a directory.`);return Array.from(n.children.keys()).sort()}tree(t="/"){let e=j(t),n=X(this.root,e);if(n.type!=="directory")throw new Error(`Cannot render tree for '${t}': not a directory.`);let i=t==="/"?"/":pt.posix.basename(e);return this.renderTreeLines(n,i)}renderTreeLines(t,e){let n=[e],i=Array.from(t.children.keys()).sort();for(let s=0;s<i.length;s++){let o=i[s],a=t.children.get(o),l=s===i.length-1,c=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=l?" ":"\u2502 ";if(n.push(`${c}${o}`),a.type==="directory"){let d=this.renderTreeLines(a,"").split(`
337
338
  `).slice(1).map(m=>`${u}${m}`);n.push(...d)}}return n.join(`
338
- `)}getUsageBytes(t="/"){return this.computeUsage(X(this.root,W(t)))}computeUsage(t){if(t.type==="file")return t.content.length;let e=0;for(let n of t.children.values())e+=this.computeUsage(n);return e}compressFile(t){let e=X(this.root,W(t));if(e.type!=="file")throw new Error(`Cannot compress '${t}': not a file.`);let n=e;n.compressed||(n.content=Qn(n.content),n.compressed=!0,n.updatedAt=new Date)}decompressFile(t){let e=X(this.root,W(t));if(e.type!=="file")throw new Error(`Cannot decompress '${t}': not a file.`);let n=e;n.compressed&&(n.content=$e(n.content),n.compressed=!1,n.updatedAt=new Date)}symlink(t,e){let n=W(e),i=t.startsWith("/")?W(t):t,{parent:s,name:o}=Et(this.root,n,!0,l=>this.mkdirRecursive(l,493)),a={type:"file",name:o,content:Buffer.from(i,"utf8"),mode:41471,compressed:!1,createdAt:new Date,updatedAt:new Date};s.children.set(o,a),this.emit("symlink:create",{link:n,target:i})}isSymlink(t){try{let e=X(this.root,W(t));return e.type==="file"&&e.mode===41471}catch{return!1}}resolveSymlink(t,e=8){let n=W(t);for(let i=0;i<e;i++){try{let s=X(this.root,n);if(s.type==="file"&&s.mode===41471){let o=s.content.toString("utf8");n=o.startsWith("/")?o:W(pt.posix.join(pt.posix.dirname(n),o));continue}}catch{break}return n}throw new Error(`Too many levels of symbolic links: ${t}`)}remove(t,e={}){let n=W(t);if(n==="/")throw new Error("Cannot remove root directory.");let i=X(this.root,n);if(i.type==="directory"){let a=i;if(!e.recursive&&a.children.size>0)throw new Error(`Directory '${n}' is not empty. Use recursive option.`)}let{parent:s,name:o}=Et(this.root,n,!1,()=>{});s.children.delete(o),this.emit("node:remove",{path:n})}move(t,e){let n=W(t),i=W(e);if(n==="/"||i==="/")throw new Error("Cannot move root directory.");let s=X(this.root,n);if(this.exists(i))throw new Error(`Destination '${i}' already exists.`);this.mkdirRecursive(pt.posix.dirname(i),493);let{parent:o,name:a}=Et(this.root,i,!1,()=>{}),{parent:l,name:c}=Et(this.root,n,!1,()=>{});l.children.delete(c),s.name=a,o.children.set(a,s)}toSnapshot(){return{root:this.serializeDir(this.root)}}serializeDir(t){let e=[];for(let n of t.children.values())e.push(n.type==="file"?this.serializeFile(n):this.serializeDir(n));return{type:"directory",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),children:e}}serializeFile(t){return{type:"file",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),compressed:t.compressed,contentBase64:t.content.toString("base64")}}static fromSnapshot(t){let e=new r;return e.root=e.deserializeDir(t.root,""),e}importSnapshot(t){this.root=this.deserializeDir(t.root,""),this.emit("snapshot:import")}deserializeDir(t,e){let n={type:"directory",name:e,mode:t.mode,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),children:new Map};for(let i of t.children)if(i.type==="file"){let s=i;n.children.set(s.name,{type:"file",name:s.name,mode:s.mode,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt),compressed:s.compressed,content:Buffer.from(s.contentBase64,"base64")})}else{let s=this.deserializeDir(i,i.name);n.children.set(i.name,s)}return n}},Xn=Pe;var ke=[{name:"vim",version:"2:9.0.1378-2",section:"editors",description:"Vi IMproved - enhanced vi editor",shortDesc:"Vi IMproved",installedSizeKb:3812,files:[{path:"/usr/bin/vim",content:`#!/bin/sh
339
+ `)}getUsageBytes(t="/"){return this.computeUsage(X(this.root,j(t)))}computeUsage(t){if(t.type==="file")return t.content.length;let e=0;for(let n of t.children.values())e+=this.computeUsage(n);return e}compressFile(t){let e=X(this.root,j(t));if(e.type!=="file")throw new Error(`Cannot compress '${t}': not a file.`);let n=e;n.compressed||(n.content=Qn(n.content),n.compressed=!0,n.updatedAt=new Date)}decompressFile(t){let e=X(this.root,j(t));if(e.type!=="file")throw new Error(`Cannot decompress '${t}': not a file.`);let n=e;n.compressed&&(n.content=$e(n.content),n.compressed=!1,n.updatedAt=new Date)}symlink(t,e){let n=j(e),i=t.startsWith("/")?j(t):t,{parent:s,name:o}=Et(this.root,n,!0,l=>this.mkdirRecursive(l,493)),a={type:"file",name:o,content:Buffer.from(i,"utf8"),mode:41471,compressed:!1,createdAt:new Date,updatedAt:new Date};s.children.set(o,a),this.emit("symlink:create",{link:n,target:i})}isSymlink(t){try{let e=X(this.root,j(t));return e.type==="file"&&e.mode===41471}catch{return!1}}resolveSymlink(t,e=8){let n=j(t);for(let i=0;i<e;i++){try{let s=X(this.root,n);if(s.type==="file"&&s.mode===41471){let o=s.content.toString("utf8");n=o.startsWith("/")?o:j(pt.posix.join(pt.posix.dirname(n),o));continue}}catch{break}return n}throw new Error(`Too many levels of symbolic links: ${t}`)}remove(t,e={}){let n=j(t);if(n==="/")throw new Error("Cannot remove root directory.");let i=X(this.root,n);if(i.type==="directory"){let a=i;if(!e.recursive&&a.children.size>0)throw new Error(`Directory '${n}' is not empty. Use recursive option.`)}let{parent:s,name:o}=Et(this.root,n,!1,()=>{});s.children.delete(o),this.emit("node:remove",{path:n})}move(t,e){let n=j(t),i=j(e);if(n==="/"||i==="/")throw new Error("Cannot move root directory.");let s=X(this.root,n);if(this.exists(i))throw new Error(`Destination '${i}' already exists.`);this.mkdirRecursive(pt.posix.dirname(i),493);let{parent:o,name:a}=Et(this.root,i,!1,()=>{}),{parent:l,name:c}=Et(this.root,n,!1,()=>{});l.children.delete(c),s.name=a,o.children.set(a,s)}toSnapshot(){return{root:this.serializeDir(this.root)}}serializeDir(t){let e=[];for(let n of t.children.values())e.push(n.type==="file"?this.serializeFile(n):this.serializeDir(n));return{type:"directory",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),children:e}}serializeFile(t){return{type:"file",name:t.name,mode:t.mode,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),compressed:t.compressed,contentBase64:t.content.toString("base64")}}static fromSnapshot(t){let e=new r;return e.root=e.deserializeDir(t.root,""),e}importSnapshot(t){this.root=this.deserializeDir(t.root,""),this.emit("snapshot:import")}deserializeDir(t,e){let n={type:"directory",name:e,mode:t.mode,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),children:new Map};for(let i of t.children)if(i.type==="file"){let s=i;n.children.set(s.name,{type:"file",name:s.name,mode:s.mode,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt),compressed:s.compressed,content:Buffer.from(s.contentBase64,"base64")})}else{let s=this.deserializeDir(i,i.name);n.children.set(i.name,s)}return n}},Xn=Pe;var ke=[{name:"vim",version:"2:9.0.1378-2",section:"editors",description:"Vi IMproved - enhanced vi editor",shortDesc:"Vi IMproved",installedSizeKb:3812,files:[{path:"/usr/bin/vim",content:`#!/bin/sh
339
340
  echo 'vim: use nano for editing in this environment'
340
341
  `,mode:493},{path:"/usr/bin/vi",content:`#!/bin/sh
341
342
  exec vim "$@"
@@ -432,7 +433,7 @@ echo 'journalctl: virtual stub'
432
433
  `),exitCode:0}}remove(t,e={}){let n=[],i=[];for(let s of t){let o=this.installed.get(s.toLowerCase());o?i.push(o):n.push(`Package '${s}' is not installed, so not removed`)}if(i.length===0)return{output:n.join(`
433
434
  `)||"Nothing to remove.",exitCode:0};e.quiet||n.push("Reading package lists... Done","Building dependency tree... Done","The following packages will be REMOVED:",` ${i.map(s=>s.name).join(" ")}`,`0 upgraded, 0 newly installed, ${i.length} to remove and 0 not upgraded.`);for(let s of i){e.quiet||n.push(`Removing ${s.name} (${s.version}) ...`);for(let a of s.files)if(!(!e.purge&&(a.startsWith("/etc/")||a.endsWith(".conf"))))try{this.vfs.exists(a)&&this.vfs.remove(a)}catch{}this.findInRegistry(s.name)?.onRemove?.(this.vfs),this.installed.delete(s.name),this.log(`remove ${s.name} ${s.version}`)}return this.aptLog("remove",i.map(s=>s.name)),this.persist(),{output:n.join(`
434
435
  `),exitCode:0}}search(t){let e=t.toLowerCase();return ke.filter(n=>n.name.includes(e)||n.description.toLowerCase().includes(e)||(n.shortDesc??"").toLowerCase().includes(e)).sort((n,i)=>n.name.localeCompare(i.name))}show(t){let e=this.findInRegistry(t);if(!e)return null;let n=this.installed.get(t);return[`Package: ${e.name}`,`Version: ${e.version}`,`Architecture: ${e.architecture??"amd64"}`,`Maintainer: ${e.maintainer??"Fortune Maintainers <pkg@fortune.local>"}`,`Installed-Size: ${e.installedSizeKb??0}`,`Depends: ${(e.depends??[]).join(", ")||"(none)"}`,`Section: ${e.section??"misc"}`,"Priority: optional",`Description: ${e.description}`,`Status: ${n?"install ok installed":"install ok not-installed"}`].join(`
435
- `)}};import{createHash as vi,randomBytes as Ci,randomUUID as $i,scryptSync as Pi}from"node:crypto";import{EventEmitter as ki}from"node:events";import*as es from"node:path";function Mi(){let r=process.env.SSH_MIMIC_FAST_PASSWORD_HASH;return!!r&&!["0","false","no","off"].includes(r.toLowerCase())}var J=ee("VirtualUserManager"),se=class r extends ki{constructor(e,n=!0){super();this.vfs=e;this.autoSudoForNewUsers=n;J.mark("constructor")}vfs;autoSudoForNewUsers;static recordCache=new Map;static fastPasswordHash=Mi();usersPath="/virtual-env-js/.auth/htpasswd";sudoersPath="/virtual-env-js/.auth/sudoers";quotasPath="/virtual-env-js/.auth/quotas";authDirPath="/virtual-env-js/.auth";users=new Map;sudoers=new Set;quotas=new Map;activeSessions=new Map;nextTty=0;async initialize(){J.mark("initialize"),this.loadFromVfs(),this.loadSudoersFromVfs(),this.loadQuotasFromVfs();let e=!1;this.users.has("root")||(this.users.set("root",this.createRecord("root","")),e=!0),this.sudoers.add("root"),e&&await this.persist(),this.emit("initialized")}async setQuotaBytes(e,n){if(J.mark("setQuotaBytes"),this.validateUsername(e),!this.users.has(e))throw new Error(`quota: user '${e}' does not exist`);if(!Number.isFinite(n)||n<0)throw new Error("quota: maxBytes must be a non-negative number");this.quotas.set(e,Math.floor(n)),await this.persist()}async clearQuota(e){J.mark("clearQuota"),this.validateUsername(e),this.quotas.delete(e),await this.persist()}getQuotaBytes(e){return J.mark("getQuotaBytes"),this.quotas.get(e)??null}getUsageBytes(e){J.mark("getUsageBytes");let n=`/home/${e}`;return this.vfs.exists(n)?this.vfs.getUsageBytes(n):0}assertWriteWithinQuota(e,n,i){J.mark("assertWriteWithinQuota");let s=this.quotas.get(e);if(s===void 0)return;let o=ts(n),a=ts(`/home/${e}`);if(!(o===a||o.startsWith(`${a}/`)))return;let c=this.getUsageBytes(e),u=0;if(this.vfs.exists(o)){let f=this.vfs.stat(o);f.type==="file"&&(u=f.size)}let d=Buffer.isBuffer(i)?i.length:Buffer.byteLength(i,"utf8"),m=c-u+d;if(m>s)throw new Error(`quota exceeded for '${e}': ${m}/${s} bytes`)}verifyPassword(e,n){J.mark("verifyPassword");let i=this.users.get(e);return i?this.hashPassword(n)===i.passwordHash:!1}async addUser(e,n){if(J.mark("addUser"),this.validateUsername(e),this.validatePassword(n),this.users.has(e))return;this.users.set(e,this.createRecord(e,n)),this.autoSudoForNewUsers&&this.sudoers.add(e);let i=`/home/${e}`;this.vfs.exists(i)||(this.vfs.mkdir(i,493),this.vfs.writeFile(`${i}/README.txt`,`Welcome to the virtual environment, ${e}`)),await this.persist(),this.emit("user:add",{username:e})}getPasswordHash(e){J.mark("getPasswordHash");let n=this.users.get(e);return n?n.passwordHash:null}async setPassword(e,n){if(J.mark("setPassword"),this.validateUsername(e),this.validatePassword(n),!this.users.has(e))throw new Error(`passwd: user '${e}' does not exist`);this.users.set(e,this.createRecord(e,n)),await this.persist()}async deleteUser(e){if(J.mark("deleteUser"),this.validateUsername(e),e==="root")throw new Error("deluser: cannot delete root");if(!this.users.delete(e))throw new Error(`deluser: user '${e}' does not exist`);this.sudoers.delete(e),this.emit("user:delete",{username:e}),await this.persist()}isSudoer(e){return J.mark("isSudoer"),this.sudoers.has(e)}async addSudoer(e){if(J.mark("addSudoer"),this.validateUsername(e),!this.users.has(e))throw new Error(`sudoers: user '${e}' does not exist`);this.sudoers.add(e),await this.persist()}async removeSudoer(e){if(J.mark("removeSudoer"),this.validateUsername(e),e==="root")throw new Error("sudoers: cannot remove root");this.sudoers.delete(e),await this.persist()}registerSession(e,n){J.mark("registerSession");let i={id:$i(),username:e,tty:`pts/${this.nextTty++}`,remoteAddress:n,startedAt:new Date().toISOString()};return this.activeSessions.set(i.id,i),this.emit("session:register",{sessionId:i.id,username:e,remoteAddress:n}),i}unregisterSession(e){if(J.mark("unregisterSession"),!e)return;let n=this.activeSessions.get(e);this.activeSessions.delete(e),n&&this.emit("session:unregister",{sessionId:e,username:n.username}),this.activeSessions.delete(e)}updateSession(e,n,i){if(J.mark("updateSession"),!e)return;let s=this.activeSessions.get(e);s&&this.activeSessions.set(e,{...s,username:n,remoteAddress:i})}listActiveSessions(){return J.mark("listActiveSessions"),Array.from(this.activeSessions.values()).sort((e,n)=>e.startedAt.localeCompare(n.startedAt))}listUsers(){return Array.from(this.users.keys()).sort()}loadFromVfs(){if(this.users.clear(),!this.vfs.exists(this.usersPath))return;let e=this.vfs.readFile(this.usersPath);for(let n of e.split(`
436
+ `)}};import{createHash as vi,randomBytes as Ci,randomUUID as $i,scryptSync as Pi}from"node:crypto";import{EventEmitter as ki}from"node:events";import*as es from"node:path";function Mi(){let r=process.env.SSH_MIMIC_FAST_PASSWORD_HASH;return!!r&&!["0","false","no","off"].includes(r.toLowerCase())}var J=ee("VirtualUserManager"),se=class r extends ki{constructor(e,n=!0){super();this.vfs=e;this.autoSudoForNewUsers=n;J.mark("constructor")}vfs;autoSudoForNewUsers;static recordCache=new Map;static fastPasswordHash=Mi();usersPath="/virtual-env-js/.auth/htpasswd";sudoersPath="/virtual-env-js/.auth/sudoers";quotasPath="/virtual-env-js/.auth/quotas";authDirPath="/virtual-env-js/.auth";users=new Map;sudoers=new Set;quotas=new Map;activeSessions=new Map;nextTty=0;async initialize(){J.mark("initialize"),this.loadFromVfs(),this.loadSudoersFromVfs(),this.loadQuotasFromVfs();let e=!1;this.users.has("root")||(this.users.set("root",this.createRecord("root","")),e=!0),this.sudoers.add("root");let n="/home/root";this.vfs.exists(n)||(this.vfs.mkdir(n,493),this.vfs.writeFile(`${n}/README.txt`,"Welcome to the virtual environment, root")),e&&await this.persist(),this.emit("initialized")}async setQuotaBytes(e,n){if(J.mark("setQuotaBytes"),this.validateUsername(e),!this.users.has(e))throw new Error(`quota: user '${e}' does not exist`);if(!Number.isFinite(n)||n<0)throw new Error("quota: maxBytes must be a non-negative number");this.quotas.set(e,Math.floor(n)),await this.persist()}async clearQuota(e){J.mark("clearQuota"),this.validateUsername(e),this.quotas.delete(e),await this.persist()}getQuotaBytes(e){return J.mark("getQuotaBytes"),this.quotas.get(e)??null}getUsageBytes(e){J.mark("getUsageBytes");let n=`/home/${e}`;return this.vfs.exists(n)?this.vfs.getUsageBytes(n):0}assertWriteWithinQuota(e,n,i){J.mark("assertWriteWithinQuota");let s=this.quotas.get(e);if(s===void 0)return;let o=ts(n),a=ts(`/home/${e}`);if(!(o===a||o.startsWith(`${a}/`)))return;let c=this.getUsageBytes(e),u=0;if(this.vfs.exists(o)){let f=this.vfs.stat(o);f.type==="file"&&(u=f.size)}let d=Buffer.isBuffer(i)?i.length:Buffer.byteLength(i,"utf8"),m=c-u+d;if(m>s)throw new Error(`quota exceeded for '${e}': ${m}/${s} bytes`)}verifyPassword(e,n){J.mark("verifyPassword");let i=this.users.get(e);return i?this.hashPassword(n)===i.passwordHash:!1}async addUser(e,n){if(J.mark("addUser"),this.validateUsername(e),this.validatePassword(n),this.users.has(e))return;this.users.set(e,this.createRecord(e,n)),this.autoSudoForNewUsers&&this.sudoers.add(e);let i=`/home/${e}`;this.vfs.exists(i)||(this.vfs.mkdir(i,493),this.vfs.writeFile(`${i}/README.txt`,`Welcome to the virtual environment, ${e}`)),await this.persist(),this.emit("user:add",{username:e})}getPasswordHash(e){J.mark("getPasswordHash");let n=this.users.get(e);return n?n.passwordHash:null}async setPassword(e,n){if(J.mark("setPassword"),this.validateUsername(e),this.validatePassword(n),!this.users.has(e))throw new Error(`passwd: user '${e}' does not exist`);this.users.set(e,this.createRecord(e,n)),await this.persist()}async deleteUser(e){if(J.mark("deleteUser"),this.validateUsername(e),e==="root")throw new Error("deluser: cannot delete root");if(!this.users.delete(e))throw new Error(`deluser: user '${e}' does not exist`);this.sudoers.delete(e),this.emit("user:delete",{username:e}),await this.persist()}isSudoer(e){return J.mark("isSudoer"),this.sudoers.has(e)}async addSudoer(e){if(J.mark("addSudoer"),this.validateUsername(e),!this.users.has(e))throw new Error(`sudoers: user '${e}' does not exist`);this.sudoers.add(e),await this.persist()}async removeSudoer(e){if(J.mark("removeSudoer"),this.validateUsername(e),e==="root")throw new Error("sudoers: cannot remove root");this.sudoers.delete(e),await this.persist()}registerSession(e,n){J.mark("registerSession");let i={id:$i(),username:e,tty:`pts/${this.nextTty++}`,remoteAddress:n,startedAt:new Date().toISOString()};return this.activeSessions.set(i.id,i),this.emit("session:register",{sessionId:i.id,username:e,remoteAddress:n}),i}unregisterSession(e){if(J.mark("unregisterSession"),!e)return;let n=this.activeSessions.get(e);this.activeSessions.delete(e),n&&this.emit("session:unregister",{sessionId:e,username:n.username}),this.activeSessions.delete(e)}updateSession(e,n,i){if(J.mark("updateSession"),!e)return;let s=this.activeSessions.get(e);s&&this.activeSessions.set(e,{...s,username:n,remoteAddress:i})}listActiveSessions(){return J.mark("listActiveSessions"),Array.from(this.activeSessions.values()).sort((e,n)=>e.startedAt.localeCompare(n.startedAt))}listUsers(){return Array.from(this.users.keys()).sort()}loadFromVfs(){if(this.users.clear(),!this.vfs.exists(this.usersPath))return;let e=this.vfs.readFile(this.usersPath);for(let n of e.split(`
436
437
  `)){let i=n.trim();if(i.length===0)continue;let s=i.split(":");if(s.length<3)continue;let[o,a,l]=s;!o||!a||!l||this.users.set(o,{username:o,salt:a,passwordHash:l})}}loadSudoersFromVfs(){if(this.sudoers.clear(),!this.vfs.exists(this.sudoersPath))return;let e=this.vfs.readFile(this.sudoersPath);for(let n of e.split(`
437
438
  `)){let i=n.trim();i.length>0&&this.sudoers.add(i)}}loadQuotasFromVfs(){if(this.quotas.clear(),!this.vfs.exists(this.quotasPath))return;let e=this.vfs.readFile(this.quotasPath);for(let n of e.split(`
438
439
  `)){let i=n.trim();if(i.length===0)continue;let[s,o]=i.split(":"),a=Number.parseInt(o??"",10);!s||!Number.isFinite(a)||a<0||this.quotas.set(s,a)}}async persist(){this.vfs.exists(this.authDirPath)||this.vfs.mkdir(this.authDirPath,448);let e=Array.from(this.users.values()).sort((o,a)=>o.username.localeCompare(a.username)).map(o=>[o.username,o.salt,o.passwordHash].join(":")).join(`
@@ -470,10 +471,10 @@ Sorry, try again.\r
470
471
  `),L.stderr&&t.write(`${Dt(L.stderr)}\r
471
472
  `),L.closeSession){t.write(`logout\r
472
473
  `),t.exit(L.exitCode??0),t.end();return}L.nextCwd&&(f=L.nextCwd),L.switchUser&&(e=L.switchUser,f=L.nextCwd??`/home/${e}`,a.users.updateSession(i,e,s),l="",c=0),await a.vfs.flushMirror()}k();continue}if(F==="\x7F"||F==="\b"){c>0&&(l=`${l.slice(0,c-1)}${l.slice(c)}`,c-=1,k());continue}P(F)}}),t.on("close",()=>{g&&(g.process.kill("SIGTERM"),g=null)})}function Vi(r){let t="/virtual-env-js/.bash_history";return r.exists(t)?r.readFile(t).split(`
473
- `).map(n=>n.trim()).filter(n=>n.length>0):(r.writeFile(t,""),[])}function Di(r){return typeof r=="object"&&r!==null&&"vfsInstance"in r&&us(r.vfsInstance)}function us(r){if(typeof r!="object"||r===null)return!1;let t=r;return typeof t.restoreMirror=="function"&&typeof t.flushMirror=="function"&&typeof t.writeFile=="function"&&typeof t.readFile=="function"&&typeof t.mkdir=="function"&&typeof t.exists=="function"&&typeof t.stat=="function"&&typeof t.list=="function"&&typeof t.remove=="function"&&typeof t.copy=="function"&&typeof t.move=="function"&&typeof t.touch=="function"}var _i={kernel:"1.0.0+itsrealfortune+1-amd64",os:"Fortune GNU/Linux x64",arch:"x86_64"},_t=ee("VirtualShell");function Li(){let r=process.env.SSH_MIMIC_AUTO_SUDO_NEW_USERS;return r?!["0","false","no","off"].includes(r.toLowerCase()):!0}var oe=class extends Ri{vfs;users;packageManager;hostname;properties;startTime;initialized;constructor(t,e,n){super(),_t.mark("constructor"),this.hostname=t,this.properties=e||_i,this.startTime=Date.now(),us(n)?this.vfs=n:Di(n)?this.vfs=n.vfsInstance:this.vfs=new Xn(n??{}),this.users=new se(this.vfs,Li()),this.packageManager=new ne(this.vfs,this.users);let i=this.vfs,s=this.users,o=this.packageManager,a=this.properties,l=this.hostname,c=this.startTime;this.initialized=(async()=>{await i.restoreMirror(),await s.initialize(),Un(i,s,l,a,c),o.load(),this.emit("initialized")})()}async ensureInitialized(){_t.mark("ensureInitialized"),await this.initialized}addCommand(t,e,n){let i=t.trim().toLowerCase();if(i.length===0||/\s/.test(i))throw new Error("Command name must be non-empty and contain no spaces");ye(Se(i,e,n))}executeCommand(t,e,n){_t.mark("executeCommand"),Z(t,e,this.hostname,"shell",n,this),this.emit("command",{command:t,user:e,cwd:n})}startInteractiveSession(t,e,n,i,s){_t.mark("startInteractiveSession"),this.emit("session:start",{user:e,sessionId:n,remoteAddress:i}),cs(this.properties,t,e,this.hostname,n,i,s,this),this.refreshProcSessions()}refreshProcFs(){te(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}refreshProcSessions(){te(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}syncPasswd(){be(this.vfs,this.users)}getVfs(){return this?.vfs??null}getUsers(){return this?.users??null}getHostname(){return this?.hostname}writeFileAsUser(t,e,n){_t.mark("writeFileAsUser"),this.users.assertWriteWithinQuota(t,e,n),this.vfs.writeFile(e,n)}};var Tt=process.env.SSH_MIMIC_HOSTNAME??"typescript-vm",Ae=process.argv.slice(2);function Bi(){for(let r=0;r<Ae.length;r+=1){let t=Ae[r];if(t==="--user"){let e=Ae[r+1];if(!e||e.startsWith("--"))throw new Error("self-standalone: --user requires a value");return e}if(t?.startsWith("--user="))return t.slice(7)||"root"}return"root"}var Ui=Bi(),st=new oe(Tt,void 0,{mode:"fs",snapshotPath:".vfs"});function ji(r){let t=`/virtual-env-js/.lastlog/${r}.json`;if(!st.vfs.exists(t))return null;try{return JSON.parse(st.vfs.readFile(t))}catch{return null}}function Wi(r,t){return new Promise(e=>{r.question(t,e)})}function Hi(r,t){let e="/virtual-env-js/.lastlog";st.vfs.exists(e)||st.vfs.mkdir(e,448),st.vfs.writeFile(`/virtual-env-js/.lastlog/${r}.json`,JSON.stringify({at:new Date().toISOString(),from:t}))}st.addCommand("demo",[],()=>({stdout:"This is a demo command. It does nothing useful.",exitCode:0}));async function qi(){let r=zi({input:Oi,output:Lt,terminal:!0});await st.ensureInitialized();let t=Ui.trim()||"root";st.users.getPasswordHash(t)!==null||(process.stderr.write(`self-standalone: user '${t}' does not exist
474
- `),process.exit(1));let n=kt(t,Tt),i=t,s=`/home/${i}`;n.vars.PWD=s;let o="localhost";if(process.env.USER!=="root"&&st.users.hasPassword(i)){let c=await Wi(r,`Password for ${i}: `);st.users.verifyPassword(i,c)||(process.stderr.write(`self-standalone: authentication failed
474
+ `).map(n=>n.trim()).filter(n=>n.length>0):(r.writeFile(t,""),[])}function Di(r){return typeof r=="object"&&r!==null&&"vfsInstance"in r&&us(r.vfsInstance)}function us(r){if(typeof r!="object"||r===null)return!1;let t=r;return typeof t.restoreMirror=="function"&&typeof t.flushMirror=="function"&&typeof t.writeFile=="function"&&typeof t.readFile=="function"&&typeof t.mkdir=="function"&&typeof t.exists=="function"&&typeof t.stat=="function"&&typeof t.list=="function"&&typeof t.remove=="function"&&typeof t.copy=="function"&&typeof t.move=="function"&&typeof t.touch=="function"}var _i={kernel:"1.0.0+itsrealfortune+1-amd64",os:"Fortune GNU/Linux x64",arch:"x86_64"},_t=ee("VirtualShell");function Li(){let r=process.env.SSH_MIMIC_AUTO_SUDO_NEW_USERS;return r?!["0","false","no","off"].includes(r.toLowerCase()):!0}var oe=class extends Ri{vfs;users;packageManager;hostname;properties;startTime;initialized;constructor(t,e,n){super(),_t.mark("constructor"),this.hostname=t,this.properties=e||_i,this.startTime=Date.now(),us(n)?this.vfs=n:Di(n)?this.vfs=n.vfsInstance:this.vfs=new Xn(n??{}),this.users=new se(this.vfs,Li()),this.packageManager=new ne(this.vfs,this.users);let i=this.vfs,s=this.users,o=this.packageManager,a=this.properties,l=this.hostname,c=this.startTime;this.initialized=(async()=>{await i.restoreMirror(),await s.initialize(),Un(i,s,l,a,c),o.load(),this.emit("initialized")})()}async ensureInitialized(){_t.mark("ensureInitialized"),await this.initialized}addCommand(t,e,n){let i=t.trim().toLowerCase();if(i.length===0||/\s/.test(i))throw new Error("Command name must be non-empty and contain no spaces");ye(Se(i,e,n))}executeCommand(t,e,n){_t.mark("executeCommand"),Z(t,e,this.hostname,"shell",n,this),this.emit("command",{command:t,user:e,cwd:n})}startInteractiveSession(t,e,n,i,s){_t.mark("startInteractiveSession"),this.emit("session:start",{user:e,sessionId:n,remoteAddress:i}),cs(this.properties,t,e,this.hostname,n,i,s,this),this.refreshProcSessions()}refreshProcFs(){te(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}refreshProcSessions(){te(this.vfs,this.properties,this.hostname,this.startTime,this.users.listActiveSessions())}syncPasswd(){be(this.vfs,this.users)}getVfs(){return this?.vfs??null}getUsers(){return this?.users??null}getHostname(){return this?.hostname}writeFileAsUser(t,e,n){_t.mark("writeFileAsUser"),this.users.assertWriteWithinQuota(t,e,n),this.vfs.writeFile(e,n)}};var Tt=process.env.SSH_MIMIC_HOSTNAME??"typescript-vm",Ae=process.argv.slice(2);function Bi(){for(let r=0;r<Ae.length;r+=1){let t=Ae[r];if(t==="--user"){let e=Ae[r+1];if(!e||e.startsWith("--"))throw new Error("self-standalone: --user requires a value");return e}if(t?.startsWith("--user="))return t.slice(7)||"root"}return"root"}var Ui=Bi(),st=new oe(Tt,void 0,{mode:"fs",snapshotPath:".vfs"});function Wi(r){let t=`/virtual-env-js/.lastlog/${r}.json`;if(!st.vfs.exists(t))return null;try{return JSON.parse(st.vfs.readFile(t))}catch{return null}}function ji(r,t){return new Promise(e=>{r.question(t,e)})}function Hi(r,t){let e="/virtual-env-js/.lastlog";st.vfs.exists(e)||st.vfs.mkdir(e,448),st.vfs.writeFile(`/virtual-env-js/.lastlog/${r}.json`,JSON.stringify({at:new Date().toISOString(),from:t}))}st.addCommand("demo",[],()=>({stdout:"This is a demo command. It does nothing useful.",exitCode:0}));async function qi(){let r=zi({input:Oi,output:Lt,terminal:!0});await st.ensureInitialized();let t=Ui.trim()||"root";st.users.getPasswordHash(t)!==null||(process.stderr.write(`self-standalone: user '${t}' does not exist
475
+ `),process.exit(1));let n=kt(t,Tt),i=t,s=`/home/${i}`;n.vars.PWD=s;let o="localhost";if(process.env.USER!=="root"&&st.users.hasPassword(i)){let c=await ji(r,`Password for ${i}: `);st.users.verifyPassword(i,c)||(process.stderr.write(`self-standalone: authentication failed
475
476
  `),process.exit(1))}let a=()=>{let c=s===`/home/${i}`?"~":Ti(s)||"/";return Xt(i,Tt,c)},l=()=>{r.setPrompt(a()),r.prompt()};for(r.on("SIGINT",()=>{Lt.write(`^C
476
- `),r.write("",{ctrl:!0,name:"u"}),l()}),r.on("close",()=>{console.log(""),process.exit(0)}),Lt.write(Qt(Tt,st.properties,ji(i))),Hi(i,o),l();;){let c=await new Promise(d=>{r.once("line",m=>d(m))});r.pause();let u=await Z(c,i,Tt,"shell",s,st,void 0,n);u.stdout&&Lt.write(u.stdout.endsWith(`
477
+ `),r.write("",{ctrl:!0,name:"u"}),l()}),r.on("close",()=>{console.log(""),process.exit(0)}),Lt.write(Qt(Tt,st.properties,Wi(i))),Hi(i,o),l();;){let c=await new Promise(d=>{r.once("line",m=>d(m))});r.pause();let u=await Z(c,i,Tt,"shell",s,st,void 0,n);u.stdout&&Lt.write(u.stdout.endsWith(`
477
478
  `)?u.stdout:`${u.stdout}
478
479
  `),u.stderr&&process.stderr.write(u.stderr.endsWith(`
479
480
  `)?u.stderr:`${u.stderr}