@innovatorved/code-lab 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +2 -2
- package/CHANGELOG.md +20 -0
- package/README.md +2 -2
- package/dist/apps/web/src/index.d.ts +0 -9
- package/dist/code-lab-sql.esm.js +19 -19
- package/dist/code-lab-sql.umd.js +20 -20
- package/dist/code-lab.css +1 -1
- package/dist/code-lab.d.ts +1 -1
- package/dist/code-lab.esm.js +679 -1439
- package/dist/code-lab.js +678 -1438
- package/dist/extensions/cpp.esm.js +132 -8760
- package/dist/extensions/cpp.js +124 -8770
- package/dist/extensions/guided-lab.esm.js +33 -6836
- package/dist/extensions/guided-lab.js +33 -6854
- package/dist/extensions/javascript.esm.js +1 -36
- package/dist/extensions/javascript.js +1 -58
- package/dist/extensions/python.esm.js +79 -8118
- package/dist/extensions/python.js +79 -8136
- package/dist/extensions/typescript.esm.js +1 -55
- package/dist/extensions/typescript.js +1 -77
- package/dist/modular-kernel.d.ts +0 -4
- package/dist/preview-sw.js +1 -1
- package/dist/runtime.esm.js +77 -77
- package/dist/runtime.js +77 -77
- package/dist/schemas.d.ts +9 -0
- package/dist/schemas.esm.js +33 -6815
- package/dist/schemas.js +33 -6831
- package/dist/shell.esm.js +33 -33
- package/dist/shell.js +33 -33
- package/dist/terminal.esm.js +8 -6
- package/dist/terminal.js +6 -6
- package/dist/workbench/command-palette.d.ts +0 -4
- package/dist/workbench/index.d.ts +0 -20
- package/dist/workbench/intellisense.d.ts +1 -7
- package/package.json +3 -10
- package/src/code-lab.css +4 -502
- package/src/extensions/cpp.ts +11 -29
- package/src/extensions/guided-lab.ts +6 -2
- package/src/extensions/python.ts +9 -3
- package/src/modular-kernel.ts +0 -4
- package/src/runtime.ts +124 -39
- package/src/schemas.ts +2 -2
- package/src/shell.ts +3 -0
- package/src/terminal.ts +4 -2
- package/src/workbench/command-palette.ts +22 -302
- package/src/workbench/diff-editor.ts +2 -0
- package/src/workbench/icons.ts +1 -1
- package/src/workbench/index.ts +0 -15
- package/src/workbench/intellisense.ts +17 -4
- package/src/workbench.ts +68 -375
- package/dist/code-lab.umd.js +0 -6117
- package/dist/packages/editor/src/index.d.ts +0 -118
- package/dist/packages/preview/src/index.d.ts +0 -34
- package/dist/packages/runtime/src/index.d.ts +0 -47
- package/dist/packages/terminal/src/index.d.ts +0 -54
- package/dist/workbench/drawer.d.ts +0 -18
- package/dist/workbench/file-tree.d.ts +0 -11
- package/dist/workbench/guided-pane.d.ts +0 -11
- package/dist/workbench/styles.d.ts +0 -4
- package/dist/workbench/toolbar.d.ts +0 -17
- package/packages/commands/README.md +0 -7
- package/packages/commands/package.json +0 -16
- package/packages/commands/src/index.ts +0 -467
- package/packages/commands/tsconfig.json +0 -22
- package/packages/core/README.md +0 -12
- package/packages/core/package.json +0 -13
- package/packages/core/src/di.ts +0 -147
- package/packages/core/src/disposable.ts +0 -112
- package/packages/core/src/errors.ts +0 -205
- package/packages/core/src/events.ts +0 -157
- package/packages/core/src/index.ts +0 -49
- package/packages/core/src/path.ts +0 -118
- package/packages/core/src/registry.ts +0 -61
- package/packages/core/tsconfig.json +0 -19
- package/packages/editor/README.md +0 -9
- package/packages/editor/package.json +0 -18
- package/packages/editor/src/index.ts +0 -344
- package/packages/editor/tsconfig.json +0 -24
- package/packages/fs/README.md +0 -7
- package/packages/fs/package.json +0 -16
- package/packages/fs/src/backends.ts +0 -301
- package/packages/fs/src/index.ts +0 -18
- package/packages/fs/src/types.ts +0 -44
- package/packages/fs/src/vfs-service.ts +0 -257
- package/packages/fs/tsconfig.json +0 -22
- package/packages/preview/README.md +0 -3
- package/packages/preview/package.json +0 -16
- package/packages/preview/src/index.ts +0 -125
- package/packages/preview/tsconfig.json +0 -22
- package/packages/runtime/README.md +0 -3
- package/packages/runtime/package.json +0 -17
- package/packages/runtime/src/index.ts +0 -134
- package/packages/runtime/tsconfig.json +0 -23
- package/packages/settings/README.md +0 -7
- package/packages/settings/package.json +0 -16
- package/packages/settings/src/builtin-schemas.ts +0 -262
- package/packages/settings/src/configuration-service.ts +0 -609
- package/packages/settings/src/index.ts +0 -38
- package/packages/settings/src/jsonc.ts +0 -189
- package/packages/settings/src/schema.ts +0 -164
- package/packages/settings/tsconfig.json +0 -22
- package/packages/sql/README.md +0 -12
- package/packages/sql/package.json +0 -13
- package/packages/sql/src/completions.ts +0 -359
- package/packages/sql/src/diagnostics.ts +0 -200
- package/packages/sql/src/formatter.ts +0 -271
- package/packages/sql/src/index.ts +0 -54
- package/packages/sql/src/sql-editor.ts +0 -802
- package/packages/sql/src/styles.ts +0 -524
- package/packages/sql/src/tokenizer.ts +0 -457
- package/packages/sql/src/types.ts +0 -148
- package/packages/sql/tsconfig.json +0 -19
- package/packages/terminal/README.md +0 -3
- package/packages/terminal/package.json +0 -16
- package/packages/terminal/src/index.ts +0 -183
- package/packages/terminal/tsconfig.json +0 -22
- package/packages/ui/README.md +0 -8
- package/packages/ui/package.json +0 -18
- package/packages/ui/src/index.ts +0 -40
- package/packages/ui/src/observability.ts +0 -173
- package/packages/ui/src/plugin-registry.ts +0 -289
- package/packages/ui/src/settings-dialog.ts +0 -939
- package/packages/ui/src/themes.ts +0 -333
- package/packages/ui/tsconfig.json +0 -24
- package/src/workbench/drawer.ts +0 -157
- package/src/workbench/file-tree.ts +0 -51
- package/src/workbench/guided-pane.ts +0 -43
- package/src/workbench/styles.ts +0 -211
- package/src/workbench/toolbar.ts +0 -182
package/dist/shell.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.7.
|
|
3
|
+
* @innovatorved/code-lab v0.7.1 — Standalone Browser Code IDE & Virtual Runtime
|
|
4
4
|
* ============================================================
|
|
5
5
|
* Features:
|
|
6
6
|
* - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
|
|
@@ -180,7 +180,7 @@ isomorphic-git/index.js:
|
|
|
180
180
|
|
|
181
181
|
if (typeof CodeLabScm !== 'undefined') root.CodeLabScm = CodeLabScm;
|
|
182
182
|
(function () {
|
|
183
|
-
(function(W,M){const U=M(W);W&&(W.CodeLabShell=U,W.createPosixShell=U.createPosixShell,W.PosixShell=U.PosixShell,W.parseShellCommand=U.parseShellCommand,W.tokenizeShell=U.tokenizeShell,W.COREUTILS=U.COREUTILS,W.createVirtualPortTable=U.createVirtualPortTable,W.parseGitHubRepoUrl=U.parseGitHubRepoUrl,W.cloneGitHubRepository=U.cloneGitHubRepository),typeof module<"u"&&module.exports?module.exports=U:typeof define=="function"&&define.amd&&define([],function(){return U})})(typeof globalThis<"u"?globalThis:this,function(W){"use strict";const M=W&&W.CodeLabLogger&&typeof W.CodeLabLogger.createLogger=="function"?W.CodeLabLogger.createLogger():{debug(){},info(...n){typeof console<"u"&&console.info&&console.info("[code-lab]",...n)},warn(...n){typeof console<"u"&&console.warn&&console.warn("[code-lab]",...n)},error(...n){typeof console<"u"&&console.error&&console.error("[code-lab]",...n)}};function U(){if(typeof W<"u"&&W&&W.CodeLabRuntime)return W.CodeLabRuntime;if(typeof globalThis<"u"&&globalThis.CodeLabRuntime)return globalThis.CodeLabRuntime;try{if(typeof require<"u")return require("./runtime.js")}catch(n){M.debug("Optional ./runtime.js require skipped in shell.",n)}return null}function je(){if(typeof W<"u"&&W&&W.CodeLabScm)return W.CodeLabScm;if(typeof globalThis<"u"&&globalThis.CodeLabScm)return globalThis.CodeLabScm;try{if(typeof require<"u")return require("./scm.js")}catch(n){M.debug("Optional ./scm.js require skipped in shell.",n)}return null}function Re(){const n=U();return!!(n&&typeof n.executeInVirtualRuntime=="function")}function Oe(...n){const e=U();if(e&&typeof e.executeInVirtualRuntime=="function")return e.executeInVirtualRuntime(...n);throw new Error("Virtual runtime engine is not available")}async function q(n,e){const s=U();if(!s||typeof s.executeInVirtualRuntime!="function")throw new Error("Virtual runtime engine is not available");let t=typeof n.replCode=="string"?n.replCode:"";if(!t&&typeof n.entry=="string"&&e&&e.vfs&&typeof e.vfs.existsSync=="function")try{const h=typeof e.resolvePath=="function"?e.resolvePath(n.entry):n.entry,u=e.vfs.existsSync(h)?h:e.vfs.existsSync(n.entry)?n.entry:"";u&&(t=String(e.vfs.readFileSync(u,"utf8")||""))}catch(h){}let r=n.npmModules;const o=new Set(["assert","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","sqlite","stream","string_decoder","sys","test","timers","tls","tty","url","util","v8","vm","wasi","worker_threads","zlib"]);let i=!1;if(t&&!(n.isBackground||e&&e.isBackground)){const h=/(?:from\s+|require\s*\(\s*)['"]([^./'"]+)['"]/g;let u;for(;(u=h.exec(t))!==null;){const p=u[1];if(p.startsWith("node:")||p.startsWith("bun:"))continue;const g=p.startsWith("@")?p.split("/").slice(0,2).join("/"):p.split("/")[0];if(!o.has(g)){i=!0;break}}}if(i&&typeof s.preloadNpmPackages=="function")try{const h=await s.preloadNpmPackages({[n.entry||"eval.js"]:t});h&&typeof h=="object"&&(r=Object.assign({},h,r||{}))}catch(h){M.debug("preloadNpmPackages skipped in shell:",h)}const f=(e&&typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e&&e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:void 0),d=e&&e.shell?e.shell.portTable:null,y=!!(d&&typeof d.listServers=="function"&&d.listServers().length>0),l=!!(n.isBackground||e&&e.isBackground||y||/(?:\bcreateServer\b|\.listen\s*\(|\bBun\.serve\b|\blocalhost\b|127\.0\.0\.1)/.test(t)),a=n.instanceId||(e&&e.shell&&e.shell.options&&e.shell.options.instanceId?e.shell.options.instanceId:void 0),c={...n,...a?{instanceId:a}:{},concurrent:!0,npmModules:r,onRequestStdin:f};if(!l&&typeof Worker<"u"&&typeof s.executeInWorker=="function"){const h={...c};return delete h.activePortTable,delete h.portTable,s.executeInWorker(h)}return s.executeInVirtualRuntime({...c,activePortTable:d})}function le(...n){const e=U();return e&&typeof e.createVirtualPortTable=="function"?e.createVirtualPortTable(...n):null}function Je(n,e){const s=U();return s&&typeof s.transpileTS=="function"?s.transpileTS(n,e):String(n).replace(/^\s*import\s+type\s+[^\n;]+;?\s*$/gm,"").replace(/^\s*export\s+(?:interface|type)\s+[A-Za-z0-9_$]+[\s\S]*?(?:^\}|\n)/gm,"").replace(/^\s*(?:interface|type)\s+[A-Za-z0-9_$]+[^;{]*\{[^}]*\}/gm,"").replace(/:\s*[A-Za-z0-9_$<>\[\]|&\s]+(?=[,=)\n;{])/g,"")}const j={normalize(n){if(typeof n!="string"||!n)return"/";const e=n.startsWith("/"),s=n.split("/").filter(Boolean),t=[];for(const o of s)o!=="."&&(o===".."?t.length>0&&t.pop():t.push(o));return(e?"/":"")+t.join("/")||(e?"/":".")},resolve(n,...e){let s=n.startsWith("/")?n:"/"+n;const t=j._homeDir||"/home/codelab";for(const r of e)r&&(r.startsWith("/")?s=r:r==="~"||r.startsWith("~/")?s=t+r.slice(1):s=s.endsWith("/")?s+r:s+"/"+r);return j.normalize(s)},dirname(n){const e=j.normalize(n);if(e==="/"||e===".")return e;const s=e.lastIndexOf("/");return s===-1?".":s===0?"/":e.slice(0,s)},basename(n,e){const s=j.normalize(n);if(s==="/")return"/";const t=s.lastIndexOf("/");let r=t===-1?s:s.slice(t+1);return e&&r.endsWith(e)&&r!==e&&(r=r.slice(0,-e.length)),r},join(...n){return j.normalize(n.filter(Boolean).join("/"))}};function Pe(n,e=!0){let s="^",t=0;for(;t<n.length;){const r=n[t];if(r==="*"&&n[t+1]==="*"&&(n[t+2]==="/"||t+2===n.length))s+="(?:.+/)?",t+=n[t+2]==="/"?3:2;else if(r==="*"&&n[t+1]==="*")s+=".*",t+=2;else if(r==="*")s+=e?"[^/]*":".*",t++;else if(r==="?")s+=e?"[^/]":".",t++;else if(r==="["){const o=n.indexOf("]",t+1);if(o!==-1){let i=n.slice(t+1,o);i.startsWith("!")&&(i="^"+i.slice(1)),s+="["+i+"]",t=o+1}else s+="\\[",t++}else[".","$","^","+","(",")","{","}","|","\\"].includes(r)?(s+="\\"+r,t++):(s+=r,t++)}return s+="$",new RegExp(s)}function Ee(n){if(typeof n!="string"||!n.includes("{")||!n.includes("}"))return[n];let e=-1,s=-1,t=0;for(let a=0;a<n.length;a++){if(n[a]==="\\"){a++;continue}if(n[a]==="{")t===0&&(e=a),t++;else if(n[a]==="}"&&t>0&&(t--,t===0)){const c=n.slice(e+1,a);if(ae(c)||/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(c)||/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(c)){s=a;break}}}if(e===-1||s===-1)return[n];const r=n.slice(0,e),o=n.slice(e+1,s),i=n.slice(s+1);let f=[];const d=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/),y=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);if(d&&!ae(o)){const a=d[1],c=d[2],h=parseInt(a,10),u=parseInt(c,10);let p=d[3]!==void 0?parseInt(d[3],10):h<=u?1:-1;p===0&&(p=1),(h<=u&&p<0||h>u&&p>0)&&(p=-p);const g=a.startsWith("0")&&a.length>1||c.startsWith("0")&&c.length>1?Math.max(a.length,c.length):0;for(let m=h;p>0?m<=u:m>=u;m+=p){let S=String(Math.abs(m));g>0&&(S=S.padStart(g-(m<0?1:0),"0")),f.push(m<0?"-"+S:S)}}else if(y&&!ae(o)){const a=y[1].charCodeAt(0),c=y[2].charCodeAt(0);let h=y[3]!==void 0&&Math.abs(parseInt(y[3],10))||1;a>c&&(h=-h);for(let u=a;h>0?u<=c:u>=c;u+=h)f.push(String.fromCharCode(u))}else f=Ge(o);const l=[];for(const a of f)for(const c of Ee(a))for(const h of Ee(i))l.push(r+c+h);return l}function ae(n){let e=0;for(let s=0;s<n.length;s++){if(n[s]==="\\"){s++;continue}if(n[s]==="{")e++;else if(n[s]==="}")e=Math.max(0,e-1);else if(n[s]===","&&e===0)return!0}return!1}function Ge(n){const e=[];let s="",t=0;for(let r=0;r<n.length;r++){if(n[r]==="\\"&&r+1<n.length){s+=n[r]+n[r+1],r++;continue}n[r]==="{"?(t++,s+=n[r]):n[r]==="}"?(t=Math.max(0,t-1),s+=n[r]):n[r]===","&&t===0?(e.push(s),s=""):s+=n[r]}return e.push(s),e}function ce(n,e={},s=null){const t=String(n||"").trim();if(!t)return 0;const r=[];let o=0;const i=t.length;for(;o<i;){const k=t[o];if(/\s/.test(k)){o++;continue}const O=t.slice(o,o+3);if(O==="<<="||O===">>="){r.push({type:"OP",value:O}),o+=3;continue}const F=t.slice(o,o+2);if(["**","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^=","|="].includes(F)){r.push({type:"OP",value:F}),o+=2;continue}if("+-*/%<>&|^!~?:=,()".includes(k)){r.push({type:"OP",value:k}),o++;continue}if(k==="$"){o++;let P="";if(t[o]==="{"){for(o++;o<i&&t[o]!=="}";)P+=t[o++];t[o]==="}"&&o++}else for(;o<i&&/[a-zA-Z0-9_?#]/.test(t[o]);)P+=t[o++];const A=e[P]!==void 0?e[P]:s&&s[P]!==void 0?s[P]:"0",_=Number(A);r.push({type:"NUM",value:Number.isFinite(_)?Math.trunc(_):0,name:P});continue}if(/[0-9]/.test(k)){let P="";for(;o<i&&/[0-9a-fA-FxXbBoO_]/.test(t[o]);)t[o]!=="_"&&(P+=t[o]),o++;let A=0;/^0[xX]/.test(P)?A=parseInt(P.slice(2),16)||0:/^0[bB]/.test(P)?A=parseInt(P.slice(2),2)||0:/^0[oO]/.test(P)?A=parseInt(P.slice(2),8)||0:P.length>1&&P.startsWith("0")&&/^[0-7]+$/.test(P)?A=parseInt(P,8)||0:A=parseInt(P,10)||0,r.push({type:"NUM",value:A});continue}if(/[a-zA-Z_]/.test(k)){let P="";for(;o<i&&/[a-zA-Z0-9_]/.test(t[o]);)P+=t[o++];r.push({type:"IDENT",name:P});continue}o++}let f=0;const d=()=>r[f]||null,y=()=>r[f++]||null;function l(k){const O=e[k]!==void 0?e[k]:s&&s[k]!==void 0?s[k]:0,F=Number(O);return Number.isFinite(F)?Math.trunc(F):0}function a(k,O){const F=Math.trunc(Number(O)||0);return e[k]=String(F),s&&(s[k]=String(F)),F}function c(){let k=h();for(;d()&&d().type==="OP"&&d().value===",";)y(),k=h();return k}function h(){if(d()&&(d().type==="IDENT"||d().type==="NUM"&&d().name)){const k=r[f+1];if(k&&k.type==="OP"&&["=","+=","-=","*=","/=","%=","<<=",">>=","&=","^=","|="].includes(k.value)){const O=y().name,F=y().value,P=h(),A=l(O);if(F==="=")return a(O,P);if(F==="+=")return a(O,A+P);if(F==="-=")return a(O,A-P);if(F==="*=")return a(O,A*P);if(F==="/=")return a(O,P===0?0:Math.trunc(A/P));if(F==="%=")return a(O,P===0?0:A%P);if(F==="<<=")return a(O,A<<P);if(F===">>=")return a(O,A>>P);if(F==="&=")return a(O,A&P);if(F==="^=")return a(O,A^P);if(F==="|=")return a(O,A|P)}}return u()}function u(){const k=p();if(d()&&d().type==="OP"&&d().value==="?"){y();const O=h();d()&&d().type==="OP"&&d().value===":"&&y();const F=h();return k!==0?O:F}return k}function p(){let k=g();for(;d()&&d().type==="OP"&&d().value==="||";){y();const O=g();k=k!==0||O!==0?1:0}return k}function g(){let k=m();for(;d()&&d().type==="OP"&&d().value==="&&";){y();const O=m();k=k!==0&&O!==0?1:0}return k}function m(){let k=S();for(;d()&&d().type==="OP"&&d().value==="|";)y(),k=k|S();return k}function S(){let k=b();for(;d()&&d().type==="OP"&&d().value==="^";)y(),k=k^b();return k}function b(){let k=v();for(;d()&&d().type==="OP"&&d().value==="&";)y(),k=k&v();return k}function v(){let k=w();for(;d()&&d().type==="OP"&&(d().value==="=="||d().value==="!=");){const O=y().value,F=w();k=O==="=="?k===F?1:0:k!==F?1:0}return k}function w(){let k=$();for(;d()&&d().type==="OP"&&["<","<=",">",">="].includes(d().value);){const O=y().value,F=$();O==="<"?k=k<F?1:0:O==="<="?k=k<=F?1:0:O===">"?k=k>F?1:0:O===">="&&(k=k>=F?1:0)}return k}function $(){let k=R();for(;d()&&d().type==="OP"&&(d().value==="<<"||d().value===">>");){const O=y().value,F=R();k=O==="<<"?k<<F:k>>F}return k}function R(){let k=I();for(;d()&&d().type==="OP"&&(d().value==="+"||d().value==="-");){const O=y().value,F=I();k=O==="+"?k+F:k-F}return k}function I(){let k=C();for(;d()&&d().type==="OP"&&["*","/","%"].includes(d().value);){const O=y().value,F=C();O==="*"?k=k*F:O==="/"?k=F===0?0:Math.trunc(k/F):O==="%"&&(k=F===0?0:k%F)}return k}function C(){const k=E();if(d()&&d().type==="OP"&&d().value==="**"){y();const O=C();return Math.trunc(Math.pow(k,O))}return k}function E(){const k=d();if(k&&k.type==="OP"){if(k.value==="+")return y(),+E();if(k.value==="-")return y(),-E();if(k.value==="!")return y(),E()===0?1:0;if(k.value==="~")return y(),~E();if(k.value==="++"||k.value==="--"){const O=y().value,F=d();if(F&&(F.type==="IDENT"||F.name)){y();const P=l(F.name);return a(F.name,O==="++"?P+1:P-1)}return E()}}return T()}function T(){const k=d();if(!k)return 0;if(k.type==="OP"&&k.value==="("){y();const O=c();return d()&&d().type==="OP"&&d().value===")"&&y(),O}if(k.type==="IDENT"){y();const O=l(k.name);if(d()&&d().type==="OP"&&(d().value==="++"||d().value==="--")){const F=y().value;a(k.name,F==="++"?O+1:O-1)}return O}if(k.type==="NUM"){if(y(),k.name&&d()&&d().type==="OP"&&(d().value==="++"||d().value==="--")){const O=y().value;a(k.name,O==="++"?k.value+1:k.value-1)}return k.value}return y(),0}return Math.trunc(c()||0)}function Fe(n,e,s){if(!s)return[n];if(!/[*?\[]/.test(n))return[n];const t=n.startsWith("/"),r=t?"/":e,o=[];function i(l,a){let c=[];try{typeof s.readdirSync=="function"&&(c=s.readdirSync(l))}catch{return}for(const h of c){const u=l==="/"?"/"+h:l+"/"+h,p=a?a+"/"+h:h;o.push({full:u,rel:p});let g=!1;try{typeof s.statSync=="function"&&(g=s.statSync(u).isDirectory())}catch(m){M.debug("Glob statSync failed.",u,m)}g&&i(u,p)}}i(r,"");const f=t?n:n.startsWith("./")?n.slice(2):n,d=Pe(f,!0),y=[];for(const l of o){const a=t?l.full:l.rel;if(d.test(a)){const c=a.split("/").filter(Boolean),h=f.split("/").filter(Boolean);let u=!1;for(let p=0;p<c.length;p++){const g=c[p],m=h[p]!==void 0?h[p]:h[h.length-1];if(g&&g.startsWith(".")&&m&&!m.startsWith(".")){u=!0;break}}u||y.push(t?l.full:n.startsWith("./")?"./"+l.rel:l.rel)}}return y.sort(),y.length>0?y:[n]}function Te(n){if(typeof n!="string")return[];const e=[],s=n.length;let t=0,r=-1;for(;t<s;){const o=n[t];if(o===`
|
|
183
|
+
(function(W,N){const U=N(W);W&&(W.CodeLabShell=U,W.createPosixShell=U.createPosixShell,W.PosixShell=U.PosixShell,W.parseShellCommand=U.parseShellCommand,W.tokenizeShell=U.tokenizeShell,W.COREUTILS=U.COREUTILS,W.createVirtualPortTable=U.createVirtualPortTable,W.parseGitHubRepoUrl=U.parseGitHubRepoUrl,W.cloneGitHubRepository=U.cloneGitHubRepository),typeof module<"u"&&module.exports?module.exports=U:typeof define=="function"&&define.amd&&define([],function(){return U})})(typeof globalThis<"u"?globalThis:this,function(W){"use strict";const N=W&&W.CodeLabLogger&&typeof W.CodeLabLogger.createLogger=="function"?W.CodeLabLogger.createLogger():{debug(){},info(...n){typeof console<"u"&&console.info&&console.info("[code-lab]",...n)},warn(...n){typeof console<"u"&&console.warn&&console.warn("[code-lab]",...n)},error(...n){typeof console<"u"&&console.error&&console.error("[code-lab]",...n)}};function U(){if(typeof W<"u"&&W&&W.CodeLabRuntime)return W.CodeLabRuntime;if(typeof globalThis<"u"&&globalThis.CodeLabRuntime)return globalThis.CodeLabRuntime;try{if(typeof require<"u")return require("./runtime.js")}catch(n){N.debug("Optional ./runtime.js require skipped in shell.",n)}return null}function je(){if(typeof W<"u"&&W&&W.CodeLabScm)return W.CodeLabScm;if(typeof globalThis<"u"&&globalThis.CodeLabScm)return globalThis.CodeLabScm;try{if(typeof require<"u")return require("./scm.js")}catch(n){N.debug("Optional ./scm.js require skipped in shell.",n)}return null}function Re(){const n=U();return!!(n&&typeof n.executeInVirtualRuntime=="function")}function Oe(...n){const e=U();if(e&&typeof e.executeInVirtualRuntime=="function")return e.executeInVirtualRuntime(...n);throw new Error("Virtual runtime engine is not available")}async function q(n,e){const s=U();if(!s||typeof s.executeInVirtualRuntime!="function")throw new Error("Virtual runtime engine is not available");let t=typeof n.replCode=="string"?n.replCode:"";if(!t&&typeof n.entry=="string"&&e&&e.vfs&&typeof e.vfs.existsSync=="function")try{const h=typeof e.resolvePath=="function"?e.resolvePath(n.entry):n.entry,u=e.vfs.existsSync(h)?h:e.vfs.existsSync(n.entry)?n.entry:"";u&&(t=String(e.vfs.readFileSync(u,"utf8")||""))}catch(h){}let r=n.npmModules;const o=new Set(["assert","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","sqlite","stream","string_decoder","sys","test","timers","tls","tty","url","util","v8","vm","wasi","worker_threads","zlib"]);let i=!1;if(t&&!(n.isBackground||e&&e.isBackground)){const h=/(?:from\s+|require\s*\(\s*)['"]([^./'"]+)['"]/g;let u;for(;(u=h.exec(t))!==null;){const p=u[1];if(p.startsWith("node:")||p.startsWith("bun:"))continue;const g=p.startsWith("@")?p.split("/").slice(0,2).join("/"):p.split("/")[0];if(!o.has(g)){i=!0;break}}}if(i&&typeof s.preloadNpmPackages=="function")try{const h=await s.preloadNpmPackages({[n.entry||"eval.js"]:t});h&&typeof h=="object"&&(r=Object.assign({},h,r||{}))}catch(h){N.debug("preloadNpmPackages skipped in shell:",h)}const f=(e&&typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e&&e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:void 0),d=e&&e.shell?e.shell.portTable:null,y=!!(d&&typeof d.listServers=="function"&&d.listServers().length>0),l=!!(n.isBackground||e&&e.isBackground||y||/(?:\bcreateServer\b|\.listen\s*\(|\bBun\.serve\b|\blocalhost\b|127\.0\.0\.1)/.test(t)),a=n.instanceId||(e&&e.shell&&e.shell.options&&e.shell.options.instanceId?e.shell.options.instanceId:void 0),c={...n,...a?{instanceId:a}:{},concurrent:!0,npmModules:r,onRequestStdin:f};if(!l&&typeof Worker<"u"&&typeof s.executeInWorker=="function"){const h={...c};return delete h.activePortTable,delete h.portTable,s.executeInWorker(h)}return s.executeInVirtualRuntime({...c,activePortTable:d})}function le(...n){const e=U();return e&&typeof e.createVirtualPortTable=="function"?e.createVirtualPortTable(...n):null}function Je(n,e){const s=U();return s&&typeof s.transpileTS=="function"?s.transpileTS(n,e):String(n).replace(/^\s*import\s+type\s+[^\n;]+;?\s*$/gm,"").replace(/^\s*export\s+(?:interface|type)\s+[A-Za-z0-9_$]+[\s\S]*?(?:^\}|\n)/gm,"").replace(/^\s*(?:interface|type)\s+[A-Za-z0-9_$]+[^;{]*\{[^}]*\}/gm,"").replace(/:\s*[A-Za-z0-9_$<>\[\]|&\s]+(?=[,=)\n;{])/g,"")}const j={normalize(n){if(typeof n!="string"||!n)return"/";const e=n.startsWith("/"),s=n.split("/").filter(Boolean),t=[];for(const o of s)o!=="."&&(o===".."?t.length>0&&t.pop():t.push(o));return(e?"/":"")+t.join("/")||(e?"/":".")},resolve(n,...e){let s=n.startsWith("/")?n:"/"+n;const t=j._homeDir||"/home/codelab";for(const r of e)r&&(r.startsWith("/")?s=r:r==="~"||r.startsWith("~/")?s=t+r.slice(1):s=s.endsWith("/")?s+r:s+"/"+r);return j.normalize(s)},dirname(n){const e=j.normalize(n);if(e==="/"||e===".")return e;const s=e.lastIndexOf("/");return s===-1?".":s===0?"/":e.slice(0,s)},basename(n,e){const s=j.normalize(n);if(s==="/")return"/";const t=s.lastIndexOf("/");let r=t===-1?s:s.slice(t+1);return e&&r.endsWith(e)&&r!==e&&(r=r.slice(0,-e.length)),r},join(...n){return j.normalize(n.filter(Boolean).join("/"))}};function Pe(n,e=!0){let s="^",t=0;for(;t<n.length;){const r=n[t];if(r==="*"&&n[t+1]==="*"&&(n[t+2]==="/"||t+2===n.length))s+="(?:.+/)?",t+=n[t+2]==="/"?3:2;else if(r==="*"&&n[t+1]==="*")s+=".*",t+=2;else if(r==="*")s+=e?"[^/]*":".*",t++;else if(r==="?")s+=e?"[^/]":".",t++;else if(r==="["){const o=n.indexOf("]",t+1);if(o!==-1){let i=n.slice(t+1,o);i.startsWith("!")&&(i="^"+i.slice(1)),s+="["+i+"]",t=o+1}else s+="\\[",t++}else[".","$","^","+","(",")","{","}","|","\\"].includes(r)?(s+="\\"+r,t++):(s+=r,t++)}return s+="$",new RegExp(s)}function Ee(n){if(typeof n!="string"||!n.includes("{")||!n.includes("}"))return[n];let e=-1,s=-1,t=0;for(let a=0;a<n.length;a++){if(n[a]==="\\"){a++;continue}if(n[a]==="{")t===0&&(e=a),t++;else if(n[a]==="}"&&t>0&&(t--,t===0)){const c=n.slice(e+1,a);if(ae(c)||/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(c)||/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(c)){s=a;break}}}if(e===-1||s===-1)return[n];const r=n.slice(0,e),o=n.slice(e+1,s),i=n.slice(s+1);let f=[];const d=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/),y=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);if(d&&!ae(o)){const a=d[1],c=d[2],h=parseInt(a,10),u=parseInt(c,10);let p=d[3]!==void 0?parseInt(d[3],10):h<=u?1:-1;p===0&&(p=1),(h<=u&&p<0||h>u&&p>0)&&(p=-p);const g=a.startsWith("0")&&a.length>1||c.startsWith("0")&&c.length>1?Math.max(a.length,c.length):0;for(let m=h;p>0?m<=u:m>=u;m+=p){let S=String(Math.abs(m));g>0&&(S=S.padStart(g-(m<0?1:0),"0")),f.push(m<0?"-"+S:S)}}else if(y&&!ae(o)){const a=y[1].charCodeAt(0),c=y[2].charCodeAt(0);let h=y[3]!==void 0&&Math.abs(parseInt(y[3],10))||1;a>c&&(h=-h);for(let u=a;h>0?u<=c:u>=c;u+=h)f.push(String.fromCharCode(u))}else f=Ge(o);const l=[];for(const a of f)for(const c of Ee(a))for(const h of Ee(i))l.push(r+c+h);return l}function ae(n){let e=0;for(let s=0;s<n.length;s++){if(n[s]==="\\"){s++;continue}if(n[s]==="{")e++;else if(n[s]==="}")e=Math.max(0,e-1);else if(n[s]===","&&e===0)return!0}return!1}function Ge(n){const e=[];let s="",t=0;for(let r=0;r<n.length;r++){if(n[r]==="\\"&&r+1<n.length){s+=n[r]+n[r+1],r++;continue}n[r]==="{"?(t++,s+=n[r]):n[r]==="}"?(t=Math.max(0,t-1),s+=n[r]):n[r]===","&&t===0?(e.push(s),s=""):s+=n[r]}return e.push(s),e}function ce(n,e={},s=null){const t=String(n||"").trim();if(!t)return 0;const r=[];let o=0;const i=t.length;for(;o<i;){const k=t[o];if(/\s/.test(k)){o++;continue}const O=t.slice(o,o+3);if(O==="<<="||O===">>="){r.push({type:"OP",value:O}),o+=3;continue}const F=t.slice(o,o+2);if(["**","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^=","|="].includes(F)){r.push({type:"OP",value:F}),o+=2;continue}if("+-*/%<>&|^!~?:=,()".includes(k)){r.push({type:"OP",value:k}),o++;continue}if(k==="$"){o++;let P="";if(t[o]==="{"){for(o++;o<i&&t[o]!=="}";)P+=t[o++];t[o]==="}"&&o++}else for(;o<i&&/[a-zA-Z0-9_?#]/.test(t[o]);)P+=t[o++];const A=e[P]!==void 0?e[P]:s&&s[P]!==void 0?s[P]:"0",M=Number(A);r.push({type:"NUM",value:Number.isFinite(M)?Math.trunc(M):0,name:P});continue}if(/[0-9]/.test(k)){let P="";for(;o<i&&/[0-9a-fA-FxXbBoO_]/.test(t[o]);)t[o]!=="_"&&(P+=t[o]),o++;let A=0;/^0[xX]/.test(P)?A=parseInt(P.slice(2),16)||0:/^0[bB]/.test(P)?A=parseInt(P.slice(2),2)||0:/^0[oO]/.test(P)?A=parseInt(P.slice(2),8)||0:P.length>1&&P.startsWith("0")&&/^[0-7]+$/.test(P)?A=parseInt(P,8)||0:A=parseInt(P,10)||0,r.push({type:"NUM",value:A});continue}if(/[a-zA-Z_]/.test(k)){let P="";for(;o<i&&/[a-zA-Z0-9_]/.test(t[o]);)P+=t[o++];r.push({type:"IDENT",name:P});continue}o++}let f=0;const d=()=>r[f]||null,y=()=>r[f++]||null;function l(k){const O=e[k]!==void 0?e[k]:s&&s[k]!==void 0?s[k]:0,F=Number(O);return Number.isFinite(F)?Math.trunc(F):0}function a(k,O){const F=Math.trunc(Number(O)||0);return e[k]=String(F),s&&(s[k]=String(F)),F}function c(){let k=h();for(;d()&&d().type==="OP"&&d().value===",";)y(),k=h();return k}function h(){if(d()&&(d().type==="IDENT"||d().type==="NUM"&&d().name)){const k=r[f+1];if(k&&k.type==="OP"&&["=","+=","-=","*=","/=","%=","<<=",">>=","&=","^=","|="].includes(k.value)){const O=y().name,F=y().value,P=h(),A=l(O);if(F==="=")return a(O,P);if(F==="+=")return a(O,A+P);if(F==="-=")return a(O,A-P);if(F==="*=")return a(O,A*P);if(F==="/=")return a(O,P===0?0:Math.trunc(A/P));if(F==="%=")return a(O,P===0?0:A%P);if(F==="<<=")return a(O,A<<P);if(F===">>=")return a(O,A>>P);if(F==="&=")return a(O,A&P);if(F==="^=")return a(O,A^P);if(F==="|=")return a(O,A|P)}}return u()}function u(){const k=p();if(d()&&d().type==="OP"&&d().value==="?"){y();const O=h();d()&&d().type==="OP"&&d().value===":"&&y();const F=h();return k!==0?O:F}return k}function p(){let k=g();for(;d()&&d().type==="OP"&&d().value==="||";){y();const O=g();k=k!==0||O!==0?1:0}return k}function g(){let k=m();for(;d()&&d().type==="OP"&&d().value==="&&";){y();const O=m();k=k!==0&&O!==0?1:0}return k}function m(){let k=S();for(;d()&&d().type==="OP"&&d().value==="|";)y(),k=k|S();return k}function S(){let k=b();for(;d()&&d().type==="OP"&&d().value==="^";)y(),k=k^b();return k}function b(){let k=v();for(;d()&&d().type==="OP"&&d().value==="&";)y(),k=k&v();return k}function v(){let k=w();for(;d()&&d().type==="OP"&&(d().value==="=="||d().value==="!=");){const O=y().value,F=w();k=O==="=="?k===F?1:0:k!==F?1:0}return k}function w(){let k=$();for(;d()&&d().type==="OP"&&["<","<=",">",">="].includes(d().value);){const O=y().value,F=$();O==="<"?k=k<F?1:0:O==="<="?k=k<=F?1:0:O===">"?k=k>F?1:0:O===">="&&(k=k>=F?1:0)}return k}function $(){let k=R();for(;d()&&d().type==="OP"&&(d().value==="<<"||d().value===">>");){const O=y().value,F=R();k=O==="<<"?k<<F:k>>F}return k}function R(){let k=I();for(;d()&&d().type==="OP"&&(d().value==="+"||d().value==="-");){const O=y().value,F=I();k=O==="+"?k+F:k-F}return k}function I(){let k=C();for(;d()&&d().type==="OP"&&["*","/","%"].includes(d().value);){const O=y().value,F=C();O==="*"?k=k*F:O==="/"?k=F===0?0:Math.trunc(k/F):O==="%"&&(k=F===0?0:k%F)}return k}function C(){const k=E();if(d()&&d().type==="OP"&&d().value==="**"){y();const O=C();return Math.trunc(Math.pow(k,O))}return k}function E(){const k=d();if(k&&k.type==="OP"){if(k.value==="+")return y(),+E();if(k.value==="-")return y(),-E();if(k.value==="!")return y(),E()===0?1:0;if(k.value==="~")return y(),~E();if(k.value==="++"||k.value==="--"){const O=y().value,F=d();if(F&&(F.type==="IDENT"||F.name)){y();const P=l(F.name);return a(F.name,O==="++"?P+1:P-1)}return E()}}return T()}function T(){const k=d();if(!k)return 0;if(k.type==="OP"&&k.value==="("){y();const O=c();return d()&&d().type==="OP"&&d().value===")"&&y(),O}if(k.type==="IDENT"){y();const O=l(k.name);if(d()&&d().type==="OP"&&(d().value==="++"||d().value==="--")){const F=y().value;a(k.name,F==="++"?O+1:O-1)}return O}if(k.type==="NUM"){if(y(),k.name&&d()&&d().type==="OP"&&(d().value==="++"||d().value==="--")){const O=y().value;a(k.name,O==="++"?k.value+1:k.value-1)}return k.value}return y(),0}return Math.trunc(c()||0)}function Fe(n,e,s){if(!s)return[n];if(!/[*?\[]/.test(n))return[n];const t=n.startsWith("/"),r=t?"/":e,o=[];function i(l,a){let c=[];try{typeof s.readdirSync=="function"&&(c=s.readdirSync(l))}catch{return}for(const h of c){const u=l==="/"?"/"+h:l+"/"+h,p=a?a+"/"+h:h;o.push({full:u,rel:p});let g=!1;try{typeof s.statSync=="function"&&(g=s.statSync(u).isDirectory())}catch(m){N.debug("Glob statSync failed.",u,m)}g&&i(u,p)}}i(r,"");const f=t?n:n.startsWith("./")?n.slice(2):n,d=Pe(f,!0),y=[];for(const l of o){const a=t?l.full:l.rel;if(d.test(a)){const c=a.split("/").filter(Boolean),h=f.split("/").filter(Boolean);let u=!1;for(let p=0;p<c.length;p++){const g=c[p],m=h[p]!==void 0?h[p]:h[h.length-1];if(g&&g.startsWith(".")&&m&&!m.startsWith(".")){u=!0;break}}u||y.push(t?l.full:n.startsWith("./")?"./"+l.rel:l.rel)}}return y.sort(),y.length>0?y:[n]}function Te(n){if(typeof n!="string")return[];const e=[],s=n.length;let t=0,r=-1;for(;t<s;){const o=n[t];if(o===`
|
|
184
184
|
`){if(r>t?(t=r,r=-1):t++,e.length>0){const l=e[e.length-1].type;l!=="SEMICOLON"&&l!=="DSEMI"&&l!=="AND"&&l!=="OR"&&l!=="PIPE"&&l!=="LPAREN"&&e.push({type:"SEMICOLON",raw:";"})}continue}if(/[ \t\r\f\v]/.test(o)){t++;continue}if(o==="#"){for(;t<s&&n[t]!==`
|
|
185
185
|
`;)t++;continue}if(o===";"&&n[t+1]===";"){e.push({type:"DSEMI",raw:";;"}),t+=2;continue}if(o===";"){e.push({type:"SEMICOLON",raw:";"}),t++;continue}if(o==="("){e.push({type:"LPAREN",raw:"("}),t++;continue}if(o===")"){e.push({type:"RPAREN",raw:")"}),t++;continue}if(o==="&"&&n[t+1]==="&"){e.push({type:"AND",raw:"&&"}),t+=2;continue}if(o==="|"&&n[t+1]==="|"){e.push({type:"OR",raw:"||"}),t+=2;continue}if(o==="|"){e.push({type:"PIPE",raw:"|"}),t++;continue}if(o==="&"&&n[t+1]===">"){e.push({type:"REDIRECT",op:"&>",sourceFd:"all",raw:"&>"}),t+=2;continue}if(o==="&"){e.push({type:"BACKGROUND",raw:"&"}),t++;continue}if((o==="1"||o==="2"||o==="0")&&(n[t+1]===">"||n[t+1]==="<")){const l=parseInt(o,10),a=n[t+1];if(a===">"&&n[t+2]==="&"&&(n[t+3]==="1"||n[t+3]==="2")){const c=parseInt(n[t+3],10);e.push({type:"REDIRECT_FD",sourceFd:l,targetFd:c,raw:`${l}>&${c}`}),t+=4;continue}if(a===">"&&n[t+2]===">"){e.push({type:"REDIRECT",op:">>",sourceFd:l,raw:`${l}>>`}),t+=3;continue}e.push({type:"REDIRECT",op:a,sourceFd:l,raw:`${l}${a}`}),t+=2;continue}if(o===">"){if(n[t+1]==="&"&&(n[t+2]==="1"||n[t+2]==="2")){const l=parseInt(n[t+2],10);e.push({type:"REDIRECT_FD",sourceFd:1,targetFd:l,raw:`>&${l}`}),t+=3;continue}if(n[t+1]===">"){e.push({type:"REDIRECT",op:">>",sourceFd:1,raw:">>"}),t+=2;continue}e.push({type:"REDIRECT",op:">",sourceFd:1,raw:">"}),t++;continue}if(o==="<"){if(n[t+1]==="<"&&n[t+2]==="<"){e.push({type:"REDIRECT",op:"<<<",sourceFd:0,raw:"<<<"}),t+=3;continue}if(n[t+1]==="<"){const l=n[t+2]==="-";for(t+=l?3:2;t<s&&(n[t]===" "||n[t]===" ");)t++;let a="",c=!1;for(;t<s&&!/[\s;|&<>()]/.test(n[t]);)if(n[t]==="'"||n[t]==='"'){const p=n[t++];for(c=!0;t<s&&n[t]!==p;)a+=n[t++];t<s&&n[t]===p&&t++}else n[t]==="\\"&&t+1<s&&(c=!0,t++),a+=n[t++];const h=r>t?r:n.indexOf(`
|
|
186
186
|
`,t);let u="";if(h!==-1&&h<s){let p=h+1;for(;p<=s;){let g=n.indexOf(`
|
|
@@ -196,7 +196,7 @@ isomorphic-git/index.js:
|
|
|
196
196
|
`;for(const u of l)u.type==="common"?h+=` ${u.line}
|
|
197
197
|
`:u.type==="added"?h+=`+${u.line}
|
|
198
198
|
`:u.type==="removed"&&(h+=`-${u.line}
|
|
199
|
-
`);return h}function fe(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;let s=null,t=null,r=null,o=null;const i=e.indexOf("#");if(i!==-1){const l=e.slice(i+1).trim();e=e.slice(0,i).trim(),l&&(r=l)}const f=e.match(/^git@github\.com:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/);if(f)return s=f[1],t=f[2],{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`};const d=e.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:\/(tree|blob)\/([^/]+)(?:\/(.+?))?)?\/?$/);if(d){s=d[1],t=d[2];const l=d[4]?d[5]?`${d[4]}/${d[5].replace(/^\/+|\/+$/g,"")}`:d[4]:null;return l&&/^(?:feature|feat|fix|bugfix|hotfix|release|chore|refactor|docs|test|ci|depend|dependabot)\/[^/]+$/.test(l)&&!r?(r=l,o=null):(r=d[4]||r||null,o=d[5]?d[5].replace(/^\/+|\/+$/g,""):null),{owner:s,repo:t,branch:r,subpath:o,rawTreeTail:l,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}}const y=e.match(/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:@([A-Za-z0-9_./-]+))?$/);return y&&!y[1].startsWith("-")?(s=y[1],t=y[2],r=y[3]||r||null,{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}):null}function L(n,e){const s={};if(!n||!e||!n.existsSync(e))return s;const t=j.normalize(e);function r(o){let i=[];try{i=n.readdirSync(o)}catch{return}for(const f of i){if(f===".git"||f==="node_modules")continue;const d=j.join(o,f);let y;try{y=n.statSync(d)}catch{continue}if(y.isDirectory())r(d);else{const l=d.startsWith(t==="/"?"/":t+"/")?d.slice(t==="/"?1:t.length+1):f;try{s[l]=String(n.readFileSync(d,"utf8"))}catch(a){M.debug("Skipped unreadable VFS file in snapshot.",d,a)}}}}return r(t),s}function re(n){const e=String(n||"");let s=3735928559^e.length,t=1103547991^e.length;for(let o=0;o<e.length;o++){const i=e.charCodeAt(o);s=Math.imul(s^i,2654435761),t=Math.imul(t^i,1597334677)}return s=Math.imul(s^s>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(s^s>>>13,3266489909),(4294967296*(2097151&t)+(s>>>0)).toString(16).padStart(7,"0").slice(0,7)}function ee(n,e){if(!n||typeof n!="string")return"";let s=n.trim().replace(/\\/g,"/");if(!s)return"";const t=j.normalize(e||"/workspace"),r=t==="/"?"/":t+"/";if(s===t)return"";for(s.startsWith(r)?s=s.slice(r.length):s.startsWith("/workspace/")&&(s=s.slice(11));s.startsWith("./");)s=s.slice(2);s.startsWith("/")&&(s=s.replace(/^\/+/,""));const o=[];for(const f of s.split("/"))if(!(!f||f===".")){if(f===".."){if(o.length===0)return"";o.pop();continue}o.push(f)}const i=o.join("/");return!i||i===".git"||i.startsWith(".git/")||i.includes("/.git/")||i.endsWith("/.git")||i==="node_modules"||i.startsWith("node_modules/")||i.includes("/node_modules/")||i.endsWith("/node_modules")?"":i}function oe(n){return(!Array.isArray(n&&n.commits)||n.commits.length===0)&&!(n&&n.headCommit)}function ue(n,e,s,t){if(!e)return!1;const r=t||n&&(n.headSnapshot||n.headFiles)||{},o=Object.prototype.hasOwnProperty.call(r,e),i=s==null?null:String(s);return i===null?o:!o||oe(n)?!0:i!==r[e]}function K(n,e,s,t,r){const o=n&&n.repoRoot||"/workspace",i=ee(s,o);if(!i)return;const f=t==null?null:String(t);ue(n,i,f,r)?e.set(i,f):e.delete(i)}function Y(n,e,s){if(!(e instanceof Map))return;const t=n&&n.repoRoot||"/workspace",r=s||n&&(n.headSnapshot||n.headFiles)||{};for(const[o,i]of Array.from(e.entries())){const f=ee(o,t);if(f!==o&&e.delete(o),!f){e.delete(o);continue}const d=i==null?null:String(i);ue(n,f,d,r)?e.set(f,d):e.delete(f)}}function Ke(n,e){if(!n||!n._initialBootSnapshot||!n._initialBootRoot)return{};const s=j.normalize(e),t=n._initialBootRoot;if(s===t)return n._initialBootSnapshot;const r=t==="/"?"/":t+"/";if(s.startsWith(r)){const o=s.slice(r.length)+"/",i={};for(const[f,d]of Object.entries(n._initialBootSnapshot))f.startsWith(o)&&(i[f.slice(o.length)]=d);return i}return{}}function Q(n,e,s,t){return n instanceof Map&&(n._hasShellStagedShim||(Object.defineProperty(n,"_hasShellStagedShim",{value:!0,enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(n,"add",{value(r){const o=typeof t=="function"?t():null,i=typeof s=="function"?s():o&&o.repoRoot||"/workspace",f=ee(r,i);if(!f)return n;let d=null;if(e&&typeof e.existsSync=="function"){const y=j.join(i,f);if(e.existsSync(y)){if(typeof e.statSync=="function")try{if(e.statSync(y).isDirectory())return n}catch(l){M.debug("Failed statting staged path in VFS.",y,l)}if(typeof e.readFileSync=="function")try{d=String(e.readFileSync(y,"utf8"))}catch(l){return M.debug("Failed reading staged file from VFS.",y,l),n}}}return o?K(o,n,f,d):n.set(f,d),n},enumerable:!1,configurable:!0,writable:!0}))),n}function Xe(n,e,s){const t=()=>n&&n.repoRoot||s||"/workspace",r=()=>n;if(n.staged instanceof Map)return Q(n.staged,e,t,r),Y(n,n.staged),n.stagedFiles=n.staged,n.staged;const o=Q(new Map,e,t,r);if(n.staged&&typeof n.staged[Symbol.iterator]=="function")for(const i of n.staged)Array.isArray(i)&&i.length>=2?K(n,o,i[0],i[1]===null?null:String(i[1])):typeof i=="string"&&o.add(i);return n.staged=o,n.stagedFiles=o,o}function Ye(n,e){if(!n||typeof n.existsSync!="function"||typeof n.readFileSync!="function")return null;const s=[j.join(e,".git/HEAD"),"/workspace/.git/HEAD"];for(const t of s)if(n.existsSync(t))try{const r=String(n.readFileSync(t,"utf8")).trim(),o=/^ref:\s*refs\/heads\/([^\s]+)$/.exec(r);if(o&&o[1])return o[1]}catch(r){M.debug("Could not parse .git/HEAD branch.",t,r)}return null}function Qe(n,e,s={}){const t=j.normalize(e||"/workspace"),r=!!(n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(t,".git"))||n.existsSync(j.join(t,".git/HEAD"))||n.existsSync("/workspace/.git")||n.existsSync("/workspace/.git/HEAD")));let o=!!(s.gitInitialized===!0||r),i=t;const d=(r?Ye(n,t):null)||"main";let y=o?L(n,t):{},l=o?re(JSON.stringify(y)+":init"):"";const a=Date.now();let c=o?[{hash:l,author:"CodeLab Developer <dev@codelab.internal>",date:new Date(a).toUTCString(),timestamp:a,message:"Initial commit",files:Object.assign({},y)}]:[];const h={branch:d,branches:new Set([d]),remoteUrl:null,remotes:{}};let u=Q(new Map,n,()=>i,()=>h);return Object.defineProperties(h,{initialized:{enumerable:!0,configurable:!0,get(){if(o)return!0;const p=i||t;return n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(p,".git"))||n.existsSync(j.join(p,".git/HEAD")))?(o=!0,!0):!1},set(p){o=!!p}},repoRoot:{enumerable:!0,configurable:!0,get(){return i},set(p){i=j.normalize(String(p||t))}},headCommit:{enumerable:!0,configurable:!0,get(){return l},set(p){l=String(p||"")}},headSnapshot:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},headFiles:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},staged:{enumerable:!0,configurable:!0,get(){return u},set(p){if(p instanceof Map)u=Q(p,n,()=>i,()=>h),Y(h,u);else{const g=Q(new Map,n,()=>i,()=>h);if(p&&typeof p[Symbol.iterator]=="function")for(const m of p)typeof m=="string"?g.add(m):Array.isArray(m)&&m.length>=2&&K(h,g,m[0],m[1]===null?null:String(m[1]));u=g}}},stagedFiles:{enumerable:!0,configurable:!0,get(){return u},set(p){p instanceof Map&&(u=Q(p,n,()=>i,()=>h),Y(h,u))}},commits:{enumerable:!0,configurable:!0,get(){return c},set(p){c=Array.isArray(p)?p:[],c.length>0&&c[0]&&c[0].hash?l=String(c[0].hash):c.length===0&&(l="")}}}),h}const xe=/\.(png|jpg|jpeg|gif|webp|ico|bmp|tiff|woff|woff2|ttf|eot|otf|mp3|mp4|wav|ogg|webm|avi|mov|pdf|zip|tar|gz|tgz|bz2|7z|rar|exe|dll|so|dylib|wasm|pyc|pyo|class|jar|war|ear|bin|dat|iso|dmg|pkg|deb|rpm|o|a|lib|DS_Store)$/i;function et(n){const e=n.toLowerCase(),s=j.basename(e),t=n.split("/").length;return s==="readme.md"||s==="package.json"||s==="cargo.toml"||s==="go.mod"||s==="pyproject.toml"?0:t===1&&/\.(js|ts|jsx|tsx|mjs|cjs|py|go|rs|json|md|yml|yaml|toml|sh)$/.test(e)?1:e.startsWith("src/")||e.startsWith("lib/")||e.startsWith("app/")?2+t*.1:e.startsWith("test/")||e.startsWith("tests/")||e.startsWith("examples/")?5+t*.1:10+t*.1}async function tt(n,e,s={}){const t=typeof s.onProgress=="function"?s.onProgress:null;t&&t({phase:"connecting",message:`Connecting to repository '${n}'...`});const r=fe(n);if(!r)throw new Error(`fatal: repository '${n}' does not exist or is not a valid GitHub repository URL`);if(!e)throw new Error("fatal: virtual filesystem (vfs) is required to clone repository");const o=s.fetchImpl||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!o)throw new Error("fatal: global fetch API is unavailable in this environment");const i=j.normalize(s.targetDir||"/workspace"),f=s.maxFiles||250,d=s.maxFileSize||512*1024,y=s.branch||r.branch||null,{owner:l,repo:a}=r,c=s.signal||null,h=()=>{if(c&&c.aborted){const T=new Error("fatal: clone cancelled (SIGINT)");throw T.name="AbortError",T}};h();let u=y,p=null,g=!1;t&&t({phase:"metadata",message:`Fetching repository metadata for ${l}/${a}...`});try{if(!u){const T=await o(`https://api.github.com/repos/${l}/${a}`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(T.status===404)g=!0;else if(T.ok){const k=await T.json();k&&k.default_branch&&(u=k.default_branch)}}if(!g){const T=Array.from(y?new Set([y,!s.branch&&r.rawTreeTail&&r.rawTreeTail!==y?r.rawTreeTail:null].filter(Boolean)):new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://api.github.com/repos/${l}/${a}/git/trees/${encodeURIComponent(k)}?recursive=1`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(O.ok){const F=await O.json();if(F&&Array.isArray(F.tree)){u=k,r.rawTreeTail&&k===r.rawTreeTail&&(r.subpath=null),p=F.tree.filter(P=>P&&P.type==="blob"&&P.path).map(P=>({path:P.path.replace(/^\/+/,""),size:P.size||0}));break}}}}}catch(T){M.debug("GitHub REST API tree fetch failed; falling back to jsDelivr.",T)}if(!p&&!g)try{const T=y?[y]:Array.from(new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://data.jsdelivr.com/v1/package/gh/${l}/${a}@${encodeURIComponent(k)}/flat`,{signal:c});if(O&&O.ok){const F=await O.json();if(F&&Array.isArray(F.files)&&F.files.length>0){u=k,p=F.files.filter(P=>P&&P.name).map(P=>({path:P.name.replace(/^\/+/,""),size:P.size||0}));break}}}}catch(T){M.debug("jsDelivr flat tree fetch failed.",T)}if(g||!p)throw new Error(`fatal: repository '${r.url}' not found or could not be fetched`);const m=r.subpath?r.subpath.replace(/^\/+|\/+$/g,"")+"/":null,S=[];for(const T of p){let k=T.path;if(m)if(T.path===r.subpath)k=j.basename(T.path);else if(T.path.startsWith(m))k=T.path.slice(m.length);else continue;!k||k.startsWith(".git/")||k.includes("/node_modules/")||k.startsWith("node_modules/")||xe.test(k)||T.size&&T.size>d||S.push({repoPath:T.path,destPath:k,size:T.size||0,priority:et(k)})}S.sort((T,k)=>T.priority-k.priority||T.destPath.localeCompare(k.destPath));const b=S.slice(0,f),v=b.length;t&&t({phase:"downloading",message:`Downloading files (0/${v})...`,loaded:0,total:v}),e.existsSync(i)||e.mkdirSync(i,{recursive:!0});const w={};let $=0,R=0;const I=12;for(let T=0;T<b.length;T+=I){h();const k=b.slice(T,T+I);await Promise.all(k.map(async O=>{h();const F=O.repoPath.split("/").map(encodeURIComponent).join("/"),P=`https://raw.githubusercontent.com/${l}/${a}/${encodeURIComponent(u)}/${F}`,A=`https://cdn.jsdelivr.net/gh/${l}/${a}@${encodeURIComponent(u)}/${F}`;let _=null;try{const D=await o(P,{signal:c});D&&D.ok&&(_=await D.text())}catch(D){if(c&&c.aborted)throw D}if(_===null)try{const D=await o(A,{signal:c});D&&D.ok&&(_=await D.text())}catch(D){if(c&&c.aborted)throw D}if(_!==null&&_.length<=d){const D=j.join(i,O.destPath),N=j.dirname(D);e.existsSync(N)||e.mkdirSync(N,{recursive:!0}),e.writeFileSync(D,_),w[O.destPath]=_,$++,R+=_.length,t&&t({phase:"downloading",message:`Downloading files (${$}/${v}): ${O.destPath}`,loaded:$,total:v}),typeof s.onFile=="function"&&s.onFile(D,_,O.destPath)}}))}h(),t&&t({phase:"mounting",message:`Mounting files and writing Git metadata into ${i}...`,loaded:$,total:v});const C=j.join(i,".git");e.existsSync(C)||e.mkdirSync(C,{recursive:!0}),e.writeFileSync(j.join(C,"HEAD"),`ref: refs/heads/${u}
|
|
199
|
+
`);return h}function fe(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;let s=null,t=null,r=null,o=null;const i=e.indexOf("#");if(i!==-1){const l=e.slice(i+1).trim();e=e.slice(0,i).trim(),l&&(r=l)}const f=e.match(/^git@github\.com:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/);if(f)return s=f[1],t=f[2],{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`};const d=e.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:\/(tree|blob)\/([^/]+)(?:\/(.+?))?)?\/?$/);if(d){s=d[1],t=d[2];const l=d[4]?d[5]?`${d[4]}/${d[5].replace(/^\/+|\/+$/g,"")}`:d[4]:null;return l&&/^(?:feature|feat|fix|bugfix|hotfix|release|chore|refactor|docs|test|ci|depend|dependabot)\/[^/]+$/.test(l)&&!r?(r=l,o=null):(r=d[4]||r||null,o=d[5]?d[5].replace(/^\/+|\/+$/g,""):null),{owner:s,repo:t,branch:r,subpath:o,rawTreeTail:l,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}}const y=e.match(/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:@([A-Za-z0-9_./-]+))?$/);return y&&!y[1].startsWith("-")?(s=y[1],t=y[2],r=y[3]||r||null,{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}):null}function L(n,e){const s={};if(!n||!e||!n.existsSync(e))return s;const t=j.normalize(e);function r(o){let i=[];try{i=n.readdirSync(o)}catch{return}for(const f of i){if(f===".git"||f==="node_modules")continue;const d=j.join(o,f);let y;try{y=n.statSync(d)}catch{continue}if(y.isDirectory())r(d);else{const l=d.startsWith(t==="/"?"/":t+"/")?d.slice(t==="/"?1:t.length+1):f;try{s[l]=String(n.readFileSync(d,"utf8"))}catch(a){N.debug("Skipped unreadable VFS file in snapshot.",d,a)}}}}return r(t),s}function re(n){const e=String(n||"");let s=3735928559^e.length,t=1103547991^e.length;for(let o=0;o<e.length;o++){const i=e.charCodeAt(o);s=Math.imul(s^i,2654435761),t=Math.imul(t^i,1597334677)}return s=Math.imul(s^s>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(s^s>>>13,3266489909),(4294967296*(2097151&t)+(s>>>0)).toString(16).padStart(7,"0").slice(0,7)}function ee(n,e){if(!n||typeof n!="string")return"";let s=n.trim().replace(/\\/g,"/");if(!s)return"";const t=j.normalize(e||"/workspace"),r=t==="/"?"/":t+"/";if(s===t)return"";for(s.startsWith(r)?s=s.slice(r.length):s.startsWith("/workspace/")&&(s=s.slice(11));s.startsWith("./");)s=s.slice(2);s.startsWith("/")&&(s=s.replace(/^\/+/,""));const o=[];for(const f of s.split("/"))if(!(!f||f===".")){if(f===".."){if(o.length===0)return"";o.pop();continue}o.push(f)}const i=o.join("/");return!i||i===".git"||i.startsWith(".git/")||i.includes("/.git/")||i.endsWith("/.git")||i==="node_modules"||i.startsWith("node_modules/")||i.includes("/node_modules/")||i.endsWith("/node_modules")?"":i}function oe(n){return(!Array.isArray(n&&n.commits)||n.commits.length===0)&&!(n&&n.headCommit)}function ue(n,e,s,t){if(!e)return!1;const r=t||n&&(n.headSnapshot||n.headFiles)||{},o=Object.prototype.hasOwnProperty.call(r,e),i=s==null?null:String(s);return i===null?o:!o||oe(n)?!0:i!==r[e]}function K(n,e,s,t,r){const o=n&&n.repoRoot||"/workspace",i=ee(s,o);if(!i)return;const f=t==null?null:String(t);ue(n,i,f,r)?e.set(i,f):e.delete(i)}function Y(n,e,s){if(!(e instanceof Map))return;const t=n&&n.repoRoot||"/workspace",r=s||n&&(n.headSnapshot||n.headFiles)||{};for(const[o,i]of Array.from(e.entries())){const f=ee(o,t);if(f!==o&&e.delete(o),!f){e.delete(o);continue}const d=i==null?null:String(i);ue(n,f,d,r)?e.set(f,d):e.delete(f)}}function Ke(n,e){if(!n||!n._initialBootSnapshot||!n._initialBootRoot)return{};const s=j.normalize(e),t=n._initialBootRoot;if(s===t)return n._initialBootSnapshot;const r=t==="/"?"/":t+"/";if(s.startsWith(r)){const o=s.slice(r.length)+"/",i={};for(const[f,d]of Object.entries(n._initialBootSnapshot))f.startsWith(o)&&(i[f.slice(o.length)]=d);return i}return{}}function Q(n,e,s,t){return n instanceof Map&&(n._hasShellStagedShim||(Object.defineProperty(n,"_hasShellStagedShim",{value:!0,enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(n,"add",{value(r){const o=typeof t=="function"?t():null,i=typeof s=="function"?s():o&&o.repoRoot||"/workspace",f=ee(r,i);if(!f)return n;let d=null;if(e&&typeof e.existsSync=="function"){const y=j.join(i,f);if(e.existsSync(y)){if(typeof e.statSync=="function")try{if(e.statSync(y).isDirectory())return n}catch(l){N.debug("Failed statting staged path in VFS.",y,l)}if(typeof e.readFileSync=="function")try{d=String(e.readFileSync(y,"utf8"))}catch(l){return N.debug("Failed reading staged file from VFS.",y,l),n}}}return o?K(o,n,f,d):n.set(f,d),n},enumerable:!1,configurable:!0,writable:!0}))),n}function Xe(n,e,s){const t=()=>n&&n.repoRoot||s||"/workspace",r=()=>n;if(n.staged instanceof Map)return Q(n.staged,e,t,r),Y(n,n.staged),n.stagedFiles=n.staged,n.staged;const o=Q(new Map,e,t,r);if(n.staged&&typeof n.staged[Symbol.iterator]=="function")for(const i of n.staged)Array.isArray(i)&&i.length>=2?K(n,o,i[0],i[1]===null?null:String(i[1])):typeof i=="string"&&o.add(i);return n.staged=o,n.stagedFiles=o,o}function Ye(n,e){if(!n||typeof n.existsSync!="function"||typeof n.readFileSync!="function")return null;const s=[j.join(e,".git/HEAD"),"/workspace/.git/HEAD"];for(const t of s)if(n.existsSync(t))try{const r=String(n.readFileSync(t,"utf8")).trim(),o=/^ref:\s*refs\/heads\/([^\s]+)$/.exec(r);if(o&&o[1])return o[1]}catch(r){N.debug("Could not parse .git/HEAD branch.",t,r)}return null}function Qe(n,e,s={}){const t=j.normalize(e||"/workspace"),r=!!(n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(t,".git"))||n.existsSync(j.join(t,".git/HEAD"))||n.existsSync("/workspace/.git")||n.existsSync("/workspace/.git/HEAD")));let o=!!(s.gitInitialized===!0||r),i=t;const d=(r?Ye(n,t):null)||"main";let y=o?L(n,t):{},l=o?re(JSON.stringify(y)+":init"):"";const a=Date.now();let c=o?[{hash:l,author:"CodeLab Developer <dev@codelab.internal>",date:new Date(a).toUTCString(),timestamp:a,message:"Initial commit",files:Object.assign({},y)}]:[];const h={branch:d,branches:new Set([d]),remoteUrl:null,remotes:{}};let u=Q(new Map,n,()=>i,()=>h);return Object.defineProperties(h,{initialized:{enumerable:!0,configurable:!0,get(){if(o)return!0;const p=i||t;return n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(p,".git"))||n.existsSync(j.join(p,".git/HEAD")))?(o=!0,!0):!1},set(p){o=!!p}},repoRoot:{enumerable:!0,configurable:!0,get(){return i},set(p){i=j.normalize(String(p||t))}},headCommit:{enumerable:!0,configurable:!0,get(){return l},set(p){l=String(p||"")}},headSnapshot:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},headFiles:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},staged:{enumerable:!0,configurable:!0,get(){return u},set(p){if(p instanceof Map)u=Q(p,n,()=>i,()=>h),Y(h,u);else{const g=Q(new Map,n,()=>i,()=>h);if(p&&typeof p[Symbol.iterator]=="function")for(const m of p)typeof m=="string"?g.add(m):Array.isArray(m)&&m.length>=2&&K(h,g,m[0],m[1]===null?null:String(m[1]));u=g}}},stagedFiles:{enumerable:!0,configurable:!0,get(){return u},set(p){p instanceof Map&&(u=Q(p,n,()=>i,()=>h),Y(h,u))}},commits:{enumerable:!0,configurable:!0,get(){return c},set(p){c=Array.isArray(p)?p:[],c.length>0&&c[0]&&c[0].hash?l=String(c[0].hash):c.length===0&&(l="")}}}),h}const xe=/\.(png|jpg|jpeg|gif|webp|ico|bmp|tiff|woff|woff2|ttf|eot|otf|mp3|mp4|wav|ogg|webm|avi|mov|pdf|zip|tar|gz|tgz|bz2|7z|rar|exe|dll|so|dylib|wasm|pyc|pyo|class|jar|war|ear|bin|dat|iso|dmg|pkg|deb|rpm|o|a|lib|DS_Store)$/i;function et(n){const e=n.toLowerCase(),s=j.basename(e),t=n.split("/").length;return s==="readme.md"||s==="package.json"||s==="cargo.toml"||s==="go.mod"||s==="pyproject.toml"?0:t===1&&/\.(js|ts|jsx|tsx|mjs|cjs|py|go|rs|json|md|yml|yaml|toml|sh)$/.test(e)?1:e.startsWith("src/")||e.startsWith("lib/")||e.startsWith("app/")?2+t*.1:e.startsWith("test/")||e.startsWith("tests/")||e.startsWith("examples/")?5+t*.1:10+t*.1}async function tt(n,e,s={}){const t=typeof s.onProgress=="function"?s.onProgress:null;t&&t({phase:"connecting",message:`Connecting to repository '${n}'...`});const r=fe(n);if(!r)throw new Error(`fatal: repository '${n}' does not exist or is not a valid GitHub repository URL`);if(!e)throw new Error("fatal: virtual filesystem (vfs) is required to clone repository");const o=s.fetchImpl||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!o)throw new Error("fatal: global fetch API is unavailable in this environment");const i=j.normalize(s.targetDir||"/workspace"),f=s.maxFiles||250,d=s.maxFileSize||512*1024,y=s.branch||r.branch||null,{owner:l,repo:a}=r,c=s.signal||null,h=()=>{if(c&&c.aborted){const T=new Error("fatal: clone cancelled (SIGINT)");throw T.name="AbortError",T}};h();let u=y,p=null,g=!1;t&&t({phase:"metadata",message:`Fetching repository metadata for ${l}/${a}...`});try{if(!u){const T=await o(`https://api.github.com/repos/${l}/${a}`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(T.status===404)g=!0;else if(T.ok){const k=await T.json();k&&k.default_branch&&(u=k.default_branch)}}if(!g){const T=Array.from(y?new Set([y,!s.branch&&r.rawTreeTail&&r.rawTreeTail!==y?r.rawTreeTail:null].filter(Boolean)):new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://api.github.com/repos/${l}/${a}/git/trees/${encodeURIComponent(k)}?recursive=1`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(O.ok){const F=await O.json();if(F&&Array.isArray(F.tree)){u=k,r.rawTreeTail&&k===r.rawTreeTail&&(r.subpath=null),p=F.tree.filter(P=>P&&P.type==="blob"&&P.path).map(P=>({path:P.path.replace(/^\/+/,""),size:P.size||0}));break}}}}}catch(T){N.debug("GitHub REST API tree fetch failed; falling back to jsDelivr.",T)}if(!p&&!g)try{const T=y?[y]:Array.from(new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://data.jsdelivr.com/v1/package/gh/${l}/${a}@${encodeURIComponent(k)}/flat`,{signal:c});if(O&&O.ok){const F=await O.json();if(F&&Array.isArray(F.files)&&F.files.length>0){u=k,p=F.files.filter(P=>P&&P.name).map(P=>({path:P.name.replace(/^\/+/,""),size:P.size||0}));break}}}}catch(T){N.debug("jsDelivr flat tree fetch failed.",T)}if(g||!p)throw new Error(`fatal: repository '${r.url}' not found or could not be fetched`);const m=r.subpath?r.subpath.replace(/^\/+|\/+$/g,"")+"/":null,S=[];for(const T of p){let k=T.path;if(m)if(T.path===r.subpath)k=j.basename(T.path);else if(T.path.startsWith(m))k=T.path.slice(m.length);else continue;!k||k.startsWith(".git/")||k.includes("/node_modules/")||k.startsWith("node_modules/")||xe.test(k)||T.size&&T.size>d||S.push({repoPath:T.path,destPath:k,size:T.size||0,priority:et(k)})}S.sort((T,k)=>T.priority-k.priority||T.destPath.localeCompare(k.destPath));const b=S.slice(0,f),v=b.length;t&&t({phase:"downloading",message:`Downloading files (0/${v})...`,loaded:0,total:v}),e.existsSync(i)||e.mkdirSync(i,{recursive:!0});const w={};let $=0,R=0;const I=12;for(let T=0;T<b.length;T+=I){h();const k=b.slice(T,T+I);await Promise.all(k.map(async O=>{h();const F=O.repoPath.split("/").map(encodeURIComponent).join("/"),P=`https://raw.githubusercontent.com/${l}/${a}/${encodeURIComponent(u)}/${F}`,A=`https://cdn.jsdelivr.net/gh/${l}/${a}@${encodeURIComponent(u)}/${F}`;let M=null;try{const D=await o(P,{signal:c});D&&D.ok&&(M=await D.text())}catch(D){if(c&&c.aborted)throw D}if(M===null)try{const D=await o(A,{signal:c});D&&D.ok&&(M=await D.text())}catch(D){if(c&&c.aborted)throw D}if(M!==null&&M.length<=d){const D=j.join(i,O.destPath),_=j.dirname(D);e.existsSync(_)||e.mkdirSync(_,{recursive:!0}),e.writeFileSync(D,M),w[O.destPath]=M,$++,R+=M.length,t&&t({phase:"downloading",message:`Downloading files (${$}/${v}): ${O.destPath}`,loaded:$,total:v}),typeof s.onFile=="function"&&s.onFile(D,M,O.destPath)}}))}h(),t&&t({phase:"mounting",message:`Mounting files and writing Git metadata into ${i}...`,loaded:$,total:v});const C=j.join(i,".git");e.existsSync(C)||e.mkdirSync(C,{recursive:!0}),e.writeFileSync(j.join(C,"HEAD"),`ref: refs/heads/${u}
|
|
200
200
|
`),e.writeFileSync(j.join(C,"config"),`[core]
|
|
201
201
|
repositoryformatversion = 0
|
|
202
202
|
filemode = true
|
|
@@ -208,17 +208,17 @@ isomorphic-git/index.js:
|
|
|
208
208
|
remote = origin
|
|
209
209
|
merge = refs/heads/${u}
|
|
210
210
|
`);let E=[];try{const T=await o(`https://api.github.com/repos/${l}/${a}/commits?sha=${encodeURIComponent(u)}&per_page=10`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(T&&T.ok){const k=await T.json();Array.isArray(k)&&k.length>0&&(E=k.map((O,F)=>{const P=O.commit&&O.commit.message?String(O.commit.message).split(`
|
|
211
|
-
`)[0]:"Commit",A=re(`${l}/${a}:${u}:${F}:${P}`),
|
|
212
|
-
`;n.writeFileSync(e,o),typeof t=="function"&&t("change",e)}function G(n,e,s){n.existsSync(e)||(n.mkdirSync(e,{recursive:!0}),typeof s=="function"&&s("create",e))}function pe(n,e,s){if(n.existsSync(e))try{if(typeof n.rmSync=="function")n.rmSync(e,{recursive:!0,force:!0});else{const t=n.readdirSync(e);for(const r of t){const o=j.join(e,r);n.statSync(o).isDirectory()?pe(n,o,s):n.unlinkSync(o)}n.rmdirSync(e)}typeof s=="function"&&s("delete",e)}catch(t){
|
|
211
|
+
`)[0]:"Commit",A=re(`${l}/${a}:${u}:${F}:${P}`),M=O.commit&&O.commit.author&&O.commit.author.date&&Date.parse(O.commit.author.date)||Date.now();return{hash:String(O.sha||A).slice(0,7),author:O.commit&&O.commit.author?`${O.commit.author.name||l} <${O.commit.author.email||`${l}@users.noreply.github.com`}>`:`${l} <${l}@users.noreply.github.com>`,date:new Date(M).toUTCString(),timestamp:M,message:P}}))}}catch(T){N.debug("Optional commit history fetch skipped.",T)}if(E.length===0){const T=Date.now();E=[{hash:re(`${l}/${a}:${u}:${$}`),author:`${l} <${l}@users.noreply.github.com>`,date:new Date(T).toUTCString(),timestamp:T,message:`Clone ${l}/${a} (${u})`}]}return t&&t({phase:"ready",message:`Repository cloned successfully (${$} files).`,loaded:$,total:v}),{owner:l,repo:a,branch:u,url:r.url,targetDir:i,count:$,fileCount:$,filesWritten:$,totalBytes:R,commits:E,headSnapshot:w}}async function he(n,e,s={}){const t=typeof s.onProgress=="function"?s.onProgress:null;try{return await tt(n,e,s)}catch(r){throw t&&t({phase:"error",message:r&&r.message?r.message:String(r)}),r}}function nt(n,e){const s=j.join(e||"/workspace","package.json");if(n.existsSync(s))return s;const t="/workspace/package.json";return n.existsSync(t)?t:s}function H(n,e){const s=nt(n,e);if(n.existsSync(s))try{const t=JSON.parse(n.readFileSync(s,"utf8"));return{path:s,data:t}}catch(t){N.warn(`Invalid JSON in ${s}; falling back to default package metadata.`,t)}return{path:s,data:{name:"app",dependencies:{},devDependencies:{},scripts:{}}}}function De(n,e,s,t){const r=j.dirname(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0});const o=JSON.stringify(s,null,2)+`
|
|
212
|
+
`;n.writeFileSync(e,o),typeof t=="function"&&t("change",e)}function G(n,e,s){n.existsSync(e)||(n.mkdirSync(e,{recursive:!0}),typeof s=="function"&&s("create",e))}function pe(n,e,s){if(n.existsSync(e))try{if(typeof n.rmSync=="function")n.rmSync(e,{recursive:!0,force:!0});else{const t=n.readdirSync(e);for(const r of t){const o=j.join(e,r);n.statSync(o).isDirectory()?pe(n,o,s):n.unlinkSync(o)}n.rmdirSync(e)}typeof s=="function"&&s("delete",e)}catch(t){N.debug("removeDirRecursive failed.",e,t)}}const Ie="https://cdn.jsdelivr.net/npm",st=["https://cdn.jsdelivr.net/npm","https://unpkg.com","https://esm.sh"],rt={"is-even":`module.exports = function isEven(n) { return (Number(n) % 2) === 0; };
|
|
213
213
|
`,"tiny-invariant":`module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };
|
|
214
214
|
`,lodash:`module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };
|
|
215
215
|
`,"left-pad":`module.exports = function leftPad(str, len, ch) { str = String(str); ch = (ch === undefined ? " " : String(ch)); while (str.length < len) str = ch + str; return str.slice(-len); };
|
|
216
|
-
`};function ot(n){return n&&n.shell&&n.shell.options&&typeof n.shell.options.fetchImpl=="function"?n.shell.options.fetchImpl:typeof fetch=="function"?fetch.bind(globalThis):null}function ye(n){const e=String(n||"").trim();if(!e)return{name:"",range:null};if(e.startsWith("@")){const t=e.indexOf("@",1);return t===-1?{name:e,range:null}:{name:e.slice(0,t),range:e.slice(t+1)||null}}const s=e.indexOf("@");return s<=0?{name:e,range:null}:{name:e.slice(0,s),range:e.slice(s+1)||null}}function te(n){if(typeof n=="string")return n;if(Array.isArray(n)){for(const e of n){const s=te(e);if(s)return s}return null}if(!n||typeof n!="object")return null;for(const e of["require","node","default","browser","import","module"])if(n[e]!==void 0){const s=te(n[e]);if(s)return s}return null}function Ae(n){let e=null;const s=n&&n.exports;return typeof s=="string"?e=s:s&&typeof s=="object"&&s["."]!==void 0&&(e=te(s["."])),e||(e=n.main||n.module||(typeof n.browser=="string"?n.browser:"")||"index.js"),e=String(e).replace(/^[./]+/,""),e||"index.js"}function
|
|
216
|
+
`};function ot(n){return n&&n.shell&&n.shell.options&&typeof n.shell.options.fetchImpl=="function"?n.shell.options.fetchImpl:typeof fetch=="function"?fetch.bind(globalThis):null}function ye(n){const e=String(n||"").trim();if(!e)return{name:"",range:null};if(e.startsWith("@")){const t=e.indexOf("@",1);return t===-1?{name:e,range:null}:{name:e.slice(0,t),range:e.slice(t+1)||null}}const s=e.indexOf("@");return s<=0?{name:e,range:null}:{name:e.slice(0,s),range:e.slice(s+1)||null}}function te(n){if(typeof n=="string")return n;if(Array.isArray(n)){for(const e of n){const s=te(e);if(s)return s}return null}if(!n||typeof n!="object")return null;for(const e of["require","node","default","browser","import","module"])if(n[e]!==void 0){const s=te(n[e]);if(s)return s}return null}function Ae(n){let e=null;const s=n&&n.exports;return typeof s=="string"?e=s:s&&typeof s=="object"&&s["."]!==void 0&&(e=te(s["."])),e||(e=n.main||n.module||(typeof n.browser=="string"?n.browser:"")||"index.js"),e=String(e).replace(/^[./]+/,""),e||"index.js"}function _e(n){return String(n||"").replace(/^[./]+/,"")}function it(n){const e=new Set,s=[/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g];for(const t of s){let r;for(;(r=t.exec(n))!==null;)e.add(r[1])}return Array.from(e)}function lt(n,e){const s=String(n||"").split("/").filter(Boolean);for(const t of String(e).split("/"))!t||t==="."||(t===".."?s.pop():s.push(t));return s.join("/")}function me(n){return new Promise(e=>{typeof setTimeout=="function"?setTimeout(e,n):e()})}async function ge(n,e){for(let t=1;t<=3;t++)try{const r=await n(e);if(!r){if(t<3){await me(t*150);continue}return null}if(!(r.ok===!0||r.status===200||r.status===void 0)){if((r.status>=500||r.status===429||r.status===408)&&t<3){await me(t*150);continue}return null}const i=r.headers&&typeof r.headers.get=="function"&&r.headers.get("content-type")||"",f=/\.html?(?:[?#]|$)/i.test(e);if(/text\/html/i.test(i)&&!f)return null;const d=typeof r.text=="function"?await r.text():String(r.body!=null?r.body:"");return!f&&/^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(d)?null:d}catch{if(t<3){await me(t*150);continue}return null}return null}async function at(n,e,s){for(const t of st){const r=s?[`${t}/${e}@${s}/package.json`,`${t}/${e}/package.json`]:[`${t}/${e}/package.json`];for(const o of r){const i=await ge(n,o);if(i)try{const f=JSON.parse(i);if(f&&f.version)return f._resolvedCdnBase=t,f}catch(f){N.debug("Invalid package.json metadata from CDN.",o,f)}}}return null}async function ct(n,e,s,t){const r=await at(n,e,s);if(!r){const b=rt[e];return b?{ok:!0,offline:!0,version:s&&s.replace(/^[\^~>=<\s]+/,"")||"1.0.0",entry:"index.js",files:[{rel:"index.js",content:b}],deps:[]}:{ok:!1,reason:`${e}: package metadata not found on the registry (offline?)`}}const o=r._resolvedCdnBase||Ie,i=r.version,f=`${e}@${i}`;if(t.has(f))return{ok:!0,deduped:!0,version:i,entry:Ae(r),files:[],deps:[]};t.add(f);const d=Ae(r),y=[],l=new Set,a=[d,`${d}.js`,`${d}.json`,`${d}.mjs`,`${d}.cjs`,`${d}/index.js`,`${d}/index.json`,`${d}/index.mjs`,`${d}/index.cjs`],c=r.exports;if(c&&typeof c=="object")for(const b of Object.keys(c)){if(b==="."||b.slice(0,2)!=="./"||b.includes("*"))continue;const v=te(c[b]);v&&a.push(v)}let h=a;for(;h.length>0;){const b=[];for(const w of h){const $=_e(w);!$||$.endsWith("/")||l.has($)||(l.add($),b.push($))}if(h=[],b.length===0)break;const v=await Promise.all(b.map(w=>ge(n,`${o}/${e}@${i}/${w}`)));for(let w=0;w<b.length;w++){const $=b[w],R=v[w];if(R===null)continue;y.push({rel:$,content:R});const I=$.includes("/")?$.slice(0,$.lastIndexOf("/")):"";for(const C of it(R)){const E=lt(I,C),T=/\.[a-z0-9]+$/i.test(E)?[E]:[E,`${E}.js`,`${E}.json`,`${E}.mjs`,`${E}.cjs`,`${E}/index.js`];for(const k of T){const O=_e(k);O&&!l.has(O)&&h.push(k)}}}}if(!y.some(b=>b.rel===d)){const b=await ge(n,`${o}/${e}@${i}/index.js`);b!==null&&y.push({rel:"index.js",content:b})}const u=[],p=new Set,g=r.dependencies||{};for(const b of Object.keys(g))p.has(b)||(p.add(b),u.push({name:b,range:g[b]||null}));const m=r.peerDependenciesMeta||{},S=r.peerDependencies||{};for(const b of Object.keys(S))m[b]&&m[b].optional||p.has(b)||(p.add(b),u.push({name:b,range:S[b]||null}));return{ok:!0,version:i,entry:d,files:y,deps:u,pkgBin:r.bin||null,pkgExports:r.exports&&typeof r.exports=="object"?r.exports:null}}function Ne(n,e){const s=["/workspace/node_modules/"+e],t=j.join(n.cwd||"/workspace","node_modules",e);return s.includes(t)||s.push(t),s}function Me(n,e,s,t){for(const r of e){G(n.vfs,r,n.emitMutation);for(const f of t.files){if(!f||!f.rel||f.rel.endsWith("/"))continue;const d=j.join(r,f.rel);try{if(n.vfs.existsSync(d)&&n.vfs.statSync(d).isDirectory())continue}catch(y){N.debug("Package install statSync check skipped.",d,y)}G(n.vfs,j.dirname(d),n.emitMutation),n.vfs.writeFileSync(d,f.content),typeof n.emitMutation=="function"&&n.emitMutation("create",d)}const o=j.join(r,"package.json"),i={name:s,version:t.version||"1.0.0",main:"./"+(t.entry||"index.js")};if(t.pkgBin&&(i.bin=t.pkgBin),t.pkgExports&&typeof t.pkgExports=="object"){const f={".":"./"+(t.entry||"index.js")};for(const d of Object.keys(t.pkgExports)){if(d==="."||d.indexOf("*")!==-1)continue;const y=te(t.pkgExports[d]);y&&(f[d]=y.charAt(0)==="."?y:"./"+y)}i.exports=f}if(n.vfs.writeFileSync(o,JSON.stringify(i,null,2)+`
|
|
217
217
|
`),typeof n.emitMutation=="function"&&n.emitMutation("create",o),t.pkgBin){const f=r.slice(0,r.length-s.length-1),d=j.join(f,".bin");G(n.vfs,d,n.emitMutation);const y=typeof t.pkgBin=="string"?{[s.includes("/")?s.split("/").pop():s]:t.pkgBin}:typeof t.pkgBin=="object"?t.pkgBin:{};for(const[l,a]of Object.entries(y)){if(!l||!a)continue;const c=j.join(r,String(a).replace(/^\.\//,"")),h=j.join(d,l),u=`// Auto-generated bin shim for ${s}
|
|
218
218
|
require(${JSON.stringify(c)});
|
|
219
|
-
`;if(n.vfs.writeFileSync(h,u),typeof n.vfs.chmodSync=="function")try{n.vfs.chmodSync(h,493)}catch(p){}typeof n.emitMutation=="function"&&n.emitMutation("create",h)}}}}async function dt(n,e,s,t){const r=s&&typeof s=="object"?s:t||{},o=typeof s=="function"?s:typeof r.onLine=="function"?r.onLine:null,i=!!r.dev,{name:f,range:d}=ye(n);if(!f)return{name:null,ok:!1,installed:[],warning:null};const{path:y,data:l}=H(e.vfs,e.cwd),a=i?"devDependencies":"dependencies";l[a]||(l[a]={});const c=ot(e),h=e.shell&&e.shell._cdnSeen?e.shell._cdnSeen:e.shell?e.shell._cdnSeen=new Set:new Set,u=[{name:f,range:d,direct:!0}],p=new Set([f]),g=[];let m=null,S=null;for(;u.length>0;){const b=u.shift(),v=c?await ct(c,b.name,b.range,h):{ok:!1,reason:`${b.name}: no fetch implementation available`};if(!v.ok){
|
|
220
|
-
`}]}),m||(m=v.reason),g.push({name:b.name,version:"0.0.0"}),typeof o=="function"&&o({name:b.name,version:"0.0.0",offline:!0});continue}
|
|
221
|
-
`),typeof e.emitMutation=="function"&&e.emitMutation("modify",b)}catch(b){
|
|
219
|
+
`;if(n.vfs.writeFileSync(h,u),typeof n.vfs.chmodSync=="function")try{n.vfs.chmodSync(h,493)}catch(p){}typeof n.emitMutation=="function"&&n.emitMutation("create",h)}}}}async function dt(n,e,s,t){const r=s&&typeof s=="object"?s:t||{},o=typeof s=="function"?s:typeof r.onLine=="function"?r.onLine:null,i=!!r.dev,{name:f,range:d}=ye(n);if(!f)return{name:null,ok:!1,installed:[],warning:null};const{path:y,data:l}=H(e.vfs,e.cwd),a=i?"devDependencies":"dependencies";l[a]||(l[a]={});const c=ot(e),h=e.shell&&e.shell._cdnSeen?e.shell._cdnSeen:e.shell?e.shell._cdnSeen=new Set:new Set,u=[{name:f,range:d,direct:!0}],p=new Set([f]),g=[];let m=null,S=null;for(;u.length>0;){const b=u.shift(),v=c?await ct(c,b.name,b.range,h):{ok:!1,reason:`${b.name}: no fetch implementation available`};if(!v.ok){Me(e,Ne(e,b.name),b.name,{version:"0.0.0",entry:"index.js",files:[{rel:"index.js",content:`module.exports = {};
|
|
220
|
+
`}]}),m||(m=v.reason),g.push({name:b.name,version:"0.0.0"}),typeof o=="function"&&o({name:b.name,version:"0.0.0",offline:!0});continue}Me(e,Ne(e,b.name),b.name,v),g.push({name:b.name,version:v.version||"1.0.0"}),typeof o=="function"&&o({name:b.name,version:v.version||"1.0.0",deduped:!!v.deduped}),b.direct&&(S=v.version||null);for(const w of v.deps||[]){const $=w&&typeof w=="object"?w.name:ye(w).name,R=w&&typeof w=="object"?w.range:ye(w).range;$&&!p.has($)&&(p.add($),u.push({name:$,range:R||null,direct:!1}))}}l[a][f]=d||(S?`^${S}`:l[a][f]||"latest"),De(e.vfs,y,l,e.emitMutation);try{const b=j.join(j.dirname(y),"package-lock.json");let v={name:l.name||"workspace",version:l.version||"1.0.0",lockfileVersion:3,packages:{}};if(e.vfs.existsSync(b)){const w=String(e.vfs.readFileSync(b,"utf8")||""),$=JSON.parse(w);$&&typeof $=="object"&&(v=$,(!v.packages||typeof v.packages!="object")&&(v.packages={}))}for(const w of g)w&&w.name&&(v.packages[`node_modules/${w.name}`]={version:w.version||"1.0.0",resolved:`${Ie}/${w.name}@${w.version||"1.0.0"}`});e.vfs.writeFileSync(b,JSON.stringify(v,null,2)+`
|
|
221
|
+
`),typeof e.emitMutation=="function"&&e.emitMutation("modify",b)}catch(b){N.debug("Could not write package-lock.json during installPackage.",b)}return{name:f,ok:!0,version:S,installed:g,warning:m}}function ft(n,e){const s=n&&typeof n.onStdout=="function"?n.onStdout:null;return function(r){r&&(e.push(r),s&&s(r))}}function ut(n){if(!n||!n.name)return"";const e=n.offline?" (offline fallback)":n.deduped?" (deduped)":"";return` + ${n.name}@${n.version||"1.0.0"}${e}
|
|
222
222
|
`}function ht(n){const e=new Set;for(const s of n)if(s){s.name&&e.add(s.name);for(const t of s.installed||[])t&&t.name&&e.add(t.name)}return e.size}async function ne(n,e,s){const t=s||{},r=t.manager||"bun",o=t.header||(r==="npm"?"npm install v10.2.0":"bun add v1.1.20 (1.1.20)"),i=[],f=ft(e,i),d=Date.now();f(`${o}
|
|
223
223
|
|
|
224
224
|
Resolving dependencies...
|
|
@@ -236,24 +236,24 @@ ${a} package(s) installed [${c}ms]
|
|
|
236
236
|
`;const r=Object.keys(s);if(r.length===0)t+=`\u2514\u2500\u2500 (empty)
|
|
237
237
|
`;else for(let o=0;o<r.length;o++){const i=r[o],f=String(s[i]).replace(/^[\^~]/,""),d=o===r.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";t+=`${d}${i}@${f}
|
|
238
238
|
`}return t}function We(n){const e=String(n??"");return e.length===0?"''":/[\s"'\\$&|;<>()`!*?~#]/.test(e)?"'"+e.replace(/'/g,"'\\''")+"'":e}async function Z(n,e,s){const{data:t}=H(s.vfs,s.cwd);if(!t.scripts||!t.scripts[n])return{code:1,stdout:"",stderr:`npm ERR! Missing script: "${n}"
|
|
239
|
-
`};let r=t.scripts[n];e&&e.length>0&&(r+=" "+e.map(We).join(" "));const o=await Ve(n,r,s);if(o)return o;const i=`${j.join(s.cwd||"/workspace","node_modules/.bin")}:/workspace/node_modules/.bin`,f={...s.env,PATH:s.env&&s.env.PATH?`${i}:${s.env.PATH}`:`${i}:/usr/local/bin:/usr/bin:/bin`},d=await s.shell.execute(r,{cwd:s.cwd,env:f,stdin:s.stdin,signal:s.signal,isBackground:s.isBackground,onStdout:s.onStdout,onStderr:s.onStderr,onRequestStdin:s.onRequestStdin||(s.shell&&s.shell.options?s.shell.options.onRequestStdin:void 0)});return{code:d.code!==void 0?d.code:0,stdout:d.stdout||"",stderr:d.stderr||"",alreadyStreamed:!!s.onStdout,aborted:d.aborted}}const Be="https://cdn.jsdelivr.net/npm",pt={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".cjs":"text/javascript; charset=utf-8",".jsx":"text/javascript; charset=utf-8",".ts":"text/javascript; charset=utf-8",".tsx":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".wasm":"application/wasm",".pdf":"application/pdf",".mp3":"audio/mpeg",".mp4":"video/mp4",".webm":"video/webm",".txt":"text/plain; charset=utf-8"};function yt(n){const e=String(n||"").toLowerCase().split(";")[0].trim();return e?!(e.startsWith("text/")||e==="application/javascript"||e==="application/json"||e==="application/xml"||e==="application/xhtml+xml"||e==="image/svg+xml"):!1}function mt(n){const e=String(n).toLowerCase(),s=e.lastIndexOf(".");return s===-1?"application/octet-stream":pt[e.slice(s)]||"application/octet-stream"}function Se(n){return/\.(?:[cm]?jsx?|tsx?)$/i.test(n)&&!/\.d\.ts$/i.test(n)}function ve(n){const e=new Set,s=[/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g];for(const t of s){let r;for(;(r=t.exec(n))!==null;){const o=r[1];!o||o.startsWith(".")||o.startsWith("/")||o.includes(":")||e.add(o)}}return Array.from(e)}function gt(n){if(!n||typeof n!="string")return"latest";const e=n.trim();return!e||e==="*"||/^(?:latest|next|beta|canary)$/.test(e)||/^(?:file|link|workspace|portal|git|https?):/.test(e)?"latest":e.replace(/\s+/g,"").replace(/^[v=\s]+/,"")||"latest"}function Ue(n,e,s){try{const t=j.join(e,"node_modules",s,"package.json");if(n.existsSync(t)){const r=JSON.parse(n.readFileSync(t,"utf8"));if(r&&r.version)return r.version}}catch(t){
|
|
239
|
+
`};let r=t.scripts[n];e&&e.length>0&&(r+=" "+e.map(We).join(" "));const o=await Ve(n,r,s);if(o)return o;const i=`${j.join(s.cwd||"/workspace","node_modules/.bin")}:/workspace/node_modules/.bin`,f={...s.env,PATH:s.env&&s.env.PATH?`${i}:${s.env.PATH}`:`${i}:/usr/local/bin:/usr/bin:/bin`},d=await s.shell.execute(r,{cwd:s.cwd,env:f,stdin:s.stdin,signal:s.signal,isBackground:s.isBackground,onStdout:s.onStdout,onStderr:s.onStderr,onRequestStdin:s.onRequestStdin||(s.shell&&s.shell.options?s.shell.options.onRequestStdin:void 0)});return{code:d.code!==void 0?d.code:0,stdout:d.stdout||"",stderr:d.stderr||"",alreadyStreamed:!!s.onStdout,aborted:d.aborted}}const Be="https://cdn.jsdelivr.net/npm",pt={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".cjs":"text/javascript; charset=utf-8",".jsx":"text/javascript; charset=utf-8",".ts":"text/javascript; charset=utf-8",".tsx":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".wasm":"application/wasm",".pdf":"application/pdf",".mp3":"audio/mpeg",".mp4":"video/mp4",".webm":"video/webm",".txt":"text/plain; charset=utf-8"};function yt(n){const e=String(n||"").toLowerCase().split(";")[0].trim();return e?!(e.startsWith("text/")||e==="application/javascript"||e==="application/json"||e==="application/xml"||e==="application/xhtml+xml"||e==="image/svg+xml"):!1}function mt(n){const e=String(n).toLowerCase(),s=e.lastIndexOf(".");return s===-1?"application/octet-stream":pt[e.slice(s)]||"application/octet-stream"}function Se(n){return/\.(?:[cm]?jsx?|tsx?)$/i.test(n)&&!/\.d\.ts$/i.test(n)}function ve(n){const e=new Set,s=[/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g];for(const t of s){let r;for(;(r=t.exec(n))!==null;){const o=r[1];!o||o.startsWith(".")||o.startsWith("/")||o.includes(":")||e.add(o)}}return Array.from(e)}function gt(n){if(!n||typeof n!="string")return"latest";const e=n.trim();return!e||e==="*"||/^(?:latest|next|beta|canary)$/.test(e)||/^(?:file|link|workspace|portal|git|https?):/.test(e)?"latest":e.replace(/\s+/g,"").replace(/^[v=\s]+/,"")||"latest"}function Ue(n,e,s){try{const t=j.join(e,"node_modules",s,"package.json");if(n.existsSync(t)){const r=JSON.parse(n.readFileSync(t,"utf8"));if(r&&r.version)return r.version}}catch(t){N.debug("Could not read installed module package.json.",s,t)}try{for(const t of[e,"/workspace"]){const r=j.join(t,"package.json");if(!n.existsSync(r))continue;const o=JSON.parse(n.readFileSync(r,"utf8")),i=Object.assign({},o.dependencies||{},o.devDependencies||{},o.peerDependencies||{});if(i[s])return gt(i[s])}}catch(t){N.debug("Could not read workspace package.json for version resolution.",s,t)}return"latest"}function ze(n,e,s){const t=`${Be}/${n}@${e}`,r=s?"/"+String(s).replace(/^\/+|\/+$/g,""):"";return`${t}${r}/+esm`}function bt(n,e,s){const t={};for(const r of s){const o=String(r).split("/"),i=r.startsWith("@")?o.slice(0,2).join("/"):o[0];if(!i)continue;const f=r.slice(i.length).replace(/^\/+/,""),d=Ue(n,e,i);if(f&&/\.css$/i.test(f)){const y=`${Be}/${i}@${d}/${f.replace(/^\/+/,"")}`,l=`if(typeof document!=='undefined'){const l=document.createElement('link');l.rel='stylesheet';l.href=${JSON.stringify(y)};document.head.appendChild(l);}export default ${JSON.stringify(y)};`;t[r]=`data:text/javascript;charset=utf-8,${encodeURIComponent(l)}`;continue}t[r]=ze(i,d,f||void 0)}return t}const St=/https?:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/((?:@[^\/'"`@\s]+\/)?[^\/'"`@\s]+)@([^\s'"`),;]+)/g;function He(n,e,s,t){if(!s||typeof s!="string")return;const r=new RegExp(St.source,"g");let o;for(;(o=r.exec(s))!==null;){const i=o[0];if(i.includes("${"))continue;const f=decodeURIComponent(o[1]),d=o[2],y=d.split(/[\/?]/)[0],l=d.slice(y.length),c=(l.startsWith("/")&&l!=="/+esm"?l.slice(1).split(/[?#]/)[0]:"").replace(/^\/+|\/+$/g,""),h=c?`${f}/${c}`:f,u=Ue(n,e,f),p=u&&u!=="latest"?u:decodeURIComponent(y),g=t[h]||ze(f,p,c||void 0);g&&g!==i&&(t[i]=g)}}function qe(n,e,s=200){const t=[],r=(o,i)=>{if(i>8||t.length>=s)return;let f=[];try{f=n.readdirSync(o)}catch{return}for(const d of f){if(d==="node_modules"||d.startsWith("."))continue;const y=j.join(o,d);let l;try{l=n.statSync(y)}catch{continue}if(l&&(typeof l.isDirectory=="function"?l.isDirectory():l.isDirectory))r(y,i+1);else if(Se(d)&&t.length<s)try{const c=n.readFileSync(y,"utf8"),h=y.startsWith(e+"/")?y.slice(e.length+1):d;t.push({full:y,rel:h,content:c})}catch(c){N.debug("Preview script read skipped.",y,c)}}};return r(e,0),t}function vt(n,e,s=200){const t=[],r=(o,i)=>{if(i>8||t.length>=s)return;let f=[];try{f=n.readdirSync(o)}catch{return}for(const d of f){if(d==="node_modules"||d.startsWith("."))continue;const y=j.join(o,d);let l;try{l=n.statSync(y)}catch{continue}if(l&&(typeof l.isDirectory=="function"?l.isDirectory():l.isDirectory))r(y,i+1);else if(/\.(?:css|json|svg)$/i.test(d)&&t.length<s)try{const c=n.readFileSync(y,"utf8"),h=y.startsWith(e+"/")?y.slice(e.length+1):d;t.push({full:y,rel:h,content:c})}catch(c){N.debug("Preview asset read skipped.",y,c)}}};return r(e,0),t}function Pt(n,e,s=200){return qe(n,e,s).map(t=>t.content)}function wt(n,e){let s=n;const r=`<script type="importmap">
|
|
240
240
|
${JSON.stringify({imports:e},null,2).replace(/</g,"\\u003c")}
|
|
241
241
|
<\/script>`;/<head[^>]*>/i.test(s)?s=s.replace(/<head[^>]*>/i,i=>`${i}
|
|
242
242
|
${r}`):s=r+`
|
|
243
243
|
`+s;const o="<script>window.__CODELAB_PREVIEW__ = true;<\/script>";return/<\/body>/i.test(s)?s=s.replace(/<\/body>/i,`${o}
|
|
244
244
|
</body>`):s=s+`
|
|
245
|
-
`+o,s}function we(n,e,s){const t=n.shell&&n.shell.portTable;if(!t||typeof t.registerServer!="function")return null;let r=Number(s)||3e3;const o=new Set((typeof t.listServers=="function"?t.listServers():[]).map(S=>Number(S.port)));for(;o.has(r);)r++;const i=S=>{try{return n.vfs.existsSync(S)}catch{return!1}},f=S=>{try{const b=n.vfs.statSync(S);return!!(b&&(typeof b.isDirectory=="function"?b.isDirectory():b.isDirectory))}catch{return!1}},d=S=>i(S)&&!f(S),y=S=>{try{return n.vfs.readFileSync(S,"utf8")}catch{return null}},l=S=>{const b=e==="/"?"/":e+"/";return S===e||S.startsWith(b)},a=(S,b)=>{if(!b||typeof b!="string")return null;const v=b.split(/[?#]/)[0].trim();if(!v||/^(?:https?:|data:|blob:|\/\/)/i.test(v))return null;const w=v.startsWith("/")?j.join(e,v.replace(/^\/+/,"")):j.join(S,v);if(!l(w))return null;if(d(w))return w;const $=[w+".tsx",w+".ts",w+".jsx",w+".js",w+".mjs",w+".cjs",j.join(w,"index.tsx"),j.join(w,"index.ts"),j.join(w,"index.jsx"),j.join(w,"index.js")];for(const R of $)if(l(R)&&d(R))return R;return null},c=S=>`@codelab-local/${S.startsWith(e+"/")?S.slice(e.length+1):S.replace(/^\/+/,"")}`,h=(S,b)=>{let v=S;try{const R=U();R&&typeof R.transpileForBrowser=="function"&&(v=R.transpileForBrowser(v,b))}catch(R){
|
|
245
|
+
`+o,s}function we(n,e,s){const t=n.shell&&n.shell.portTable;if(!t||typeof t.registerServer!="function")return null;let r=Number(s)||3e3;const o=new Set((typeof t.listServers=="function"?t.listServers():[]).map(S=>Number(S.port)));for(;o.has(r);)r++;const i=S=>{try{return n.vfs.existsSync(S)}catch{return!1}},f=S=>{try{const b=n.vfs.statSync(S);return!!(b&&(typeof b.isDirectory=="function"?b.isDirectory():b.isDirectory))}catch{return!1}},d=S=>i(S)&&!f(S),y=S=>{try{return n.vfs.readFileSync(S,"utf8")}catch{return null}},l=S=>{const b=e==="/"?"/":e+"/";return S===e||S.startsWith(b)},a=(S,b)=>{if(!b||typeof b!="string")return null;const v=b.split(/[?#]/)[0].trim();if(!v||/^(?:https?:|data:|blob:|\/\/)/i.test(v))return null;const w=v.startsWith("/")?j.join(e,v.replace(/^\/+/,"")):j.join(S,v);if(!l(w))return null;if(d(w))return w;const $=[w+".tsx",w+".ts",w+".jsx",w+".js",w+".mjs",w+".cjs",j.join(w,"index.tsx"),j.join(w,"index.ts"),j.join(w,"index.jsx"),j.join(w,"index.js")];for(const R of $)if(l(R)&&d(R))return R;return null},c=S=>`@codelab-local/${S.startsWith(e+"/")?S.slice(e.length+1):S.replace(/^\/+/,"")}`,h=(S,b)=>{let v=S;try{const R=U();R&&typeof R.transpileForBrowser=="function"&&(v=R.transpileForBrowser(v,b))}catch(R){N.warn(`Preview script transpilation failed for ${b}.`,R)}const w=j.dirname(b),$=R=>{if(!R||!R.startsWith(".")&&!R.startsWith("/"))return R;const I=a(w,R);return I?c(I):R};return v=v.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g,(R,I,C,E)=>`${I}${$(C)}${E}`),v=v.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g,(R,I,C,E)=>`${I}${$(C)}${E}`),v},u=(S,b)=>S?S.replace(/@import\s+(?:url\(\s*['"]?([^'")]+)['"]?\s*\)|['"]([^'"]+)['"])\s*;?/gi,(v,w,$)=>{const R=(w||$||"").trim();if(!R||/^(?:https?:|data:|\/\/)/i.test(R))return v;if(R==="tailwindcss")return"";const I=a(b,R);if(I&&/\.css$/i.test(I)){const C=y(I);if(C!==null)return C}return""}):"",p=(S,b)=>{const v=qe(n.vfs,e),w=vt(n.vfs,e),$=new Set,R=[];for(const P of v){for(const M of ve(P.content))$.add(M);const A=h(P.content,P.full);for(const M of ve(A))$.add(M);R.push({file:P,compiled:A})}const I=/<script\b[^>]*>([\s\S]*?)<\/script>/gi;let C;for(;(C=I.exec(S))!==null;)if(C[1])for(const P of ve(C[1]))$.add(P);const E=bt(n.vfs,e,$);for(const P of v)He(n.vfs,e,P.content,E);He(n.vfs,e,S,E);for(const{file:P,compiled:A}of R){const M=c(P.full);E[M]=`data:text/javascript;charset=utf-8,${encodeURIComponent(A)}`}let T=!1;for(const P of w){const A=c(P.full);if(/\.css$/i.test(P.full)){/@import\s+['"]tailwindcss['"]/i.test(P.content)&&(T=!0);const M=u(P.content,j.dirname(P.full)),D=`const __css=${JSON.stringify(M)};if(typeof document!=='undefined'){const __s=document.createElement('style');__s.setAttribute('data-codelab-css',${JSON.stringify(P.rel)});__s.textContent=__css;document.head.appendChild(__s);}export default __css;`;E[A]=`data:text/javascript;charset=utf-8,${encodeURIComponent(D)}`}else if(/\.json$/i.test(P.full)){const M=`export default ${P.content.trim()||"null"};`;E[A]=`data:text/javascript;charset=utf-8,${encodeURIComponent(M)}`}else if(/\.svg$/i.test(P.full)){const M=`data:image/svg+xml;utf8,${encodeURIComponent(P.content)}`,D=`export default ${JSON.stringify(M)};`;E[A]=`data:text/javascript;charset=utf-8,${encodeURIComponent(D)}`}}const k=j.dirname(b);let O=S.replace(/%PUBLIC_URL%\//g,"/").replace(/%PUBLIC_URL%/g,"");if(!/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/i.test(O)){const P=["/src/main.tsx","/src/main.jsx","/src/main.ts","/src/main.js","/src/index.tsx","/src/index.jsx","/src/index.ts","/src/index.js"];for(const A of P)if(d(j.join(e,A.slice(1)))){const M=`<script type="module" src="${A}"><\/script>`;/<\/body>/i.test(O)?O=O.replace(/<\/body>/i,` ${M}
|
|
246
246
|
</body>`):O+=`
|
|
247
|
-
${
|
|
247
|
+
${M}`;break}}if(O=O.replace(/<link\b([^>]*?)>/gi,(P,A)=>{if(!/\brel\s*=\s*["']stylesheet["']/i.test(A))return P;const M=/\bhref\s*=\s*["']([^"']+)["']/i.exec(A);if(!M)return P;const D=a(k,M[1]);if(!D||!/\.css$/i.test(D))return P;const _=y(D);if(_===null)return P;/@import\s+['"]tailwindcss['"]/i.test(_)&&(T=!0);const B=u(_,j.dirname(D)).replace(/<\/style/gi,"<\\/style");return`<style data-codelab-href="${M[1].replace(/"/g,""")}">
|
|
248
248
|
${B}
|
|
249
|
-
</style>`}),O=O.replace(/<script\b([^>]*?)>\s*<\/script>/gi,(P,A)=>{const
|
|
249
|
+
</style>`}),O=O.replace(/<script\b([^>]*?)>\s*<\/script>/gi,(P,A)=>{const M=/\bsrc\s*=\s*["']([^"']+)["']/i.exec(A);if(!M)return P;const D=a(k,M[1]);if(!D||!Se(D))return P;const _=y(D);if(_===null)return P;const B=h(_,D).replace(/<\/script/gi,"<\\/script");return`<script${/\btype\s*=\s*["']module["']/i.test(A)||/\.(?:tsx|ts|jsx|mjs)$/i.test(D)||/^\s*(?:import|export)\b/m.test(_)?' type="module"':""} data-codelab-src="${M[1].replace(/"/g,""")}">
|
|
250
250
|
${B}
|
|
251
251
|
<\/script>`}),T&&!O.includes("@tailwindcss/browser")){const P='<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"><\/script>';/<head[^>]*>/i.test(O)?O=O.replace(/<head[^>]*>/i,A=>`${A}
|
|
252
252
|
${P}`):O=P+`
|
|
253
|
-
`+O}return wt(O,E)},g=async S=>{let b="/";try{b=decodeURIComponent(new URL(S.url).pathname)}catch(C){
|
|
253
|
+
`+O}return wt(O,E)},g=async S=>{let b="/";try{b=decodeURIComponent(new URL(S.url).pathname)}catch(C){N.debug("Preview URL decode failed.",C)}const v=b.replace(/^\/+/,"");let w=j.join(e,v);if(!l(w))return new Response('<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',{status:403,headers:{"content-type":"text/html; charset=utf-8"}});const $=/\.[A-Za-z0-9]+$/.test(v);if(!v||b.endsWith("/")||f(w)){const C=j.join(w,"index.html"),E=j.join(w,"public","index.html");w=!i(C)&&i(E)?E:C}if(!i(w)&&!$){const C=[w+".tsx",w+".ts",w+".jsx",w+".js",w+".mjs",w+".cjs",j.join(w,"index.tsx"),j.join(w,"index.ts"),j.join(w,"index.jsx"),j.join(w,"index.js")];for(const E of C)if(i(E)){w=E;break}}if(!i(w)&&!$){const C=j.join(e,"index.html"),E=j.join(e,"public","index.html");w=!i(C)&&i(E)?E:C}if(!i(w)){const C=String(b).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return new Response(`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${C}</p>`,{status:404,headers:{"content-type":"text/html; charset=utf-8"}})}const R=mt(w);if(yt(R)){let C=null;try{C=n.vfs.readFileSync(w)}catch(T){N.debug("Binary preview asset read failed.",w,T)}const E=C instanceof Uint8Array?C:typeof C=="string"?new TextEncoder().encode(C):new Uint8Array(0);return new Response(E,{status:200,headers:{"content-type":R}})}let I=y(w);if(I===null&&(I=""),/\.html?$/i.test(w))I=p(I,w);else if(Se(w))try{const C=U();C&&typeof C.transpileForBrowser=="function"&&(I=C.transpileForBrowser(I,w))}catch(C){N.warn(`Preview script transpilation failed for ${w}.`,C)}return new Response(I,{status:200,headers:{"content-type":R}})},m=n.shell&&typeof n.shell.nextPid=="number"?n.shell.nextPid++:n.pid||1e3;return t.registerServer(r,{server:{close(){try{t.unregisterServer(r)}catch(S){N.debug("Preview server unregister failed.",r,S)}}},fetch:g,name:"code-lab-serve",pid:m,root:e})}const Le=/\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/,$t=/^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts)$/,kt=/^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;async function $e(n,e,s){const t=e&&e.shell?e.shell.portTable:null;if(!!!(e&&!e.isBackground&&e.signal))return{code:0,stdout:s,stderr:""};const o=`${s.replace(/\n+$/,"")}
|
|
254
254
|
\u279C Press Ctrl+C to stop
|
|
255
255
|
|
|
256
|
-
`;typeof e.onStdout=="function"&&e.onStdout(o);const i=()=>{if(n&&n.server&&typeof n.server.close=="function")try{n.server.close()}catch(f){
|
|
256
|
+
`;typeof e.onStdout=="function"&&e.onStdout(o);const i=()=>{if(n&&n.server&&typeof n.server.close=="function")try{n.server.close()}catch(f){N.debug("Foreground server close failed.",f)}else if(t&&typeof t.unregisterServer=="function"&&n)try{t.unregisterServer(n.port)}catch(f){N.debug("Foreground server unregister failed.",f)}};return e.signal.aborted?(i(),{code:130,stdout:o,stderr:"",alreadyStreamed:typeof e.onStdout=="function",aborted:!0}):await new Promise(f=>{let d=!1;const y=()=>{if(e.signal&&typeof e.signal.removeEventListener=="function")try{e.signal.removeEventListener("abort",a)}catch(h){}if(t&&typeof t.off=="function")try{t.off("close",c)}catch(h){}},l=(h,u)=>{d||(d=!0,y(),f({code:h,stdout:o,stderr:"",alreadyStreamed:typeof e.onStdout=="function",aborted:u}))},a=()=>{i(),l(130,!0)},c=(h,u)=>{n&&Number(h)===Number(n.port)&&(!u||u===n)&&l(0,!1)};e.signal.addEventListener("abort",a,{once:!0}),t&&typeof t.on=="function"&&t.on("close",c)})}async function Ve(n,e,s,t){if(!Le.test(e))return null;const r=(e.match(Le)||[])[1],o=!!(t&&t.force),i=j.join("/workspace/node_modules/.bin",r),f=s.vfs.existsSync(i);if(!o&&!$t.test(r)&&f)return null;const d=e.match(/--port(?:=|\s+)(\d+)/),l=d?Number(d[1]):{ng:4200,vite:5173,astro:4321,next:3e3}[r]||3e3,a=typeof s.resolvePath=="function"?s.resolvePath("."):s.cwd||"/workspace",c=we(s,a,l);if(!c)return null;const h=o||f?`${r} is a native dev server and cannot execute inside this virtual runtime \u2014 using the CodeLab preview server instead.`:`${r} is not available in this virtual runtime \u2014 using the CodeLab preview server instead.`,u=`
|
|
257
257
|
> ${n}
|
|
258
258
|
> ${e}
|
|
259
259
|
|
|
@@ -263,11 +263,11 @@ ${B}
|
|
|
263
263
|
|
|
264
264
|
`;return await $e(c,s,u)}function ke(n,e){const s=[...n];if(s.length>0&&s[s.length-1]==="]"&&s.pop(),s.length===0)return 1;if(s[0]==="!")return ke(s.slice(1),e)===0?1:0;if(s.length===1)return s[0]?0:1;if(s.length===2){const[t,r]=s;if(t==="-z")return r.length===0?0:1;if(t==="-n")return r.length>0?0:1;if(t==="-e"||t==="-f"||t==="-d"||t==="-s"){const o=e.resolvePath(r);if(!e.vfs.existsSync(o))return 1;if(t==="-e")return 0;const i=e.vfs.statSync(o);if(t==="-f")return typeof i.isFile=="function"?i.isFile()?0:1:i.isFile?0:1;if(t==="-d")return typeof i.isDirectory=="function"?i.isDirectory()?0:1:i.isDirectory?0:1;if(t==="-s")return i.size>0?0:1}}if(s.length===3){const[t,r,o]=s;if(r==="="||r==="==")return t===o?0:1;if(r==="!=")return t!==o?0:1;const i=parseInt(t,10),f=parseInt(o,10);if(r==="-eq")return i===f?0:1;if(r==="-ne")return i!==f?0:1;if(r==="-lt")return i<f?0:1;if(r==="-le")return i<=f?0:1;if(r==="-gt")return i>f?0:1;if(r==="-ge")return i>=f?0:1}return 1}const V={async pwd(n,e){return{code:0,stdout:(e.shell?e.shell.cwd:e.cwd)+`
|
|
265
265
|
`,stderr:""}},async cd(n,e){const s=e.env&&e.env.HOME||"/home/codelab";j._homeDir=s;let t=n[0];!t||t==="~"?t=s:t==="-"&&(t=e.env.OLDPWD||e.cwd);const r=e.resolvePath(t);if(r===s&&!e.vfs.existsSync(r)&&typeof e.vfs.mkdirSync=="function")try{e.vfs.mkdirSync(r,{recursive:!0})}catch(f){}if(!e.vfs.existsSync(r))return{code:1,stdout:"",stderr:`cd: ${t}: No such file or directory
|
|
266
|
-
`};let o=!1;try{o=e.vfs.statSync(r).isDirectory()}catch(f){
|
|
266
|
+
`};let o=!1;try{o=e.vfs.statSync(r).isDirectory()}catch(f){N.debug("cd statSync failed.",r,f)}if(!o)return{code:1,stdout:"",stderr:`cd: ${t}: Not a directory
|
|
267
267
|
`};const i=e.cwd;return e.cwd=r,e.env.OLDPWD=i,e.env.PWD=r,e.vfs&&typeof e.vfs._setCwd=="function"&&e.vfs._setCwd(r),e.shell&&(e.shell.cwd=r,e.shell.env.OLDPWD=i,e.shell.env.PWD=r),{code:0,stdout:"",stderr:""}},async ls(n,e){let s=!1,t=!1,r=!1,o=!1,i=!1,f=!1,d=!1,y=!1;const l=[];for(const m of n)if(m.startsWith("-")&&m.length>1)for(let S=1;S<m.length;S++){const b=m[S];b==="a"||b==="A"?s=!0:b==="l"?t=!0:b==="h"?r=!0:b==="r"?o=!0:b==="t"?i=!0:b==="1"?f=!0:b==="R"?d=!0:b==="d"&&(y=!0)}else l.push(m);l.length===0&&l.push(".");function a(m){return r?m<1024?`${m}B`.padStart(5," "):m<1024*1024?`${(m/1024).toFixed(1)}K`.padStart(5," "):`${(m/(1024*1024)).toFixed(1)}M`.padStart(5," "):String(m).padStart(6," ")}function c(m){const S=new Date(m||Date.now()),v=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][S.getMonth()],w=String(S.getDate()).padStart(2," "),$=String(S.getHours()).padStart(2,"0"),R=String(S.getMinutes()).padStart(2,"0");return`${v} ${w} ${$}:${R}`}let h="",u="",p=0;function g(m,S,b){b&&(h+=(h.length>0?`
|
|
268
268
|
`:"")+`${m}:
|
|
269
269
|
`);let v=[];try{v=e.vfs.readdirSync(S)}catch($){u+=`ls: cannot open directory '${m}': ${$.message}
|
|
270
|
-
`,p=2;return}s?v=[".","..",...v]:v=v.filter($=>!$.startsWith("."));const w=v.map($=>{const R=S==="/"?"/"+$:S+"/"+$;let I=!1,C=0,E=Date.now();try{const T=e.vfs.statSync(R);I=T.isDirectory(),C=T.size,E=T.mtimeMs||Date.now()}catch(T){
|
|
270
|
+
`,p=2;return}s?v=[".","..",...v]:v=v.filter($=>!$.startsWith("."));const w=v.map($=>{const R=S==="/"?"/"+$:S+"/"+$;let I=!1,C=0,E=Date.now();try{const T=e.vfs.statSync(R);I=T.isDirectory(),C=T.size,E=T.mtimeMs||Date.now()}catch(T){N.debug("ls statSync skipped.",R,T)}return{name:$,isDirectory:I,size:C,mtimeMs:E,absPath:R}});if(i?w.sort(($,R)=>R.mtimeMs-$.mtimeMs):w.sort(($,R)=>$.name.localeCompare(R.name)),o&&w.reverse(),t){let $=0;for(const R of w)$+=Math.ceil(R.size/512);h+=`total ${$}
|
|
271
271
|
`;for(const R of w){const I=R.isDirectory?"drwxr-xr-x":"-rw-r--r--";h+=`${I} 1 ${e.env.USER||"codelab"} ${e.env.USER||"codelab"} ${a(R.size)} ${c(R.mtimeMs)} ${R.name}
|
|
272
272
|
`}}else if(f)for(const $ of w)h+=`${$.name}
|
|
273
273
|
`;else h+=w.map($=>$.name).join(" ")+(w.length>0?`
|
|
@@ -308,13 +308,13 @@ ${B}
|
|
|
308
308
|
`),stderr:""}},async printf(n,e){if(n.length===0)return{code:0,stdout:"",stderr:""};let s=n[0].replace(/\\n/g,`
|
|
309
309
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\"),t=1;return{code:0,stdout:s.replace(/%([-+0 #]*)(\d+)?(?:\.(\d+))?([sdifxX%])/g,(o,i,f,d,y)=>{if(y==="%")return"%";const l=n[t++];if(l===void 0)return"";let a="";if(y==="s")a=String(l),d!==void 0&&d!==""&&(a=a.slice(0,parseInt(d,10)));else if(y==="d"||y==="i")a=String(parseInt(l,10)||0);else if(y==="f"){const c=parseFloat(l)||0;a=d!==void 0&&d!==""?c.toFixed(parseInt(d,10)):String(c)}else if(y==="x")a=(Number(l)||0).toString(16);else if(y==="X")a=(Number(l)||0).toString(16).toUpperCase();else return o;if(f){const c=parseInt(f,10);if(i&&i.includes("0")&&(y==="d"||y==="i")){const h=a.startsWith("-");h&&(a=a.slice(1)),a=a.padStart(c-(h?1:0),"0"),h&&(a="-"+a)}else i&&i.includes("-")?a=a.padEnd(c," "):a=a.padStart(c," ")}return a}),stderr:""}},async grep(n,e){let s=!1,t=!1,r=!1,o=!1,i=!1,f=!1,d=!1,y=null;const l=[];for(let b=0;b<n.length;b++){const v=n[b];if(v.startsWith("-")&&v.length>1)for(let w=1;w<v.length;w++){const $=v[w];$==="i"?s=!0:$==="v"?t=!0:$==="n"?r=!0:$==="c"?o=!0:$==="l"?i=!0:$==="r"||$==="R"?f=!0:$==="E"&&(d=!0)}else y===null?y=v:l.push(v)}if(!y)return{code:2,stdout:"",stderr:`grep: missing pattern
|
|
310
310
|
`};let a;try{a=new RegExp(y,s?"i":"")}catch(b){return{code:2,stdout:"",stderr:`grep: invalid pattern: ${b.message}
|
|
311
|
-
`}}const c=[];if(f){const b=l.length>0?l:["."];for(const v of b){let $=function(R){try{const I=e.vfs.readdirSync(R);for(const C of I){const E=R==="/"?"/"+C:R+"/"+C;e.vfs.statSync(E).isDirectory()?$(E):c.push(E)}}catch(I){
|
|
311
|
+
`}}const c=[];if(f){const b=l.length>0?l:["."];for(const v of b){let $=function(R){try{const I=e.vfs.readdirSync(R);for(const C of I){const E=R==="/"?"/"+C:R+"/"+C;e.vfs.statSync(E).isDirectory()?$(E):c.push(E)}}catch(I){N.debug("grep directory walk skipped.",R,I)}};const w=e.resolvePath(v);e.vfs.existsSync(w)&&(e.vfs.statSync(w).isDirectory()?$(w):c.push(w))}}else for(const b of l)c.push(e.resolvePath(b));let h="",u="",p=0,g=!1;function m(b,v){const w=b.split(`
|
|
312
312
|
`);w.length>0&&w[w.length-1]===""&&w.pop();let $=0,R="";for(let I=0;I<w.length;I++){const C=w[I],E=a.test(C);if(t?!E:E){if($++,p++,i){h+=`${v}
|
|
313
313
|
`;return}if(!o){const k=v?`${v}:`:"",O=r?`${I+1}:`:"";R+=`${k}${O}${C}
|
|
314
314
|
`}}}if(o){const I=v?`${v}:`:"";h+=`${I}${$}
|
|
315
315
|
`}else h+=R}if(c.length===0)m(e.stdin||"","");else{const b=c.length>1;for(const v of c){if(!e.vfs.existsSync(v)){u+=`grep: ${v}: No such file or directory
|
|
316
316
|
`,g=!0;continue}try{const w=e.vfs.readFileSync(v,"utf8"),$=b?j.normalize(v.replace("/workspace/","")):"";m(w,$)}catch(w){u+=`grep: ${v}: ${w.message}
|
|
317
|
-
`,g=!0}}}let S=1;return p>0?S=0:g&&(S=2),{code:S,stdout:h,stderr:u}},async find(n,e){let s=".",t=null,r=null,o=1/0,i=0;for(n[0]&&!n[0].startsWith("-")&&(s=n[0],i=1);i<n.length;){const a=n[i];if(a==="-name"&&i+1<n.length)t=n[++i];else if(a==="-type"&&i+1<n.length)r=n[++i];else if(a==="-maxdepth"&&i+1<n.length){const c=parseInt(n[++i],10);o=isNaN(c)?1/0:c}i++}const f=t?Pe(t,!1):null,d=e.resolvePath(s),y=[];function l(a,c){if(c>o)return;let h=[];try{h=e.vfs.readdirSync(a)}catch{return}for(const u of h){const p=a==="/"?"/"+u:a+"/"+u;let g=!1;try{g=e.vfs.statSync(p).isDirectory()}catch(b){
|
|
317
|
+
`,g=!0}}}let S=1;return p>0?S=0:g&&(S=2),{code:S,stdout:h,stderr:u}},async find(n,e){let s=".",t=null,r=null,o=1/0,i=0;for(n[0]&&!n[0].startsWith("-")&&(s=n[0],i=1);i<n.length;){const a=n[i];if(a==="-name"&&i+1<n.length)t=n[++i];else if(a==="-type"&&i+1<n.length)r=n[++i];else if(a==="-maxdepth"&&i+1<n.length){const c=parseInt(n[++i],10);o=isNaN(c)?1/0:c}i++}const f=t?Pe(t,!1):null,d=e.resolvePath(s),y=[];function l(a,c){if(c>o)return;let h=[];try{h=e.vfs.readdirSync(a)}catch{return}for(const u of h){const p=a==="/"?"/"+u:a+"/"+u;let g=!1;try{g=e.vfs.statSync(p).isDirectory()}catch(b){N.debug("find statSync skipped.",p,b)}const m=s==="."?"./"+p.replace(d.endsWith("/")?d:d+"/",""):p;let S=!0;r==="f"&&g&&(S=!1),r==="d"&&!g&&(S=!1),f&&!f.test(u)&&(S=!1),S&&y.push(m),g&&l(p,c+1)}}if(e.vfs.existsSync(d)){let a=!1;try{a=e.vfs.statSync(d).isDirectory()}catch(c){N.debug("find root statSync skipped.",d,c)}(!r||r==="d"&&a||r==="f"&&!a)&&(!f||f.test(j.basename(s)))&&y.push(s),a&&l(d,1)}else return{code:1,stdout:"",stderr:`find: '${s}': No such file or directory
|
|
318
318
|
`};return y.sort(),{code:0,stdout:y.join(`
|
|
319
319
|
`)+(y.length>0?`
|
|
320
320
|
`:""),stderr:""}},async wc(n,e){let s=!1,t=!1,r=!1;const o=[];for(const c of n)c==="-l"?s=!0:c==="-w"?t=!0:c==="-c"||c==="-m"?r=!0:o.push(c);!s&&!t&&!r&&(s=!0,t=!0,r=!0);function i(c){const h=c.length===0?0:(c.match(/\n/g)||[]).length,u=(c.trim().match(/\S+/g)||[]).length,p=typeof Buffer<"u"?Buffer.byteLength(c,"utf8"):typeof TextEncoder<"u"?new TextEncoder().encode(c).length:c.length;return{lines:h,words:u,bytes:p}}function f(c,h){let u=[];return s&&u.push(String(c.lines).padStart(4," ")),t&&u.push(String(c.words).padStart(4," ")),r&&u.push(String(c.bytes).padStart(4," ")),h&&u.push(h),u.join(" ")+`
|
|
@@ -386,7 +386,7 @@ ${B}
|
|
|
386
386
|
`};if(typeof e.vfs.chmodSync=="function")try{e.vfs.chmodSync(o,s)}catch(i){return{code:1,stdout:"",stderr:`chmod: ${i.message}
|
|
387
387
|
`}}}return{code:0,stdout:"",stderr:""}},async tree(n,e){let s=!1,t=1/0,r=".";for(let l=0;l<n.length;l++){const a=n[l];a==="-a"?s=!0:a==="-L"&&l+1<n.length?t=parseInt(n[++l],10)||1/0:a.startsWith("-")||(r=a)}const o=e.resolvePath(r);if(!e.vfs.existsSync(o))return{code:1,stdout:"",stderr:`tree: '${r}': No such file or directory
|
|
388
388
|
`};let i=`${r}
|
|
389
|
-
`,f=0,d=0;function y(l,a,c){if(c>t)return;let h=[];try{h=e.vfs.readdirSync(l)}catch{return}s||(h=h.filter(u=>!u.startsWith("."))),h.sort();for(let u=0;u<h.length;u++){const p=h[u],g=u===h.length-1,m=l==="/"?"/"+p:l+"/"+p;let S=!1;try{S=e.vfs.statSync(m).isDirectory()}catch(b){
|
|
389
|
+
`,f=0,d=0;function y(l,a,c){if(c>t)return;let h=[];try{h=e.vfs.readdirSync(l)}catch{return}s||(h=h.filter(u=>!u.startsWith("."))),h.sort();for(let u=0;u<h.length;u++){const p=h[u],g=u===h.length-1,m=l==="/"?"/"+p:l+"/"+p;let S=!1;try{S=e.vfs.statSync(m).isDirectory()}catch(b){N.debug("tree statSync skipped.",m,b)}i+=`${a}${g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${p}
|
|
390
390
|
`,S?(f++,y(m,a+(g?" ":"\u2502 "),c+1)):d++}}return y(o,"",1),i+=`
|
|
391
391
|
${f} directories, ${d} files
|
|
392
392
|
`,{code:0,stdout:i,stderr:""}},async env(n,e){const s=Object.keys(e.env).sort();let t="";for(const r of s)r!=="?"&&!r.startsWith("__")&&(t+=`${r}=${e.env[r]}
|
|
@@ -404,7 +404,7 @@ ${f} directories, ${d} files
|
|
|
404
404
|
`);return{code:0,stdout:s,stderr:""}},async jobs(n,e){let s="";for(const[t,r]of e.shell.jobs.entries()){const o=String(r.command||"").replace(/\s*&\s*$/,"");s+=`[${t}]+ ${r.status} ${o} &
|
|
405
405
|
`}return{code:0,stdout:s,stderr:""}},async kill(n,e){if(n.length===0)return{code:1,stdout:"",stderr:`kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ...
|
|
406
406
|
`};const s=n[n.length-1],t=parseInt(s.replace("%",""),10);if(isNaN(t))return{code:1,stdout:"",stderr:`kill: ${s}: arguments must be process or job IDs
|
|
407
|
-
`};let r=!1;for(const[i,f]of e.shell.jobs.entries())if(f.pid===t||i===t){f.status="Terminated",typeof f.abort=="function"&&f.abort(),r=!0;break}let o=!1;if(e.shell.portTable&&(typeof e.shell.portTable.killProcess=="function"&&(o=e.shell.portTable.killProcess(t)||o),typeof e.shell.portTable.unregisterByPid=="function"&&(o=e.shell.portTable.unregisterByPid(t)||o),typeof e.shell.portTable.listServers=="function"&&typeof e.shell.portTable.unregisterServer=="function")){for(const i of e.shell.portTable.listServers())if(i.pid!==void 0&&String(i.pid)===String(t)){if(i.server&&typeof i.server.close=="function")try{i.server.close()}catch(f){
|
|
407
|
+
`};let r=!1;for(const[i,f]of e.shell.jobs.entries())if(f.pid===t||i===t){f.status="Terminated",typeof f.abort=="function"&&f.abort(),r=!0;break}let o=!1;if(e.shell.portTable&&(typeof e.shell.portTable.killProcess=="function"&&(o=e.shell.portTable.killProcess(t)||o),typeof e.shell.portTable.unregisterByPid=="function"&&(o=e.shell.portTable.unregisterByPid(t)||o),typeof e.shell.portTable.listServers=="function"&&typeof e.shell.portTable.unregisterServer=="function")){for(const i of e.shell.portTable.listServers())if(i.pid!==void 0&&String(i.pid)===String(t)){if(i.server&&typeof i.server.close=="function")try{i.server.close()}catch(f){N.debug("kill server.close failed.",f)}if(typeof i.stop=="function")try{i.stop()}catch(f){N.debug("kill server.stop failed.",f)}e.shell.portTable.unregisterServer(i.port),o=!0}}return r||o?{code:0,stdout:"",stderr:""}:{code:1,stdout:"",stderr:`kill: (${s}) - No such process
|
|
408
408
|
`}},async dirname(n){const e=n[0]||".";return{code:0,stdout:j.dirname(e)+`
|
|
409
409
|
`,stderr:""}},async basename(n){const e=n[0]||"",s=n[1]||"";return{code:0,stdout:j.basename(e,s)+`
|
|
410
410
|
`,stderr:""}},async seq(n){let e=1,s=1,t=1;n.length===1?t=parseFloat(n[0])||1:n.length===2?(e=parseFloat(n[0])||1,t=parseFloat(n[1])||1):n.length>=3&&(e=parseFloat(n[0])||1,s=parseFloat(n[1])||1,t=parseFloat(n[2])||1);let r="";for(let o=e;s>0?o<=t:o>=t;o+=s)r+=`${o}
|
|
@@ -481,7 +481,7 @@ nothing to commit, working tree clean
|
|
|
481
481
|
`:"",stderr:""}:{code:128,stdout:"",stderr:(m.error||`fatal: ambiguous argument '${u}'`)+`
|
|
482
482
|
`}}const g=h.filter(m=>m!=="HEAD");if(g.length>0&&!l&&!a){for(const m of g){const S=i(m);if(S)if(S===".")o.clear();else{const b=S.replace(/\/+$/,""),v=b+"/";o.delete(b);for(const w of Array.from(o.keys()))w.startsWith(v)&&o.delete(w)}}return{code:0,stdout:"",stderr:""}}if(a||o.clear(),l){const m=t.headSnapshot||t.headFiles||{},S=L(e.vfs,r);for(const b of Object.keys(S))if(!Object.prototype.hasOwnProperty.call(m,b)){const v=j.join(r,b);typeof e.vfs.rmSync=="function"?e.vfs.rmSync(v,{force:!0}):typeof e.vfs.unlinkSync=="function"&&e.vfs.existsSync(v)&&e.vfs.unlinkSync(v),e.emitMutation("delete",v)}for(const[b,v]of Object.entries(m)){const w=j.join(r,b);G(e.vfs,j.dirname(w),e.emitMutation),e.vfs.writeFileSync(w,v),e.emitMutation("change",w)}}return y(),{code:0,stdout:"",stderr:""}}if(s==="rm"){const l=n.includes("--cached"),a=n.some(g=>g==="-r"||g==="-rf"||g==="-fr"),c=n.slice(1).filter(g=>!g.startsWith("-")&&g!=="--"),h=t.headSnapshot||t.headFiles||{},u=L(e.vfs,r);if(c.length===0)return{code:128,stdout:"",stderr:`usage: git rm [--cached] [-r] [-f] <file>...
|
|
483
483
|
`};const p=g=>{if(!g)return;const m=j.join(r,g);!l&&e.vfs.existsSync(m)&&(typeof e.vfs.rmSync=="function"?e.vfs.rmSync(m,{force:!0,recursive:a}):typeof e.vfs.unlinkSync=="function"&&e.vfs.unlinkSync(m),e.emitMutation("delete",m)),Object.prototype.hasOwnProperty.call(h,g)?o.set(g,null):o.delete(g)};for(const g of c){const m=i(g);if(!m)continue;if(m==="."){if(a){const v=Array.from(new Set([...Object.keys(h),...Object.keys(u),...Array.from(o.keys())]));for(const w of v)p(w)}continue}const S=m.replace(/\/+$/,"")+"/",b=a?Array.from(new Set([...Object.keys(h).filter(v=>v.startsWith(S)),...Object.keys(u).filter(v=>v.startsWith(S)),...Array.from(o.keys()).filter(v=>v.startsWith(S))])):[];if(b.length>0){for(const v of b)p(v);l||pe(e.vfs,j.join(r,m),e.emitMutation)}else{const v=j.join(r,m);if(!a&&e.vfs&&typeof e.vfs.existsSync=="function"&&e.vfs.existsSync(v)&&typeof e.vfs.statSync=="function")try{if(e.vfs.statSync(v).isDirectory())return{code:128,stdout:"",stderr:`fatal: not removing '${g}' recursively without -r
|
|
484
|
-
`}}catch(w){
|
|
484
|
+
`}}catch(w){N.debug("Failed statting path in git rm.",v,w)}p(m)}}return{code:0,stdout:"",stderr:""}}if(s==="remote"){const l=n[1];if(!l){const a=Object.keys(t.remotes);return{code:0,stdout:a.length>0?a.join(`
|
|
485
485
|
`)+`
|
|
486
486
|
`:"",stderr:""}}if(l==="-v"||l==="--verbose"){let a="";for(const[c,h]of Object.entries(t.remotes))a+=`${c} ${h} (fetch)
|
|
487
487
|
${c} ${h} (push)
|
|
@@ -610,7 +610,7 @@ compilation terminated.
|
|
|
610
610
|
`};for(const a of s)if(!e.vfs.existsSync(a))return{code:1,stdout:"",stderr:`g++: error: ${a}: No such file or directory
|
|
611
611
|
`};const f=e.shell&&e.shell.options&&e.shell.options.cppCompiler||typeof globalThis<"u"&&globalThis.__codelabCppCompiler||typeof window<"u"&&window.__codelabCppCompiler;if(typeof f!="function")return{code:1,stdout:"",stderr:`g++: C++ toolchain is not enabled. Enable cppExtension from "@innovatorved/code-lab/extensions/cpp" to compile C++ files.
|
|
612
612
|
`};let d="",y="";const l=await f({entry:s[0],sourceFiles:s,outputPath:r,std:o,optLevel:i,extraFlags:t,vfs:e.vfs,onStdout:a=>{d+=a,e.onStdout&&e.onStdout(a)},onStderr:a=>{y+=a,e.onStderr&&e.onStderr(a)}});if(!l||l.exitCode!==0)return{code:l&&l.exitCode||1,stdout:d,stderr:y||`g++: error: linker command failed with exit code 1
|
|
613
|
-
`};if(l.wasmBinary){if(e.vfs.writeFileSync(r,l.wasmBinary),typeof e.vfs.chmodSync=="function")try{e.vfs.chmodSync(r,493)}catch(a){
|
|
613
|
+
`};if(l.wasmBinary){if(e.vfs.writeFileSync(r,l.wasmBinary),typeof e.vfs.chmodSync=="function")try{e.vfs.chmodSync(r,493)}catch(a){N.debug("chmodSync failed on compiled binary",a)}typeof e.emitMutation=="function"&&e.emitMutation("create",r)}return{code:0,stdout:d,stderr:y}},async"clang++"(n,e){return V["g++"](n,e)},async"c++"(n,e){return V["g++"](n,e)},async python3(n,e){if(n[0]==="--version"||n[0]==="-V")return{code:0,stdout:`Python 3.12.8 (CPython WebAssembly via Pyodide)
|
|
614
614
|
`,stderr:""};if(n[0]==="-m"&&n[1]==="http.server"){let y=8e3,l=".";for(let u=2;u<n.length;u++){const p=n[u];(p==="-d"||p==="--directory")&&n[u+1]?l=n[++u]:p.startsWith("--directory=")?l=p.slice(12)||".":p==="-b"||p==="--bind"?u++:/^\d+$/.test(p)&&(y=Number(p))}const a=e.resolvePath(l);if(!e.vfs.existsSync(a))return{code:1,stdout:"",stderr:`python3: http.server: ${l}: No such file or directory
|
|
615
615
|
`};const c=we(e,a,y);if(!c)return{code:1,stdout:"",stderr:`python3: http.server: no virtual port table available
|
|
616
616
|
`};const h=`Serving HTTP on 127.0.0.1 port ${c.port} (http://127.0.0.1:${c.port}/) ...
|
|
@@ -699,17 +699,17 @@ Commands:
|
|
|
699
699
|
`,stderr:""};const t=s.listServers();let r=`PORT PID NAME
|
|
700
700
|
`;for(const o of t){const i=String(o.port||"").padEnd(8," "),f=String(o.pid!==void 0?o.pid:"-").padEnd(8," "),d=o.name||o.type||"server";r+=`${i} ${f} ${d}
|
|
701
701
|
`}return{code:0,stdout:r,stderr:""}},async curl(n,e){let s=null;const t={};let r=null,o=!1,i=null;for(let p=0;p<n.length;p++){const g=n[p];if(g==="-X"||g==="--request")s=n[++p];else if(g==="-H"||g==="--header"){const m=n[++p]||"",S=m.indexOf(":");S!==-1&&(t[m.slice(0,S).trim().toLowerCase()]=m.slice(S+1).trim())}else g==="-d"||g==="--data"||g==="--data-raw"?(r=n[++p],s||(s="POST")):g==="-i"||g==="--include"||g==="-v"||g==="--verbose"?o=!0:g==="-s"||g==="--silent"||g.startsWith("-")||(i=g)}if(!i)return{code:1,stdout:"",stderr:`curl: no URL specified!
|
|
702
|
-
`};!i.startsWith("http://")&&!i.startsWith("https://")&&(i="http://"+i),s||(s="GET");const f=e.shell&&e.shell.portTable||null,d=e.shell&&e.shell.options&&typeof(e.shell.options.fetch||e.shell.options.fetchImpl)=="function"?e.shell.options.fetch||e.shell.options.fetchImpl:fetch;let y=!1;try{const g=new URL(i).hostname.toLowerCase();y=g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g==="::1"||g==="[::1]"}catch(p){
|
|
702
|
+
`};!i.startsWith("http://")&&!i.startsWith("https://")&&(i="http://"+i),s||(s="GET");const f=e.shell&&e.shell.portTable||null,d=e.shell&&e.shell.options&&typeof(e.shell.options.fetch||e.shell.options.fetchImpl)=="function"?e.shell.options.fetch||e.shell.options.fetchImpl:fetch;let y=!1;try{const g=new URL(i).hostname.toLowerCase();y=g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g==="::1"||g==="[::1]"}catch(p){N.debug("curl URL parse fallback",i,p)}let l=null,a=null;const c=f&&y?25:1;for(let p=0;p<c;p++)try{if(f&&y){l=await f.dispatchRequest(i,{method:s,headers:t,body:r}),a=null;break}else{l=await d(i,{method:s,headers:t,body:r}),a=null;break}}catch(g){if(a=g,g&&g.chaosEffect)break;p+1<c&&await new Promise(m=>setTimeout(m,15))}if(!l)return{code:7,stdout:"",stderr:`curl: (7) Failed to connect to host: ${a?a.message:"Connection refused"}
|
|
703
703
|
`};const h=typeof l.text=="function"?await l.text():String(l.body||"");let u="";if(o){if(u+=`HTTP/1.1 ${l.status||200} ${l.statusText||"OK"}\r
|
|
704
704
|
`,l.headers)if(typeof l.headers.forEach=="function")l.headers.forEach((p,g)=>{u+=`${g}: ${p}\r
|
|
705
705
|
`});else if(typeof l.headers.entries=="function")for(const[p,g]of l.headers.entries())u+=`${p}: ${g}\r
|
|
706
706
|
`;else for(const[p,g]of Object.entries(l.headers))u+=`${p}: ${g}\r
|
|
707
707
|
`;u+=`\r
|
|
708
|
-
`}return u+=h,{code:0,stdout:u,stderr:""}},async hey(n,e){let s=50,t=10,r="GET";const o={};let i=null,f=!1,d="";for(let D=0;D<n.length;D++){const
|
|
709
|
-
`};!d.startsWith("http://")&&!d.startsWith("https://")&&(d="http://"+d),t=Math.min(t,s);const y=e.shell&&e.shell.portTable||null,l=e.shell&&e.shell.options&&typeof(e.shell.options.fetch||e.shell.options.fetchImpl)=="function"?e.shell.options.fetch||e.shell.options.fetchImpl:fetch;let a=!1;try{const
|
|
708
|
+
`}return u+=h,{code:0,stdout:u,stderr:""}},async hey(n,e){let s=50,t=10,r="GET";const o={};let i=null,f=!1,d="";for(let D=0;D<n.length;D++){const _=n[D];if((_==="-n"||_==="--requests")&&D+1<n.length)s=Math.max(1,Math.min(2e3,parseInt(n[++D],10)||50));else if((_==="-c"||_==="--concurrency")&&D+1<n.length)t=Math.max(1,Math.min(200,parseInt(n[++D],10)||10));else if((_==="-m"||_==="-X"||_==="--method")&&D+1<n.length)r=String(n[++D]).toUpperCase();else if((_==="-H"||_==="--header")&&D+1<n.length){const B=n[++D],z=B.indexOf(":");z!==-1&&(o[B.slice(0,z).trim()]=B.slice(z+1).trim())}else(_==="-d"||_==="--body"||_==="--data")&&D+1<n.length?(i=n[++D],r==="GET"&&(r="POST")):_==="--json"?f=!0:_.startsWith("-")||(d=_)}if(!d)return{code:1,stdout:"",stderr:`Usage: hey [-n requests] [-c concurrency] [-m METHOD] [-H "Header: val"] [-d body] [--json] <url>
|
|
709
|
+
`};!d.startsWith("http://")&&!d.startsWith("https://")&&(d="http://"+d),t=Math.min(t,s);const y=e.shell&&e.shell.portTable||null,l=e.shell&&e.shell.options&&typeof(e.shell.options.fetch||e.shell.options.fetchImpl)=="function"?e.shell.options.fetch||e.shell.options.fetchImpl:fetch;let a=!1;try{const _=new URL(d).hostname.toLowerCase();a=_==="localhost"||_==="127.0.0.1"||_==="0.0.0.0"||_==="::1"||_==="[::1]"}catch(D){N.debug("hey URL parse fallback",d,D)}const c=[],h={},u={};let p=0,g=0;const m=typeof performance<"u"&&performance.now?performance.now():Date.now(),S=async()=>{for(;!(g++>=s);){const _=typeof performance<"u"&&performance.now?performance.now():Date.now();try{let B;y&&a?B=await y.dispatchRequest(d,{method:r,headers:{...o},body:i}):B=await l(d,{method:r,headers:{...o},body:i});const z=typeof performance<"u"&&performance.now?performance.now():Date.now(),X=Math.max(.05,z-_);c.push(X);const J=B&&B.status||200;h[J]=(h[J]||0)+1;const se=B&&typeof B.text=="function"?await B.text():String(B&&B.body||"");p+=se.length}catch(B){const z=typeof performance<"u"&&performance.now?performance.now():Date.now();c.push(Math.max(.05,z-_));const X=B&&(B.chaosEffect||B.code)||"ERROR";u[X]=(u[X]||0)+1}}},b=[];for(let D=0;D<t;D++)b.push(S());await Promise.all(b);const v=typeof performance<"u"&&performance.now?performance.now():Date.now(),w=Math.max(.001,(v-m)/1e3);c.sort((D,_)=>D-_);const $=D=>{if(c.length===0)return 0;const _=Math.min(c.length-1,Math.floor(D/100*c.length));return Number(c[_].toFixed(2))},R=c.length?Number(c[0].toFixed(2)):0,I=c.length?Number(c[c.length-1].toFixed(2)):0,C=c.length?Number((c.reduce((D,_)=>D+_,0)/c.length).toFixed(2)):0,E=Number((s/w).toFixed(2)),T=$(50),k=$(90),O=$(95),F=$(99);if(f)return{code:0,stdout:JSON.stringify({url:d,method:r,requests:s,concurrency:t,durationSec:Number(w.toFixed(4)),rps:E,totalBytes:p,latencyMs:{min:R,avg:C,p50:T,p90:k,p95:O,p99:F,max:I},statusCodes:h,errors:u},null,2)+`
|
|
710
710
|
`,stderr:""};let P="";if(c.length>0){const B=Math.max(.5,I-R)/5,z=new Array(5).fill(0);for(const J of c){const se=Math.min(4,Math.floor((J-R)/B));z[se]++}const X=Math.max(1,...z);for(let J=0;J<5;J++){const se=(R+B*(J+1)).toFixed(2).padStart(7),Rt=`[${z[J]}]`.padStart(6),Ot=Math.round(z[J]/X*28);P+=` ${se} ms ${Rt} |${"\u25A0".repeat(Ot)}
|
|
711
|
-
`}}let A="";for(const[D,
|
|
712
|
-
`;for(const[D,
|
|
711
|
+
`}}let A="";for(const[D,_]of Object.entries(h))A+=` [${D}] ${_} responses
|
|
712
|
+
`;for(const[D,_]of Object.entries(u))A+=` [${D}] ${_} failed
|
|
713
713
|
`;return{code:0,stdout:`
|
|
714
714
|
Summary:
|
|
715
715
|
Total: ${w.toFixed(4)} secs
|
|
@@ -789,7 +789,7 @@ Options:
|
|
|
789
789
|
`,f=2;continue}const y=String(e.vfs.readFileSync(d,"utf8")||"");try{const l=typeof globalThis<"u"&&globalThis.ts?globalThis.ts:null;let a="";if(l&&typeof l.transpileModule=="function"){const c=l.transpileModule(y,{fileName:d,reportDiagnostics:!0,compilerOptions:{target:l.ScriptTarget?l.ScriptTarget.ES2022:9,module:l.ModuleKind?l.ModuleKind.ESNext:99}});if(Array.isArray(c.diagnostics)&&c.diagnostics.length>0){for(const h of c.diagnostics){const u=typeof h.messageText=="string"?h.messageText:h.messageText&&h.messageText.messageText||"Syntax error";i+=`${j.relative(e.cwd,d)}(1,1): error TS${h.code||1005}: ${u}
|
|
790
790
|
`}f=2;continue}a=c.outputText}else{let c=null,h=!1,u=!1,p=0,g=0,m=1;for(let S=0;S<y.length;S++){const b=y[S],v=y[S+1];if(b===`
|
|
791
791
|
`){if(m++,c==='"'||c==="'")throw new Error(`Line ${m-1}: Unterminated string literal.`);h=!1;continue}if(!h){if(u){b==="*"&&v==="/"&&(u=!1,S++);continue}if(c){if(b==="\\"){S++;continue}b===c&&(c=null);continue}if(b==="/"&&v==="/"){h=!0,S++;continue}if(b==="/"&&v==="*"){u=!0,S++;continue}if(b==='"'||b==="'"||b==="`"){c=b;continue}if(b==="{"?p++:b==="}"?p--:b==="("?g++:b===")"&&g--,p<0||g<0)throw new Error(`Line ${m}: Unexpected closing token '${b}'.`)}}if(c)throw new Error(`Line ${m}: Unterminated string literal.`);if(p!==0||g!==0)throw new Error(`Line ${m}: Unexpected end of file (unclosed '${p!==0?"{":"("}').`);a=Je(y,d)}if(!s){const c=j.relative(e.cwd,d).replace(/\.(tsx|ts)$/i,".js"),h=t?j.join(t,c):d.replace(/\.(tsx|ts)$/i,".js"),u=j.dirname(h);e.vfs.existsSync(u)||e.vfs.mkdirSync(u,{recursive:!0}),e.vfs.writeFileSync(h,a),typeof e.emitMutation=="function"&&e.emitMutation("create",h)}}catch(l){i+=`${j.relative(e.cwd,d)}(1,1): error TS1005: ${l.message||String(l)}
|
|
792
|
-
`,f=2}}return{code:f,stdout:"",stderr:i}}};V["redis-cli"]=async function(e,s){const t="/workspace/.codelab-redis.json",r=()=>{try{if(s.vfs.existsSync(t)){const u=JSON.parse(s.vfs.readFileSync(t,"utf8"));if(u&&typeof u=="object")return u}}catch(u){
|
|
792
|
+
`,f=2}}return{code:f,stdout:"",stderr:i}}};V["redis-cli"]=async function(e,s){const t="/workspace/.codelab-redis.json",r=()=>{try{if(s.vfs.existsSync(t)){const u=JSON.parse(s.vfs.readFileSync(t,"utf8"));if(u&&typeof u=="object")return u}}catch(u){N.debug("redis-cli state read fallback:",u)}return{kv:{},hashes:{},lists:{},sets:{},zsets:{},expires:{}}},o=u=>{try{s.vfs.writeFileSync(t,JSON.stringify(u))}catch(p){N.debug("redis-cli state write failed:",p)}},i=r(),f=Date.now();for(const[u,p]of Object.entries(i.expires||{}))typeof p=="number"&&p<=f&&(delete i.kv[u],delete i.hashes[u],delete i.lists[u],delete i.sets[u],delete i.zsets[u],delete i.expires[u]);const d=[];for(let u=0;u<e.length;u++){if((e[u]==="-h"||e[u]==="-p"||e[u]==="-n")&&u+1<e.length){u++;continue}d.push(e[u])}if(d.length===0&&s.stdin){const u=String(s.stdin).trim().split(/\r?\n/)[0];u&&d.push(...u.split(/\s+/))}if(d.length===0)return{code:0,stdout:`redis-cli 7.2.4 (CodeLab VFS Store)
|
|
793
793
|
Usage: redis-cli <COMMAND> [args...]
|
|
794
794
|
`,stderr:""};const y=String(d[0]).toUpperCase(),l=d.slice(1),a=u=>`(integer) ${u}
|
|
795
795
|
`,c=u=>u==null?`(nil)
|
|
@@ -821,13 +821,13 @@ db0:keys=${new Set([...Object.keys(i.kv),...Object.keys(i.hashes),...Object.keys
|
|
|
821
821
|
`){o+=2;continue}r+=t[o+1],o+=2;continue}if(i==="$"&&t[o+1]==="("&&t[o+2]==="("){o+=3;let f=2,d="";for(;o<t.length&&f>0;)if(t[o]==="(")f++,d+="(",o++;else if(t[o]===")"){if(f===2&&t[o+1]===")"){f=0,o+=2;break}f--,f>0&&(d+=")"),o++}else d+=t[o++];r+=ce(d,s,this.env);continue}if(i==="$"&&t[o+1]==="("){o+=2;let f=1,d="";for(;o<t.length&&f>0;)t[o]==="("?f++:t[o]===")"&&f--,f>0&&(d+=t[o]),o++;r+=await this._executeSubshell(d,s);continue}if(i==="`"){o++;let f="";for(;o<t.length&&t[o]!=="`";)f+=t[o++];o<t.length&&t[o]==="`"&&o++,r+=await this._executeSubshell(f,s);continue}if(i==="$"){if(o++,t[o]==="{"){o++;let f="",d=1;for(;o<t.length&&d>0;)t[o]==="{"?d++:t[o]==="}"&&d--,d>0&&(f+=t[o]),o++;r+=this._expandVariable(f,s)}else if(o<t.length&&/[0-9?!$#@*]/.test(t[o]))r+=this._expandVariable(t[o++],s);else if(o<t.length&&/[a-zA-Z_]/.test(t[o])){let f="";for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)f+=t[o++];r+=this._expandVariable(f,s)}else r+="$";continue}r+=i,o++}return r}async _resolveInputRedirect(e,s){if(e.type==="<"){const t=await this.evaluateWord(e.target,s),r=this.resolvePath(t);if(!this.vfs.existsSync(r))return{ok:!1,error:{code:1,stdout:"",stderr:`shell: ${t}: No such file or directory
|
|
822
822
|
`}};try{return{ok:!0,stdin:this.vfs.readFileSync(r,"utf8")}}catch(o){return{ok:!1,error:{code:1,stdout:"",stderr:`shell: ${t}: ${o.message}
|
|
823
823
|
`}}}}if(e.type==="<<<")return{ok:!0,stdin:await this.evaluateWord(e.target,s)+`
|
|
824
|
-
`};if(e.type==="<<"){let t=String(e.body||"");return e.stripTabs&&(t=t.replace(/^\t+/gm,"")),e.quoted||(t=await this._expandHeredocBody(t,s)),{ok:!0,stdin:t}}return null}_evaluateDoubleBracket(e){const s=e.lastIndexOf("]]");if(s===-1)return{code:2,stdout:"",stderr:"shell: [[: missing `]]`\n"};const t=e.slice(0,s);let r=0;const o=a=>{let c="^";for(let h=0;h<a.length;h++){const u=a[h];u==="*"?c+=".*":u==="?"?c+=".":c+=u.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(c+"$")},i=()=>{let a=f();for(;t[r]==="||";){r++;const c=f();a=a||c}return a},f=()=>{let a=d();for(;t[r]==="&&";){r++;const c=d();a=a&&c}return a},d=()=>t[r]==="!"?(r++,!d()):y(),y=()=>{if(r>=t.length)return!1;if(t[r]==="("){r++;const u=i();return t[r]===")"&&r++,u}const a=t[r];if(/^-(?:z|n|e|f|d|s)$/.test(a)&&r+1<t.length){r++;const u=String(t[r++]??"");if(a==="-z")return u.length===0;if(a==="-n")return u.length>0;const p=this.resolvePath(u),g=this.vfs.existsSync(p);if(a==="-e")return g;if(!g)return!1;const m=this.vfs.statSync(p);if(a==="-d")return!!(m&&m.isDirectory());if(a==="-f")return!!(m&&!m.isDirectory());if(a==="-s")return!!(m&&!m.isDirectory()&&m.size>0)}const c=String(t[r++]??""),h=t[r];if(h&&/^(?:==|=|!=|=~|<|>|-eq|-ne|-lt|-le|-gt|-ge)$/.test(h)&&r+1<t.length){r++;const u=String(t[r++]??"");if(h==="=="||h==="=")return o(u).test(c);if(h==="!=")return!o(u).test(c);if(h==="=~")try{return new RegExp(u).test(c)}catch(m){return
|
|
824
|
+
`};if(e.type==="<<"){let t=String(e.body||"");return e.stripTabs&&(t=t.replace(/^\t+/gm,"")),e.quoted||(t=await this._expandHeredocBody(t,s)),{ok:!0,stdin:t}}return null}_evaluateDoubleBracket(e){const s=e.lastIndexOf("]]");if(s===-1)return{code:2,stdout:"",stderr:"shell: [[: missing `]]`\n"};const t=e.slice(0,s);let r=0;const o=a=>{let c="^";for(let h=0;h<a.length;h++){const u=a[h];u==="*"?c+=".*":u==="?"?c+=".":c+=u.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(c+"$")},i=()=>{let a=f();for(;t[r]==="||";){r++;const c=f();a=a||c}return a},f=()=>{let a=d();for(;t[r]==="&&";){r++;const c=d();a=a&&c}return a},d=()=>t[r]==="!"?(r++,!d()):y(),y=()=>{if(r>=t.length)return!1;if(t[r]==="("){r++;const u=i();return t[r]===")"&&r++,u}const a=t[r];if(/^-(?:z|n|e|f|d|s)$/.test(a)&&r+1<t.length){r++;const u=String(t[r++]??"");if(a==="-z")return u.length===0;if(a==="-n")return u.length>0;const p=this.resolvePath(u),g=this.vfs.existsSync(p);if(a==="-e")return g;if(!g)return!1;const m=this.vfs.statSync(p);if(a==="-d")return!!(m&&m.isDirectory());if(a==="-f")return!!(m&&!m.isDirectory());if(a==="-s")return!!(m&&!m.isDirectory()&&m.size>0)}const c=String(t[r++]??""),h=t[r];if(h&&/^(?:==|=|!=|=~|<|>|-eq|-ne|-lt|-le|-gt|-ge)$/.test(h)&&r+1<t.length){r++;const u=String(t[r++]??"");if(h==="=="||h==="=")return o(u).test(c);if(h==="!=")return!o(u).test(c);if(h==="=~")try{return new RegExp(u).test(c)}catch(m){return N.debug("[[ =~ invalid regex",u,m),!1}if(h==="<")return c<u;if(h===">")return c>u;const p=Number(c)||0,g=Number(u)||0;if(h==="-eq")return p===g;if(h==="-ne")return p!==g;if(h==="-lt")return p<g;if(h==="-le")return p<=g;if(h==="-gt")return p>g;if(h==="-ge")return p>=g}return c.length>0};return{code:i()?0:1,stdout:"",stderr:""}}async _executeWithRedirects(e,s,t){if(!e||e.length===0)return t(s);const r=Object.assign({},this.env,s.env);let o={type:"stdout"},i={type:"stderr"},f=s.stdin||"";for(const h of e)if(h.type==="<"||h.type==="<<"||h.type==="<<<"){const u=await this._resolveInputRedirect(h,r);if(u&&!u.ok)return u.error;u&&u.ok&&(f=u.stdin)}for(const h of e)if(!(h.type==="<"||h.type==="<<"||h.type==="<<<"))if(h.type===">"||h.type===">>"||h.type==="&>"){const u=await this.evaluateWord(h.target,r),p=this.resolvePath(u),g=j.dirname(p);if(!this.vfs.existsSync(g))return{code:1,stdout:"",stderr:`shell: ${u}: No such file or directory
|
|
825
825
|
`};if(h.type===">"){this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p);const m={type:"file",path:p,append:!0};h.sourceFd===2?i=m:o=m}else if(h.type===">>"){this.vfs.existsSync(p)||(this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p));const m={type:"file",path:p,append:!0};h.sourceFd===2?i=m:o=m}else if(h.type==="&>"){this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p);const m={type:"file",path:p,append:!0};o=m,i=m}}else h.type===">&"&&(h.sourceFd===2&&h.targetFd===1?i={...o}:h.sourceFd===1&&h.targetFd===2&&(o={...i}));let d="",y="";const l=(h,u)=>{u&&(h.type==="stdout"?(d+=u,s.onStdout&&s.onStdout(u)):h.type==="stderr"?(y+=u,s.onStderr&&s.onStderr(u)):h.type==="file"&&(this.vfs.appendFileSync(h.path,u),this._emitVfsMutation("change",h.path)))},a={...s,stdin:f,onStdout:h=>l(o,h),onStderr:h=>l(i,h)};return{...await t(a),stdout:d,stderr:y}}async _executeAstNode(e,s){if(!e)return{code:0,stdout:"",stderr:""};if(s.signal&&s.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};if(e.type==="Sequence"){let t="",r="",o=0,i=null;for(const f of e.items||[]){if(s.signal&&s.signal.aborted)return{code:130,stdout:t,stderr:r,aborted:!0};if(f.background){const d=this.nextPid++,y=this.nextJobId++,l=typeof AbortController<"u"?new AbortController:null,a={id:y,pid:d,command:"background",status:"Running",startTime:Date.now(),abort:()=>{l&&l.abort()}};this.jobs.set(y,a),typeof this.options.onJobStart=="function"&&this.options.onJobStart(a),this._executeAstNode(f.node,{...s,signal:l?l.signal:void 0,pid:d,isBackground:!0}).then(h=>{a.status!=="Terminated"&&(a.status="Done",a.exitCode=h.code,typeof this.options.onJobEnd=="function"&&this.options.onJobEnd(a))}).catch(h=>{a.status!=="Terminated"&&(a.status="Failed",a.error=h,typeof this.options.onJobEnd=="function"&&this.options.onJobEnd(a))});const c=`[${y}] ${d}
|
|
826
|
-
`;t+=c,o=0,s.onStdout&&s.onStdout(c)}else{const d=await this._executeAstNode(f.node,s);if(t+=d.stdout||"",r+=d.stderr||"",o=d.code!==void 0?d.code:0,this.env["?"]=String(o),s.env&&(s.env["?"]=String(o)),d.controlFlow){i=d.controlFlow;break}if(d.aborted||s.signal&&s.signal.aborted)return{code:130,stdout:t,stderr:r,aborted:!0}}}return{code:o,stdout:t,stderr:r,controlFlow:i}}if(e.type==="Logical"){const t=await this._executeAstNode(e.left,s);if(t.aborted||s.signal&&s.signal.aborted)return{...t,code:130,aborted:!0};if(t.controlFlow)return t;if(e.op==="&&"){if(t.code===0){const r={...s,cwd:this.cwd,env:Object.assign({},this.env)},o=await this._executeAstNode(e.right,r);return{code:o.code,stdout:(t.stdout||"")+(o.stdout||""),stderr:(t.stderr||"")+(o.stderr||""),controlFlow:o.controlFlow,aborted:o.aborted}}return t}else if(e.op==="||"){if(t.code!==0){const r={...s,cwd:this.cwd,env:Object.assign({},this.env)},o=await this._executeAstNode(e.right,r);return{code:o.code,stdout:(t.stdout||"")+(o.stdout||""),stderr:(t.stderr||"")+(o.stderr||""),controlFlow:o.controlFlow,aborted:o.aborted}}return t}}return e.type==="Pipeline"?this._executePipeline(e,s):e.type==="Command"?this._executeSimpleCommand(e,s):e.type==="FunctionDef"?(this.functions||(this.functions={}),this.functions[e.name]=e,{code:0,stdout:"",stderr:""}):e.type==="For"?this._executeWithRedirects(e.redirects,s,async t=>{let r="",o="",i=0;const f=[];if(e.items)for(const y of e.items){const l=await this.evaluateWordToArgs(y,t.env);f.push(...l)}else f.push(...t.positionalArgs||[]);let d=0;for(const y of f){if(++d%250===0&&typeof setTimeout=="function"&&await new Promise(a=>setTimeout(a,0)),t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};t.env[e.varName]=y,this.env[e.varName]=y;const l=await this._executeAstNode(e.body,t);if(r+=l.stdout||"",o+=l.stderr||"",i=l.code!==void 0?l.code:0,this.env["?"]=String(i),t.env&&(t.env["?"]=String(i)),l.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};if(l.controlFlow)if(l.controlFlow.type==="break"){const a=l.controlFlow.count||1;if(a>1)return{code:i,stdout:r,stderr:o,controlFlow:{type:"break",count:a-1}};break}else if(l.controlFlow.type==="continue"){const a=l.controlFlow.count||1;if(a>1)return{code:i,stdout:r,stderr:o,controlFlow:{type:"continue",count:a-1}};continue}else return{code:i,stdout:r,stderr:o,controlFlow:l.controlFlow}}return{code:i,stdout:r,stderr:o}}):e.type==="While"||e.type==="Until"?this._executeWithRedirects(e.redirects,s,async t=>{const r=e.type==="While";let o="",i="",f=0,d=0;for(;;){if(++d%250===0&&typeof setTimeout=="function"&&await new Promise(c=>setTimeout(c,0)),t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};const y=await this._executeAstNode(e.cond,t);if(o+=y.stdout||"",i+=y.stderr||"",y.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};if(y.controlFlow)return{code:y.code,stdout:o,stderr:i,controlFlow:y.controlFlow};const l=y.code===0;if(r?!l:l)break;if(t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};const a=await this._executeAstNode(e.body,t);if(o+=a.stdout||"",i+=a.stderr||"",f=a.code!==void 0?a.code:0,this.env["?"]=String(f),t.env&&(t.env["?"]=String(f)),a.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};if(a.controlFlow)if(a.controlFlow.type==="break"){const c=a.controlFlow.count||1;if(c>1)return{code:f,stdout:o,stderr:i,controlFlow:{type:"break",count:c-1}};break}else if(a.controlFlow.type==="continue"){const c=a.controlFlow.count||1;if(c>1)return{code:f,stdout:o,stderr:i,controlFlow:{type:"continue",count:c-1}};continue}else return{code:f,stdout:o,stderr:i,controlFlow:a.controlFlow}}return{code:f,stdout:o,stderr:i}}):e.type==="If"?this._executeWithRedirects(e.redirects,s,async t=>{let r="",o="";for(const i of e.branches||[]){if(t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};const f=await this._executeAstNode(i.cond,t);if(r+=f.stdout||"",o+=f.stderr||"",f.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};if(f.code===0){const d=await this._executeAstNode(i.body,t);return r+=d.stdout||"",o+=d.stderr||"",{code:d.code,stdout:r,stderr:o,controlFlow:d.controlFlow,aborted:d.aborted}}}if(e.elseBody){const i=await this._executeAstNode(e.elseBody,t);return r+=i.stdout||"",o+=i.stderr||"",{code:i.code,stdout:r,stderr:o,controlFlow:i.controlFlow,aborted:i.aborted}}return{code:0,stdout:r,stderr:o}}):e.type==="BraceGroup"?this._executeWithRedirects(e.redirects,s,t=>this._executeAstNode(e.body,t)):e.type==="Subshell"?this._executeWithRedirects(e.redirects,s,async t=>{const r=new x({...this.options,vfs:this.vfs,portTable:this.portTable,gitState:this.gitState,env:Object.assign({},this.env,t.env||{})});r.cwd=t.cwd||this.cwd;const o={...t,env:Object.assign({},this.env,t.env||{}),cwd:r.cwd};return r._executeAstNode(e.body,o)}):e.type==="Case"?this._executeWithRedirects(e.redirects,s,async t=>{const r=await this.evaluateWord(e.word,t.env);for(const o of e.clauses||[]){let i=!1;for(const f of o.patterns||[]){const d=await this.evaluateWord(f,t.env);if(d==="*"||d===r){i=!0;break}if(new RegExp("^"+d.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$").test(r)){i=!0;break}}if(i)return this._executeAstNode(o.body,t)}return{code:0,stdout:"",stderr:""}}):{code:0,stdout:"",stderr:""}}async _executePipeline(e,s){const t=e.commands||[];let r=s.stdin||"",o="",i={code:0,stdout:"",stderr:""};const f=t.length>1,d=this.cwd;for(let l=0;l<t.length;l++){if(s.signal&&s.signal.aborted)return{code:130,stdout:i.stdout||"",stderr:o,aborted:!0};const a=t[l],c=l===t.length-1,h={...s,stdin:r,onStdout:c?s.onStdout:null,onStderr:s.onStderr};let u;if(f){const p=Object.assign({},this.env,s.env||{}),g=new x({...this.options,vfs:this.vfs,portTable:this.portTable,gitState:this.gitState,_initialBootRoot:this._initialBootRoot,_initialBootSnapshot:this._initialBootSnapshot,env:p});g.cwd=s.cwd||d,g.functions=Object.assign({},this.functions||{}),u=await g._executeAstNode(a,{...h,cwd:g.cwd,env:Object.assign({},p)}),this.vfs&&typeof this.vfs._setCwd=="function"&&this.vfs._setCwd(d)}else u=await this._executeAstNode(a,h);if(r=u.stdout||"",o+=u.stderr||"",i=u,u.aborted||s.signal&&s.signal.aborted)return{code:130,stdout:i.stdout||"",stderr:o,aborted:!0}}let y=i.code!==void 0?i.code:0;return e.negated&&!i.aborted&&(y=y===0?1:0),{code:y,stdout:i.stdout||"",stderr:o,controlFlow:i.controlFlow,aborted:!!(i.aborted||s.signal&&s.signal.aborted)}}async _executeSimpleCommand(e,s){const t=Object.assign({},this.env,s.env);for(const m of e.envVars){const S=await this.evaluateWord(m.token,t),b=S.indexOf("=");if(b!==-1){const v=S.slice(0,b),w=S.slice(b+1);t[v]=w,e.name||(this.env[v]=w,s.env[v]=w)}}if(!e.name)return Object.assign(s.env,this.env),{code:0,stdout:"",stderr:""};const r=await this.evaluateWord(e.name,t),o=[];for(const m of e.args){const S=await this.evaluateWordToArgs(m,t);o.push(...S)}if(r===":")return Object.assign(this.env,t),Object.assign(s.env,t),{code:0,stdout:"",stderr:""};if(r==="exit"){const m=o.length>0?parseInt(o[0],10):parseInt(this.env["?"]||"0",10),S=Number.isNaN(m)?2:(m%256+256)%256;return{code:S,stdout:"",stderr:"",controlFlow:{type:"exit",code:S}}}if(r==="[[")return this._evaluateDoubleBracket(o);if(r==="break")return{code:0,stdout:"",stderr:"",controlFlow:{type:"break",count:parseInt(o[0],10)||1}};if(r==="continue")return{code:0,stdout:"",stderr:"",controlFlow:{type:"continue",count:parseInt(o[0],10)||1}};if(r==="return"){const m=parseInt(o[0],10)||0;return{code:m,stdout:"",stderr:"",controlFlow:{type:"return",code:m}}}if(s.signal&&s.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};let i=s.stdin||"";for(const m of e.redirects)if(m.type==="<"||m.type==="<<"||m.type==="<<<"){const S=await this._resolveInputRedirect(m,t);if(S&&!S.ok)return S.error;S&&S.ok&&(i=S.stdin)}let f={type:"stdout"},d={type:"stderr"};for(const m of e.redirects)if(!(m.type==="<"||m.type==="<<"||m.type==="<<<"))if(m.type===">"||m.type===">>"||m.type==="&>"){const S=await this.evaluateWord(m.target,t),b=this.resolvePath(S),v=j.dirname(b);if(!this.vfs.existsSync(v))return{code:1,stdout:"",stderr:`shell: ${S}: No such file or directory
|
|
826
|
+
`;t+=c,o=0,s.onStdout&&s.onStdout(c)}else{const d=await this._executeAstNode(f.node,s);if(t+=d.stdout||"",r+=d.stderr||"",o=d.code!==void 0?d.code:0,this.env["?"]=String(o),s.env&&(s.env["?"]=String(o)),d.controlFlow){i=d.controlFlow;break}if(d.aborted||s.signal&&s.signal.aborted)return{code:130,stdout:t,stderr:r,aborted:!0}}}return{code:o,stdout:t,stderr:r,controlFlow:i}}if(e.type==="Logical"){const t=await this._executeAstNode(e.left,s);if(t.aborted||s.signal&&s.signal.aborted)return{...t,code:130,aborted:!0};if(t.controlFlow)return t;if(e.op==="&&"){if(t.code===0){const r={...s,cwd:this.cwd,env:Object.assign({},this.env)},o=await this._executeAstNode(e.right,r);return{code:o.code,stdout:(t.stdout||"")+(o.stdout||""),stderr:(t.stderr||"")+(o.stderr||""),controlFlow:o.controlFlow,aborted:o.aborted}}return t}else if(e.op==="||"){if(t.code!==0){const r={...s,cwd:this.cwd,env:Object.assign({},this.env)},o=await this._executeAstNode(e.right,r);return{code:o.code,stdout:(t.stdout||"")+(o.stdout||""),stderr:(t.stderr||"")+(o.stderr||""),controlFlow:o.controlFlow,aborted:o.aborted}}return t}}return e.type==="Pipeline"?this._executePipeline(e,s):e.type==="Command"?this._executeSimpleCommand(e,s):e.type==="FunctionDef"?(this.functions||(this.functions={}),this.functions[e.name]=e,{code:0,stdout:"",stderr:""}):e.type==="For"?this._executeWithRedirects(e.redirects,s,async t=>{let r="",o="",i=0;const f=[];if(e.items)for(const y of e.items){const l=await this.evaluateWordToArgs(y,t.env);f.push(...l)}else f.push(...t.positionalArgs||[]);let d=0;for(const y of f){if(++d%250===0&&typeof setTimeout=="function"&&await new Promise(a=>setTimeout(a,0)),t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};t.env[e.varName]=y,this.env[e.varName]=y;const l=await this._executeAstNode(e.body,t);if(r+=l.stdout||"",o+=l.stderr||"",i=l.code!==void 0?l.code:0,this.env["?"]=String(i),t.env&&(t.env["?"]=String(i)),l.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};if(l.controlFlow)if(l.controlFlow.type==="break"){const a=l.controlFlow.count||1;if(a>1)return{code:i,stdout:r,stderr:o,controlFlow:{type:"break",count:a-1}};break}else if(l.controlFlow.type==="continue"){const a=l.controlFlow.count||1;if(a>1)return{code:i,stdout:r,stderr:o,controlFlow:{type:"continue",count:a-1}};continue}else return{code:i,stdout:r,stderr:o,controlFlow:l.controlFlow}}return{code:i,stdout:r,stderr:o}}):e.type==="While"||e.type==="Until"?this._executeWithRedirects(e.redirects,s,async t=>{const r=e.type==="While";let o="",i="",f=0,d=0;for(;;){if(++d%250===0&&typeof setTimeout=="function"&&await new Promise(c=>setTimeout(c,0)),t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};const y=await this._executeAstNode(e.cond,t);if(o+=y.stdout||"",i+=y.stderr||"",y.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};if(y.controlFlow)return{code:y.code,stdout:o,stderr:i,controlFlow:y.controlFlow};const l=y.code===0;if(r?!l:l)break;if(t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};const a=await this._executeAstNode(e.body,t);if(o+=a.stdout||"",i+=a.stderr||"",f=a.code!==void 0?a.code:0,this.env["?"]=String(f),t.env&&(t.env["?"]=String(f)),a.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};if(a.controlFlow)if(a.controlFlow.type==="break"){const c=a.controlFlow.count||1;if(c>1)return{code:f,stdout:o,stderr:i,controlFlow:{type:"break",count:c-1}};break}else if(a.controlFlow.type==="continue"){const c=a.controlFlow.count||1;if(c>1)return{code:f,stdout:o,stderr:i,controlFlow:{type:"continue",count:c-1}};continue}else return{code:f,stdout:o,stderr:i,controlFlow:a.controlFlow}}return{code:f,stdout:o,stderr:i}}):e.type==="If"?this._executeWithRedirects(e.redirects,s,async t=>{let r="",o="";for(const i of e.branches||[]){if(t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};const f=await this._executeAstNode(i.cond,t);if(r+=f.stdout||"",o+=f.stderr||"",f.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};if(f.code===0){const d=await this._executeAstNode(i.body,t);return r+=d.stdout||"",o+=d.stderr||"",{code:d.code,stdout:r,stderr:o,controlFlow:d.controlFlow,aborted:d.aborted}}}if(e.elseBody){const i=await this._executeAstNode(e.elseBody,t);return r+=i.stdout||"",o+=i.stderr||"",{code:i.code,stdout:r,stderr:o,controlFlow:i.controlFlow,aborted:i.aborted}}return{code:0,stdout:r,stderr:o}}):e.type==="BraceGroup"?this._executeWithRedirects(e.redirects,s,t=>this._executeAstNode(e.body,t)):e.type==="Subshell"?this._executeWithRedirects(e.redirects,s,async t=>{const r=new x({...this.options,vfs:this.vfs,portTable:this.portTable,gitState:this.gitState,_initialBootRoot:this._initialBootRoot,_initialBootSnapshot:this._initialBootSnapshot,env:Object.assign({},this.env,t.env||{})});r.cwd=t.cwd||this.cwd;const o={...t,env:Object.assign({},this.env,t.env||{}),cwd:r.cwd};return r._executeAstNode(e.body,o)}):e.type==="Case"?this._executeWithRedirects(e.redirects,s,async t=>{const r=await this.evaluateWord(e.word,t.env);for(const o of e.clauses||[]){let i=!1;for(const f of o.patterns||[]){const d=await this.evaluateWord(f,t.env);if(d==="*"||d===r){i=!0;break}if(new RegExp("^"+d.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$").test(r)){i=!0;break}}if(i)return this._executeAstNode(o.body,t)}return{code:0,stdout:"",stderr:""}}):{code:0,stdout:"",stderr:""}}async _executePipeline(e,s){const t=e.commands||[];let r=s.stdin||"",o="",i={code:0,stdout:"",stderr:""};const f=t.length>1,d=this.cwd;for(let l=0;l<t.length;l++){if(s.signal&&s.signal.aborted)return{code:130,stdout:i.stdout||"",stderr:o,aborted:!0};const a=t[l],c=l===t.length-1,h={...s,stdin:r,onStdout:c?s.onStdout:null,onStderr:s.onStderr};let u;if(f){const p=Object.assign({},this.env,s.env||{}),g=new x({...this.options,vfs:this.vfs,portTable:this.portTable,gitState:this.gitState,_initialBootRoot:this._initialBootRoot,_initialBootSnapshot:this._initialBootSnapshot,env:p});g.cwd=s.cwd||d,g.functions=Object.assign({},this.functions||{}),u=await g._executeAstNode(a,{...h,cwd:g.cwd,env:Object.assign({},p)}),this.vfs&&typeof this.vfs._setCwd=="function"&&this.vfs._setCwd(d)}else u=await this._executeAstNode(a,h);if(r=u.stdout||"",o+=u.stderr||"",i=u,u.aborted||s.signal&&s.signal.aborted)return{code:130,stdout:i.stdout||"",stderr:o,aborted:!0}}let y=i.code!==void 0?i.code:0;return e.negated&&!i.aborted&&(y=y===0?1:0),{code:y,stdout:i.stdout||"",stderr:o,controlFlow:i.controlFlow,aborted:!!(i.aborted||s.signal&&s.signal.aborted)}}async _executeSimpleCommand(e,s){const t=Object.assign({},this.env,s.env);for(const m of e.envVars){const S=await this.evaluateWord(m.token,t),b=S.indexOf("=");if(b!==-1){const v=S.slice(0,b),w=S.slice(b+1);t[v]=w,e.name||(this.env[v]=w,s.env[v]=w)}}if(!e.name)return Object.assign(s.env,this.env),{code:0,stdout:"",stderr:""};const r=await this.evaluateWord(e.name,t),o=[];for(const m of e.args){const S=await this.evaluateWordToArgs(m,t);o.push(...S)}if(r===":")return Object.assign(this.env,t),Object.assign(s.env,t),{code:0,stdout:"",stderr:""};if(r==="exit"){const m=o.length>0?parseInt(o[0],10):parseInt(this.env["?"]||"0",10),S=Number.isNaN(m)?2:(m%256+256)%256;return{code:S,stdout:"",stderr:"",controlFlow:{type:"exit",code:S}}}if(r==="[[")return this._evaluateDoubleBracket(o);if(r==="break")return{code:0,stdout:"",stderr:"",controlFlow:{type:"break",count:parseInt(o[0],10)||1}};if(r==="continue")return{code:0,stdout:"",stderr:"",controlFlow:{type:"continue",count:parseInt(o[0],10)||1}};if(r==="return"){const m=parseInt(o[0],10)||0;return{code:m,stdout:"",stderr:"",controlFlow:{type:"return",code:m}}}if(s.signal&&s.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};let i=s.stdin||"";for(const m of e.redirects)if(m.type==="<"||m.type==="<<"||m.type==="<<<"){const S=await this._resolveInputRedirect(m,t);if(S&&!S.ok)return S.error;S&&S.ok&&(i=S.stdin)}let f={type:"stdout"},d={type:"stderr"};for(const m of e.redirects)if(!(m.type==="<"||m.type==="<<"||m.type==="<<<"))if(m.type===">"||m.type===">>"||m.type==="&>"){const S=await this.evaluateWord(m.target,t),b=this.resolvePath(S),v=j.dirname(b);if(!this.vfs.existsSync(v))return{code:1,stdout:"",stderr:`shell: ${S}: No such file or directory
|
|
827
827
|
`};if(!this.vfs.statSync(v).isDirectory())return{code:1,stdout:"",stderr:`shell: ${S}: Not a directory
|
|
828
828
|
`};if(this.vfs.existsSync(b)&&this.vfs.statSync(b).isDirectory())return{code:1,stdout:"",stderr:`shell: ${S}: Is a directory
|
|
829
|
-
`};if(m.type===">"){this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b);const $={type:"file",path:b,append:!0};m.sourceFd===2?d=$:f=$}else if(m.type===">>"){this.vfs.existsSync(b)||(this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b));const $={type:"file",path:b,append:!0};m.sourceFd===2?d=$:f=$}else if(m.type==="&>"){this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b);const $={type:"file",path:b,append:!0};f=$,d=$}}else m.type===">&"&&(m.sourceFd===2&&m.targetFd===1?d={...f}:m.sourceFd===1&&m.targetFd===2&&(f={...d}));let y="",l="",a=0,c=0;const h=(m,S,b=!1)=>{S&&(m.type==="stdout"?(y+=S,b&&s.onStdout&&s.onStdout(S)):m.type==="stderr"?(l+=S,b&&s.onStderr&&s.onStderr(S)):m.type==="file"&&(this.vfs.appendFileSync(m.path,S),this._emitVfsMutation("change",m.path)))},u={vfs:this.vfs,shell:this,portTable:this.portTable,cwd:this.cwd,env:t,stdin:i,pid:s.pid||1e3,isBackground:!!s.isBackground,resolvePath:m=>this.resolvePath(m),emitMutation:(m,S)=>this._emitVfsMutation(m,S),signal:s.signal,onRequestStdin:(typeof s.onRequestStdin=="function"?s.onRequestStdin:null)||(this.options&&typeof this.options.onRequestStdin=="function"?this.options.onRequestStdin:void 0),onStdout:m=>{m&&(a+=m.length,h(f,m,!0))},onStderr:m=>{m&&(c+=m.length,h(d,m,!0))}};let p;const g=!(this.functions&&this.functions[r])&&!this.commands[r]?this._resolvePathBinary(r):null;if(this.functions&&this.functions[r]){const m=this.functions[r],S=Object.assign({},t);o.forEach((v,w)=>{S[String(w+1)]=v}),S["#"]=String(o.length),S["@"]=o.join(" "),S["*"]=o.join(" ");const b=await this._executeAstNode(m.body,{...s,env:S,positionalArgs:o});p={code:b.controlFlow?.type==="return"?b.controlFlow.code:b.code||0,stdout:b.stdout||"",stderr:b.stderr||""}}else if(this.commands[r]){if(p=await this.commands[r](o,u),r==="export"||r==="unset"||r==="cd"||r==="read"){for(const m of Object.keys(s.env))m in this.env||delete s.env[m];Object.assign(s.env,this.env),s.cwd=this.cwd}}else if(g){const S=String(this.vfs.readFileSync(g,"utf8")||"").match(/exec\s+node\s+"([^"]+)"/);S&&S[1]?p=await this.commands.node([S[1],...o],u):p=await this.commands.node([g,...o],u)}else if((r.startsWith("./")||r.startsWith("../")||r.startsWith("/"))&&this.vfs.existsSync(this.resolvePath(r))){const m=this.resolvePath(r),S=this.vfs.statSync(m);if(S&&S.isDirectory())p={code:126,stdout:"",stderr:`shell: ${r}: Is a directory
|
|
830
|
-
`};else if(Re()){let b=null;try{b=typeof this.vfs._getRawFileBytes=="function"?this.vfs._getRawFileBytes(m)||this.vfs.readFileSync(m):this.vfs.readFileSync(m)}catch(R){
|
|
829
|
+
`};if(m.type===">"){this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b);const $={type:"file",path:b,append:!0};m.sourceFd===2?d=$:f=$}else if(m.type===">>"){this.vfs.existsSync(b)||(this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b));const $={type:"file",path:b,append:!0};m.sourceFd===2?d=$:f=$}else if(m.type==="&>"){this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b);const $={type:"file",path:b,append:!0};f=$,d=$}}else m.type===">&"&&(m.sourceFd===2&&m.targetFd===1?d={...f}:m.sourceFd===1&&m.targetFd===2&&(f={...d}));let y="",l="",a=0,c=0;const h=(m,S,b=!1)=>{S&&(m.type==="stdout"?(y+=S,b&&s.onStdout&&s.onStdout(S)):m.type==="stderr"?(l+=S,b&&s.onStderr&&s.onStderr(S)):m.type==="file"&&(this.vfs.appendFileSync(m.path,S),this._emitVfsMutation("change",m.path)))},u={vfs:this.vfs,shell:this,portTable:this.portTable,cwd:this.cwd,env:t,stdin:i,pid:s.pid||1e3,isBackground:!!s.isBackground,resolvePath:m=>this.resolvePath(m),emitMutation:(m,S)=>this._emitVfsMutation(m,S),signal:s.signal,onRequestStdin:(typeof s.onRequestStdin=="function"?s.onRequestStdin:null)||(this.options&&typeof this.options.onRequestStdin=="function"?this.options.onRequestStdin:void 0),onStdout:m=>{m&&(a+=m.length,h(f,m,!0))},onStderr:m=>{m&&(c+=m.length,h(d,m,!0))}};let p;const g=!(this.functions&&this.functions[r])&&!this.commands[r]?this._resolvePathBinary(r):null;if(this.functions&&this.functions[r]){const m=this.functions[r],S=Object.assign({},t);o.forEach((v,w)=>{S[String(w+1)]=v}),S["#"]=String(o.length),S["@"]=o.join(" "),S["*"]=o.join(" ");const b=await this._executeAstNode(m.body,{...s,env:S,positionalArgs:o});p={code:b.controlFlow?.type==="return"?b.controlFlow.code:b.code||0,stdout:b.stdout||"",stderr:b.stderr||""}}else if(this.commands[r]){if(p=await this.commands[r](o,u),r==="export"||r==="unset"||r==="cd"||r==="read"){for(const m of Object.keys(s.env))/^(\d+|#|@|\*)$/.test(m)||m in this.env||delete s.env[m];Object.assign(s.env,this.env),s.cwd=this.cwd}}else if(g){const S=String(this.vfs.readFileSync(g,"utf8")||"").match(/exec\s+node\s+"([^"]+)"/);S&&S[1]?p=await this.commands.node([S[1],...o],u):p=await this.commands.node([g,...o],u)}else if((r.startsWith("./")||r.startsWith("../")||r.startsWith("/"))&&this.vfs.existsSync(this.resolvePath(r))){const m=this.resolvePath(r),S=this.vfs.statSync(m);if(S&&S.isDirectory())p={code:126,stdout:"",stderr:`shell: ${r}: Is a directory
|
|
830
|
+
`};else if(Re()){let b=null;try{b=typeof this.vfs._getRawFileBytes=="function"?this.vfs._getRawFileBytes(m)||this.vfs.readFileSync(m):this.vfs.readFileSync(m)}catch(R){N.debug("Failed to read binary",R)}const v=b instanceof Uint8Array&&b.length>=4&&b[0]===0&&b[1]===97&&b[2]===115&&b[3]===109||typeof b=="string"&&b.startsWith("\0asm"),$=await(v?Oe:R=>q(R,u))({mode:"run",entry:m,wasmBinary:v&&b instanceof Uint8Array?b:void 0,argv:[r,...o],stdin:i,env:t,cwd:this.cwd,vfs:this.vfs,activePortTable:this.portTable,pid:u.pid,isBackground:u.isBackground,onRequestStdin:u.onRequestStdin,onStdout:u.onStdout,onStderr:u.onStderr,signal:s.signal});p={code:$.ok?0:$.exitCode||1,stdout:$.stdout||"",stderr:$.stderr||""}}else p={code:126,stdout:"",stderr:`shell: ${r}: cannot execute binary file
|
|
831
831
|
`}}else if(kt.test(r))p=await Ve(r,[r,...o].join(" "),u,{force:!0})||{code:127,stdout:"",stderr:`shell: ${r}: command not found
|
|
832
832
|
`};else if(typeof this.options.onProcessSpawn=="function"){const m=await this.options.onProcessSpawn(r,o,{cwd:this.cwd,env:t,stdin:i,onStdout:u.onStdout,onStderr:u.onStderr,signal:s.signal});m!=null?p=m:p={code:127,stdout:"",stderr:`shell: ${r}: command not found
|
|
833
833
|
`}}else p={code:127,stdout:"",stderr:`shell: ${r}: command not found
|