just-bash 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -12
- package/dist/Bash.d.ts +20 -2
- package/dist/ai/index.d.ts +1 -1
- package/dist/bin/just-bash.js +68 -68
- package/dist/bin/shell/shell.js +68 -68
- package/dist/bundle/ai/index.js +209 -209
- package/dist/bundle/index.js +88 -88
- package/dist/custom-commands.d.ts +42 -0
- package/dist/index.d.ts +6 -3
- package/dist/interpreter/interpreter.d.ts +2 -2
- package/dist/interpreter/types.d.ts +1 -1
- package/dist/sandbox/Sandbox.d.ts +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
package/dist/bundle/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"e":case"E":e+="\x1B",r+=2;break;case"c":return{output:e,stop:!0};case"0":{let s="",o=r+2;for(;o<t.length&&o<r+5&&/[0-7]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\0";else{let i=parseInt(s,8)%256;e+=String.fromCharCode(i)}r=o;break}case"x":{let s="",o=r+2;for(;o<t.length&&o<r+4&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\x",r+=2;else{let i=parseInt(s,16);e+=String.fromCharCode(i),r=o}break}case"u":{let s="",o=r+2;for(;o<t.length&&o<r+6&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\u",r+=2;else{let i=parseInt(s,16);e+=String.fromCodePoint(i),r=o}break}case"U":{let s="",o=r+2;for(;o<t.length&&o<r+10&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\U",r+=2;else{let i=parseInt(s,16);try{e+=String.fromCodePoint(i)}catch{e+=`\\U${s}`}r=o}break}default:e+=`\\${n}`,r+=2}}else e+=t[r],r++;return{output:e,stop:!1}}var
|
|
1
|
+
var Ga=Object.defineProperty;var C=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>{for(var r in e)Ga(t,r,{get:e[r],enumerable:!0})};var Nn={};I(Nn,{echoCommand:()=>Za});function Va(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"){if(r+1>=t.length){e+="\\";break}let n=t[r+1];switch(n){case"\\":e+="\\",r+=2;break;case"n":e+=`
|
|
2
|
+
`,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"e":case"E":e+="\x1B",r+=2;break;case"c":return{output:e,stop:!0};case"0":{let s="",o=r+2;for(;o<t.length&&o<r+5&&/[0-7]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\0";else{let i=parseInt(s,8)%256;e+=String.fromCharCode(i)}r=o;break}case"x":{let s="",o=r+2;for(;o<t.length&&o<r+4&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\x",r+=2;else{let i=parseInt(s,16);e+=String.fromCharCode(i),r=o}break}case"u":{let s="",o=r+2;for(;o<t.length&&o<r+6&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\u",r+=2;else{let i=parseInt(s,16);e+=String.fromCodePoint(i),r=o}break}case"U":{let s="",o=r+2;for(;o<t.length&&o<r+10&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\U",r+=2;else{let i=parseInt(s,16);try{e+=String.fromCodePoint(i)}catch{e+=`\\U${s}`}r=o}break}default:e+=`\\${n}`,r+=2}}else e+=t[r],r++;return{output:e,stop:!1}}var Za,vn=C(()=>{"use strict";Za={name:"echo",async execute(t,e){let r=!1,n=!1,s=0;for(;s<t.length;){let i=t[s];if(i==="-n")r=!0,s++;else if(i==="-e")n=!0,s++;else if(i==="-E")n=!1,s++;else if(i==="-ne"||i==="-en")r=!0,n=!0,s++;else break}let o=t.slice(s).join(" ");if(n){let i=Va(o);if(o=i.output,i.stop)return{stdout:o,stderr:"",exitCode:0}}return r||(o+=`
|
|
3
3
|
`),{stdout:o,stderr:"",exitCode:0}}}});function x(t){let e=`${t.name} - ${t.summary}
|
|
4
4
|
|
|
5
5
|
`;if(e+=`Usage: ${t.usage}
|
|
@@ -24,70 +24,70 @@ Notes:
|
|
|
24
24
|
`,exitCode:1}}var R=C(()=>{"use strict"});function M(t,e,r){let n=new Map,s=new Map;for(let[c,l]of Object.entries(r)){let u={name:c,type:l.type};l.short&&n.set(l.short,u),l.long&&s.set(l.long,u)}let o={};for(let[c,l]of Object.entries(r))l.default!==void 0?o[c]=l.default:l.type==="boolean"&&(o[c]=!1);let i=[],a=!1;for(let c=0;c<e.length;c++){let l=e[c];if(a||!l.startsWith("-")||l==="-"){i.push(l);continue}if(l==="--"){a=!0;continue}if(l.startsWith("--")){let u=l.indexOf("="),f,d;u!==-1?(f=l.slice(2,u),d=l.slice(u+1)):f=l.slice(2);let h=s.get(f);if(!h)return{ok:!1,error:O(t,l)};let{name:p,type:b}=h;if(b==="boolean")o[p]=!0;else{if(d===void 0){if(c+1>=e.length)return{ok:!1,error:{stdout:"",stderr:`${t}: option '--${f}' requires an argument
|
|
25
25
|
`,exitCode:1}};d=e[++c]}o[p]=b==="number"?parseInt(d,10):d}}else{let u=l.slice(1);for(let f=0;f<u.length;f++){let d=u[f],h=n.get(d);if(!h)return{ok:!1,error:O(t,`-${d}`)};let{name:p,type:b}=h;if(b==="boolean")o[p]=!0;else{let g;if(f+1<u.length)g=u.slice(f+1);else if(c+1<e.length)g=e[++c];else return{ok:!1,error:{stdout:"",stderr:`${t}: option requires an argument -- '${d}'
|
|
26
26
|
`,exitCode:1}};o[p]=b==="number"?parseInt(g,10):g;break}}}}return{ok:!0,result:{flags:o,positional:i}}}var Y=C(()=>{"use strict";R()});async function tt(t,e,r){let{cmdName:n,allowStdinMarker:s=!0,stopOnError:o=!1}=r;if(e.length===0)return{files:[{filename:"",content:t.stdin}],stderr:"",exitCode:0};let i=[],a="",c=0;for(let l of e){if(s&&l==="-"){i.push({filename:"-",content:t.stdin});continue}try{let u=t.fs.resolvePath(t.cwd,l),f=await t.fs.readFile(u);i.push({filename:l,content:f})}catch{if(a+=`${n}: ${l}: No such file or directory
|
|
27
|
-
`,c=1,o)return{files:i,stderr:a,exitCode:c}}}return{files:i,stderr:a,exitCode:c}}async function Ie(t,e,r){let n=await tt(t,e,{...r,stopOnError:!0});return n.exitCode!==0?{ok:!1,error:{stdout:"",stderr:n.stderr,exitCode:n.exitCode}}:{ok:!0,content:n.files.map(o=>o.content).join("")}}var
|
|
27
|
+
`,c=1,o)return{files:i,stderr:a,exitCode:c}}}return{files:i,stderr:a,exitCode:c}}async function Ie(t,e,r){let n=await tt(t,e,{...r,stopOnError:!0});return n.exitCode!==0?{ok:!1,error:{stdout:"",stderr:n.stderr,exitCode:n.exitCode}}:{ok:!0,content:n.files.map(o=>o.content).join("")}}var Le=C(()=>{"use strict"});var kn={};I(kn,{catCommand:()=>Xa});function Ya(t,e){let r=t.split(`
|
|
28
28
|
`),n=t.endsWith(`
|
|
29
29
|
`),s=n?r.slice(0,-1):r;return{content:s.map((i,a)=>`${String(e+a).padStart(6," ")} ${i}`).join(`
|
|
30
30
|
`)+(n?`
|
|
31
|
-
`:""),nextLineNumber:e+s.length}}var
|
|
32
|
-
`,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",o=r+1;for(;o<t.length&&o<r+4&&/[0-7]/.test(t[o]);)s+=t[o],o++;e+=String.fromCharCode(parseInt(s,8)),r=o;break}case"x":r+3<t.length&&/[0-9a-fA-F]{2}/.test(t.slice(r+2,r+4))?(e+=String.fromCharCode(parseInt(t.slice(r+2,r+4),16)),r+=4):(e+=t[r],r++);break;default:e+=t[r],r++}else e+=t[r],r++;return e}function
|
|
33
|
-
`),{value:
|
|
34
|
-
`),{value:
|
|
35
|
-
`);let i=o<0?o>>>0:o;return{value:
|
|
36
|
-
`),{value:
|
|
37
|
-
`}}}}function
|
|
38
|
-
`?n+="\\n":s===" "?n+="\\t":s==="\r"?n+="\\r":s==="\x07"?n+="\\a":s==="\b"?n+="\\b":s==="\f"?n+="\\f":s==="\v"?n+="\\v":s==="\x1B"?n+="\\E":o<32||o>126?n+=`\\x${o.toString(16).padStart(2,"0")}`:s==='"'?n+='\\"':n+=s}return n+="'",n}let r="";for(let n of t)" |&;<>()$`\\\"'*?[#~=%!{}".includes(n)?r+=`\\${n}`:r+=n;return r}function
|
|
39
|
-
`,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"c":return{value:e,stopped:!0};case"x":{let s="",o=r+2;for(;o<t.length&&o<r+4&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;s?(e+=String.fromCharCode(parseInt(s,16)),r=o):(e+="\\x",r+=2);break}case"u":{let s="",o=r+2;for(;o<t.length&&o<r+6&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;s?(e+=String.fromCodePoint(parseInt(s,16)),r=o):(e+="\\u",r+=2);break}case"0":{let s="",o=r+2;for(;o<t.length&&o<r+5&&/[0-7]/.test(t[o]);)s+=t[o],o++;s?e+=String.fromCharCode(parseInt(s,8)):e+="\0",r=o;break}case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",o=r+1;for(;o<t.length&&o<r+4&&/[0-7]/.test(t[o]);)s+=t[o],o++;e+=String.fromCharCode(parseInt(s,8)),r=o;break}default:e+=t[r],r++}else e+=t[r],r++;return{value:e,stopped:!1}}var
|
|
31
|
+
`:""),nextLineNumber:e+s.length}}var Qa,Ka,Xa,In=C(()=>{"use strict";Y();Le();R();Qa={name:"cat",summary:"concatenate files and print on the standard output",usage:"cat [OPTION]... [FILE]...",options:["-n, --number number all output lines"," --help display this help and exit"]},Ka={number:{short:"n",long:"number",type:"boolean"}},Xa={name:"cat",async execute(t,e){if(S(t))return x(Qa);let r=M("cat",t,Ka);if(!r.ok)return r.error;let n=r.result.flags.number,s=r.result.positional,o=await tt(e,s,{cmdName:"cat",allowStdinMarker:!0,stopOnError:!1}),i="",a=1;for(let{content:c}of o.files)if(n){let l=Ya(c,a);i+=l.content,a=l.nextLineNumber}else i+=c;return{stdout:i,stderr:o.stderr,exitCode:o.exitCode}}}});function q(t){return t instanceof Error?t.message:String(t)}var ye=C(()=>{"use strict"});var Rn={};I(Rn,{printfCommand:()=>el});import{sprintf as qe}from"sprintf-js";function tl(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"&&r+1<t.length)switch(t[r+1]){case"n":e+=`
|
|
32
|
+
`,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",o=r+1;for(;o<t.length&&o<r+4&&/[0-7]/.test(t[o]);)s+=t[o],o++;e+=String.fromCharCode(parseInt(s,8)),r=o;break}case"x":r+3<t.length&&/[0-9a-fA-F]{2}/.test(t.slice(r+2,r+4))?(e+=String.fromCharCode(parseInt(t.slice(r+2,r+4),16)),r+=4):(e+=t[r],r++);break;default:e+=t[r],r++}else e+=t[r],r++;return e}function rl(t,e,r){let n="",s=0,o=0,i=!1,a="";for(;s<t.length;)if(t[s]==="%"&&s+1<t.length){let c=s;if(s++,t[s]==="%"){n+="%",s++;continue}for(;s<t.length&&"+-0 #'".includes(t[s]);)s++;let l=!1;if(t[s]==="*")l=!0,s++;else for(;s<t.length&&/\d/.test(t[s]);)s++;let u=!1;if(t[s]===".")if(s++,t[s]==="*")u=!0,s++;else for(;s<t.length&&/\d/.test(t[s]);)s++;s<t.length&&"hlL".includes(t[s])&&s++;let f=t[s]||"";s++;let h=t.slice(c,s);if(l){let E=parseInt(e[r+o]||"0",10);o++,h=h.replace("*",String(E))}if(u){let E=parseInt(e[r+o]||"0",10);o++,h=h.replace(".*",`.${E}`)}let p=e[r+o]||"";o++;let{value:b,parseError:g,parseErrMsg:y,stopped:w}=nl(h,f,p);if(n+=b,g&&(i=!0,y&&(a=y)),w)return{result:n,argsConsumed:o,error:i,errMsg:a,stopped:!0}}else n+=t[s],s++;return{result:n,argsConsumed:o,error:i,errMsg:a,stopped:!1}}function nl(t,e,r){let n=!1,s="";switch(e){case"d":case"i":{let o=gt(r);return n=we,n&&(s=`printf: ${r}: invalid number
|
|
33
|
+
`),{value:Pn(t,o),parseError:n,parseErrMsg:s}}case"o":{let o=gt(r);return n=we,n&&(s=`printf: ${r}: invalid number
|
|
34
|
+
`),{value:sl(t,o),parseError:n,parseErrMsg:s}}case"u":{let o=gt(r);n=we,n&&(s=`printf: ${r}: invalid number
|
|
35
|
+
`);let i=o<0?o>>>0:o;return{value:Pn(t.replace("u","d"),i),parseError:n,parseErrMsg:s}}case"x":case"X":{let o=gt(r);return n=we,n&&(s=`printf: ${r}: invalid number
|
|
36
|
+
`),{value:il(t,o),parseError:n,parseErrMsg:s}}case"e":case"E":case"f":case"F":case"g":case"G":{let o=parseFloat(r)||0;return{value:cl(t,e,o),parseError:!1,parseErrMsg:""}}case"c":return{value:r.charAt(0)||"",parseError:!1,parseErrMsg:""};case"s":return{value:al(t,r),parseError:!1,parseErrMsg:""};case"q":return{value:ll(t,r),parseError:!1,parseErrMsg:""};case"b":{let o=ul(r);return{value:o.value,parseError:!1,parseErrMsg:"",stopped:o.stopped}}default:try{return{value:qe(t,r),parseError:!1,parseErrMsg:""}}catch{return{value:"",parseError:!0,parseErrMsg:`printf: [sprintf] unexpected placeholder
|
|
37
|
+
`}}}}function gt(t){we=!1;let e=t.trimStart(),r=e!==e.trimEnd();if(t=e.trimEnd(),t.startsWith("'")&&t.length>=2||t.startsWith('"')&&t.length>=2)return t.charCodeAt(1);if(t.startsWith("\\'")&&t.length>=3||t.startsWith('\\"')&&t.length>=3)return t.charCodeAt(2);if(t.startsWith("+")&&(t=t.slice(1)),t.startsWith("0x")||t.startsWith("0X")){let n=parseInt(t,16);return Number.isNaN(n)?(we=!0,0):(r&&(we=!0),n)}if(t.startsWith("0")&&t.length>1&&/^-?0[0-7]+$/.test(t))return r&&(we=!0),parseInt(t,8)||0;if(/^\d+#/.test(t)){we=!0;let n=t.match(/^(\d+)#/);return n?parseInt(n[1],10):0}if(t!==""&&!/^-?\d+$/.test(t)){we=!0;let n=parseInt(t,10);return Number.isNaN(n)?0:n}return r&&(we=!0),parseInt(t,10)||0}function Pn(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[diu]$/);if(!r)return qe(t.replace(/\.\d*/,""),e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,o=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,i=e<0,a=Math.abs(e),c=String(a);o>=0&&(c=c.padStart(o,"0"));let l="";i?l="-":n.includes("+")?l="+":n.includes(" ")&&(l=" ");let u=l+c;return s>u.length&&(n.includes("-")?u=u.padEnd(s," "):n.includes("0")&&o<0?u=l+c.padStart(s-l.length,"0"):u=u.padStart(s," ")),u}function sl(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?o$/);if(!r)return qe(t,e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,o=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,i=Math.abs(e).toString(8);o>=0&&(i=i.padStart(o,"0")),n.includes("#")&&!i.startsWith("0")&&(i=`0${i}`);let a=i;return s>a.length&&(n.includes("-")?a=a.padEnd(s," "):n.includes("0")&&o<0?a=a.padStart(s,"0"):a=a.padStart(s," ")),a}function il(t,e){let r=t.includes("X"),n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[xX]$/);if(!n)return qe(t,e);let s=n[1]||"",o=n[2]?parseInt(n[2],10):0,i=n[3]!==void 0?n[4]?parseInt(n[4],10):0:-1,a=Math.abs(e).toString(16);r&&(a=a.toUpperCase()),i>=0&&(a=a.padStart(i,"0"));let c="";s.includes("#")&&e!==0&&(c=r?"0X":"0x");let l=c+a;return o>l.length&&(s.includes("-")?l=l.padEnd(o," "):s.includes("0")&&i<0?l=c+a.padStart(o-c.length,"0"):l=l.padStart(o," ")),l}function ol(t){if(t==="")return"''";if(/^[a-zA-Z0-9_./-]+$/.test(t))return t;if(/[\x00-\x1f\x7f]/.test(t)){let n="$'";for(let s of t){let o=s.charCodeAt(0);s==="'"?n+="\\'":s==="\\"?n+="\\\\":s===`
|
|
38
|
+
`?n+="\\n":s===" "?n+="\\t":s==="\r"?n+="\\r":s==="\x07"?n+="\\a":s==="\b"?n+="\\b":s==="\f"?n+="\\f":s==="\v"?n+="\\v":s==="\x1B"?n+="\\E":o<32||o>126?n+=`\\x${o.toString(16).padStart(2,"0")}`:s==='"'?n+='\\"':n+=s}return n+="'",n}let r="";for(let n of t)" |&;<>()$`\\\"'*?[#~=%!{}".includes(n)?r+=`\\${n}`:r+=n;return r}function al(t,e){let r=t.match(/^%(-?)(\d*)(\.(\d*))?s$/);if(!r)return qe(t.replace(/0+(?=\d)/,""),e);let n=r[1]==="-",s=r[2]?parseInt(r[2],10):0,o=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,i=e;return o>=0&&i.length>o&&(i=i.slice(0,o)),s>i.length&&(n?i=i.padEnd(s," "):i=i.padStart(s," ")),i}function ll(t,e){let r=ol(e),n=t.match(/^%(-?)(\d*)q$/);if(!n)return r;let s=n[1]==="-",o=n[2]?parseInt(n[2],10):0,i=r;return o>i.length&&(s?i=i.padEnd(o," "):i=i.padStart(o," ")),i}function cl(t,e,r){let n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[eEfFgG]$/);if(!n)return qe(t,r);let s=n[1]||"",o=n[2]?parseInt(n[2],10):0,i=n[3]!==void 0?n[4]?parseInt(n[4],10):0:6,a,c=e.toLowerCase();if(c==="e"?(a=r.toExponential(i),a=a.replace(/e([+-])(\d)$/,"e$10$2"),e==="E"&&(a=a.toUpperCase())):c==="f"?(a=r.toFixed(i),s.includes("#")&&i===0&&!a.includes(".")&&(a+=".")):c==="g"?(a=r.toPrecision(i||1),s.includes("#")||(a=a.replace(/\.?0+$/,""),a=a.replace(/\.?0+e/,"e")),a=a.replace(/e([+-])(\d)$/,"e$10$2"),e==="G"&&(a=a.toUpperCase())):a=r.toString(),r>=0&&(s.includes("+")?a=`+${a}`:s.includes(" ")&&(a=` ${a}`)),o>a.length)if(s.includes("-"))a=a.padEnd(o," ");else if(s.includes("0")){let l=a.match(/^[+ -]/)?.[0]||"",u=l?a.slice(1):a;a=l+u.padStart(o-l.length,"0")}else a=a.padStart(o," ");return a}function ul(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"&&r+1<t.length)switch(t[r+1]){case"n":e+=`
|
|
39
|
+
`,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"c":return{value:e,stopped:!0};case"x":{let s="",o=r+2;for(;o<t.length&&o<r+4&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;s?(e+=String.fromCharCode(parseInt(s,16)),r=o):(e+="\\x",r+=2);break}case"u":{let s="",o=r+2;for(;o<t.length&&o<r+6&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;s?(e+=String.fromCodePoint(parseInt(s,16)),r=o):(e+="\\u",r+=2);break}case"0":{let s="",o=r+2;for(;o<t.length&&o<r+5&&/[0-7]/.test(t[o]);)s+=t[o],o++;s?e+=String.fromCharCode(parseInt(s,8)):e+="\0",r=o;break}case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",o=r+1;for(;o<t.length&&o<r+4&&/[0-7]/.test(t[o]);)s+=t[o],o++;e+=String.fromCharCode(parseInt(s,8)),r=o;break}default:e+=t[r],r++}else e+=t[r],r++;return{value:e,stopped:!1}}var Ja,el,we,On=C(()=>{"use strict";ye();R();Ja={name:"printf",summary:"format and print data",usage:"printf [-v var] FORMAT [ARGUMENT...]",options:[" -v var assign the output to shell variable VAR rather than display it"," --help display this help and exit"],notes:["FORMAT controls the output like in C printf.","Escape sequences: \\n (newline), \\t (tab), \\\\ (backslash)","Format specifiers: %s (string), %d (integer), %f (float), %x (hex), %o (octal), %% (literal %)","Width and precision: %10s (width 10), %.2f (2 decimal places), %010d (zero-padded)","Flags: %- (left-justify), %+ (show sign), %0 (zero-pad)"]},el={name:"printf",async execute(t,e){if(S(t))return x(Ja);if(t.length===0)return{stdout:"",stderr:`printf: usage: printf format [arguments]
|
|
40
40
|
`,exitCode:2};let r=null,n=0;for(;n<t.length;){let i=t[n];if(i==="--"){n++;break}if(i==="-v"){if(n+1>=t.length)return{stdout:"",stderr:`printf: -v: option requires an argument
|
|
41
41
|
`,exitCode:1};if(r=t[n+1],!/^[a-zA-Z_][a-zA-Z0-9_]*(\[[^\]]+\])?$/.test(r))return{stdout:"",stderr:`printf: \`${r}': not a valid identifier
|
|
42
42
|
`,exitCode:2};n+=2}else{if(i.startsWith("-")&&i!=="-")break;break}}if(n>=t.length)return{stdout:"",stderr:`printf: usage: printf format [arguments]
|
|
43
|
-
`,exitCode:1};let s=t[n],o=t.slice(n+1);try{let i=
|
|
44
|
-
`,exitCode:1}}}};we=!1});var
|
|
45
|
-
`,exitCode:2};if(a){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let b=await e.fs.stat(p);d.push({path:h,size:b.size??0})}catch{d.push({path:h,size:0})}}d.sort((h,p)=>p.size-h.size),f.length=0,f.push(...d.map(h=>h.path))}else f.sort();if(o&&f.reverse(),s){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let b=await e.fs.stat(p),g=b.isDirectory?"drwxr-xr-x":"-rw-r--r--",y=b.isDirectory?"/":"",w=b.size??0,E=i?
|
|
43
|
+
`,exitCode:1};let s=t[n],o=t.slice(n+1);try{let i=tl(s),a="",c=0,l=!1,u="";do{let{result:f,argsConsumed:d,error:h,errMsg:p,stopped:b}=rl(i,o,c);if(a+=f,c+=d,h&&(l=!0,p&&(u=p)),b)break}while(c<o.length&&c>0);return c===0&&o.length>0,r?(e.env[r]=a,{stdout:"",stderr:u,exitCode:l?1:0}):{stdout:a,stderr:u,exitCode:l?1:0}}catch(i){return{stdout:"",stderr:`printf: ${q(i)}
|
|
44
|
+
`,exitCode:1}}}};we=!1});var Mn={};I(Mn,{lsCommand:()=>hl});import{minimatch as Dn}from"minimatch";function yt(t){if(t<1024)return String(t);if(t<1024*1024){let r=t/1024;return r<10?`${r.toFixed(1)}K`:`${Math.round(r)}K`}if(t<1024*1024*1024){let r=t/1048576;return r<10?`${r.toFixed(1)}M`:`${Math.round(r)}M`}let e=t/(1024*1024*1024);return e<10?`${e.toFixed(1)}G`:`${Math.round(e)}G`}function wt(t){let r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],n=String(t.getDate()).padStart(2," "),s=new Date,o=new Date(s.getTime()-4320*60*60*1e3);if(t>o){let a=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0");return`${r} ${n} ${a}:${c}`}let i=t.getFullYear();return`${r} ${n} ${i}`}async function pl(t,e,r,n,s,o=!1,i=!1,a=!1){let c=r||n,l=e.fs.getAllPaths(),u=e.fs.resolvePath(e.cwd,"."),f=[];for(let d of l){let h=d.startsWith(u)&&d.slice(u.length+1)||d;if(Dn(h,t)||Dn(d,t)){let p=h.split("/").pop()||h;if(!c&&p.startsWith("."))continue;f.push(h||d)}}if(f.length===0)return{stdout:"",stderr:`ls: ${t}: No such file or directory
|
|
45
|
+
`,exitCode:2};if(a){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let b=await e.fs.stat(p);d.push({path:h,size:b.size??0})}catch{d.push({path:h,size:0})}}d.sort((h,p)=>p.size-h.size),f.length=0,f.push(...d.map(h=>h.path))}else f.sort();if(o&&f.reverse(),s){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let b=await e.fs.stat(p),g=b.isDirectory?"drwxr-xr-x":"-rw-r--r--",y=b.isDirectory?"/":"",w=b.size??0,E=i?yt(w).padStart(5):String(w).padStart(5),$=b.mtime??new Date(0),A=wt($);d.push(`${g} 1 user user ${E} ${A} ${h}${y}`)}catch{d.push(`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${h}`)}}return{stdout:`${d.join(`
|
|
46
46
|
`)}
|
|
47
47
|
`,stderr:"",exitCode:0}}return{stdout:`${f.join(`
|
|
48
48
|
`)}
|
|
49
|
-
`,stderr:"",exitCode:0}}async function
|
|
49
|
+
`,stderr:"",exitCode:0}}async function Tn(t,e,r,n,s,o,i,a=!1,c=!1,l=!1,u=!1){let f=r||n,d=e.fs.resolvePath(e.cwd,t);try{let h=await e.fs.stat(d);if(!h.isDirectory){if(s){let g=h.size??0,y=c?yt(g).padStart(5):String(g).padStart(5),w=h.mtime??new Date(0),E=wt(w);return{stdout:`-rw-r--r-- 1 user user ${y} ${E} ${t}
|
|
50
50
|
`,stderr:"",exitCode:0}}return{stdout:`${t}
|
|
51
51
|
`,stderr:"",exitCode:0}}let p=await e.fs.readdir(d);if(f||(p=p.filter(g=>!g.startsWith("."))),l){let g=[];for(let y of p){let w=d==="/"?`/${y}`:`${d}/${y}`;try{let E=await e.fs.stat(w);g.push({name:y,size:E.size??0})}catch{g.push({name:y,size:0})}}g.sort((y,w)=>w.size-y.size),p=g.map(y=>y.name)}else p.sort();r&&(p=[".","..",...p]),a&&p.reverse();let b="";if((o||i)&&(b+=`${t}:
|
|
52
52
|
`),s){b+=`total ${p.length}
|
|
53
53
|
`;for(let g of p){if(g==="."||g===".."){b+=`drwxr-xr-x 1 user user 0 Jan 1 00:00 ${g}
|
|
54
|
-
`;continue}let y=d==="/"?`/${g}`:`${d}/${g}`;try{let w=await e.fs.stat(y),E=w.isDirectory?"drwxr-xr-x":"-rw-r--r--",$=w.isDirectory?"/":"",A=w.size??0,P=c?
|
|
54
|
+
`;continue}let y=d==="/"?`/${g}`:`${d}/${g}`;try{let w=await e.fs.stat(y),E=w.isDirectory?"drwxr-xr-x":"-rw-r--r--",$=w.isDirectory?"/":"",A=w.size??0,P=c?yt(A).padStart(5):String(A).padStart(5),J=w.mtime??new Date(0),L=wt(J);b+=`${E} 1 user user ${P} ${L} ${g}${$}
|
|
55
55
|
`}catch{b+=`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${g}
|
|
56
56
|
`}}}else b+=p.join(`
|
|
57
57
|
`)+(p.length?`
|
|
58
58
|
`:"");if(o)for(let g of p){if(g==="."||g==="..")continue;let y=d==="/"?`/${g}`:`${d}/${g}`;try{if((await e.fs.stat(y)).isDirectory){b+=`
|
|
59
|
-
`;let E=t==="."?`./${g}`:`${t}/${g}`,$=await
|
|
60
|
-
`,exitCode:2}}}var
|
|
59
|
+
`;let E=t==="."?`./${g}`:`${t}/${g}`,$=await Tn(E,e,r,n,s,o,!1,a,c,l,!0);b+=$.stdout}}catch{}}return{stdout:b,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`ls: ${t}: No such file or directory
|
|
60
|
+
`,exitCode:2}}}var fl,dl,hl,Fn=C(()=>{"use strict";Y();R();fl={name:"ls",summary:"list directory contents",usage:"ls [OPTION]... [FILE]...",options:["-a, --all do not ignore entries starting with .","-A, --almost-all do not list . and ..","-d, --directory list directories themselves, not their contents","-h, --human-readable with -l, print sizes like 1K 234M 2G etc.","-l use a long listing format","-r, --reverse reverse order while sorting","-R, --recursive list subdirectories recursively","-S sort by file size, largest first","-t sort by time, newest first","-1 list one file per line"," --help display this help and exit"]},dl={showAll:{short:"a",long:"all",type:"boolean"},showAlmostAll:{short:"A",long:"almost-all",type:"boolean"},longFormat:{short:"l",type:"boolean"},humanReadable:{short:"h",long:"human-readable",type:"boolean"},recursive:{short:"R",long:"recursive",type:"boolean"},reverse:{short:"r",long:"reverse",type:"boolean"},sortBySize:{short:"S",type:"boolean"},directoryOnly:{short:"d",long:"directory",type:"boolean"},sortByTime:{short:"t",type:"boolean"},onePerLine:{short:"1",type:"boolean"}},hl={name:"ls",async execute(t,e){if(S(t))return x(fl);let r=M("ls",t,dl);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.showAlmostAll,o=r.result.flags.longFormat,i=r.result.flags.humanReadable,a=r.result.flags.recursive,c=r.result.flags.reverse,l=r.result.flags.sortBySize,u=r.result.flags.directoryOnly,f=r.result.flags.sortByTime;r.result.flags.onePerLine;let d=r.result.positional;d.length===0&&d.push(".");let h="",p="",b=0;for(let g=0;g<d.length;g++){let y=d[g];if(g>0&&h&&!h.endsWith(`
|
|
61
61
|
|
|
62
62
|
`)&&(h+=`
|
|
63
|
-
`),u){let w=e.fs.resolvePath(e.cwd,y);try{let E=await e.fs.stat(w);if(o){let $=E.isDirectory?"drwxr-xr-x":"-rw-r--r--",A=E.isDirectory?"/":"",P=E.size??0,J=i?
|
|
63
|
+
`),u){let w=e.fs.resolvePath(e.cwd,y);try{let E=await e.fs.stat(w);if(o){let $=E.isDirectory?"drwxr-xr-x":"-rw-r--r--",A=E.isDirectory?"/":"",P=E.size??0,J=i?yt(P).padStart(5):String(P).padStart(5),L=E.mtime??new Date(0),Se=wt(L);h+=`${$} 1 user user ${J} ${Se} ${y}${A}
|
|
64
64
|
`}else h+=`${y}
|
|
65
65
|
`}catch{p+=`ls: cannot access '${y}': No such file or directory
|
|
66
|
-
`,b=2}continue}if(y.includes("*")||y.includes("?")||y.includes("[")){let w=await
|
|
66
|
+
`,b=2}continue}if(y.includes("*")||y.includes("?")||y.includes("[")){let w=await pl(y,e,n,s,o,c,i,l);h+=w.stdout,p+=w.stderr,w.exitCode!==0&&(b=w.exitCode)}else{let w=await Tn(y,e,n,s,o,a,d.length>1,c,i,l);h+=w.stdout,p+=w.stderr,w.exitCode!==0&&(b=w.exitCode)}}return{stdout:h,stderr:p,exitCode:b}}}});var Ln={};I(Ln,{mkdirCommand:()=>gl});var ml,gl,Wn=C(()=>{"use strict";ye();Y();ml={recursive:{short:"p",long:"parents",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},gl={name:"mkdir",async execute(t,e){let r=M("mkdir",t,ml);if(!r.ok)return r.error;let n=r.result.flags.recursive,s=r.result.flags.verbose,o=r.result.positional;if(o.length===0)return{stdout:"",stderr:`mkdir: missing operand
|
|
67
67
|
`,exitCode:1};let i="",a="",c=0;for(let l of o)try{let u=e.fs.resolvePath(e.cwd,l);await e.fs.mkdir(u,{recursive:n}),s&&(i+=`mkdir: created directory '${l}'
|
|
68
68
|
`)}catch(u){let f=q(u);f.includes("ENOENT")||f.includes("no such file")?a+=`mkdir: cannot create directory '${l}': No such file or directory
|
|
69
69
|
`:f.includes("EEXIST")||f.includes("already exists")?a+=`mkdir: cannot create directory '${l}': File exists
|
|
70
70
|
`:a+=`mkdir: cannot create directory '${l}': ${f}
|
|
71
|
-
`,c=1}return{stdout:i,stderr:a,exitCode:c}}}});var
|
|
71
|
+
`,c=1}return{stdout:i,stderr:a,exitCode:c}}}});var _n={};I(_n,{touchCommand:()=>yl});var yl,Hn=C(()=>{"use strict";ye();R();yl={name:"touch",async execute(t,e){let r=[];for(let o of t){if(o.startsWith("--"))return O("touch",o);if(o.startsWith("-")&&o.length>1)return O("touch",o);r.push(o)}if(r.length===0)return{stdout:"",stderr:`touch: missing file operand
|
|
72
72
|
`,exitCode:1};let n="",s=0;for(let o of r)try{let i=e.fs.resolvePath(e.cwd,o);await e.fs.exists(i)||await e.fs.writeFile(i,"")}catch(i){n+=`touch: cannot touch '${o}': ${q(i)}
|
|
73
|
-
`,s=1}return{stdout:"",stderr:n,exitCode:s}}}});var
|
|
73
|
+
`,s=1}return{stdout:"",stderr:n,exitCode:s}}}});var Bn={};I(Bn,{rmCommand:()=>bl});var wl,bl,zn=C(()=>{"use strict";ye();Y();wl={recursive:{short:"r",long:"recursive",type:"boolean"},recursiveUpper:{short:"R",type:"boolean"},force:{short:"f",long:"force",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},bl={name:"rm",async execute(t,e){let r=M("rm",t,wl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.force,o=r.result.flags.verbose,i=r.result.positional;if(i.length===0)return s?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:`rm: missing operand
|
|
74
74
|
`,exitCode:1};let a="",c="",l=0;for(let u of i)try{let f=e.fs.resolvePath(e.cwd,u);if((await e.fs.stat(f)).isDirectory&&!n){c+=`rm: cannot remove '${u}': Is a directory
|
|
75
75
|
`,l=1;continue}await e.fs.rm(f,{recursive:n,force:s}),o&&(a+=`removed '${u}'
|
|
76
76
|
`)}catch(f){if(!s){let d=q(f);d.includes("ENOENT")||d.includes("no such file")?c+=`rm: cannot remove '${u}': No such file or directory
|
|
77
77
|
`:d.includes("ENOTEMPTY")||d.includes("not empty")?c+=`rm: cannot remove '${u}': Directory not empty
|
|
78
78
|
`:c+=`rm: cannot remove '${u}': ${d}
|
|
79
|
-
`,l=1}}return{stdout:a,stderr:c,exitCode:l}}}});var
|
|
79
|
+
`,l=1}}return{stdout:a,stderr:c,exitCode:l}}}});var Un={};I(Un,{cpCommand:()=>Sl});var El,xl,Sl,jn=C(()=>{"use strict";ye();Y();R();El={name:"cp",summary:"copy files and directories",usage:"cp [OPTION]... SOURCE... DEST",options:["-r, -R, --recursive copy directories recursively","-n, --no-clobber do not overwrite an existing file","-p, --preserve preserve file attributes","-v, --verbose explain what is being done"," --help display this help and exit"]},xl={recursive:{short:"r",long:"recursive",type:"boolean"},recursiveUpper:{short:"R",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},preserve:{short:"p",long:"preserve",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Sl={name:"cp",async execute(t,e){if(S(t))return x(El);let r=M("cp",t,xl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.noClobber,o=r.result.flags.preserve,i=r.result.flags.verbose,a=r.result.positional;if(a.length<2)return{stdout:"",stderr:`cp: missing destination file operand
|
|
80
80
|
`,exitCode:1};let c=a.pop()??"",l=a,u=e.fs.resolvePath(e.cwd,c),f="",d="",h=0,p=!1;try{p=(await e.fs.stat(u)).isDirectory}catch{}if(l.length>1&&!p)return{stdout:"",stderr:`cp: target '${c}' is not a directory
|
|
81
81
|
`,exitCode:1};for(let b of l)try{let g=e.fs.resolvePath(e.cwd,b),y=await e.fs.stat(g),w=u;if(p){let E=b.split("/").pop()||b;w=u==="/"?`/${E}`:`${u}/${E}`}if(y.isDirectory&&!n){d+=`cp: -r not specified; omitting directory '${b}'
|
|
82
82
|
`,h=1;continue}if(s)try{await e.fs.stat(w);continue}catch{}await e.fs.cp(g,w,{recursive:n}),i&&(f+=`'${b}' -> '${w}'
|
|
83
83
|
`)}catch(g){let y=q(g);y.includes("ENOENT")||y.includes("no such file")?d+=`cp: cannot stat '${b}': No such file or directory
|
|
84
84
|
`:d+=`cp: cannot copy '${b}': ${y}
|
|
85
|
-
`,h=1}return{stdout:f,stderr:d,exitCode:h}}}});var
|
|
85
|
+
`,h=1}return{stdout:f,stderr:d,exitCode:h}}}});var qn={};I(qn,{mvCommand:()=>$l});var Cl,Al,$l,Gn=C(()=>{"use strict";ye();Y();R();Cl={name:"mv",summary:"move (rename) files",usage:"mv [OPTION]... SOURCE... DEST",options:["-f, --force do not prompt before overwriting","-n, --no-clobber do not overwrite an existing file","-v, --verbose explain what is being done"," --help display this help and exit"]},Al={force:{short:"f",long:"force",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},$l={name:"mv",async execute(t,e){if(S(t))return x(Cl);let r=M("mv",t,Al);if(!r.ok)return r.error;let n=r.result.flags.force,s=r.result.flags.noClobber,o=r.result.flags.verbose,i=r.result.positional;if(s&&(n=!1),i.length<2)return{stdout:"",stderr:`mv: missing destination file operand
|
|
86
86
|
`,exitCode:1};let a=i.pop()??"",c=i,l=e.fs.resolvePath(e.cwd,a),u="",f="",d=0,h=!1;try{h=(await e.fs.stat(l)).isDirectory}catch{}if(c.length>1&&!h)return{stdout:"",stderr:`mv: target '${a}' is not a directory
|
|
87
87
|
`,exitCode:1};for(let p of c)try{let b=e.fs.resolvePath(e.cwd,p),g=l;if(h){let y=p.split("/").pop()||p;g=l==="/"?`/${y}`:`${l}/${y}`}if(s)try{await e.fs.stat(g);continue}catch{}if(await e.fs.mv(b,g),o){let y=h?`${a}/${p.split("/").pop()||p}`:a;u+=`renamed '${p}' -> '${y}'
|
|
88
88
|
`}}catch(b){let g=q(b);g.includes("ENOENT")||g.includes("no such file")?f+=`mv: cannot stat '${p}': No such file or directory
|
|
89
89
|
`:f+=`mv: cannot move '${p}': ${g}
|
|
90
|
-
`,d=1}return{stdout:u,stderr:f,exitCode:d}}}});var
|
|
90
|
+
`,d=1}return{stdout:u,stderr:f,exitCode:d}}}});var Vn={};I(Vn,{lnCommand:()=>vl});var Nl,vl,Zn=C(()=>{"use strict";R();Nl={name:"ln",summary:"make links between files",usage:"ln [OPTIONS] TARGET LINK_NAME",options:["-s create a symbolic link instead of a hard link","-f remove existing destination files","-n treat LINK_NAME as a normal file if it is a symbolic link to a directory","-v print name of each linked file"," --help display this help and exit"]},vl={name:"ln",async execute(t,e){if(S(t))return x(Nl);let r=!1,n=!1,s=!1,o=0;for(;o<t.length&&t[o].startsWith("-");){let f=t[o];if(f==="-s"||f==="--symbolic")r=!0,o++;else if(f==="-f"||f==="--force")n=!0,o++;else if(f==="-v"||f==="--verbose")s=!0,o++;else if(f==="-n"||f==="--no-dereference")o++;else if(/^-[sfvn]+$/.test(f))f.includes("s")&&(r=!0),f.includes("f")&&(n=!0),f.includes("v")&&(s=!0),o++;else if(f==="--"){o++;break}else return{stdout:"",stderr:`ln: invalid option -- '${f.slice(1)}'
|
|
91
91
|
`,exitCode:1}}let i=t.slice(o);if(i.length<2)return{stdout:"",stderr:`ln: missing file operand
|
|
92
92
|
`,exitCode:1};let a=i[0],c=i[1],l=e.fs.resolvePath(e.cwd,c);if(await e.fs.exists(l))if(n)try{await e.fs.rm(l,{force:!0})}catch{return{stdout:"",stderr:`ln: cannot remove '${c}': Permission denied
|
|
93
93
|
`,exitCode:1}}else return{stdout:"",stderr:`ln: failed to create ${r?"symbolic ":""}link '${c}': File exists
|
|
@@ -95,76 +95,76 @@ Notes:
|
|
|
95
95
|
`,exitCode:1};await e.fs.link(f,l)}}catch(f){let d=f;return d.message.includes("EPERM")?{stdout:"",stderr:`ln: '${a}': hard link not allowed for directory
|
|
96
96
|
`,exitCode:1}:{stdout:"",stderr:`ln: ${d.message}
|
|
97
97
|
`,exitCode:1}}let u="";return s&&(u=`'${c}' -> '${a}'
|
|
98
|
-
`),{stdout:u,stderr:"",exitCode:0}}}});var
|
|
99
|
-
`),(await t.fs.stat(a)).isDirectory&&(s+=await
|
|
98
|
+
`),{stdout:u,stderr:"",exitCode:0}}}});var Kn={};I(Kn,{chmodCommand:()=>Il});async function Qn(t,e,r,n){let s="",o=await t.fs.readdir(e);for(let i of o){let a=e==="/"?`/${i}`:`${e}/${i}`;await t.fs.chmod(a,r),n&&(s+=`mode of '${a}' changed to ${r.toString(8).padStart(4,"0")}
|
|
99
|
+
`),(await t.fs.stat(a)).isDirectory&&(s+=await Qn(t,a,r,n))}return s}function Pl(t){if(/^[0-7]+$/.test(t))return parseInt(t,8);let e=420,r=t.split(",");for(let n of r){let s=n.match(/^([ugoa]*)([+\-=])([rwxXst]*)$/);if(!s)throw new Error(`Invalid mode: ${t}`);let o=s[1]||"a",i=s[2],a=s[3];(o==="a"||o==="")&&(o="ugo");let c=0;a.includes("r")&&(c|=4),a.includes("w")&&(c|=2),(a.includes("x")||a.includes("X"))&&(c|=1);for(let l of o){let u=0;l==="u"?u=6:l==="g"?u=3:l==="o"&&(u=0);let f=c<<u;i==="+"?e|=f:i==="-"?e&=~f:i==="="&&(e&=~(7<<u),e|=f)}}return e}var kl,Il,Xn=C(()=>{"use strict";R();kl={name:"chmod",summary:"change file mode bits",usage:"chmod [OPTIONS] MODE FILE...",options:["-R change files recursively","-v output a diagnostic for every file processed"," --help display this help and exit"]},Il={name:"chmod",async execute(t,e){if(S(t))return x(kl);if(t.length<2)return{stdout:"",stderr:`chmod: missing operand
|
|
100
100
|
`,exitCode:1};let r=!1,n=!1,s=0;for(;s<t.length&&t[s].startsWith("-");){let f=t[s];if(f==="-R"||f==="--recursive")r=!0,s++;else if(f==="-v"||f==="--verbose")n=!0,s++;else if(f==="--"){s++;break}else{if(/^[+-]?[rwxugo]+/.test(f)||/^\d+$/.test(f))break;if(/^-[Rv]+$/.test(f)){f.includes("R")&&(r=!0),f.includes("v")&&(n=!0),s++;continue}return{stdout:"",stderr:`chmod: invalid option -- '${f.slice(1)}'
|
|
101
101
|
`,exitCode:1}}}if(t.length-s<2)return{stdout:"",stderr:`chmod: missing operand
|
|
102
|
-
`,exitCode:1};let o=t[s],i=t.slice(s+1),a;try{a=
|
|
102
|
+
`,exitCode:1};let o=t[s],i=t.slice(s+1),a;try{a=Pl(o)}catch{return{stdout:"",stderr:`chmod: invalid mode: '${o}'
|
|
103
103
|
`,exitCode:1}}let c="",l="",u=!1;for(let f of i){let d=e.fs.resolvePath(e.cwd,f);try{if(await e.fs.chmod(d,a),n&&(c+=`mode of '${f}' changed to ${a.toString(8).padStart(4,"0")}
|
|
104
|
-
`),r&&(await e.fs.stat(d)).isDirectory){let p=await
|
|
105
|
-
`,u=!0}}return{stdout:c,stderr:l,exitCode:u?1:0}}}});var
|
|
106
|
-
`,stderr:"",exitCode:0}}}});var
|
|
104
|
+
`),r&&(await e.fs.stat(d)).isDirectory){let p=await Qn(e,d,a,n);c+=p}}catch{l+=`chmod: cannot access '${f}': No such file or directory
|
|
105
|
+
`,u=!0}}return{stdout:c,stderr:l,exitCode:u?1:0}}}});var Yn={};I(Yn,{pwdCommand:()=>Rl});var Rl,Jn=C(()=>{"use strict";Rl={name:"pwd",async execute(t,e){return{stdout:`${e.cwd}
|
|
106
|
+
`,stderr:"",exitCode:0}}}});var es={};I(es,{readlinkCommand:()=>Dl});var Ol,Dl,ts=C(()=>{"use strict";R();Ol={name:"readlink",summary:"print resolved symbolic links or canonical file names",usage:"readlink [OPTIONS] FILE...",options:["-f canonicalize by following every symlink in every component of the given name recursively"," --help display this help and exit"]},Dl={name:"readlink",async execute(t,e){if(S(t))return x(Ol);let r=!1,n=0;for(;n<t.length&&t[n].startsWith("-");){let a=t[n];if(a==="-f"||a==="--canonicalize")r=!0,n++;else if(a==="--"){n++;break}else return{stdout:"",stderr:`readlink: invalid option -- '${a.slice(1)}'
|
|
107
107
|
`,exitCode:1}}let s=t.slice(n);if(s.length===0)return{stdout:"",stderr:`readlink: missing operand
|
|
108
108
|
`,exitCode:1};let o="",i=!1;for(let a of s){let c=e.fs.resolvePath(e.cwd,a);try{if(r){let l=c,u=new Set;for(;!u.has(l);){u.add(l);try{let f=await e.fs.readlink(l);if(f.startsWith("/"))l=f;else{let d=l.substring(0,l.lastIndexOf("/"))||"/";l=e.fs.resolvePath(d,f)}}catch{break}}o+=`${l}
|
|
109
109
|
`}else{let l=await e.fs.readlink(c);o+=`${l}
|
|
110
110
|
`}}catch{r?o+=`${c}
|
|
111
|
-
`:i=!0}}return{stdout:o,stderr:"",exitCode:i?1:0}}}});function
|
|
111
|
+
`:i=!0}}return{stdout:o,stderr:"",exitCode:i?1:0}}}});function bt(t,e){let r=10,n=null,s=!1,o=!1,i=!1,a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="-n"&&c+1<t.length){let u=t[++c];e==="tail"&&u.startsWith("+")?(i=!0,r=parseInt(u.slice(1),10)):r=parseInt(u,10)}else if(e==="tail"&&l.startsWith("-n+"))i=!0,r=parseInt(l.slice(3),10);else if(l.startsWith("-n"))r=parseInt(l.slice(2),10);else if(l==="-c"&&c+1<t.length)n=parseInt(t[++c],10);else if(l.startsWith("-c"))n=parseInt(l.slice(2),10);else if(l.startsWith("--bytes="))n=parseInt(l.slice(8),10);else if(l.startsWith("--lines="))r=parseInt(l.slice(8),10);else if(l==="-q"||l==="--quiet"||l==="--silent")s=!0;else if(l==="-v"||l==="--verbose")o=!0;else if(l.match(/^-\d+$/))r=parseInt(l.slice(1),10);else{if(l.startsWith("--"))return{ok:!1,error:O(e,l)};if(l.startsWith("-")&&l!=="-")return{ok:!1,error:O(e,l)};a.push(l)}}return n!==null&&(Number.isNaN(n)||n<0)?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of bytes
|
|
112
112
|
`,exitCode:1}}:Number.isNaN(r)||r<0?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of lines
|
|
113
|
-
`,exitCode:1}}:{ok:!0,options:{lines:r,bytes:n,quiet:s,verbose:o,files:a,fromLine:i}}}async function
|
|
113
|
+
`,exitCode:1}}:{ok:!0,options:{lines:r,bytes:n,quiet:s,verbose:o,files:a,fromLine:i}}}async function Et(t,e,r,n){let{quiet:s,verbose:o,files:i}=e;if(i.length===0)return{stdout:n(t.stdin),stderr:"",exitCode:0};let a="",c="",l=0,u=o||!s&&i.length>1;for(let f=0;f<i.length;f++){let d=i[f];u&&(f>0&&(a+=`
|
|
114
114
|
`),a+=`==> ${d} <==
|
|
115
115
|
`);try{let h=t.fs.resolvePath(t.cwd,d),p=await t.fs.readFile(h);a+=n(p)}catch{c+=`${r}: ${d}: No such file or directory
|
|
116
|
-
`,l=1}}return{stdout:a,stderr:c,exitCode:l}}function
|
|
116
|
+
`,l=1}}return{stdout:a,stderr:c,exitCode:l}}function rs(t,e,r){if(r!==null)return t.slice(0,r);if(e===0)return"";let n=0,s=0,o=t.length;for(;n<o&&s<e;){let i=t.indexOf(`
|
|
117
117
|
`,n);if(i===-1)return`${t}
|
|
118
|
-
`;s++,n=i+1}return n>0?t.slice(0,n):""}function
|
|
118
|
+
`;s++,n=i+1}return n>0?t.slice(0,n):""}function ns(t,e,r,n){if(r!==null)return t.slice(-r);let s=t.length;if(s===0)return"";if(n){let c=0,l=1;for(;c<s&&l<e;){let f=t.indexOf(`
|
|
119
119
|
`,c);if(f===-1)break;l++,c=f+1}let u=t.slice(c);return u.endsWith(`
|
|
120
120
|
`)?u:`${u}
|
|
121
121
|
`}if(e===0)return"";let o=s-1;t[o]===`
|
|
122
122
|
`&&o--;let i=0;for(;o>=0&&i<e;){if(t[o]===`
|
|
123
123
|
`&&(i++,i===e)){o++;break}o--}o<0&&(o=0);let a=t.slice(o);return t[s-1]===`
|
|
124
124
|
`?a:`${a}
|
|
125
|
-
`}var
|
|
126
|
-
`?(r++,s&&(n++,s=!1)):i===" "||i===" "||i==="\r"?s&&(n++,s=!1):s=!0}return s&&n++,{lines:r,words:n,chars:e}}function
|
|
127
|
-
`,stderr:"",exitCode:0}}let c="",l=0,u=0,f=0;for(let{filename:d,content:h}of a.files){let p=
|
|
128
|
-
`}return i.length>1&&(c+=`${
|
|
129
|
-
`),{stdout:c,stderr:a.stderr,exitCode:a.exitCode}}}});var
|
|
130
|
-
`,exitCode:1};let o="",i="",a=!1;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{let u=await e.fs.stat(l);if(n){let f=n,d=u.mode.toString(8),h=
|
|
131
|
-
`}else{let f=u.mode.toString(8).padStart(4,"0"),d=
|
|
125
|
+
`}var ir=C(()=>{"use strict";R()});var ss={};I(ss,{headCommand:()=>Ml});var Tl,Ml,is=C(()=>{"use strict";R();ir();Tl={name:"head",summary:"output the first part of files",usage:"head [OPTION]... [FILE]...",options:["-c, --bytes=NUM print the first NUM bytes","-n, --lines=NUM print the first NUM lines (default 10)","-q, --quiet never print headers giving file names","-v, --verbose always print headers giving file names"," --help display this help and exit"]},Ml={name:"head",async execute(t,e){if(S(t))return x(Tl);let r=bt(t,"head");if(!r.ok)return r.error;let{lines:n,bytes:s}=r.options;return Et(e,r.options,"head",o=>rs(o,n,s))}}});var os={};I(os,{tailCommand:()=>Ll});var Fl,Ll,as=C(()=>{"use strict";ir();R();Fl={name:"tail",summary:"output the last part of files",usage:"tail [OPTION]... [FILE]...",options:["-c, --bytes=NUM print the last NUM bytes","-n, --lines=NUM print the last NUM lines (default 10)","-n +NUM print starting from line NUM","-q, --quiet never print headers giving file names","-v, --verbose always print headers giving file names"," --help display this help and exit"]},Ll={name:"tail",async execute(t,e){if(S(t))return x(Fl);let r=bt(t,"tail");if(!r.ok)return r.error;let{lines:n,bytes:s,fromLine:o}=r.options;return Et(e,r.options,"tail",i=>ns(i,n,s,o??!1))}}});var cs={};I(cs,{wcCommand:()=>Hl});function ls(t){let e=t.length,r=0,n=0,s=!1;for(let o=0;o<e;o++){let i=t[o];i===`
|
|
126
|
+
`?(r++,s&&(n++,s=!1)):i===" "||i===" "||i==="\r"?s&&(n++,s=!1):s=!0}return s&&n++,{lines:r,words:n,chars:e}}function or(t,e,r,n,s){let o=[];e&&o.push(String(t.lines)),r&&o.push(String(t.words)),n&&o.push(String(t.chars));let i=o.join(" ");return s&&(i+=` ${s}`),i}var Wl,_l,Hl,us=C(()=>{"use strict";Y();Le();R();Wl={name:"wc",summary:"print newline, word, and byte counts for each file",usage:"wc [OPTION]... [FILE]...",options:["-c, --bytes print the byte counts","-m, --chars print the character counts","-l, --lines print the newline counts","-w, --words print the word counts"," --help display this help and exit"]},_l={lines:{short:"l",long:"lines",type:"boolean"},words:{short:"w",long:"words",type:"boolean"},bytes:{short:"c",long:"bytes",type:"boolean"},chars:{short:"m",long:"chars",type:"boolean"}},Hl={name:"wc",async execute(t,e){if(S(t))return x(Wl);let r=M("wc",t,_l);if(!r.ok)return r.error;let{lines:n,words:s}=r.result.flags,o=r.result.flags.bytes||r.result.flags.chars,i=r.result.positional;!n&&!s&&!o&&(n=s=o=!0);let a=await tt(e,i,{cmdName:"wc",stopOnError:!1});if(i.length===0){let d=ls(a.files[0].content);return{stdout:`${or(d,n,s,o,"")}
|
|
127
|
+
`,stderr:"",exitCode:0}}let c="",l=0,u=0,f=0;for(let{filename:d,content:h}of a.files){let p=ls(h);l+=p.lines,u+=p.words,f+=p.chars,c+=`${or(p,n,s,o,d)}
|
|
128
|
+
`}return i.length>1&&(c+=`${or({lines:l,words:u,chars:f},n,s,o,"total")}
|
|
129
|
+
`),{stdout:c,stderr:a.stderr,exitCode:a.exitCode}}}});var ds={};I(ds,{statCommand:()=>Ul});function fs(t,e){let r=e?"d":"-",n=[t&256?"r":"-",t&128?"w":"-",t&64?"x":"-",t&32?"r":"-",t&16?"w":"-",t&8?"x":"-",t&4?"r":"-",t&2?"w":"-",t&1?"x":"-"];return r+n.join("")}var Bl,zl,Ul,hs=C(()=>{"use strict";Y();R();Bl={name:"stat",summary:"display file or file system status",usage:"stat [OPTION]... FILE...",options:["-c FORMAT use the specified FORMAT instead of the default"," --help display this help and exit"]},zl={format:{short:"c",type:"string"}},Ul={name:"stat",async execute(t,e){if(S(t))return x(Bl);let r=M("stat",t,zl);if(!r.ok)return r.error;let n=r.result.flags.format??null,s=r.result.positional;if(s.length===0)return{stdout:"",stderr:`stat: missing operand
|
|
130
|
+
`,exitCode:1};let o="",i="",a=!1;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{let u=await e.fs.stat(l);if(n){let f=n,d=u.mode.toString(8),h=fs(u.mode,u.isDirectory);f=f.replace(/%n/g,c),f=f.replace(/%N/g,`'${c}'`),f=f.replace(/%s/g,String(u.size)),f=f.replace(/%F/g,u.isDirectory?"directory":"regular file"),f=f.replace(/%a/g,d),f=f.replace(/%A/g,h),f=f.replace(/%u/g,"1000"),f=f.replace(/%U/g,"user"),f=f.replace(/%g/g,"1000"),f=f.replace(/%G/g,"group"),o+=`${f}
|
|
131
|
+
`}else{let f=u.mode.toString(8).padStart(4,"0"),d=fs(u.mode,u.isDirectory);o+=` File: ${c}
|
|
132
132
|
`,o+=` Size: ${u.size} Blocks: ${Math.ceil(u.size/512)}
|
|
133
133
|
`,o+=`Access: (${f}/${d})
|
|
134
134
|
`,o+=`Modify: ${u.mtime.toISOString()}
|
|
135
135
|
`}}catch{i+=`stat: cannot stat '${c}': No such file or directory
|
|
136
|
-
`,a=!0}}return{stdout:o,stderr:i,exitCode:a?1:0}}}});function ue(t,e,r){let n=typeof r=="boolean"?{ignoreCase:r}:r??{},s=e;n.stripQuotes&&(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1));let o=n.ignoreCase?`i:${s}`:s,i=
|
|
136
|
+
`,a=!0}}return{stdout:o,stderr:i,exitCode:a?1:0}}}});function ue(t,e,r){let n=typeof r=="boolean"?{ignoreCase:r}:r??{},s=e;n.stripQuotes&&(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1));let o=n.ignoreCase?`i:${s}`:s,i=ps.get(o);return i||(i=jl(s,n.ignoreCase),ps.set(o,i)),i.test(t)}function jl(t,e){let r="^";for(let n=0;n<t.length;n++){let s=t[n];if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let o=n+1;for(;o<t.length&&t[o]!=="]";)o++;r+=t.slice(n,o+1),n=o}else s==="."||s==="+"||s==="^"||s==="$"||s==="{"||s==="}"||s==="("||s===")"||s==="|"||s==="\\"?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r,e?"i":"")}var ps,ar=C(()=>{"use strict";ps=new Map});var xt={};I(xt,{egrepCommand:()=>Ql,fgrepCommand:()=>Zl,grepCommand:()=>cr});function Gl(t){let e="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){let s=t[r+1];if(s==="|"||s==="("||s===")"){e+=s,r+=2;continue}else if(s==="{"||s==="}"){e+=`\\${s}`,r+=2;continue}}n==="+"||n==="?"||n==="|"||n==="("||n===")"||n==="{"||n==="}"?e+=`\\${n}`:e+=n,r++}return e}function ms(t,e,r,n,s,o,i=!1,a=0,c=0){let l=t.split(`
|
|
137
137
|
`),u=l.length,f=u>0&&l[u-1]===""?u-1:u;if(s){let g=0;for(let w=0;w<f;w++)e.lastIndex=0,e.test(l[w])!==r&&g++;return{output:`${o?`${o}:${g}`:String(g)}
|
|
138
138
|
`,matched:g>0}}if(a===0&&c===0){let g=[],y=!1;for(let w=0;w<f;w++){let E=l[w];if(e.lastIndex=0,e.test(E)!==r)if(y=!0,i){e.lastIndex=0;for(let A=e.exec(E);A!==null;A=e.exec(E))g.push(o?`${o}:${A[0]}`:A[0]),A[0].length===0&&e.lastIndex++}else n?g.push(o?`${o}:${w+1}:${E}`:`${w+1}:${E}`):g.push(o?`${o}:${E}`:E)}return{output:g.length>0?`${g.join(`
|
|
139
139
|
`)}
|
|
140
140
|
`:"",matched:y}}let d=[],h=0,p=new Set,b=[];for(let g=0;g<f;g++)e.lastIndex=0,e.test(l[g])!==r&&(b.push(g),h++);for(let g of b){for(let w=Math.max(0,g-a);w<g;w++)if(!p.has(w)){p.add(w);let E=l[w];n&&(E=`${w+1}-${E}`),o&&(E=`${o}-${E}`),d.push(E)}if(!p.has(g)){p.add(g);let w=l[g];if(i){e.lastIndex=0;for(let E=e.exec(w);E!==null;E=e.exec(w))d.push(o?`${o}:${E[0]}`:E[0]),E[0].length===0&&e.lastIndex++}else{let E=w;n&&(E=`${g+1}:${E}`),o&&(E=`${o}:${E}`),d.push(E)}}let y=Math.min(f-1,g+c);for(let w=g+1;w<=y;w++)if(!p.has(w)){p.add(w);let E=l[w];n&&(E=`${w+1}-${E}`),o&&(E=`${o}-${E}`),d.push(E)}}return{output:d.length>0?`${d.join(`
|
|
141
141
|
`)}
|
|
142
|
-
`:"",matched:h>0}}async function
|
|
143
|
-
`,exitCode:2};let P;f?P=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):u?P=$:P=
|
|
144
|
-
`,exitCode:2}}if(A.length===0&&e.stdin){let B=
|
|
145
|
-
`,exitCode:2};let
|
|
146
|
-
`);continue}let T=await e.fs.readFile(se),
|
|
147
|
-
`:a||(
|
|
148
|
-
`:o&&!i&&(
|
|
149
|
-
`,
|
|
142
|
+
`:"",matched:h>0}}async function lr(t,e,r=[],n=[],s=[]){let o=e.fs.resolvePath(e.cwd,t),i=[];try{if(!(await e.fs.stat(o)).isDirectory){let u=t.split("/").pop()||t;return n.length>0&&n.some(f=>ue(u,f,{stripQuotes:!0}))?[]:r.length>0&&!r.some(f=>ue(u,f,{stripQuotes:!0}))?[]:[t]}let c=t.split("/").pop()||t;if(s.length>0&&s.some(u=>ue(c,u,{stripQuotes:!0})))return[];let l=await e.fs.readdir(o);for(let u of l){if(u.startsWith("."))continue;let f=t==="."?u:`${t}/${u}`,d=await lr(f,e,r,n,s);i.push(...d)}}catch{}return i}async function Vl(t,e){let r=[],n=t.lastIndexOf("/"),s,o;if(n===-1?(s=e.cwd,o=t):(s=t.slice(0,n)||"/",o=t.slice(n+1)),t.includes("**")){let a=t.split("**"),c=a[0].replace(/\/$/,"")||".",l=a[1]||"";return await gs(c,l,e,r),r}let i=e.fs.resolvePath(e.cwd,s);try{let a=await e.fs.readdir(i);for(let c of a)if(ue(c,o,{stripQuotes:!0})){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async function gs(t,e,r,n){let s=r.fs.resolvePath(r.cwd,t);try{if(!(await r.fs.stat(s)).isDirectory){let a=t.split("/").pop()||"";if(e){let c=e.replace(/^\//,"");ue(a,c,{stripQuotes:!0})&&n.push(t)}return}let i=await r.fs.readdir(s);for(let a of i){let c=t==="."?a:`${t}/${a}`,l=r.fs.resolvePath(r.cwd,c);if((await r.fs.stat(l)).isDirectory)await gs(c,e,r,n);else if(e){let f=e.replace(/^\//,"");ue(a,f,{stripQuotes:!0})&&n.push(c)}}}catch{}}var ql,cr,Zl,Ql,St=C(()=>{"use strict";ar();R();ql={name:"grep",summary:"print lines that match patterns",usage:"grep [OPTION]... PATTERN [FILE]...",options:["-E, --extended-regexp PATTERN is an extended regular expression","-F, --fixed-strings PATTERN is a set of newline-separated strings","-i, --ignore-case ignore case distinctions","-v, --invert-match select non-matching lines","-w, --word-regexp match only whole words","-c, --count print only a count of matching lines","-l, --files-with-matches print only names of files with matches","-L, --files-without-match print names of files with no matches","-n, --line-number print line number with output lines","-h, --no-filename suppress the file name prefix on output","-o, --only-matching show only nonempty parts of lines that match","-q, --quiet, --silent suppress all normal output","-r, -R, --recursive search directories recursively","-A NUM print NUM lines of trailing context","-B NUM print NUM lines of leading context","-C NUM print NUM lines of context","-e PATTERN use PATTERN for matching"," --include=GLOB search only files matching GLOB"," --exclude=GLOB skip files matching GLOB"," --exclude-dir=DIR skip directories matching DIR"," --help display this help and exit"]},cr={name:"grep",async execute(t,e){if(S(t))return x(ql);let r=!1,n=!1,s=!1,o=!1,i=!1,a=!1,c=!1,l=!1,u=!1,f=!1,d=!1,h=!1,p=!1,b=0,g=0,y=[],w=[],E=[],$=null,A=[];for(let B=0;B<t.length;B++){let H=t[B];if(H.startsWith("-")&&H!=="-"){if(H==="-e"&&B+1<t.length){$=t[++B];continue}if(H.startsWith("--include=")){y.push(H.slice(10));continue}if(H.startsWith("--exclude=")){w.push(H.slice(10));continue}if(H.startsWith("--exclude-dir=")){E.push(H.slice(14));continue}let se=H.match(/^-([ABC])(\d+)$/);if(se){let T=parseInt(se[2],10);se[1]==="A"?g=T:se[1]==="B"?b=T:se[1]==="C"&&(b=T,g=T);continue}if((H==="-A"||H==="-B"||H==="-C")&&B+1<t.length){let T=parseInt(t[++B],10);H==="-A"?g=T:H==="-B"?b=T:(b=T,g=T);continue}let mt=H.startsWith("--")?[H]:H.slice(1).split("");for(let T of mt)if(T==="i"||T==="--ignore-case")r=!0;else if(T==="n"||T==="--line-number")n=!0;else if(T==="v"||T==="--invert-match")s=!0;else if(T==="c"||T==="--count")o=!0;else if(T==="l"||T==="--files-with-matches")i=!0;else if(T==="L"||T==="--files-without-match")a=!0;else if(T==="r"||T==="R"||T==="--recursive")c=!0;else if(T==="w"||T==="--word-regexp")l=!0;else if(T==="E"||T==="--extended-regexp")u=!0;else if(T==="F"||T==="--fixed-strings")f=!0;else if(T==="o"||T==="--only-matching")d=!0;else if(T==="h"||T==="--no-filename")h=!0;else if(T==="q"||T==="--quiet"||T==="--silent")p=!0;else{if(T.startsWith("--"))return O("grep",T);if(T.length===1)return O("grep",`-${T}`)}}else $===null?$=H:A.push(H)}if($===null)return{stdout:"",stderr:`grep: missing pattern
|
|
143
|
+
`,exitCode:2};let P;f?P=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):u?P=$:P=Gl($),l&&(P=`\\b${P}\\b`);let J;try{J=new RegExp(P,r?"gi":"g")}catch{return{stdout:"",stderr:`grep: invalid regular expression: ${$}
|
|
144
|
+
`,exitCode:2}}if(A.length===0&&e.stdin){let B=ms(e.stdin,J,s,n,o,"",d,b,g);return p?{stdout:"",stderr:"",exitCode:B.matched?0:1}:{stdout:B.output,stderr:"",exitCode:B.matched?0:1}}if(A.length===0)return{stdout:"",stderr:`grep: no input files
|
|
145
|
+
`,exitCode:2};let L="",Se="",Fe=!1,pt=!1,je=[];for(let B of A)if(B.includes("*")||B.includes("?")||B.includes("[")){let H=await Vl(B,e);if(c)for(let se of H){let mt=await lr(se,e,y,w,E);je.push(...mt)}else je.push(...H)}else if(c){let H=await lr(B,e,y,w,E);je.push(...H)}else je.push(B);let qa=(je.length>1||c)&&!h;for(let B of je){let H=B.split("/").pop()||B;if(!(w.length>0&&!c&&w.some(se=>ue(H,se,{stripQuotes:!0})))&&!(y.length>0&&!c&&!y.some(se=>ue(H,se,{stripQuotes:!0}))))try{let se=e.fs.resolvePath(e.cwd,B);if((await e.fs.stat(se)).isDirectory){c||(Se+=`grep: ${B}: Is a directory
|
|
146
|
+
`);continue}let T=await e.fs.readFile(se),sr=ms(T,J,s,n,o,qa?B:"",d,b,g);if(sr.matched){if(Fe=!0,p)return{stdout:"",stderr:"",exitCode:0};i?L+=`${B}
|
|
147
|
+
`:a||(L+=sr.output)}else a?L+=`${B}
|
|
148
|
+
`:o&&!i&&(L+=sr.output)}catch{Se+=`grep: ${B}: No such file or directory
|
|
149
|
+
`,pt=!0}}let et;return pt?et=2:a?et=L.length>0?0:1:et=Fe?0:1,p?{stdout:"",stderr:"",exitCode:et}:{stdout:L,stderr:Se,exitCode:et}}};Zl={name:"fgrep",async execute(t,e){return cr.execute(["-F",...t],e)}},Ql={name:"egrep",async execute(t,e){return cr.execute(["-E",...t],e)}}});function Ct(t){return t instanceof te||t instanceof ie||t instanceof re}var be,te,ie,re,Ee,fe,z,V,Ce,j,Z=C(()=>{"use strict";be=class extends Error{stdout;stderr;constructor(e,r="",n=""){super(e),this.stdout=r,this.stderr=n}prependOutput(e,r){this.stdout=e+this.stdout,this.stderr=r+this.stderr}},te=class extends be{levels;name="BreakError";constructor(e=1,r="",n=""){super("break",r,n),this.levels=e}},ie=class extends be{levels;name="ContinueError";constructor(e=1,r="",n=""){super("continue",r,n),this.levels=e}},re=class extends be{exitCode;name="ReturnError";constructor(e=0,r="",n=""){super("return",r,n),this.exitCode=e}},Ee=class extends be{exitCode;name="ErrexitError";constructor(e,r="",n=""){super(`errexit: command exited with status ${e}`,r,n),this.exitCode=e}},fe=class extends be{varName;name="NounsetError";constructor(e,r=""){super(`${e}: unbound variable`,r,`bash: ${e}: unbound variable
|
|
150
150
|
`),this.varName=e}},z=class extends be{exitCode;name="ExitError";constructor(e,r="",n=""){super("exit",r,n),this.exitCode=e}},V=class extends be{name="ArithmeticError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}
|
|
151
151
|
`}},Ce=class extends be{name="BadSubstitutionError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}: bad substitution
|
|
152
152
|
`}},j=class extends be{limitType;name="ExecutionLimitError";static EXIT_CODE=126;constructor(e,r,n="",s=""){super(e,n,s),this.limitType=r,this.stderr=s||`bash: ${e}
|
|
153
|
-
`}}});function
|
|
154
|
-
`,s+=2;continue}if(o==="t"){n+=" ",s+=2;continue}let i=parseInt(o,10);if(i>=1&&i<=9){n+=r[i-1]||"",s+=2;continue}n+=o,s+=2;continue}if(t[s]==="&"){n+=e,s++;continue}n+=t[s],s++}return n}function
|
|
153
|
+
`}}});function bs(t){return{patternSpace:"",holdSpace:"",lineNumber:0,totalLines:t,deleted:!1,printed:!1,quit:!1,appendBuffer:[],substitutionMade:!1,lineNumberOutput:[],restartCycle:!1}}function Xl(t){return typeof t=="object"&&"first"in t&&"step"in t}function ys(t,e,r,n){if(t==="$")return e===r;if(typeof t=="number")return e===t;if(Xl(t)){let{first:s,step:o}=t;return o===0?e===s:(e-s)%o===0&&e>=s}if(typeof t=="object"&&"pattern"in t)try{return new RegExp(t.pattern).test(n)}catch{return!1}return!1}function Ge(t,e,r,n){if(!t||!t.start&&!t.end)return!0;let s=t.start,o=t.end;if(s!==void 0&&o===void 0)return ys(s,e,r,n);if(s!==void 0&&o!==void 0){let i=typeof s=="number"?s:s==="$"?r:1,a=typeof o=="number"?o:r;return typeof s=="object"&&"pattern"in s&&ys(s,e,r,n)?!0:e>=i&&e<=a}return!0}function ws(t,e,r){let n="",s=0;for(;s<t.length;){if(t[s]==="\\"&&s+1<t.length){let o=t[s+1];if(o==="&"){n+="&",s+=2;continue}if(o==="n"){n+=`
|
|
154
|
+
`,s+=2;continue}if(o==="t"){n+=" ",s+=2;continue}let i=parseInt(o,10);if(i>=1&&i<=9){n+=r[i-1]||"",s+=2;continue}n+=o,s+=2;continue}if(t[s]==="&"){n+=e,s++;continue}n+=t[s],s++}return n}function Yl(t,e){let{lineNumber:r,totalLines:n,patternSpace:s}=e;if(t.type!=="label"&&Ge(t.address,r,n,s))switch(t.type){case"substitute":{let o=t,i="";o.global&&(i+="g"),o.ignoreCase&&(i+="i");try{let a=new RegExp(o.pattern,i),c=e.patternSpace;if(o.nthOccurrence&&o.nthOccurrence>0&&!o.global){let u=0,f=o.nthOccurrence;e.patternSpace=e.patternSpace.replace(new RegExp(o.pattern,`g${o.ignoreCase?"i":""}`),(d,...h)=>{if(u++,u===f){let p=h.slice(0,-2);return ws(o.replacement,d,p)}return d})}else e.patternSpace=e.patternSpace.replace(a,(u,...f)=>{let d=f.slice(0,-2);return ws(o.replacement,u,d)});c!==e.patternSpace&&(e.substitutionMade=!0,o.printOnMatch&&(e.printed=!0))}catch{}break}case"print":e.printed=!0;break;case"printFirstLine":{let o=e.patternSpace.indexOf(`
|
|
155
155
|
`);o!==-1?e.lineNumberOutput.push(e.patternSpace.slice(0,o)):e.lineNumberOutput.push(e.patternSpace);break}case"delete":e.deleted=!0;break;case"deleteFirstLine":{let o=e.patternSpace.indexOf(`
|
|
156
156
|
`);o!==-1?(e.patternSpace=e.patternSpace.slice(o+1),e.restartCycle=!0):e.deleted=!0;break}case"zap":e.patternSpace="";break;case"append":e.appendBuffer.push(t.text);break;case"insert":e.appendBuffer.unshift(`__INSERT__${t.text}`);break;case"change":e.patternSpace=t.text,e.deleted=!0,e.appendBuffer.push(t.text);break;case"hold":e.holdSpace=e.patternSpace;break;case"holdAppend":e.holdSpace?e.holdSpace+=`
|
|
157
157
|
${e.patternSpace}`:e.holdSpace=e.patternSpace;break;case"get":e.patternSpace=e.holdSpace;break;case"getAppend":e.patternSpace+=`
|
|
158
|
-
${e.holdSpace}`;break;case"exchange":{let o=e.patternSpace;e.patternSpace=e.holdSpace,e.holdSpace=o;break}case"next":e.printed=!0;break;case"quit":e.quit=!0;break;case"transliterate":e.patternSpace=
|
|
159
|
-
${u}`,e.lineNumber=r.currentLineIndex+a+1}else{e.quit=!0,e.deleted=!0;break}c++;continue}if(l.type==="branch"){let u=l;if(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnSubst"){let u=l;if(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&e.substitutionMade){if(e.substitutionMade=!1,u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnNoSubst"){let u=l;if(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&!e.substitutionMade){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="group"){let u=l;Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&
|
|
158
|
+
${e.holdSpace}`;break;case"exchange":{let o=e.patternSpace;e.patternSpace=e.holdSpace,e.holdSpace=o;break}case"next":e.printed=!0;break;case"quit":e.quit=!0;break;case"transliterate":e.patternSpace=Jl(e.patternSpace,t);break;case"lineNumber":e.lineNumberOutput.push(String(e.lineNumber));break;case"branch":break;case"branchOnSubst":break;case"branchOnNoSubst":break;case"group":break}}function Jl(t,e){let r="";for(let n of t){let s=e.source.indexOf(n);s!==-1?r+=e.dest[s]:r+=n}return r}function ur(t,e,r,n){let s=new Map;for(let l=0;l<t.length;l++){let u=t[l];u.type==="label"&&s.set(u.name,l)}let o=n?.maxIterations??Kl,i=0,a=0,c=0;for(;c<t.length;){if(i++,i>o)throw new j(`sed: command execution exceeded maximum iterations (${o})`,"iterations");if(e.deleted||e.quit||e.restartCycle)break;let l=t[c];if(l.type==="nextAppend"){if(Ge(l.address,e.lineNumber,e.totalLines,e.patternSpace))if(r&&r.currentLineIndex+a+1<r.lines.length){a++;let u=r.lines[r.currentLineIndex+a];e.patternSpace+=`
|
|
159
|
+
${u}`,e.lineNumber=r.currentLineIndex+a+1}else{e.quit=!0,e.deleted=!0;break}c++;continue}if(l.type==="branch"){let u=l;if(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnSubst"){let u=l;if(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&e.substitutionMade){if(e.substitutionMade=!1,u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnNoSubst"){let u=l;if(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&!e.substitutionMade){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="group"){let u=l;Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&ur(u.commands,e,r,n),c++;continue}Yl(l,e),c++}return a}var Kl,Es=C(()=>{"use strict";Z();Kl=1e4});function fr(t){if(t==="$")return"$";let e=t.match(/^(\d+)~(\d+)$/);if(e)return{first:parseInt(e[1],10),step:parseInt(e[2],10)};let r=parseInt(t,10);if(!Number.isNaN(r))return r;if(t.startsWith("/")&&t.endsWith("/"))return{pattern:t.slice(1,-1)}}function ec(t){let e=t,r,n,s=e.match(/^(\d+)~(\d+)/);if(s)return r={first:parseInt(s[1],10),step:parseInt(s[2],10)},e=e.slice(s[0].length),{range:{start:r,end:void 0},rest:e};if(e.startsWith("$")){if(r="$",e=e.slice(1),e.startsWith(",")){e=e.slice(1);let i=e.match(/^(\d+|\$)/);i&&(n=fr(i[1]),e=e.slice(i[0].length))}return{range:{start:r,end:n},rest:e}}let o=e.match(/^(\d+)/);if(o){if(r=parseInt(o[1],10),e=e.slice(o[0].length),e.startsWith(",")){e=e.slice(1);let i=e.match(/^(\d+|\$)/);i&&(n=fr(i[1]),e=e.slice(i[0].length))}return{range:{start:r,end:n},rest:e}}if(e.startsWith("/")){let i=1;for(;i<e.length&&e[i]!=="/";)e[i]==="\\"&&i+1<e.length?i+=2:i++;if(i<e.length){if(r={pattern:e.slice(1,i)},e=e.slice(i+1),e.startsWith(","))if(e=e.slice(1),e.startsWith("/")){let a=1;for(;a<e.length&&e[a]!=="/";)e[a]==="\\"&&a+1<e.length?a+=2:a++;a<e.length&&(n={pattern:e.slice(1,a)},e=e.slice(a+1))}else{let a=e.match(/^(\d+|\$)/);a&&(n=fr(a[1]),e=e.slice(a[0].length))}return{range:{start:r,end:n},rest:e}}}return{rest:e}}function Cs(t){let e=t.trim();if(!e)return{command:null};let{range:r,rest:n}=ec(e),s=n.trim();if(!s&&r)return{command:{type:"print",address:r}};let o=s[0];switch(o){case"p":return{command:{type:"print",address:r}};case"d":return{command:{type:"delete",address:r}};case"h":return{command:{type:"hold",address:r}};case"H":return{command:{type:"holdAppend",address:r}};case"g":if(s.length===1||/^\s/.test(s[1]))return{command:{type:"get",address:r}};break;case"G":return{command:{type:"getAppend",address:r}};case"x":return{command:{type:"exchange",address:r}};case"n":return{command:{type:"next",address:r}};case"N":return{command:{type:"nextAppend",address:r}};case"P":return{command:{type:"printFirstLine",address:r}};case"D":return{command:{type:"deleteFirstLine",address:r}};case"q":return{command:{type:"quit",address:r}};case"z":return{command:{type:"zap",address:r}};case"=":return{command:{type:"lineNumber",address:r}};case"y":return tc(s,r);case"b":{let i=s.slice(1).trim();return{command:{type:"branch",address:r,label:i||void 0}}}case"t":{let i=s.slice(1).trim();return{command:{type:"branchOnSubst",address:r,label:i||void 0}}}case"T":{let i=s.slice(1).trim();return{command:{type:"branchOnNoSubst",address:r,label:i||void 0}}}case"{":return rc(s,r);case":":{let i=s.slice(1).trim();return i?{command:{type:"label",name:i}}:{command:null,error:"missing label name"}}case"a":if(s[1]==="\\"||s[1]===" "){let i=s.slice(2).replace(/^[\s]*/,"");return{command:{type:"append",address:r,text:i}}}break;case"i":if(s[1]==="\\"||s[1]===" "){let i=s.slice(2).replace(/^[\s]*/,"");return{command:{type:"insert",address:r,text:i}}}break;case"c":if(s[1]==="\\"||s[1]===" "){let i=s.slice(2).replace(/^[\s]*/,"");return{command:{type:"change",address:r,text:i}}}break;case"s":return Ss(s,r)}return s.startsWith("s")?Ss(s,r):o&&xs[o]?{command:null,error:`unsupported command: ${xs[o]}`}:{command:null,error:`invalid command: ${t}`}}function tc(t,e){if(!t.startsWith("y")||t.length<4)return{command:null,error:"invalid transliteration"};let r=t[1],n=2,s="",o="";for(;n<t.length&&t[n]!==r;)if(t[n]==="\\"&&n+1<t.length){let i=t[n+1];i==="n"?s+=`
|
|
160
160
|
`:i==="t"?s+=" ":s+=i,n+=2}else s+=t[n],n++;if(n>=t.length)return{command:null,error:"unterminated transliteration source"};for(n++;n<t.length&&t[n]!==r;)if(t[n]==="\\"&&n+1<t.length){let i=t[n+1];i==="n"?o+=`
|
|
161
|
-
`:i==="t"?o+=" ":o+=i,n+=2}else o+=t[n],n++;return s.length!==o.length?{command:null,error:"transliteration sets must have same length"}:{command:{type:"transliterate",address:e,source:s,dest:o}}}function
|
|
162
|
-
`);s.length>0&&s[s.length-1]===""&&s.pop();let o=s.length,i="",a="",c=!1,l=n?{maxIterations:n.maxSedIterations}:void 0;for(let u=0;u<s.length;u++){let f={...
|
|
161
|
+
`:i==="t"?o+=" ":o+=i,n+=2}else o+=t[n],n++;return s.length!==o.length?{command:null,error:"transliteration sets must have same length"}:{command:{type:"transliterate",address:e,source:s,dest:o}}}function Ss(t,e){if(!t.startsWith("s")||t.length<4)return{command:null,error:"invalid substitution"};let r=t[1],n="",s="",o="",i=2;for(;i<t.length&&t[i]!==r;)t[i]==="\\"&&i+1<t.length?(n+=t[i]+t[i+1],i+=2):(n+=t[i],i++);if(i>=t.length)return{command:null,error:"unterminated substitution pattern"};for(i++;i<t.length&&t[i]!==r;)t[i]==="\\"&&i+1<t.length?(s+=t[i]+t[i+1],i+=2):(s+=t[i],i++);i<t.length&&(i++,o=t.slice(i));let a,c=o.match(/(\d+)/);return c&&(a=parseInt(c[1],10)),{command:{type:"substitute",address:e,pattern:n,replacement:s,global:o.includes("g"),ignoreCase:o.includes("i"),printOnMatch:o.includes("p"),nthOccurrence:a}}}function rc(t,e){let r=1,n=1,s=!1,o="",i=0;for(;n<t.length&&r>0;){let u=t[n];if(u==="\\"&&n+1<t.length){n+=2;continue}if(!s&&u==="s"&&n+1<t.length&&/[^a-zA-Z0-9]/.test(t[n+1])){s=!0,o=t[n+1],i=0,n++;continue}if(s&&u===o){i++,i>=3&&(s=!1),n++;continue}s||(u==="{"?r++:u==="}"&&r--),n++}if(r!==0)return{command:null,error:"unmatched brace in grouped commands"};let a=t.slice(1,n-1).trim(),c=$s(a),l=[];for(let u of c){let f=Cs(u);if(f.error)return{command:null,error:f.error};f.command&&l.push(f.command)}return{command:{type:"group",address:e,commands:l}}}function As(t,e=!1){let r=[];for(let n of t){let s=$s(n);for(let o of s){let i=Cs(o);if(i.error)return{commands:[],error:i.error};i.command&&(i.command.type==="substitute"&&e&&(i.command.extendedRegex=!0),r.push(i.command))}}return{commands:r}}function $s(t){let e=[],r="",n=!1,s="",o=0,i=0,a=0;for(;a<t.length;){let c=t[a];if(c==="\\"&&a+1<t.length){r+=c+t[a+1],a+=2;continue}if(!n){if(c==="{"){i++,r+=c,a++;continue}if(c==="}"){i--,r+=c,a++;continue}}if(!n&&c==="s"&&a+1<t.length&&/[^a-zA-Z0-9]/.test(t[a+1])){s=t[a+1],o=0,n=!0,r+=c,a++;continue}if(n&&c===s){o++,r+=c,o>=3&&(n=!1),a++;continue}if(!n&&i===0&&c===";"){r.trim()&&e.push(r.trim()),r="",a++;continue}r+=c,a++}return r.trim()&&e.push(r.trim()),e}var xs,Ns=C(()=>{"use strict";xs={r:"r (read file) - file operations not supported",R:"R (read line from file) - file operations not supported",w:"w (write to file) - file operations not supported",W:"W (write first line to file) - file operations not supported",e:"e (execute shell command) - shell execution not supported",l:"l (list/escape special chars) - not implemented",F:"F (print filename) - not implemented",Q:"Q (quit without printing) - use 'q' instead",v:"v (version check) - not implemented"}});var vs={};I(vs,{sedCommand:()=>sc});function dr(t,e,r,n){let s=t.split(`
|
|
162
|
+
`);s.length>0&&s[s.length-1]===""&&s.pop();let o=s.length,i="",a="",c=!1,l=n?{maxIterations:n.maxSedIterations}:void 0;for(let u=0;u<s.length;u++){let f={...bs(o),patternSpace:s[u],holdSpace:a,lineNumber:u+1,totalLines:o,substitutionMade:!1},d={lines:s,currentLineIndex:u},h=0,p=1e4,b=0;do{if(h++,h>p)break;f.restartCycle=!1;let w=ur(e,f,d,l);b+=w,d.currentLineIndex+=w}while(f.restartCycle&&!f.deleted&&!f.quit);u+=b,a=f.holdSpace,c=f.substitutionMade;for(let w of f.lineNumberOutput)i+=`${w}
|
|
163
163
|
`;let g=[],y=[];for(let w of f.appendBuffer)w.startsWith("__INSERT__")?g.push(w.slice(10)):y.push(w);for(let w of g)i+=`${w}
|
|
164
164
|
`;f.deleted||(r?f.printed&&(i+=`${f.patternSpace}
|
|
165
165
|
`):i+=`${f.patternSpace}
|
|
166
166
|
`);for(let w of y)i+=`${w}
|
|
167
|
-
`;if(f.quit)break}return i}var
|
|
167
|
+
`;if(f.quit)break}return i}var nc,sc,ks=C(()=>{"use strict";R();Es();Ns();nc={name:"sed",summary:"stream editor for filtering and transforming text",usage:"sed [OPTION]... {script} [input-file]...",options:["-n, --quiet, --silent suppress automatic printing of pattern space","-e script add the script to commands to be executed","-f script-file read script from file","-i, --in-place edit files in place","-E, -r, --regexp-extended use extended regular expressions"," --help display this help and exit"],description:`Commands:
|
|
168
168
|
s/regexp/replacement/[flags] substitute
|
|
169
169
|
d delete pattern space
|
|
170
170
|
p print pattern space
|
|
@@ -189,27 +189,27 @@ Addresses:
|
|
|
189
189
|
N line number
|
|
190
190
|
$ last line
|
|
191
191
|
/regexp/ lines matching regexp
|
|
192
|
-
N,M range from line N to M`};
|
|
192
|
+
N,M range from line N to M`};sc={name:"sed",async execute(t,e){if(S(t))return x(nc);let r=[],n=[],s=!1,o=!1,i=!1,a=[];for(let d=0;d<t.length;d++){let h=t[d];if(h==="-n"||h==="--quiet"||h==="--silent")s=!0;else if(h==="-i"||h==="--in-place")o=!0;else if(h.startsWith("-i"))o=!0;else if(h==="-E"||h==="-r"||h==="--regexp-extended")i=!0;else if(h==="-e")d+1<t.length&&r.push(t[++d]);else if(h==="-f")d+1<t.length&&n.push(t[++d]);else{if(h.startsWith("--"))return O("sed",h);if(h.startsWith("-")&&h.length>1){for(let p of h.slice(1))if(p!=="n"&&p!=="e"&&p!=="f"&&p!=="i"&&p!=="E"&&p!=="r")return O("sed",`-${p}`);h.includes("n")&&(s=!0),h.includes("i")&&(o=!0),(h.includes("E")||h.includes("r"))&&(i=!0),h.includes("e")&&!h.includes("n")&&!h.includes("i")&&d+1<t.length&&r.push(t[++d]),h.includes("f")&&!h.includes("e")&&d+1<t.length&&n.push(t[++d])}else!h.startsWith("-")&&r.length===0&&n.length===0?r.push(h):h.startsWith("-")||a.push(h)}}for(let d of n){let h=e.fs.resolvePath(e.cwd,d);try{let p=await e.fs.readFile(h);for(let b of p.split(`
|
|
193
193
|
`)){let g=b.trim();g&&!g.startsWith("#")&&r.push(g)}}catch{return{stdout:"",stderr:`sed: couldn't open file ${d}: No such file or directory
|
|
194
194
|
`,exitCode:1}}}if(r.length===0)return{stdout:"",stderr:`sed: no script specified
|
|
195
|
-
`,exitCode:1};let{commands:c,error:l}=
|
|
195
|
+
`,exitCode:1};let{commands:c,error:l}=As(r,i);if(l)return{stdout:"",stderr:`sed: ${l}
|
|
196
196
|
`,exitCode:1};if(c.length===0)return{stdout:"",stderr:`sed: no valid commands
|
|
197
|
-
`,exitCode:1};let u="";if(a.length===0)return u=e.stdin,{stdout:
|
|
197
|
+
`,exitCode:1};let u="";if(a.length===0)return u=e.stdin,{stdout:dr(u,c,s,e.limits),stderr:"",exitCode:0};if(o){for(let d of a){let h=e.fs.resolvePath(e.cwd,d);try{let p=await e.fs.readFile(h),b=dr(p,c,s,e.limits);await e.fs.writeFile(h,b)}catch{return{stdout:"",stderr:`sed: ${d}: No such file or directory
|
|
198
198
|
`,exitCode:1}}}return{stdout:"",stderr:"",exitCode:0}}for(let d of a){let h=e.fs.resolvePath(e.cwd,d);try{u+=await e.fs.readFile(h)}catch{return{stdout:"",stderr:`sed: ${d}: No such file or directory
|
|
199
|
-
`,exitCode:1}}}return{stdout:
|
|
200
|
-
`,s+=2):o==="t"?(n+=" ",s+=2):(n+=o,s+=2)}else t[s]==="&"?(n+=e,s++):(n+=t[s],s++);return n}function
|
|
201
|
-
`:c==="t"?i+=" ":c==="r"?i+="\r":i+=c,a+=2}else i+=n[a++];return i}var
|
|
202
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function
|
|
203
|
-
`:o==="t"?s+=" ":o==="r"?s+="\r":s+=o,n+=2}else s+=t[n++];n++,r+=s}else if(t[n]==="$"){n++;let s="";for(;n<t.length&&/\d/.test(t[n]);)s+=t[n++];let o=parseInt(s,10);r+=o===0?e.line:e.fields[o-1]||""}else{let s="";for(;n<t.length&&!/[\s$"]/.test(t[n]);)s+=t[n++];s==="NR"?r+=e.NR:s==="NF"?r+=e.NF:e.vars[s]!==void 0?r+=e.vars[s]:r+=s}}return r}function de(t,e){if(t=t.trim(),t.includes("&&"))return
|
|
204
|
-
`)&&n===0&&s===0){r.trim()&&e.push(r.trim()),r="";continue}}r+=a}return r.trim()&&e.push(r.trim()),e}function
|
|
205
|
-
`;if(t.startsWith("print ")){let i=t.slice(6).trim();return`${
|
|
206
|
-
`}if(t.startsWith("printf ")){let i=t.slice(7).trim();return
|
|
207
|
-
`:l==="t"?a+=" ":l==="r"?a+="\r":a+=l,c+=2}else a+=n[c++];return a}function
|
|
208
|
-
`).replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function
|
|
209
|
-
`,exitCode:1};let i=t[o],a=t.slice(o+1),{begin:c,main:l,end:u,functions:f}=
|
|
199
|
+
`,exitCode:1}}}return{stdout:dr(u,c,s,e.limits),stderr:"",exitCode:0}}}});function Ps(t,e,r){if(t.length<2)return e.RSTART=0,e.RLENGTH=-1,0;let n=String(r(t[0],e)),s=t[1].trim();s.startsWith("/")&&s.endsWith("/")&&(s=s.slice(1,-1));try{let i=new RegExp(s).exec(n);if(i)return e.RSTART=i.index+1,e.RLENGTH=i[0].length,e.RSTART}catch{}return e.RSTART=0,e.RLENGTH=-1,0}function Rs(t,e,r){if(t.length<3)return"";let n=String(r(t[0],e)),s=String(r(t[1],e)),o=String(r(t[2],e)),i=t.length>=4?String(r(t[3],e)):e.line;n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1));try{let a=o.toLowerCase()==="g",c=a?0:parseInt(o,10)||1;if(a){let l=new RegExp(n,"g");return i.replace(l,(u,...f)=>Is(s,u,f.slice(0,-2)))}else{let l=0,u=new RegExp(n,"g");return i.replace(u,(f,...d)=>(l++,l===c?Is(s,f,d.slice(0,-2)):f))}}catch{return i}}function Is(t,e,r){let n="",s=0;for(;s<t.length;)if(t[s]==="\\"&&s+1<t.length){let o=t[s+1];if(o==="&")n+="&",s+=2;else if(o==="0")n+=e,s+=2;else if(o>="1"&&o<="9"){let i=parseInt(o,10)-1;n+=r[i]||"",s+=2}else o==="n"?(n+=`
|
|
200
|
+
`,s+=2):o==="t"?(n+=" ",s+=2):(n+=o,s+=2)}else t[s]==="&"?(n+=e,s++):(n+=t[s],s++);return n}function Os(t,e,r){return t.length===0?e.line.length:String(r(t[0],e)).length}function Ds(t,e,r){if(t.length<2)return"";let n=String(r(t[0],e)),s=Number(r(t[1],e))-1;if(t.length>=3){let o=Number(r(t[2],e));return n.substr(Math.max(0,s),o)}return n.substr(Math.max(0,s))}function Ts(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=String(r(t[1],e)),o=n.indexOf(s);return o===-1?0:o+1}function Ms(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=t[1].trim(),o=t.length>=3?String(r(t[2],e)):e.FS,i=n.split(o===" "?/\s+/:o);e.arrays[s]||(e.arrays[s]={}),e.arrays[s]={};for(let a=0;a<i.length;a++)e.arrays[s][String(a+1)]=i[a];return i.length}function Fs(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=String(r(t[1],e)),o=t.length>=3?t[2].trim():"$0",i;if(o==="$0")i=e.line;else if(o.startsWith("$")){let u=parseInt(o.slice(1),10)-1;i=e.fields[u]||""}else i=String(e.vars[o]??"");let a=new RegExp(n),c=i.replace(a,s),l=c!==i?1:0;if(o==="$0")e.line=c;else if(o.startsWith("$")){let u=parseInt(o.slice(1),10)-1;e.fields[u]=c}else e.vars[o]=c;return l}function Ls(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=String(r(t[1],e)),o=t.length>=3?t[2].trim():"$0",i;if(o==="$0")i=e.line;else if(o.startsWith("$")){let f=parseInt(o.slice(1),10)-1;i=e.fields[f]||""}else i=String(e.vars[o]??"");let a=new RegExp(n,"g"),c=i.match(a),l=c?c.length:0,u=i.replace(a,s);if(o==="$0")e.line=u;else if(o.startsWith("$")){let f=parseInt(o.slice(1),10)-1;e.fields[f]=u}else e.vars[o]=u;return l}function Ws(t,e,r){return t.length===0?"":String(r(t[0],e)).toLowerCase()}function _s(t,e,r){return t.length===0?"":String(r(t[0],e)).toUpperCase()}function Hs(t,e,r){if(t.length===0)return"";let n=String(r(t[0],e)),s=t.slice(1),o=0,i="",a=0;for(;a<n.length;)if(n[a]==="%"&&a+1<n.length){let c=a+1;for(;c<n.length&&/[-+ #0]/.test(n[c]);)c++;for(;c<n.length&&/\d/.test(n[c]);)c++;if(n[c]===".")for(c++;c<n.length&&/\d/.test(n[c]);)c++;let l=n[c];if(l==="s"||l==="d"||l==="i"||l==="f"){let u=s[o]?r(s[o],e):"";i+=String(u),o++,a=c+1}else l==="%"?(i+="%",a=c+1):i+=n[a++]}else if(n[a]==="\\"&&a+1<n.length){let c=n[a+1];c==="n"?i+=`
|
|
201
|
+
`:c==="t"?i+=" ":c==="r"?i+="\r":i+=c,a+=2}else i+=n[a++];return i}var Bs=C(()=>{"use strict"});function v(t,e){if(t=t.trim(),t.startsWith('"')&&t.endsWith('"'))return oc(t.slice(1,-1));let r=t.match(/^(\w+)\s*\((.*)\)$/);if(r){let c=r[1],l=r[2],u=ic(l);switch(c){case"length":return Os(u,e,v);case"substr":return Ds(u,e,v);case"index":return Ts(u,e,v);case"split":return Ms(u,e,v);case"sub":return Fs(u,e,v);case"gsub":return Ls(u,e,v);case"match":return Ps(u,e,v);case"gensub":return Rs(u,e,v);case"tolower":return Ws(u,e,v);case"toupper":return _s(u,e,v);case"sprintf":return Hs(u,e,v);case"int":return Math.floor(Number(v(u[0]||"0",e)));case"sqrt":return Math.sqrt(Number(v(u[0]||"0",e)));case"sin":return Math.sin(Number(v(u[0]||"0",e)));case"cos":return Math.cos(Number(v(u[0]||"0",e)));case"log":return Math.log(Number(v(u[0]||"0",e)));case"exp":return Math.exp(Number(v(u[0]||"0",e)));case"atan2":{let f=Number(v(u[0]||"0",e)),d=Number(v(u[1]||"0",e));return Math.atan2(f,d)}case"rand":return e.random?e.random():Math.random();case"srand":{let f=u.length>0?Number(v(u[0],e)):Date.now();return e.vars._srand_seed=f,f}case"systime":case"mktime":case"strftime":throw new Error(`function '${c}()' is not implemented`);case"system":throw new Error("system() is not supported - shell execution not allowed in sandboxed environment");case"close":throw new Error("close() is not supported - file operations not allowed");case"fflush":throw new Error("fflush() is not supported - file operations not allowed");case"nextfile":throw new Error("nextfile is not supported - use 'next' instead")}if(e.functions?.[c])return lc(c,u,e)}let n=t.match(/^(\w+)\[(.+)\]$/);if(n){let c=n[1],l=n[2],u=String(v(l,e));return e.arrays[c]?e.arrays[c][u]??"":""}if(t.startsWith("$")){if(t.startsWith("$(")){let l=t.slice(2,-1),u=Number(v(l,e));return u===0?e.line:e.fields[u-1]||""}let c=t.match(/^\$(\d+)$/);if(c){let l=parseInt(c[1],10);return l===0?e.line:e.fields[l-1]||""}}if(t==="NR")return e.NR;if(t==="NF")return e.NF;if(t==="FNR")return e.FNR;if(t==="FS")return e.FS;if(t==="OFS")return e.OFS;if(t==="FILENAME")return e.FILENAME;if(t==="RSTART")return e.RSTART;if(t==="RLENGTH")return e.RLENGTH;if(e.vars[t]!==void 0)return e.vars[t];let s=t.match(/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/);if(s){let c=de(s[1].trim(),e);return v(c?s[2].trim():s[3].trim(),e)}let o=t.match(/^(.+?)\s*(\^|\*\*)\s*(.+)$/);if(o){let c=Number(v(o[1],e)),l=Number(v(o[3],e));return c**l}let i=t.match(/^(.+?)\s+([+\-*/%])\s+(.+)$/);if(i){let c=Number(v(i[1],e)),l=Number(v(i[3],e));switch(i[2]){case"+":return c+l;case"-":return c-l;case"*":return c*l;case"/":return l!==0?c/l:0;case"%":return c%l}}let a=t.match(/^([a-zA-Z_]\w*|\$\d+|\d+(?:\.\d+)?)\s*([+\-*/%])\s*(.+)$/);if(a){let c=Number(v(a[1],e)),l=Number(v(a[3],e));switch(a[2]){case"+":return c+l;case"-":return c-l;case"*":return c*l;case"/":return l!==0?c/l:0;case"%":return c%l}}return t.includes("$")||t.includes('"')?ac(t,e):/^-?\d+(\.\d+)?$/.test(t)?parseFloat(t):/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?"":t}function ic(t){let e=[],r="",n=0,s=!1;for(let o=0;o<t.length;o++){let i=t[o];i==='"'&&t[o-1]!=="\\"?(s=!s,r+=i):!s&&i==="("?(n++,r+=i):!s&&i===")"?(n--,r+=i):!s&&i===","&&n===0?(e.push(r.trim()),r=""):r+=i}return r.trim()&&e.push(r.trim()),e}function oc(t){return t.replace(/\\n/g,`
|
|
202
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function ac(t,e){let r="",n=0;for(;n<t.length;){for(;n<t.length&&/\s/.test(t[n]);)n++;if(n>=t.length)break;if(t[n]==='"'){let s="";for(n++;n<t.length&&t[n]!=='"';)if(t[n]==="\\"&&n+1<t.length){let o=t[n+1];o==="n"?s+=`
|
|
203
|
+
`:o==="t"?s+=" ":o==="r"?s+="\r":s+=o,n+=2}else s+=t[n++];n++,r+=s}else if(t[n]==="$"){n++;let s="";for(;n<t.length&&/\d/.test(t[n]);)s+=t[n++];let o=parseInt(s,10);r+=o===0?e.line:e.fields[o-1]||""}else{let s="";for(;n<t.length&&!/[\s$"]/.test(t[n]);)s+=t[n++];s==="NR"?r+=e.NR:s==="NF"?r+=e.NF:e.vars[s]!==void 0?r+=e.vars[s]:r+=s}}return r}function de(t,e){if(t=t.trim(),t.includes("&&"))return zs(t,"&&").every(l=>de(l,e));if(t.includes("||"))return zs(t,"||").some(l=>de(l,e));if(t.startsWith("!"))return!de(t.slice(1).trim(),e);if(t.startsWith("(")&&t.endsWith(")"))return de(t.slice(1,-1),e);if(t.startsWith("/")&&t.endsWith("/"))return new RegExp(t.slice(1,-1)).test(e.line);let r=t.match(/^(.+)\s+in\s+(\w+)$/);if(r){let c=String(v(r[1].trim(),e)),l=r[2];return!!(e.arrays[l]&&e.arrays[l][c]!==void 0)}let n=t.match(/^NR\s*(==|!=|>|<|>=|<=)\s*(\d+)$/);if(n){let c=n[1],l=parseInt(n[2],10);return Us(e.NR,c,l)}let s=t.match(/^\$(\d+)\s*~\s*\/([^/]+)\/$/);if(s){let c=parseInt(s[1],10),l=s[2],u=c===0?e.line:e.fields[c-1]||"";return new RegExp(l).test(u)}let o=t.match(/^\$(\d+)\s*!~\s*\/([^/]+)\/$/);if(o){let c=parseInt(o[1],10),l=o[2],u=c===0?e.line:e.fields[c-1]||"";return!new RegExp(l).test(u)}let i=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(i){let c=i[1].trim(),l=i[2],u=i[3].trim(),f=v(c,e),d=v(u,e);return Us(f,l,d)}let a=v(t,e);return typeof a=="number"?a!==0:typeof a=="string"?a!=="":!!a}function zs(t,e){let r=[],n="",s=0,o=!1;for(let i=0;i<t.length;i++){if(t[i]==='"'&&t[i-1]!=="\\"&&(o=!o),!o){if(t[i]==="(")s++;else if(t[i]===")")s--;else if(s===0&&t.slice(i,i+e.length)===e){r.push(n.trim()),n="",i+=e.length-1;continue}}n+=t[i]}return n.trim()&&r.push(n.trim()),r}function Us(t,e,r){let n=typeof t=="number"?t:parseFloat(String(t)),s=typeof r=="number"?r:parseFloat(String(r));if(!Number.isNaN(n)&&!Number.isNaN(s))switch(e){case"==":return n===s;case"!=":return n!==s;case">":return n>s;case"<":return n<s;case">=":return n>=s;case"<=":return n<=s}else{let i=String(t),a=String(r);switch(e){case"==":return i===a;case"!=":return i!==a;case">":return i>a;case"<":return i<a;case">=":return i>=a;case"<=":return i<=a}}return!1}function lc(t,e,r){let n=r.functions[t];if(!n)throw new Error(`awk: undefined function '${t}'`);let s="__func_depth__",o=r.vars[s]||0;if(o>=js)throw new Error(`awk: function '${t}' exceeded maximum recursion depth (${js})`);r.vars[s]=o+1;let i={};for(let c of n.params)i[c]=r.vars[c];for(let c=0;c<n.params.length;c++)c<e.length?r.vars[n.params[c]]=v(e[c],r):r.vars[n.params[c]]="";let a="";try{let c=n.body.match(/return\s+(.+)/);c&&(a=v(c[1].trim(),r))}finally{for(let c of n.params){let l=i[c];l!==void 0?r.vars[c]=l:delete r.vars[c]}r.vars[s]=o}return a}var js,qs=C(()=>{"use strict";Bs();js=100});function Gs(t){let e={begin:null,main:[],end:null,functions:{}},r=t.trim(),n=/function\s+(\w+)\s*\(([^)]*)\)\s*\{/g;for(let i=n.exec(r);i!==null;i=n.exec(r)){let a=i[1],c=i[2],l=i.index,u=i.index+i[0].length-1,f=oe(r,u);if(f!==-1){let d=c.split(",").map(p=>p.trim()).filter(p=>p.length>0),h=r.slice(u+1,f).trim();e.functions[a]={params:d,body:h},r=r.slice(0,l)+r.slice(f+1),r=r.trim(),n.lastIndex=0}}let s=r.match(/\bBEGIN\s*\{/);if(s&&s.index!==void 0){let i=s.index,a=r.slice(i+5).trim();if(a.startsWith("{")){let c=oe(a,0);c!==-1&&(e.begin=a.slice(1,c).trim(),r=r.slice(0,i)+a.slice(c+1),r=r.trim())}}let o=r.match(/\bEND\s*\{/);if(o&&o.index!==void 0){let i=o.index,a=r.slice(i+3).trim();if(a.startsWith("{")){let c=oe(a,0);c!==-1&&(e.end=a.slice(1,c).trim(),r=r.slice(0,i).trim())}}for(;r&&(r=r.trim(),!!r);){let i=!1;if(r.startsWith("{")){let a=oe(r,0);a!==-1&&(e.main.push({pattern:null,action:r.slice(1,a).trim()}),r=r.slice(a+1).trim(),i=!0)}if(!i){let a=r.match(/^\/([^/]*)\/\s*,\s*\/([^/]*)\/\s*\{/);if(a){let c=r.indexOf("{"),l=oe(r,c);l!==-1&&(e.main.push({pattern:null,range:{start:a[1],end:a[2]},action:r.slice(c+1,l).trim()}),r=r.slice(l+1).trim(),i=!0)}}if(!i){let a=r.match(/^\/([^/]*)\/\s*\{/);if(a){let c=r.indexOf("{"),l=oe(r,c);l!==-1&&(e.main.push({pattern:a[1],action:r.slice(c+1,l).trim()}),r=r.slice(l+1).trim(),i=!0)}}if(!i){let a=r.match(/^\/([^/]*)\/\s*,\s*\/([^/]*)\//);a&&(e.main.push({pattern:null,range:{start:a[1],end:a[2]},action:"print"}),r=r.slice(a[0].length).trim(),i=!0)}if(!i){let a=r.match(/^\/([^/]*)\//);a&&(e.main.push({pattern:a[1],action:"print"}),r=r.slice(a[0].length).trim(),i=!0)}if(!i&&r.includes("{")){let a=r.indexOf("{"),c=oe(r,a);c!==-1&&(e.main.push({pattern:r.slice(0,a).trim()||null,action:r.slice(a+1,c).trim()}),r=r.slice(c+1).trim(),i=!0)}i||(r.startsWith("print")||r.startsWith("printf")?(e.main.push({pattern:null,action:r}),r=""):(e.main.push({pattern:r,action:"print"}),r=""))}return e.main.length===0&&!e.begin&&!e.end&&e.main.push({pattern:null,action:"print"}),e}function oe(t,e){if(t[e]!=="{")return-1;let r=1,n=!1,s="";for(let o=e+1;o<t.length;o++){let i=t[o],a=t[o-1];if(n)i===s&&a!=="\\"&&(n=!1);else if(i==='"'||i==="'")n=!0,s=i;else if(i==="{")r++;else if(i==="}"&&(r--,r===0))return o}return-1}var hr=C(()=>{"use strict"});function he(t,e){let r="",n=cc(t);for(let s of n)if(r+=pr(s,e),e.shouldNext||e.shouldExit||e.loopBreak||e.loopContinue)break;return r}function cc(t){let e=[],r="",n=0,s=0,o=!1;for(let i=0;i<t.length;i++){let a=t[i];if(a==='"'&&t[i-1]!=="\\"&&(o=!o),!o){if(a==="{")n++;else if(a==="}")n--;else if(a==="(")s++;else if(a===")")s--;else if((a===";"||a===`
|
|
204
|
+
`)&&n===0&&s===0){r.trim()&&e.push(r.trim()),r="";continue}}r+=a}return r.trim()&&e.push(r.trim()),e}function pr(t,e){if(t=t.trim(),!t)return"";if(t.startsWith("if"))return uc(t,e);if(t.startsWith("while"))return fc(t,e);if(t.startsWith("do"))return dc(t,e);if(t.startsWith("for"))return hc(t,e);if(t==="print"||t==="print $0")return`${e.line}
|
|
205
|
+
`;if(t.startsWith("print ")){let i=t.slice(6).trim();return`${pc(i,e)}
|
|
206
|
+
`}if(t.startsWith("printf ")){let i=t.slice(7).trim();return mc(i,e)}if(t==="next")return e.shouldNext=!0,"";if(t==="exit"||t.startsWith("exit ")){if(e.shouldExit=!0,t.startsWith("exit ")){let i=t.slice(5).trim();e.exitCode=Number(v(i,e))||0}else e.exitCode=0;return""}if(t==="break")return e.loopBreak=!0,"";if(t==="continue")return e.loopContinue=!0,"";if(t==="getline"||t.startsWith("getline "))return gc(t,e);let r=t.match(/^delete\s+(\w+)\[(.+)\]$/);if(r){let i=r[1],a=r[2],c=String(v(a,e));return e.arrays[i]&&delete e.arrays[i][c],""}let n=t.match(/^(\w+)\[(.+)\]\s*=\s*(.+)$/);if(n){let i=n[1],a=n[2],c=n[3];e.arrays[i]||(e.arrays[i]={});let l=String(v(a,e)),u=v(c,e);return e.arrays[i][l]=u,""}if(t.match(/^(\w+)\+\+$/)){let i=t.slice(0,-2),a=Number(e.vars[i])||0;return e.vars[i]=a+1,""}if(t.match(/^(\w+)--$/)){let i=t.slice(0,-2),a=Number(e.vars[i])||0;return e.vars[i]=a-1,""}if(t.match(/^\+\+(\w+)$/)){let i=t.slice(2),a=Number(e.vars[i])||0;return e.vars[i]=a+1,""}if(t.match(/^--(\w+)$/)){let i=t.slice(2),a=Number(e.vars[i])||0;return e.vars[i]=a-1,""}let s=t.match(/^(\w+)\[(.+)\]\+\+$/);if(s){let i=s[1],a=s[2];e.arrays[i]||(e.arrays[i]={});let c=String(v(a,e)),l=Number(e.arrays[i][c])||0;return e.arrays[i][c]=l+1,""}if(t.includes("+=")){let i=t.indexOf("+="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(v(c,e))||0,u=a.match(/^(\w+)\[(.+)\]$/);if(u){let f=u[1],d=u[2];e.arrays[f]||(e.arrays[f]={});let h=String(v(d,e)),p=Number(e.arrays[f][h])||0;e.arrays[f][h]=p+l}else{let f=Number(e.vars[a])||0;e.vars[a]=f+l}return""}if(t.includes("-=")){let i=t.indexOf("-="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(e.vars[a])||0,u=Number(v(c,e))||0;return e.vars[a]=l-u,""}if(t.includes("*=")){let i=t.indexOf("*="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(e.vars[a])||0,u=Number(v(c,e))||0;return e.vars[a]=l*u,""}if(t.includes("/=")){let i=t.indexOf("/="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(e.vars[a])||0,u=Number(v(c,e))||0;return e.vars[a]=u!==0?l/u:0,""}if(t.includes("=")&&!t.includes("==")&&!t.includes("!=")&&!t.includes(">=")&&!t.includes("<=")){let i=t.indexOf("="),a=t.slice(0,i).trim(),c=t.slice(i+1).trim();return e.vars[a]=v(c,e),""}return t.match(/^(\w+)\s*\((.+)\)$/)&&v(t,e),""}function uc(t,e){let r=t.indexOf("(");if(r===-1)return"";let n=1,s=r+1;for(;s<t.length&&n>0;)t[s]==="("?n++:t[s]===")"&&n--,s++;s--;let o=t.slice(r+1,s).trim(),i=t.slice(s+1).trim(),a,c=null,l;if(i.startsWith("{")){let u=oe(i,0);a=i.slice(1,u).trim(),l=i.slice(u+1).trim()}else{let u=i.indexOf(";");if(u!==-1)a=i.slice(0,u).trim(),l=i.slice(u+1).trim();else{let f=i.indexOf(" else ");f!==-1?(a=i.slice(0,f).trim(),l=i.slice(f+1).trim()):(a=i,l="")}}if(l.startsWith("else")){let u=l.slice(4).trim();if(u.startsWith("{")){let f=oe(u,0);c=u.slice(1,f).trim()}else if(u.startsWith("if"))c=u;else{let f=u.indexOf(";");c=f!==-1?u.slice(0,f).trim():u}}return de(o,e)?he(a,e):c?he(c,e):""}function fc(t,e){let r=t.indexOf("(");if(r===-1)return"";let n=1,s=r+1;for(;s<t.length&&n>0;)t[s]==="("?n++:t[s]===")"&&n--,s++;s--;let o=t.slice(r+1,s).trim(),i=t.slice(s+1).trim(),a;if(i.startsWith("{")){let f=oe(i,0);a=i.slice(1,f).trim()}else a=i;let c="",l=0,u=e.maxIterations??mr;for(;de(o,e);){if(l++,l>u)throw new j(`awk: while loop exceeded maximum iterations (${u})`,"iterations",c);if(e.loopContinue=!1,c+=he(a,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break}return c}function dc(t,e){if(!t.match(/^do\s*\{/))return"";let n=t.indexOf("{"),s=oe(t,n);if(s===-1)return"";let o=t.slice(n+1,s).trim(),a=t.slice(s+1).trim().match(/^while\s*\((.+)\)\s*;?$/);if(!a)return"";let c=a[1].trim(),l="",u=0,f=e.maxIterations??mr;do{if(u++,u>f)throw new j(`awk: do-while loop exceeded maximum iterations (${f})`,"iterations",l);if(e.loopContinue=!1,l+=he(o,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break}while(de(c,e));return l}function hc(t,e){let r=t.indexOf("(");if(r===-1)return"";let n=1,s=r+1;for(;s<t.length&&n>0;)t[s]==="("?n++:t[s]===")"&&n--,s++;s--;let o=t.slice(r+1,s).trim(),i=t.slice(s+1).trim(),a;if(i.startsWith("{")){let g=oe(i,0);a=i.slice(1,g).trim()}else a=i;let c=o.match(/^(\w+)\s+in\s+(\w+)$/);if(c){let g=c[1],y=c[2],w="";if(e.arrays[y])for(let E of Object.keys(e.arrays[y])){if(e.vars[g]=E,e.loopContinue=!1,w+=he(a,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break}return w}let l=o.split(";").map(g=>g.trim());if(l.length!==3)return"";let[u,f,d]=l;u&&pr(u,e);let h="",p=0,b=e.maxIterations??mr;for(;!f||de(f,e);){if(p++,p>b)throw new j(`awk: for loop exceeded maximum iterations (${b})`,"iterations",h);if(e.loopContinue=!1,h+=he(a,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break;d&&pr(d,e)}return h}function pc(t,e){let r=[],n=Vs(t);for(let s of n)r.push(String(v(s.trim(),e)));return r.join(e.OFS)}function Vs(t){let e=[],r="",n=!1,s=0;for(let o=0;o<t.length;o++){let i=t[o];i==='"'&&t[o-1]!=="\\"?(n=!n,r+=i):i==="("&&!n?(s++,r+=i):i===")"&&!n?(s--,r+=i):i===","&&!n&&s===0?(e.push(r),r=""):r+=i}return r&&e.push(r),e}function mc(t,e){let r=t.match(/^"([^"]*)"(.*)$/);if(!r)return"";let n=r[1],s=r[2].trim(),o=s?Vs(s.replace(/^,\s*/,"")):[],i=0,a="",c=0;for(;c<n.length;)if(n[c]==="%"&&c+1<n.length){let l=c+1,u="",f="";for(;l<n.length&&/[-+ #0]/.test(n[l]);)l++;for(;l<n.length&&/\d/.test(n[l]);)u+=n[l++];if(n[l]===".")for(l++;l<n.length&&/\d/.test(n[l]);)f+=n[l++];let d=n[l];if(d==="s"){let h=o[i]?String(v(o[i],e)):"";u&&(h=h.padStart(parseInt(u,10))),a+=h,i++,c=l+1}else if(d==="d"||d==="i"){let h=o[i]?Math.floor(Number(v(o[i],e))):0,p=String(h);u&&(p=p.padStart(parseInt(u,10))),a+=p,i++,c=l+1}else if(d==="f"){let h=o[i]?Number(v(o[i],e)):0,p=f?parseInt(f,10):6,b=h.toFixed(p);u&&(b=b.padStart(parseInt(u,10))),a+=b,i++,c=l+1}else if(d==="x"||d==="X"){let h=o[i]?Math.floor(Number(v(o[i],e))):0,p=Math.abs(h).toString(16);d==="X"&&(p=p.toUpperCase()),u&&(p=p.padStart(parseInt(u,10),"0")),a+=h<0?`-${p}`:p,i++,c=l+1}else if(d==="o"){let h=o[i]?Math.floor(Number(v(o[i],e))):0,p=Math.abs(h).toString(8);u&&(p=p.padStart(parseInt(u,10),"0")),a+=h<0?`-${p}`:p,i++,c=l+1}else if(d==="c"){let h=o[i]?v(o[i],e):"";typeof h=="number"?a+=String.fromCharCode(h):a+=String(h).charAt(0)||"",i++,c=l+1}else if(d==="e"||d==="E"){let h=o[i]?Number(v(o[i],e)):0,p=f?parseInt(f,10):6,b=h.toExponential(p);d==="E"&&(b=b.toUpperCase()),u&&(b=b.padStart(parseInt(u,10))),a+=b,i++,c=l+1}else if(d==="g"||d==="G"){let h=o[i]?Number(v(o[i],e)):0,p=f?parseInt(f,10):6,b=Math.floor(Math.log10(Math.abs(h))),g;h===0?g="0":b<-4||b>=p?(g=h.toExponential(p-1),d==="G"&&(g=g.toUpperCase())):g=h.toPrecision(p),g=g.replace(/\.?0+$/,"").replace(/\.?0+e/,"e"),u&&(g=g.padStart(parseInt(u,10))),a+=g,i++,c=l+1}else d==="%"?(a+="%",c=l+1):a+=n[c++]}else if(n[c]==="\\"&&c+1<n.length){let l=n[c+1];l==="n"?a+=`
|
|
207
|
+
`:l==="t"?a+=" ":l==="r"?a+="\r":a+=l,c+=2}else a+=n[c++];return a}function gc(t,e){if(!e.lines||e.lineIndex===void 0)return"";let r=e.lineIndex+1;if(r>=e.lines.length)return"";let n=e.lines[r];if(t==="getline")e.line=n,e.fields=e.fieldSep?n.split(e.fieldSep):n.split(/\s+/),e.NF=e.fields.length,e.NR++,e.lineIndex=r;else{let s=t.slice(8).trim();s&&!s.startsWith("<")&&(e.vars[s]=n,e.NR++,e.lineIndex=r)}return""}function Zs(t,e){if(t===null)return!0;if(t.startsWith("/")&&t.endsWith("/"))return new RegExp(t.slice(1,-1)).test(e.line);if(/^(NR|NF|\$\d+)\s*(==|!=|>|<|>=|<=|~)/.test(t)||/\s*(==|!=|>|<|>=|<=)\s*/.test(t))return de(t,e);try{return new RegExp(t).test(e.line)}catch{return de(t,e)}}var mr,Qs=C(()=>{"use strict";Z();qs();hr();mr=1e4});var Js={};I(Js,{awkCommand:()=>wc});function Ks(t){return t.replace(/\\t/g," ").replace(/\\n/g,`
|
|
208
|
+
`).replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function Xs(t){if(t===" ")return/\s+/;if(/[[\](){}.*+?^$|\\]/.test(t))try{return new RegExp(t)}catch{return new RegExp(Ys(t))}return new RegExp(Ys(t))}function Ys(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yc,wc,ei=C(()=>{"use strict";R();Qs();hr();yc={name:"awk",summary:"pattern scanning and text processing language",usage:"awk [OPTIONS] 'PROGRAM' [FILE...]",options:["-F FS use FS as field separator","-v VAR=VAL assign VAL to variable VAR"," --help display this help and exit"]},wc={name:"awk",async execute(t,e){if(S(t))return x(yc);let r=/\s+/,n=" ",s={},o=0;for(let g=0;g<t.length;g++){let y=t[g];if(y==="-F"&&g+1<t.length)n=Ks(t[++g]),r=Xs(n),o=g+1;else if(y.startsWith("-F"))n=Ks(y.slice(2)),r=Xs(n),o=g+1;else if(y==="-v"&&g+1<t.length){let w=t[++g],E=w.indexOf("=");if(E>0){let $=w.slice(0,E),A=w.slice(E+1);s[$]=A}o=g+1}else{if(y.startsWith("--"))return O("awk",y);if(y.startsWith("-")&&y.length>1){let w=y[1];if(w!=="F"&&w!=="v")return O("awk",`-${w}`);o=g+1}else if(!y.startsWith("-")){o=g;break}}}if(o>=t.length)return{stdout:"",stderr:`awk: missing program
|
|
209
|
+
`,exitCode:1};let i=t[o],a=t.slice(o+1),{begin:c,main:l,end:u,functions:f}=Gs(i),d={FS:n,OFS:" ",NR:0,NF:0,FNR:0,FILENAME:"",RSTART:0,RLENGTH:-1,fields:[],line:"",vars:s,arrays:{},functions:f||{},fieldSep:r,maxIterations:e.limits?.maxAwkIterations},h="";if(c&&(h+=he(c,d),d.shouldExit))return{stdout:h,stderr:"",exitCode:d.exitCode||0};let p=[];if(a.length>0)for(let g of a)try{let y=e.fs.resolvePath(e.cwd,g),E=(await e.fs.readFile(y)).split(`
|
|
210
210
|
`);E.length>0&&E[E.length-1]===""&&E.pop(),p.push({filename:g,lines:E})}catch{return{stdout:"",stderr:`awk: ${g}: No such file or directory
|
|
211
211
|
`,exitCode:1}}else{let g=e.stdin.split(`
|
|
212
|
-
`);g.length>0&&g[g.length-1]===""&&g.pop(),p.push({filename:"",lines:g})}let b=l.map(()=>!1);for(let g of p){for(d.FILENAME=g.filename,d.FNR=0,d.lines=g.lines,d.lineIndex=-1;d.lineIndex<g.lines.length-1;){d.lineIndex++;let y=g.lines[d.lineIndex];d.NR++,d.FNR++,d.line=y,d.fields=y.split(r),d.NF=d.fields.length,d.shouldNext=!1;for(let w=0;w<l.length&&!(d.shouldExit||d.shouldNext);w++){let E=l[w];if(E.range){let $=new RegExp(E.range.start),A=new RegExp(E.range.end);b[w]?(h+=he(E.action,d),A.test(y)&&(b[w]=!1)):$.test(y)&&(b[w]=!0,h+=he(E.action,d),A.test(y)&&(b[w]=!1))}else
|
|
212
|
+
`);g.length>0&&g[g.length-1]===""&&g.pop(),p.push({filename:"",lines:g})}let b=l.map(()=>!1);for(let g of p){for(d.FILENAME=g.filename,d.FNR=0,d.lines=g.lines,d.lineIndex=-1;d.lineIndex<g.lines.length-1;){d.lineIndex++;let y=g.lines[d.lineIndex];d.NR++,d.FNR++,d.line=y,d.fields=y.split(r),d.NF=d.fields.length,d.shouldNext=!1;for(let w=0;w<l.length&&!(d.shouldExit||d.shouldNext);w++){let E=l[w];if(E.range){let $=new RegExp(E.range.start),A=new RegExp(E.range.end);b[w]?(h+=he(E.action,d),A.test(y)&&(b[w]=!1)):$.test(y)&&(b[w]=!0,h+=he(E.action,d),A.test(y)&&(b[w]=!1))}else Zs(E.pattern,d)&&(h+=he(E.action,d))}if(d.shouldExit)break}if(d.shouldExit)break}return u&&!d.shouldExit&&(h+=he(u,d)),{stdout:h,stderr:"",exitCode:d.exitCode||0}}}});function gr(t,e,r){let n=r!==null?r:/\s+/,s=t.split(n),o=e.startField-1;if(o>=s.length)return"";if(e.endField===void 0){let c=s[o]||"";return e.startChar!==void 0&&(c=c.slice(e.startChar-1)),e.ignoreLeading&&(c=c.trimStart()),c}let i=Math.min(e.endField-1,s.length-1),a="";for(let c=o;c<=i&&c<s.length;c++){let l=s[c]||"";if(c===o&&e.startChar!==void 0&&(l=l.slice(e.startChar-1)),c===i&&e.endChar!==void 0){let u=c===o&&e.startChar!==void 0?e.endChar-e.startChar+1:e.endChar;l=l.slice(0,u)}c>o&&(a+=r||" "),a+=l}return e.ignoreLeading&&(a=a.trimStart()),a}function bc(t,e,r,n){if(r){let i=parseFloat(t)||0,a=parseFloat(e)||0;return i-a}let s=t,o=e;return n&&(s=s.toLowerCase(),o=o.toLowerCase()),s.localeCompare(o)}function ti(t){let{keys:e,fieldDelimiter:r,numeric:n,ignoreCase:s,reverse:o}=t;return(i,a)=>{if(e.length===0){let l=i,u=a;s&&(l=l.toLowerCase(),u=u.toLowerCase());let f;if(n){let d=parseFloat(l)||0,h=parseFloat(u)||0;if(f=d-h,f===0){let p=l.localeCompare(u);return o?-p:p}}else f=l.localeCompare(u);return o?-f:f}for(let l of e){let u=gr(i,l,r),f=gr(a,l,r),d=l.numeric??n,h=l.ignoreCase??s,p=l.reverse??o,b=bc(u,f,d,h);if(b!==0)return p?-b:b}let c=i.localeCompare(a);return o?-c:c}}function ri(t,e){if(e.keys.length===0){if(e.ignoreCase){let s=new Set;return t.filter(o=>{let i=o.toLowerCase();return s.has(i)?!1:(s.add(i),!0)})}return[...new Set(t)]}let r=e.keys[0],n=new Set;return t.filter(s=>{let o=gr(s,r,e.fieldDelimiter);return(r.ignoreCase??e.ignoreCase)&&(o=o.toLowerCase()),n.has(o)?!1:(n.add(o),!0)})}var ni=C(()=>{"use strict"});function At(t){let e={startField:1},r="",n=t,s=n.match(/([nrfb]+)$/i);s&&(r=s[1].toLowerCase(),n=n.slice(0,-r.length)),r.includes("n")&&(e.numeric=!0),r.includes("r")&&(e.reverse=!0),r.includes("f")&&(e.ignoreCase=!0),r.includes("b")&&(e.ignoreLeading=!0);let o=n.split(",");if(o.length===0||o[0]==="")return null;let i=o[0].split("."),a=parseInt(i[0],10);if(Number.isNaN(a)||a<1)return null;if(e.startField=a,i.length>1&&i[1]){let c=parseInt(i[1],10);!Number.isNaN(c)&&c>=1&&(e.startChar=c)}if(o.length>1&&o[1]){let c=o[1],l=c.match(/([nrfb]+)$/i);if(l){let f=l[1].toLowerCase();f.includes("n")&&(e.numeric=!0),f.includes("r")&&(e.reverse=!0),f.includes("f")&&(e.ignoreCase=!0),f.includes("b")&&(e.ignoreLeading=!0),c=c.slice(0,-f.length)}let u=c.split(".");if(u[0]){let f=parseInt(u[0],10);if(!Number.isNaN(f)&&f>=1&&(e.endField=f),u.length>1&&u[1]){let d=parseInt(u[1],10);!Number.isNaN(d)&&d>=1&&(e.endChar=d)}}}return e}var si=C(()=>{"use strict"});var ii={};I(ii,{sortCommand:()=>xc});var Ec,xc,oi=C(()=>{"use strict";Le();R();ni();si();Ec={name:"sort",summary:"sort lines of text files",usage:"sort [OPTION]... [FILE]...",options:["-f, --ignore-case fold lower case to upper case characters","-n, --numeric-sort compare according to string numerical value","-r, --reverse reverse the result of comparisons","-u, --unique output only unique lines","-k, --key=KEYDEF sort via a key; KEYDEF gives location and type","-t, --field-separator=SEP use SEP as field separator"," --help display this help and exit"],description:`KEYDEF is F[.C][OPTS][,F[.C][OPTS]]
|
|
213
213
|
F is a field number (1-indexed)
|
|
214
214
|
C is a character position within the field (1-indexed)
|
|
215
215
|
OPTS can be: n (numeric), r (reverse), f (fold case), b (ignore blanks)
|
|
@@ -219,24 +219,24 @@ Examples:
|
|
|
219
219
|
-k2,2 sort by second field only
|
|
220
220
|
-k1.3 sort by first field starting at 3rd character
|
|
221
221
|
-k1,2n sort by fields 1-2 numerically
|
|
222
|
-
-k2 -k1 sort by field 2, then by field 1`},
|
|
223
|
-
`);i.length>0&&i[i.length-1]===""&&i.pop();let a=
|
|
222
|
+
-k2 -k1 sort by field 2, then by field 1`},xc={name:"sort",async execute(t,e){if(S(t))return x(Ec);let r={reverse:!1,numeric:!1,unique:!1,ignoreCase:!1,keys:[],fieldDelimiter:null},n=[];for(let l=0;l<t.length;l++){let u=t[l];if(u==="-r"||u==="--reverse")r.reverse=!0;else if(u==="-n"||u==="--numeric-sort")r.numeric=!0;else if(u==="-u"||u==="--unique")r.unique=!0;else if(u==="-f"||u==="--ignore-case")r.ignoreCase=!0;else if(u==="-t"||u==="--field-separator")r.fieldDelimiter=t[++l]||null;else if(u.startsWith("-t"))r.fieldDelimiter=u.slice(2)||null;else if(u.startsWith("--field-separator="))r.fieldDelimiter=u.slice(18)||null;else if(u==="-k"||u==="--key"){let f=t[++l];if(f){let d=At(f);d&&r.keys.push(d)}}else if(u.startsWith("-k")){let f=At(u.slice(2));f&&r.keys.push(f)}else if(u.startsWith("--key=")){let f=At(u.slice(6));f&&r.keys.push(f)}else{if(u.startsWith("--"))return O("sort",u);if(u.startsWith("-")&&!u.startsWith("--")){let f=!1;for(let d of u.slice(1))if(d==="r")r.reverse=!0;else if(d==="n")r.numeric=!0;else if(d==="u")r.unique=!0;else if(d==="f")r.ignoreCase=!0;else{f=!0;break}if(f)return O("sort",u)}else n.push(u)}}let s=await Ie(e,n,{cmdName:"sort"});if(!s.ok)return s.error;let i=s.content.split(`
|
|
223
|
+
`);i.length>0&&i[i.length-1]===""&&i.pop();let a=ti(r);return i.sort(a),r.unique&&(i=ri(i,r)),{stdout:i.length>0?`${i.join(`
|
|
224
224
|
`)}
|
|
225
|
-
`:"",stderr:"",exitCode:0}}}});var
|
|
225
|
+
`:"",stderr:"",exitCode:0}}}});var ai={};I(ai,{uniqCommand:()=>Ac});var Sc,Cc,Ac,li=C(()=>{"use strict";Y();Le();R();Sc={name:"uniq",summary:"report or omit repeated lines",usage:"uniq [OPTION]... [INPUT [OUTPUT]]",options:["-c, --count prefix lines by the number of occurrences","-d, --repeated only print duplicate lines","-i, --ignore-case ignore case when comparing","-u, --unique only print unique lines"," --help display this help and exit"]},Cc={count:{short:"c",long:"count",type:"boolean"},duplicatesOnly:{short:"d",long:"repeated",type:"boolean"},uniqueOnly:{short:"u",long:"unique",type:"boolean"},ignoreCase:{short:"i",long:"ignore-case",type:"boolean"}},Ac={name:"uniq",async execute(t,e){if(S(t))return x(Sc);let r=M("uniq",t,Cc);if(!r.ok)return r.error;let{count:n,duplicatesOnly:s,uniqueOnly:o,ignoreCase:i}=r.result.flags,a=r.result.positional,c=await Ie(e,a,{cmdName:"uniq"});if(!c.ok)return c.error;let u=c.content.split(`
|
|
226
226
|
`);if(u.length>0&&u[u.length-1]===""&&u.pop(),u.length===0)return{stdout:"",stderr:"",exitCode:0};let f=[],d=u[0],h=1,p=(y,w)=>i?y.toLowerCase()===w.toLowerCase():y===w;for(let y=1;y<u.length;y++)p(u[y],d)?h++:(f.push({line:d,count:h}),d=u[y],h=1);f.push({line:d,count:h});let b=f;s?b=f.filter(y=>y.count>1):o&&(b=f.filter(y=>y.count===1));let g="";for(let{line:y,count:w}of b)n?g+=`${String(w).padStart(4)} ${y}
|
|
227
227
|
`:g+=`${y}
|
|
228
|
-
`;return{stdout:g,stderr:"",exitCode:0}}}});var
|
|
228
|
+
`;return{stdout:g,stderr:"",exitCode:0}}}});var ci={};I(ci,{cutCommand:()=>kc});function Nc(t){let e=[],r=t.split(",");for(let n of r)if(n.includes("-")){let[s,o]=n.split("-");e.push({start:s?parseInt(s,10):1,end:o?parseInt(o,10):null})}else{let s=parseInt(n,10);e.push({start:s,end:s})}return e}function vc(t,e){let r=[];for(let n of e){let s=n.start-1,o=n.end===null?t.length:n.end;for(let i=s;i<o&&i<t.length;i++)i>=0&&!r.includes(t[i])&&r.push(t[i])}return r}var $c,kc,ui=C(()=>{"use strict";Le();R();$c={name:"cut",summary:"remove sections from each line of files",usage:"cut [OPTION]... [FILE]...",options:["-c LIST select only these characters","-d DELIM use DELIM instead of TAB for field delimiter","-f LIST select only these fields","-s, --only-delimited do not print lines without delimiters"," --help display this help and exit"]};kc={name:"cut",async execute(t,e){if(S(t))return x($c);let r=" ",n=null,s=null,o=!1,i=[];for(let d=0;d<t.length;d++){let h=t[d];if(h==="-d")r=t[++d]||" ";else if(h.startsWith("-d"))r=h.slice(2);else if(h==="-f")n=t[++d];else if(h.startsWith("-f"))n=h.slice(2);else if(h==="-c")s=t[++d];else if(h.startsWith("-c"))s=h.slice(2);else if(h==="-s"||h==="--only-delimited")o=!0;else{if(h.startsWith("--"))return O("cut",h);if(h.startsWith("-")){let p=!1;for(let b of h.slice(1))if(b==="s")o=!0;else if(!"dfc".includes(b)){p=!0;break}if(p)return O("cut",h)}else i.push(h)}}if(!n&&!s)return{stdout:"",stderr:`cut: you must specify a list of bytes, characters, or fields
|
|
229
229
|
`,exitCode:1};let a=await Ie(e,i,{cmdName:"cut"});if(!a.ok)return a.error;let l=a.content.split(`
|
|
230
|
-
`);l.length>0&&l[l.length-1]===""&&l.pop();let u=
|
|
231
|
-
`}else{if(o&&!d.includes(r))continue;let h=d.split(r),p=
|
|
232
|
-
`}return{stdout:f,stderr:"",exitCode:0}}}});var
|
|
230
|
+
`);l.length>0&&l[l.length-1]===""&&l.pop();let u=Nc(n||s||"1"),f="";for(let d of l)if(s){let h=d.split(""),p=[];for(let b of u){let g=b.start-1,y=b.end===null?h.length:b.end;for(let w=g;w<y&&w<h.length;w++)w>=0&&p.push(h[w])}f+=`${p.join("")}
|
|
231
|
+
`}else{if(o&&!d.includes(r))continue;let h=d.split(r),p=vc(h,u);f+=`${p.join(r)}
|
|
232
|
+
`}return{stdout:f,stderr:"",exitCode:0}}}});var di={};I(di,{pasteCommand:()=>Rc});function fi(t,e){if(t.length===0)return"";if(t.length===1)return t[0];let r=t[0];for(let n=1;n<t.length;n++){let s=(n-1)%e.length;r+=e[s]+t[n]}return r}var Ic,Pc,Rc,hi=C(()=>{"use strict";Y();R();Ic={name:"paste",summary:"merge lines of files",usage:"paste [OPTION]... [FILE]...",description:["Write lines consisting of the sequentially corresponding lines from","each FILE, separated by TABs, to standard output.","","With no FILE, or when FILE is -, read standard input."],options:["-d, --delimiters=LIST reuse characters from LIST instead of TABs","-s, --serial paste one file at a time instead of in parallel"," --help display this help and exit"],examples:["paste file1 file2 Merge file1 and file2 side by side","paste -d, file1 file2 Use comma as delimiter","paste -s file1 Paste all lines of file1 on one line","paste - - < file Paste pairs of lines from file"]},Pc={delimiter:{short:"d",long:"delimiters",type:"string",default:" "},serial:{short:"s",long:"serial",type:"boolean"}},Rc={name:"paste",async execute(t,e){if(S(t))return x(Ic);let r=M("paste",t,Pc);if(!r.ok)return r.error;let n=r.result.flags.delimiter,s=r.result.flags.serial,o=r.result.positional;if(o.length===0)return{stdout:"",stderr:`usage: paste [-s] [-d delimiters] file ...
|
|
233
233
|
`,exitCode:1};let i=e.stdin?e.stdin.split(`
|
|
234
234
|
`):[""];i.length>0&&i[i.length-1]===""&&i.pop();let a=o.filter(f=>f==="-").length,c=[],l=0;for(let f of o)if(f==="-"){let d=[];for(let h=l;h<i.length;h+=a)d.push(i[h]);c.push(d),l++}else{let d=e.fs.resolvePath(e.cwd,f);try{let p=(await e.fs.readFile(d)).split(`
|
|
235
235
|
`);p.length>0&&p[p.length-1]===""&&p.pop(),c.push(p)}catch{return{stdout:"",stderr:`paste: ${f}: No such file or directory
|
|
236
|
-
`,exitCode:1}}}let u="";if(s)for(let f of c)f&&(u+=`${
|
|
237
|
-
`);else{let f=Math.max(...c.map(d=>d?.length??0));for(let d=0;d<f;d++){let h=[];for(let p of c)h.push(p?.[d]??"");u+=`${
|
|
238
|
-
`}}return{stdout:u,stderr:"",exitCode:0}}}});var
|
|
239
|
-
`:n==="t"?e+=" ":n==="r"?e+="\r":e+=n,r+=2;continue}if(r+2<t.length&&t[r+1]==="-"){let n=t.charCodeAt(r),s=t.charCodeAt(r+2);for(let o=n;o<=s;o++)e+=String.fromCharCode(o);r+=3;continue}e+=t[r],r++}return e}var
|
|
236
|
+
`,exitCode:1}}}let u="";if(s)for(let f of c)f&&(u+=`${fi(f,n)}
|
|
237
|
+
`);else{let f=Math.max(...c.map(d=>d?.length??0));for(let d=0;d<f;d++){let h=[];for(let p of c)h.push(p?.[d]??"");u+=`${fi(h,n)}
|
|
238
|
+
`}}return{stdout:u,stderr:"",exitCode:0}}}});var mi={};I(mi,{trCommand:()=>Mc});function pi(t){let e="",r=0;for(;r<t.length;){if(t[r]==="["&&t[r+1]===":"){let n=!1;for(let[s,o]of Object.entries(Dc))if(t.slice(r).startsWith(s)){e+=o,r+=s.length,n=!0;break}if(n)continue}if(t[r]==="\\"&&r+1<t.length){let n=t[r+1];n==="n"?e+=`
|
|
239
|
+
`:n==="t"?e+=" ":n==="r"?e+="\r":e+=n,r+=2;continue}if(r+2<t.length&&t[r+1]==="-"){let n=t.charCodeAt(r),s=t.charCodeAt(r+2);for(let o=n;o<=s;o++)e+=String.fromCharCode(o);r+=3;continue}e+=t[r],r++}return e}var Oc,Dc,Tc,Mc,gi=C(()=>{"use strict";Y();R();Oc={name:"tr",summary:"translate or delete characters",usage:"tr [OPTION]... SET1 [SET2]",options:["-c, -C, --complement use the complement of SET1","-d, --delete delete characters in SET1","-s, --squeeze-repeats squeeze repeated characters"," --help display this help and exit"],description:`SET syntax:
|
|
240
240
|
a-z character range
|
|
241
241
|
[:alnum:] all letters and digits
|
|
242
242
|
[:alpha:] all letters
|
|
@@ -250,120 +250,120 @@ Examples:
|
|
|
250
250
|
[:graph:] all printable characters except space
|
|
251
251
|
[:cntrl:] all control characters
|
|
252
252
|
[:xdigit:] all hexadecimal digits
|
|
253
|
-
\\n, \\t, \\r escape sequences`},
|
|
254
|
-
\r\f\v`,"[:upper:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","[:xdigit:]":"0123456789ABCDEFabcdef"};
|
|
253
|
+
\\n, \\t, \\r escape sequences`},Dc={"[:alnum:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789","[:alpha:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz","[:blank:]":" ","[:cntrl:]":Array.from({length:32},(t,e)=>String.fromCharCode(e)).join("").concat("\x7F"),"[:digit:]":"0123456789","[:graph:]":Array.from({length:94},(t,e)=>String.fromCharCode(33+e)).join(""),"[:lower:]":"abcdefghijklmnopqrstuvwxyz","[:print:]":Array.from({length:95},(t,e)=>String.fromCharCode(32+e)).join(""),"[:punct:]":"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~","[:space:]":`
|
|
254
|
+
\r\f\v`,"[:upper:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","[:xdigit:]":"0123456789ABCDEFabcdef"};Tc={complement:{short:"c",long:"complement",type:"boolean"},complementUpper:{short:"C",type:"boolean"},delete:{short:"d",long:"delete",type:"boolean"},squeeze:{short:"s",long:"squeeze-repeats",type:"boolean"}},Mc={name:"tr",async execute(t,e){if(S(t))return x(Oc);let r=M("tr",t,Tc);if(!r.ok)return r.error;let n=r.result.flags.complement||r.result.flags.complementUpper,s=r.result.flags.delete,o=r.result.flags.squeeze,i=r.result.positional;if(i.length<1)return{stdout:"",stderr:`tr: missing operand
|
|
255
255
|
`,exitCode:1};if(!s&&!o&&i.length<2)return{stdout:"",stderr:`tr: missing operand after SET1
|
|
256
|
-
`,exitCode:1};let a=
|
|
257
|
-
`,a=1}return{stdout:o,stderr:i,exitCode:a}}}});function
|
|
256
|
+
`,exitCode:1};let a=pi(i[0]),c=i.length>1?pi(i[1]):"",l=e.stdin,u=d=>{let h=a.includes(d);return n?!h:h},f="";if(s)for(let d of l)u(d)||(f+=d);else if(o&&i.length===1){let d="";for(let h of l)u(h)&&h===d||(f+=h,d=h)}else{if(n){let d=c.length>0?c[c.length-1]:"";for(let h of l)a.includes(h)?f+=h:f+=d}else{let d=new Map;for(let h=0;h<a.length;h++){let p=h<c.length?c[h]:c[c.length-1];d.set(a[h],p)}for(let h of l)f+=d.get(h)??h}if(o){let d="",h="";for(let p of f)c.includes(p)&&p===h||(d+=p,h=p);f=d}}return{stdout:f,stderr:"",exitCode:0}}}});var yi={};I(yi,{teeCommand:()=>Wc});var Fc,Lc,Wc,wi=C(()=>{"use strict";Y();R();Fc={name:"tee",summary:"read from stdin and write to stdout and files",usage:"tee [OPTION]... [FILE]...",options:["-a, --append append to the given FILEs, do not overwrite"," --help display this help and exit"]},Lc={append:{short:"a",long:"append",type:"boolean"}},Wc={name:"tee",async execute(t,e){if(S(t))return x(Fc);let r=M("tee",t,Lc);if(!r.ok)return r.error;let{append:n}=r.result.flags,s=r.result.positional,o=e.stdin,i="",a=0;for(let c of s)try{let l=e.fs.resolvePath(e.cwd,c);n?await e.fs.appendFile(l,o):await e.fs.writeFile(l,o)}catch{i+=`tee: ${c}: No such file or directory
|
|
257
|
+
`,a=1}return{stdout:o,stderr:i,exitCode:a}}}});function We(t,e){switch(t.type){case"name":return ue(e.name,t.pattern,t.ignoreCase);case"path":return ue(e.relativePath,t.pattern,t.ignoreCase);case"type":return t.fileType==="f"?e.isFile:t.fileType==="d"?e.isDirectory:!1;case"empty":return e.isEmpty;case"mtime":{let n=(Date.now()-e.mtime)/(1e3*60*60*24);return t.comparison==="more"?n>t.days:t.comparison==="less"?n<t.days:Math.floor(n)===t.days}case"newer":{let r=e.newerRefTimes.get(t.refPath);return r===void 0?!1:e.mtime>r}case"size":{let r=t.value;switch(t.unit){case"c":r=t.value;break;case"k":r=t.value*1024;break;case"M":r=t.value*1024*1024;break;case"G":r=t.value*1024*1024*1024;break;case"b":r=t.value*512;break}return t.comparison==="more"?e.size>r:t.comparison==="less"?e.size<r:t.unit==="b"?Math.ceil(e.size/512)===t.value:e.size===r}case"perm":{let r=e.mode&511,n=t.mode&511;return t.matchType==="exact"?r===n:t.matchType==="all"?(r&n)===n:(r&n)!==0}case"not":return!We(t.expr,e);case"and":return We(t.left,e)&&We(t.right,e);case"or":return We(t.left,e)||We(t.right,e)}}function bi(t){let e=[],r=n=>{n&&(n.type==="newer"?e.push(n.refPath):n.type==="not"?r(n.expr):(n.type==="and"||n.type==="or")&&(r(n.left),r(n.right)))};return r(t),e}var Ei=C(()=>{"use strict";ar()});function xi(t,e){let r=[],n=[],s=e;for(;s<t.length;){let l=t[s];if(l==="-name"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s]}});else if(l==="-iname"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s],ignoreCase:!0}});else if(l==="-path"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s]}});else if(l==="-ipath"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s],ignoreCase:!0}});else if(l==="-type"&&s+1<t.length){let u=t[++s];if(u==="f"||u==="d")r.push({type:"expr",expr:{type:"type",fileType:u}});else return{expr:null,pathIndex:s,error:`find: Unknown argument to -type: ${u}
|
|
258
258
|
`,actions:[]}}else if(l==="-empty")r.push({type:"expr",expr:{type:"empty"}});else if(l==="-mtime"&&s+1<t.length){let u=t[++s],f="exact",d=u;u.startsWith("+")?(f="more",d=u.slice(1)):u.startsWith("-")&&(f="less",d=u.slice(1));let h=parseInt(d,10);Number.isNaN(h)||r.push({type:"expr",expr:{type:"mtime",days:h,comparison:f}})}else if(l==="-newer"&&s+1<t.length){let u=t[++s];r.push({type:"expr",expr:{type:"newer",refPath:u}})}else if(l==="-size"&&s+1<t.length){let u=t[++s],f="exact",d=u;u.startsWith("+")?(f="more",d=u.slice(1)):u.startsWith("-")&&(f="less",d=u.slice(1));let h=d.match(/^(\d+)([ckMGb])?$/);if(h){let p=parseInt(h[1],10),b=h[2]||"b";r.push({type:"expr",expr:{type:"size",value:p,unit:b,comparison:f}})}}else if(l==="-perm"&&s+1<t.length){let u=t[++s],f="exact",d=u;u.startsWith("-")?(f="all",d=u.slice(1)):u.startsWith("/")&&(f="any",d=u.slice(1));let h=parseInt(d,8);Number.isNaN(h)||r.push({type:"expr",expr:{type:"perm",mode:h,matchType:f}})}else if(l==="-not"||l==="!")r.push({type:"not"});else if(l==="-o"||l==="-or")r.push({type:"op",op:"or"});else if(l==="-a"||l==="-and")r.push({type:"op",op:"and"});else if(l==="-maxdepth"||l==="-mindepth")s++;else if(l==="-exec"){let u=[];for(s++;s<t.length&&t[s]!==";"&&t[s]!=="+";)u.push(t[s]),s++;if(s>=t.length)return{expr:null,pathIndex:s,error:"find: missing argument to `-exec'\n",actions:[]};let f=t[s]==="+";n.push({type:"exec",command:u,batchMode:f})}else if(l==="-print")n.push({type:"print"});else if(l==="-print0")n.push({type:"print0"});else if(l==="-delete")n.push({type:"delete"});else{if(l.startsWith("-"))return{expr:null,pathIndex:s,error:`find: unknown predicate '${l}'
|
|
259
|
-
`,actions:[]};if(r.length===0){s++;continue}break}s++}if(r.length===0)return{expr:null,pathIndex:s,actions:n};let o=[];for(let l=0;l<r.length;l++){let u=r[l];if(u.type==="not"){if(l+1<r.length&&r[l+1].type==="expr"){let f=r[l+1].expr;o.push({type:"expr",expr:{type:"not",expr:f}}),l++}}else(u.type==="expr"||u.type==="op")&&o.push(u)}let i=[[]];for(let l of o)l.type==="op"&&l.op==="or"?i.push([]):l.type==="expr"&&i[i.length-1].push(l.expr);let a=[];for(let l of i){if(l.length===0)continue;let u=l[0];for(let f=1;f<l.length;f++)u={type:"and",left:u,right:l[f]};a.push(u)}if(a.length===0)return{expr:null,pathIndex:s,actions:n};let c=a[0];for(let l=1;l<a.length;l++)c={type:"or",left:c,right:a[l]};return{expr:c,pathIndex:s,actions:n}}var
|
|
260
|
-
`,exitCode:1}}let u=[],f=
|
|
259
|
+
`,actions:[]};if(r.length===0){s++;continue}break}s++}if(r.length===0)return{expr:null,pathIndex:s,actions:n};let o=[];for(let l=0;l<r.length;l++){let u=r[l];if(u.type==="not"){if(l+1<r.length&&r[l+1].type==="expr"){let f=r[l+1].expr;o.push({type:"expr",expr:{type:"not",expr:f}}),l++}}else(u.type==="expr"||u.type==="op")&&o.push(u)}let i=[[]];for(let l of o)l.type==="op"&&l.op==="or"?i.push([]):l.type==="expr"&&i[i.length-1].push(l.expr);let a=[];for(let l of i){if(l.length===0)continue;let u=l[0];for(let f=1;f<l.length;f++)u={type:"and",left:u,right:l[f]};a.push(u)}if(a.length===0)return{expr:null,pathIndex:s,actions:n};let c=a[0];for(let l=1;l<a.length;l++)c={type:"or",left:c,right:a[l]};return{expr:c,pathIndex:s,actions:n}}var Si=C(()=>{"use strict"});var Ci={};I(Ci,{findCommand:()=>Bc});var _c,Hc,Bc,Ai=C(()=>{"use strict";R();Ei();Si();_c={name:"find",summary:"search for files in a directory hierarchy",usage:"find [path...] [expression]",options:["-name PATTERN file name matches shell pattern PATTERN","-iname PATTERN like -name but case insensitive","-path PATTERN file path matches shell pattern PATTERN","-ipath PATTERN like -path but case insensitive","-type TYPE file is of type: f (regular file), d (directory)","-empty file is empty or directory is empty","-mtime N file's data was modified N*24 hours ago","-newer FILE file was modified more recently than FILE","-size N[ckMGb] file uses N units of space (c=bytes, k=KB, M=MB, G=GB, b=512B blocks)","-perm MODE file's permission bits are exactly MODE (octal)","-perm -MODE all permission bits MODE are set","-perm /MODE any permission bits MODE are set","-maxdepth LEVELS descend at most LEVELS directories","-mindepth LEVELS do not apply tests at levels less than LEVELS","-not, ! negate the following expression","-a, -and logical AND (default)","-o, -or logical OR","-exec CMD {} ; execute CMD on each file ({} is replaced by filename)","-exec CMD {} + execute CMD with multiple files at once","-print print the full file name (default action)","-print0 print the full file name followed by a null character","-delete delete found files/directories"," --help display this help and exit"]},Hc=new Set(["-name","-iname","-path","-ipath","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),Bc={name:"find",async execute(t,e){if(S(t))return x(_c);let r=".",n=null,s=null;for(let y=0;y<t.length;y++){let w=t[y];if(w==="-maxdepth"&&y+1<t.length)n=parseInt(t[++y],10);else if(w==="-mindepth"&&y+1<t.length)s=parseInt(t[++y],10);else if(w==="-exec")for(y++;y<t.length&&t[y]!==";"&&t[y]!=="+";)y++;else!w.startsWith("-")&&w!==";"&&w!=="+"?r=w:Hc.has(w)&&y++}let{expr:o,error:i,actions:a}=xi(t,0);if(i)return{stdout:"",stderr:i,exitCode:1};let c=a.length===0,l=e.fs.resolvePath(e.cwd,r);try{await e.fs.stat(l)}catch{return{stdout:"",stderr:`find: ${r}: No such file or directory
|
|
260
|
+
`,exitCode:1}}let u=[],f=bi(o),d=new Map;for(let y of f){let w=e.fs.resolvePath(e.cwd,y);try{let E=await e.fs.stat(w);d.set(y,E.mtime?.getTime()??Date.now())}catch{}}async function h(y,w){if(n!==null&&w>n)return;let E;try{E=await e.fs.stat(y)}catch{return}if(!E)return;let $;y===l?$=r.split("/").pop()||r:$=y.split("/").pop()||"";let A=y===l?r:r==="."?`./${y.slice(l.length+1)}`:r+y.slice(l.length),P=null;E.isDirectory&&(P=await e.fs.readdir(y));let J=E.isFile?E.size===0:P!==null&&P.length===0,Se=s===null||w>=s;if(Se&&o!==null){let Fe={name:$,relativePath:A,isFile:E.isFile,isDirectory:E.isDirectory,isEmpty:J,mtime:E.mtime?.getTime()??Date.now(),size:E.size??0,mode:E.mode??420,newerRefTimes:d};Se=We(o,Fe)}if(Se&&u.push(A),P!==null)for(let Fe of P){let pt=y==="/"?`/${Fe}`:`${y}/${Fe}`;await h(pt,w+1)}}await h(l,0);let p="",b="",g=0;if(a.length>0)for(let y of a)switch(y.type){case"print":p+=u.length>0?`${u.join(`
|
|
261
261
|
`)}
|
|
262
262
|
`:"";break;case"print0":p+=u.length>0?`${u.join("\0")}\0`:"";break;case"delete":{let w=[...u].sort((E,$)=>$.length-E.length);for(let E of w){let $=e.fs.resolvePath(e.cwd,E);try{await e.fs.rm($,{recursive:!1})}catch(A){let P=A instanceof Error?A.message:String(A);b+=`find: cannot delete '${E}': ${P}
|
|
263
263
|
`,g=1}}break}case"exec":if(!e.exec)return{stdout:"",stderr:`find: -exec not supported in this context
|
|
264
264
|
`,exitCode:1};if(y.batchMode){let w=[];for(let A of y.command)A==="{}"?w.push(...u):w.push(A);let E=w.map(A=>`"${A}"`).join(" "),$=await e.exec(E);p+=$.stdout,b+=$.stderr,$.exitCode!==0&&(g=$.exitCode)}else for(let w of u){let $=y.command.map(P=>P==="{}"?w:P).map(P=>`"${P}"`).join(" "),A=await e.exec($);p+=A.stdout,b+=A.stderr,A.exitCode!==0&&(g=A.exitCode)}break}else c&&(p=u.length>0?`${u.join(`
|
|
265
265
|
`)}
|
|
266
|
-
`:"");return{stdout:p,stderr:b,exitCode:g}}}});var
|
|
267
|
-
basename OPTION... NAME...`,options:["-a, --multiple support multiple arguments","-s, --suffix=SUFFIX remove a trailing SUFFIX"," --help display this help and exit"]},
|
|
266
|
+
`:"");return{stdout:p,stderr:b,exitCode:g}}}});var $i={};I($i,{basenameCommand:()=>Uc});var zc,Uc,Ni=C(()=>{"use strict";R();zc={name:"basename",summary:"strip directory and suffix from filenames",usage:`basename NAME [SUFFIX]
|
|
267
|
+
basename OPTION... NAME...`,options:["-a, --multiple support multiple arguments","-s, --suffix=SUFFIX remove a trailing SUFFIX"," --help display this help and exit"]},Uc={name:"basename",async execute(t,e){if(S(t))return x(zc);let r=!1,n="",s=[];for(let i=0;i<t.length;i++){let a=t[i];a==="-a"||a==="--multiple"?r=!0:a==="-s"&&i+1<t.length?(n=t[++i],r=!0):a.startsWith("--suffix=")?(n=a.slice(9),r=!0):a.startsWith("-")||s.push(a)}if(s.length===0)return{stdout:"",stderr:`basename: missing operand
|
|
268
268
|
`,exitCode:1};!r&&s.length>=2&&(n=s.pop()??"");let o=[];for(let i of s){let a=i.replace(/\/+$/,""),c=a.split("/").pop()||a;n&&c.endsWith(n)&&(c=c.slice(0,-n.length)),o.push(c)}return{stdout:`${o.join(`
|
|
269
269
|
`)}
|
|
270
|
-
`,stderr:"",exitCode:0}}}});var
|
|
270
|
+
`,stderr:"",exitCode:0}}}});var vi={};I(vi,{dirnameCommand:()=>qc});var jc,qc,ki=C(()=>{"use strict";R();jc={name:"dirname",summary:"strip last component from file name",usage:"dirname [OPTION] NAME...",options:[" --help display this help and exit"]},qc={name:"dirname",async execute(t,e){if(S(t))return x(jc);let r=t.filter(s=>!s.startsWith("-"));if(r.length===0)return{stdout:"",stderr:`dirname: missing operand
|
|
271
271
|
`,exitCode:1};let n=[];for(let s of r){let o=s.replace(/\/+$/,""),i=o.lastIndexOf("/");i===-1?n.push("."):i===0?n.push("/"):n.push(o.slice(0,i))}return{stdout:`${n.join(`
|
|
272
272
|
`)}
|
|
273
|
-
`,stderr:"",exitCode:0}}}});var
|
|
273
|
+
`,stderr:"",exitCode:0}}}});var Pi={};I(Pi,{treeCommand:()=>Zc});async function Qc(t,e,r,n,s){let o={output:"",stderr:"",dirCount:0,fileCount:0},i=t.fs.resolvePath(t.cwd,e);try{if(!(await t.fs.stat(i)).isDirectory)return o.output=`${e}
|
|
274
274
|
`,o.fileCount=1,o}catch{return o.stderr=`tree: ${e}: No such file or directory
|
|
275
275
|
`,o}if(o.output=`${e}
|
|
276
276
|
`,r.maxDepth!==null&&s>=r.maxDepth)return o;try{let c=(await t.fs.readdir(i)).filter(l=>!(!r.showHidden&&l.startsWith(".")));c.sort();for(let l=0;l<c.length;l++){let u=c[l],f=i==="/"?`/${u}`:`${i}/${u}`,d=l===c.length-1,h=d?"`-- ":"|-- ",p=n+(d?" ":"| ");try{if((await t.fs.stat(f)).isDirectory){o.dirCount++;let g=r.fullPath?f:u;if(o.output+=`${n+h+g}
|
|
277
|
-
`,r.maxDepth===null||s+1<r.maxDepth){let y=await
|
|
277
|
+
`,r.maxDepth===null||s+1<r.maxDepth){let y=await Ii(t,f,r,p,s+1);o.output+=y.output,o.dirCount+=y.dirCount,o.fileCount+=y.fileCount}}else if(!r.directoriesOnly){o.fileCount++;let g=r.fullPath?f:u;o.output+=`${n+h+g}
|
|
278
278
|
`}}catch{}}}catch{o.stderr=`tree: ${e}: Permission denied
|
|
279
|
-
`}return o}async function
|
|
280
|
-
`;let g=await
|
|
281
|
-
`}}catch{}}}catch{}return o}var
|
|
279
|
+
`}return o}async function Ii(t,e,r,n,s){let o={output:"",stderr:"",dirCount:0,fileCount:0};if(r.maxDepth!==null&&s>=r.maxDepth)return o;try{let a=(await t.fs.readdir(e)).filter(c=>!(!r.showHidden&&c.startsWith(".")));a.sort();for(let c=0;c<a.length;c++){let l=a[c],u=e==="/"?`/${l}`:`${e}/${l}`,f=c===a.length-1,d=f?"`-- ":"|-- ",h=n+(f?" ":"| ");try{if((await t.fs.stat(u)).isDirectory){o.dirCount++;let b=r.fullPath?u:l;o.output+=`${n+d+b}
|
|
280
|
+
`;let g=await Ii(t,u,r,h,s+1);o.output+=g.output,o.dirCount+=g.dirCount,o.fileCount+=g.fileCount}else if(!r.directoriesOnly){o.fileCount++;let b=r.fullPath?u:l;o.output+=`${n+d+b}
|
|
281
|
+
`}}catch{}}}catch{}return o}var Gc,Vc,Zc,Ri=C(()=>{"use strict";Y();R();Gc={name:"tree",summary:"list contents of directories in a tree-like format",usage:"tree [OPTION]... [DIRECTORY]...",options:["-a include hidden files","-d list directories only","-L LEVEL limit depth of directory tree","-f print full path prefix for each file"," --help display this help and exit"]},Vc={showHidden:{short:"a",type:"boolean"},directoriesOnly:{short:"d",type:"boolean"},fullPath:{short:"f",type:"boolean"},maxDepth:{short:"L",type:"number"}},Zc={name:"tree",async execute(t,e){if(S(t))return x(Gc);let r=M("tree",t,Vc);if(!r.ok)return r.error;let n={showHidden:r.result.flags.showHidden,directoriesOnly:r.result.flags.directoriesOnly,maxDepth:r.result.flags.maxDepth??null,fullPath:r.result.flags.fullPath},s=r.result.positional;s.length===0&&s.push(".");let o="",i="",a=0,c=0;for(let l of s){let u=await Qc(e,l,n,"",0);o+=u.output,i+=u.stderr,a+=u.dirCount,c+=u.fileCount}return o+=`
|
|
282
282
|
${a} director${a===1?"y":"ies"}`,n.directoriesOnly||(o+=`, ${c} file${c===1?"":"s"}`),o+=`
|
|
283
|
-
`,{stdout:o,stderr:i,exitCode:i?1:0}}}});var
|
|
284
|
-
`),o;let a=await t.fs.readdir(e),c=0;for(let l of a){let u=e==="/"?`/${l}`:`${e}/${l}`,f=r==="."?l:`${r}/${l}`;try{let d=await t.fs.stat(u);if(d.isDirectory){let h=await
|
|
285
|
-
`)}catch{}}o.totalSize=c,(n.summarize||n.maxDepth===null||s<=n.maxDepth)&&(o.output+=`${
|
|
283
|
+
`,{stdout:o,stderr:i,exitCode:i?1:0}}}});var Di={};I(Di,{duCommand:()=>Yc});async function Oi(t,e,r,n,s){let o={output:"",totalSize:0,stderr:""};try{let i=await t.fs.stat(e);if(!i.isDirectory)return o.totalSize=i.size,(n.allFiles||s===0)&&(o.output=$t(i.size,n.humanReadable)+" "+r+`
|
|
284
|
+
`),o;let a=await t.fs.readdir(e),c=0;for(let l of a){let u=e==="/"?`/${l}`:`${e}/${l}`,f=r==="."?l:`${r}/${l}`;try{let d=await t.fs.stat(u);if(d.isDirectory){let h=await Oi(t,u,f,n,s+1);c+=h.totalSize,n.summarize||(n.maxDepth===null||s+1<=n.maxDepth?o.output+=h.output:c+=0)}else c+=d.size,n.allFiles&&!n.summarize&&(o.output+=$t(d.size,n.humanReadable)+" "+f+`
|
|
285
|
+
`)}catch{}}o.totalSize=c,(n.summarize||n.maxDepth===null||s<=n.maxDepth)&&(o.output+=`${$t(c,n.humanReadable)} ${r}
|
|
286
286
|
`)}catch{o.stderr=`du: cannot read directory '${r}': Permission denied
|
|
287
|
-
`}return o}function
|
|
288
|
-
`}}return n.grandTotal&&s.length>0&&(o+=`${
|
|
289
|
-
`),{stdout:o,stderr:i,exitCode:i?1:0}}}});var
|
|
287
|
+
`}return o}function $t(t,e){return e?t<1024?`${t}`:t<1024*1024?`${(t/1024).toFixed(1)}K`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)}M`:`${(t/(1024*1024*1024)).toFixed(1)}G`:String(Math.ceil(t/1024)||1)}var Kc,Xc,Yc,Ti=C(()=>{"use strict";Y();R();Kc={name:"du",summary:"estimate file space usage",usage:"du [OPTION]... [FILE]...",options:["-a write counts for all files, not just directories","-h print sizes in human readable format","-s display only a total for each argument","-c produce a grand total","--max-depth=N print total for directory only if N or fewer levels deep"," --help display this help and exit"]},Xc={allFiles:{short:"a",type:"boolean"},humanReadable:{short:"h",type:"boolean"},summarize:{short:"s",type:"boolean"},grandTotal:{short:"c",type:"boolean"},maxDepth:{long:"max-depth",type:"number"}},Yc={name:"du",async execute(t,e){if(S(t))return x(Kc);let r=M("du",t,Xc);if(!r.ok)return r.error;let n={allFiles:r.result.flags.allFiles,humanReadable:r.result.flags.humanReadable,summarize:r.result.flags.summarize,grandTotal:r.result.flags.grandTotal,maxDepth:r.result.flags.maxDepth??null},s=r.result.positional;s.length===0&&s.push(".");let o="",i="",a=0;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{await e.fs.stat(l);let u=await Oi(e,l,c,n,0);o+=u.output,a+=u.totalSize,i+=u.stderr}catch{i+=`du: cannot access '${c}': No such file or directory
|
|
288
|
+
`}}return n.grandTotal&&s.length>0&&(o+=`${$t(a,n.humanReadable)} total
|
|
289
|
+
`),{stdout:o,stderr:i,exitCode:i?1:0}}}});var yr={};I(yr,{envCommand:()=>eu,printenvCommand:()=>ru});var Jc,eu,tu,ru,wr=C(()=>{"use strict";R();Jc={name:"env",summary:"run a program in a modified environment",usage:"env [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]",options:["-i, --ignore-environment start with an empty environment","-u NAME, --unset=NAME remove NAME from the environment"," --help display this help and exit"]},eu={name:"env",async execute(t,e){if(S(t))return x(Jc);let r=!1,n=[],s={},o=-1;for(let u=0;u<t.length;u++){let f=t[u];if(f==="-i"||f==="--ignore-environment")r=!0;else if(f==="-u"&&u+1<t.length)n.push(t[++u]);else if(f.startsWith("-u"))n.push(f.slice(2));else if(f.startsWith("--unset="))n.push(f.slice(8));else{if(f.startsWith("--")&&f!=="--")return O("env",f);if(f.startsWith("-")&&f!=="-"){for(let d of f.slice(1))if(d!=="i"&&d!=="u")return O("env",`-${d}`);f.includes("i")&&(r=!0)}else if(f.includes("=")&&o===-1){let d=f.indexOf("="),h=f.slice(0,d),p=f.slice(d+1);s[h]=p}else{o=u;break}}}let i;if(r)i={...s};else{i={...e.env};for(let u of n)delete i[u];Object.assign(i,s)}if(o===-1){let u=[];for(let[f,d]of Object.entries(i))u.push(`${f}=${d}`);return{stdout:u.join(`
|
|
290
290
|
`)+(u.length>0?`
|
|
291
291
|
`:""),stderr:"",exitCode:0}}if(!e.exec)return{stdout:"",stderr:`env: command execution not supported in this context
|
|
292
|
-
`,exitCode:1};let a=t.slice(o).join(" "),c=Object.entries(s).map(([u,f])=>`${u}="${f}"`).join(" "),l=c?`${c} ${a}`:a;return e.exec(l)}},
|
|
292
|
+
`,exitCode:1};let a=t.slice(o).join(" "),c=Object.entries(s).map(([u,f])=>`${u}="${f}"`).join(" "),l=c?`${c} ${a}`:a;return e.exec(l)}},tu={name:"printenv",summary:"print all or part of environment",usage:"printenv [OPTION]... [VARIABLE]...",options:[" --help display this help and exit"]},ru={name:"printenv",async execute(t,e){if(S(t))return x(tu);let r=t.filter(o=>!o.startsWith("-"));if(r.length===0){let o=[];for(let[i,a]of Object.entries(e.env))o.push(`${i}=${a}`);return{stdout:o.join(`
|
|
293
293
|
`)+(o.length>0?`
|
|
294
294
|
`:""),stderr:"",exitCode:0}}let n=[],s=0;for(let o of r)o in e.env?n.push(e.env[o]):s=1;return{stdout:n.join(`
|
|
295
295
|
`)+(n.length>0?`
|
|
296
|
-
`:""),stderr:"",exitCode:s}}}});var
|
|
296
|
+
`:""),stderr:"",exitCode:s}}}});var br={};I(br,{aliasCommand:()=>su,unaliasCommand:()=>iu});var nu,Ve,su,iu,Er=C(()=>{"use strict";R();nu={name:"alias",summary:"define or display aliases",usage:"alias [name[=value] ...]",options:[" --help display this help and exit"]},Ve="BASH_ALIAS_",su={name:"alias",async execute(t,e){if(S(t))return x(nu);if(t.length===0){let r="";for(let[n,s]of Object.entries(e.env))if(n.startsWith(Ve)){let o=n.slice(Ve.length);r+=`alias ${o}='${s}'
|
|
297
297
|
`}return{stdout:r,stderr:"",exitCode:0}}for(let r of t){let n=r.indexOf("=");if(n===-1){let s=Ve+r;return e.env[s]?{stdout:`alias ${r}='${e.env[s]}'
|
|
298
298
|
`,stderr:"",exitCode:0}:{stdout:"",stderr:`alias: ${r}: not found
|
|
299
|
-
`,exitCode:1}}else{let s=r.slice(0,n),o=r.slice(n+1);(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1)),e.env[Ve+s]=o}}return{stdout:"",stderr:"",exitCode:0}}},
|
|
299
|
+
`,exitCode:1}}else{let s=r.slice(0,n),o=r.slice(n+1);(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1)),e.env[Ve+s]=o}}return{stdout:"",stderr:"",exitCode:0}}},iu={name:"unalias",async execute(t,e){if(S(t))return x({name:"unalias",summary:"remove alias definitions",usage:"unalias name [name ...]",options:["-a remove all aliases"," --help display this help and exit"]});if(t.length===0)return{stdout:"",stderr:`unalias: usage: unalias [-a] name [name ...]
|
|
300
300
|
`,exitCode:1};if(t[0]==="-a"){for(let s of Object.keys(e.env))s.startsWith(Ve)&&delete e.env[s];return{stdout:"",stderr:"",exitCode:0}}let r=!1,n="";for(let s of t){let o=Ve+s;e.env[o]?delete e.env[o]:(n+=`unalias: ${s}: not found
|
|
301
|
-
`,r=!0)}return{stdout:"",stderr:n,exitCode:r?1:0}}}});var
|
|
302
|
-
`}return{stdout:i,stderr:"",exitCode:0}}}});var Wi={};I(Wi,{xargsCommand:()=>
|
|
301
|
+
`,r=!0)}return{stdout:"",stderr:n,exitCode:r?1:0}}}});var Fi={};I(Fi,{historyCommand:()=>au});var ou,Mi,au,Li=C(()=>{"use strict";R();ou={name:"history",summary:"display command history",usage:"history [n]",options:["-c clear the history list"," --help display this help and exit"]},Mi="BASH_HISTORY",au={name:"history",async execute(t,e){if(S(t))return x(ou);let r=e.env[Mi]||"[]",n;try{n=JSON.parse(r)}catch{n=[]}if(t[0]==="-c")return e.env[Mi]="[]",{stdout:"",stderr:"",exitCode:0};let s=n.length;t[0]&&/^\d+$/.test(t[0])&&(s=Math.min(parseInt(t[0],10),n.length));let o=n.length-s,i="";for(let a=o;a<n.length;a++){let c=(a+1).toString().padStart(5," ");i+=`${c} ${n[a]}
|
|
302
|
+
`}return{stdout:i,stderr:"",exitCode:0}}}});var Wi={};I(Wi,{xargsCommand:()=>cu});var lu,cu,_i=C(()=>{"use strict";R();lu={name:"xargs",summary:"build and execute command lines from standard input",usage:"xargs [OPTION]... [COMMAND [INITIAL-ARGS]]",options:["-I REPLACE replace occurrences of REPLACE with input","-n NUM use at most NUM arguments per command line","-P NUM run at most NUM processes at a time","-0, --null items are separated by null, not whitespace","-t, --verbose print commands before executing","-r, --no-run-if-empty do not run command if input is empty"," --help display this help and exit"]},cu={name:"xargs",async execute(t,e){if(S(t))return x(lu);let r=null,n=null,s=null,o=!1,i=!1,a=!1,c=0;for(let y=0;y<t.length;y++){let w=t[y];if(w==="-I"&&y+1<t.length)r=t[++y],c=y+1;else if(w==="-n"&&y+1<t.length)n=parseInt(t[++y],10),c=y+1;else if(w==="-P"&&y+1<t.length)s=parseInt(t[++y],10),c=y+1;else if(w==="-0"||w==="--null")o=!0,c=y+1;else if(w==="-t"||w==="--verbose")i=!0,c=y+1;else if(w==="-r"||w==="--no-run-if-empty")a=!0,c=y+1;else{if(w.startsWith("--"))return O("xargs",w);if(w.startsWith("-")&&w.length>1){for(let $ of w.slice(1))if(!"0trnIP".includes($))return O("xargs",`-${$}`);w.includes("0")&&(o=!0),w.includes("t")&&(i=!0),w.includes("r")&&(a=!0),c=y+1}else if(!w.startsWith("-")){c=y;break}}}let l=t.slice(c);l.length===0&&l.push("echo");let u=o?"\0":/\s+/,f=e.stdin.split(u).map(y=>y.trim()).filter(y=>y.length>0);if(f.length===0)return a?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0};let d="",h="",p=0,b=async y=>{let w=y.join(" ");return i&&(h+=`${w}
|
|
303
303
|
`),e.exec?e.exec(w):{stdout:`${w}
|
|
304
|
-
`,stderr:"",exitCode:0}},g=async y=>{if(s!==null&&s>1)for(let w=0;w<y.length;w+=s){let E=y.slice(w,w+s),$=await Promise.all(E.map(b));for(let A of $)d+=A.stdout,h+=A.stderr,A.exitCode!==0&&(p=A.exitCode)}else for(let w of y){let E=await b(w);d+=E.stdout,h+=E.stderr,E.exitCode!==0&&(p=E.exitCode)}};if(r!==null){let y=f.map(w=>l.map(E=>E.replaceAll(r,w)));await g(y)}else if(n!==null){let y=[];for(let w=0;w<f.length;w+=n){let E=f.slice(w,w+n);y.push([...l,...E])}await g(y)}else{let y=[...l,...f],w=await b(y);d+=w.stdout,h+=w.stderr,p=w.exitCode}return{stdout:d,stderr:h,exitCode:p}}}});var
|
|
304
|
+
`,stderr:"",exitCode:0}},g=async y=>{if(s!==null&&s>1)for(let w=0;w<y.length;w+=s){let E=y.slice(w,w+s),$=await Promise.all(E.map(b));for(let A of $)d+=A.stdout,h+=A.stderr,A.exitCode!==0&&(p=A.exitCode)}else for(let w of y){let E=await b(w);d+=E.stdout,h+=E.stderr,E.exitCode!==0&&(p=E.exitCode)}};if(r!==null){let y=f.map(w=>l.map(E=>E.replaceAll(r,w)));await g(y)}else if(n!==null){let y=[];for(let w=0;w<f.length;w+=n){let E=f.slice(w,w+n);y.push([...l,...E])}await g(y)}else{let y=[...l,...f],w=await b(y);d+=w.stdout,h+=w.stderr,p=w.exitCode}return{stdout:d,stderr:h,exitCode:p}}}});var xr={};I(xr,{falseCommand:()=>fu,trueCommand:()=>uu});var uu,fu,Sr=C(()=>{"use strict";uu={name:"true",async execute(){return{stdout:"",stderr:"",exitCode:0}}},fu={name:"false",async execute(){return{stdout:"",stderr:"",exitCode:1}}}});var Hi={};I(Hi,{clearCommand:()=>hu});var du,hu,Bi=C(()=>{"use strict";R();du={name:"clear",summary:"clear the terminal screen",usage:"clear [OPTIONS]",options:[" --help display this help and exit"]},hu={name:"clear",async execute(t,e){return S(t)?x(du):{stdout:"\x1B[2J\x1B[H",stderr:"",exitCode:0}}}});var Cr={};I(Cr,{bashCommand:()=>pu,shCommand:()=>mu});async function Nt(t,e,r,n){if(!n.exec)return{stdout:"",stderr:`bash: internal error: exec function not available
|
|
305
305
|
`,exitCode:1};let s={0:e,"#":String(r.length),"@":r.join(" "),"*":r.join(" ")};r.forEach((u,f)=>{s[String(f+1)]=u});let o=t;if(o.startsWith("#!")){let u=o.indexOf(`
|
|
306
306
|
`);u!==-1&&(o=o.slice(u+1))}let i=o.split(`
|
|
307
|
-
`),a=[];for(let u of i){let f=u.trim();f&&!f.startsWith("#")&&a.push(f)}let c=a.join("; ");return await n.exec(c,{env:s})}var
|
|
308
|
-
`,exitCode:127}}}},
|
|
309
|
-
`,exitCode:127}}}}});var
|
|
307
|
+
`),a=[];for(let u of i){let f=u.trim();f&&!f.startsWith("#")&&a.push(f)}let c=a.join("; ");return await n.exec(c,{env:s})}var zi,pu,mu,Ar=C(()=>{"use strict";R();zi={name:"bash",summary:"execute shell commands or scripts",usage:"bash [OPTIONS] [SCRIPT_FILE] [ARGUMENTS...]",options:["-c COMMAND execute COMMAND string"," --help display this help and exit"],notes:["Without -c, reads and executes commands from SCRIPT_FILE.","Arguments are passed as $1, $2, etc. to the script.",'$0 is set to the script name (or "bash" with -c).']},pu={name:"bash",async execute(t,e){if(S(t))return x(zi);if(t[0]==="-c"&&t.length>=2){let s=t[1],o=t[2]||"bash",i=t.slice(3);return Nt(s,o,i,e)}if(t.length===0)return{stdout:"",stderr:"",exitCode:0};let r=t[0],n=t.slice(1);try{let s=e.fs.resolvePath(e.cwd,r),o=await e.fs.readFile(s);return Nt(o,r,n,e)}catch{return{stdout:"",stderr:`bash: ${r}: No such file or directory
|
|
308
|
+
`,exitCode:127}}}},mu={name:"sh",async execute(t,e){if(S(t))return x({...zi,name:"sh",summary:"execute shell commands or scripts (POSIX shell)"});if(t[0]==="-c"&&t.length>=2){let s=t[1],o=t[2]||"sh",i=t.slice(3);return Nt(s,o,i,e)}if(t.length===0)return{stdout:"",stderr:"",exitCode:0};let r=t[0],n=t.slice(1);try{let s=e.fs.resolvePath(e.cwd,r),o=await e.fs.readFile(s);return Nt(o,r,n,e)}catch{return{stdout:"",stderr:`sh: ${r}: No such file or directory
|
|
309
|
+
`,exitCode:127}}}}});var Ui={};I(Ui,{jqCommand:()=>yu});function rt(t,e,r,n=0){if(t===null||t===void 0)return"null";if(typeof t=="boolean"||typeof t=="number")return String(t);if(typeof t=="string")return r?t:JSON.stringify(t);if(Array.isArray(t))return t.length===0?"[]":e?`[${t.map(o=>rt(o,!0,!1)).join(",")}]`:`[
|
|
310
310
|
${t.map(o=>" ".repeat(n+1)+rt(o,!1,!1,n+1)).join(`,
|
|
311
311
|
`)}
|
|
312
312
|
${" ".repeat(n)}]`;if(typeof t=="object"){let s=Object.keys(t);return s.length===0?"{}":e?`{${s.map(i=>`${JSON.stringify(i)}:${rt(t[i],!0,!1)}`).join(",")}}`:`{
|
|
313
313
|
${s.map(i=>{let a=rt(t[i],!1,!1,n+1);return`${" ".repeat(n+1)}${JSON.stringify(i)}: ${a}`}).join(`,
|
|
314
314
|
`)}
|
|
315
|
-
${" ".repeat(n)}}`}return String(t)}function Pe(t,e){if(e===""||e===".")return[t];let r=e.startsWith(".")?e.slice(1):e;if(r==="")return[t];if(r.startsWith("[]")){let i=r.slice(2);return Array.isArray(t)?t.flatMap(a=>Pe(a,`.${i}`)):t&&typeof t=="object"?Object.values(t).flatMap(a=>Pe(a,`.${i}`)):[]}let n=r.match(/^\[(-?\d+)\](.*)/);if(n){let i=Number.parseInt(n[1],10),a=n[2];if(Array.isArray(t)){let c=i<0?t.length+i:i;if(c>=0&&c<t.length)return Pe(t[c],`.${a}`)}return[null]}let s=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(.*)/);if(s){let i=s[1],a=s[2];if(t&&typeof t=="object"&&!Array.isArray(t)){let l=t[i];if(a.startsWith("[]"))return a=a.slice(2),Array.isArray(l)?l.flatMap(u=>Pe(u,`.${a}`)):l&&typeof l=="object"?Object.values(l).flatMap(u=>Pe(u,`.${a}`)):[];if(a.startsWith(".")||a.startsWith("[")||a==="")return Pe(l,a||".")}return[null]}let o=r.match(/^\["([^"]+)"\](.*)/);if(o){let i=o[1],a=o[2];return t&&typeof t=="object"&&!Array.isArray(t)?Pe(t[i],`.${a}`):[null]}return[null]}function nt(t,e){let r=e.trim();if(r.includes("|")){let n=r.split("|").map(o=>o.trim()),s=[t];for(let o of n)s=s.flatMap(i=>nt(i,o));return s}return r==="keys"?Array.isArray(t)?[t.map((n,s)=>s)]:t&&typeof t=="object"?[Object.keys(t)]:[null]:r==="values"?Array.isArray(t)?[t]:t&&typeof t=="object"?[Object.values(t)]:[null]:r==="length"?typeof t=="string"?[t.length]:Array.isArray(t)?[t.length]:t&&typeof t=="object"?[Object.keys(t).length]:t===null?[0]:[null]:r==="type"?t===null?["null"]:Array.isArray(t)?["array"]:[typeof t]:r==="first"?Array.isArray(t)&&t.length>0?[t[0]]:[null]:r==="last"?Array.isArray(t)&&t.length>0?[t[t.length-1]]:[null]:r==="reverse"?Array.isArray(t)?[[...t].reverse()]:typeof t=="string"?[t.split("").reverse().join("")]:[null]:r==="sort"?Array.isArray(t)?[[...t].sort()]:[null]:r==="unique"?Array.isArray(t)?[[...new Set(t.map(n=>JSON.stringify(n)))].map(n=>JSON.parse(n))]:[null]:r==="flatten"?Array.isArray(t)?[t.flat()]:[null]:r==="add"?Array.isArray(t)?t.length===0?[null]:t.every(n=>typeof n=="number")?[t.reduce((n,s)=>n+s,0)]:t.every(n=>typeof n=="string")?[t.join("")]:t.every(n=>Array.isArray(n))?[t.flat()]:[null]:[null]:r==="min"?Array.isArray(t)&&t.length>0?[Math.min(...t)]:[null]:r==="max"?Array.isArray(t)&&t.length>0?[Math.max(...t)]:[null]:r==="empty"?[]:r==="not"?[!t]:Pe(t,r)}var
|
|
315
|
+
${" ".repeat(n)}}`}return String(t)}function Pe(t,e){if(e===""||e===".")return[t];let r=e.startsWith(".")?e.slice(1):e;if(r==="")return[t];if(r.startsWith("[]")){let i=r.slice(2);return Array.isArray(t)?t.flatMap(a=>Pe(a,`.${i}`)):t&&typeof t=="object"?Object.values(t).flatMap(a=>Pe(a,`.${i}`)):[]}let n=r.match(/^\[(-?\d+)\](.*)/);if(n){let i=Number.parseInt(n[1],10),a=n[2];if(Array.isArray(t)){let c=i<0?t.length+i:i;if(c>=0&&c<t.length)return Pe(t[c],`.${a}`)}return[null]}let s=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(.*)/);if(s){let i=s[1],a=s[2];if(t&&typeof t=="object"&&!Array.isArray(t)){let l=t[i];if(a.startsWith("[]"))return a=a.slice(2),Array.isArray(l)?l.flatMap(u=>Pe(u,`.${a}`)):l&&typeof l=="object"?Object.values(l).flatMap(u=>Pe(u,`.${a}`)):[];if(a.startsWith(".")||a.startsWith("[")||a==="")return Pe(l,a||".")}return[null]}let o=r.match(/^\["([^"]+)"\](.*)/);if(o){let i=o[1],a=o[2];return t&&typeof t=="object"&&!Array.isArray(t)?Pe(t[i],`.${a}`):[null]}return[null]}function nt(t,e){let r=e.trim();if(r.includes("|")){let n=r.split("|").map(o=>o.trim()),s=[t];for(let o of n)s=s.flatMap(i=>nt(i,o));return s}return r==="keys"?Array.isArray(t)?[t.map((n,s)=>s)]:t&&typeof t=="object"?[Object.keys(t)]:[null]:r==="values"?Array.isArray(t)?[t]:t&&typeof t=="object"?[Object.values(t)]:[null]:r==="length"?typeof t=="string"?[t.length]:Array.isArray(t)?[t.length]:t&&typeof t=="object"?[Object.keys(t).length]:t===null?[0]:[null]:r==="type"?t===null?["null"]:Array.isArray(t)?["array"]:[typeof t]:r==="first"?Array.isArray(t)&&t.length>0?[t[0]]:[null]:r==="last"?Array.isArray(t)&&t.length>0?[t[t.length-1]]:[null]:r==="reverse"?Array.isArray(t)?[[...t].reverse()]:typeof t=="string"?[t.split("").reverse().join("")]:[null]:r==="sort"?Array.isArray(t)?[[...t].sort()]:[null]:r==="unique"?Array.isArray(t)?[[...new Set(t.map(n=>JSON.stringify(n)))].map(n=>JSON.parse(n))]:[null]:r==="flatten"?Array.isArray(t)?[t.flat()]:[null]:r==="add"?Array.isArray(t)?t.length===0?[null]:t.every(n=>typeof n=="number")?[t.reduce((n,s)=>n+s,0)]:t.every(n=>typeof n=="string")?[t.join("")]:t.every(n=>Array.isArray(n))?[t.flat()]:[null]:[null]:r==="min"?Array.isArray(t)&&t.length>0?[Math.min(...t)]:[null]:r==="max"?Array.isArray(t)&&t.length>0?[Math.max(...t)]:[null]:r==="empty"?[]:r==="not"?[!t]:Pe(t,r)}var gu,yu,ji=C(()=>{"use strict";R();gu={name:"jq",summary:"command-line JSON processor",usage:"jq [OPTIONS] FILTER [FILE]",options:["-r, --raw-output output strings without quotes","-c, --compact compact output (no pretty printing)","-e, --exit-status set exit status based on output","-s, --slurp read entire input into array","-n, --null-input don't read any input"," --help display this help and exit"]};yu={name:"jq",async execute(t,e){if(S(t))return x(gu);let r=!1,n=!1,s=!1,o=!1,i=!1,a=".",c=!1,l=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-r"||d==="--raw-output")r=!0;else if(d==="-c"||d==="--compact-output")n=!0;else if(d==="-e"||d==="--exit-status")s=!0;else if(d==="-s"||d==="--slurp")o=!0;else if(d==="-n"||d==="--null-input")i=!0;else if(d==="-")l.push("-");else{if(d.startsWith("--"))return O("jq",d);if(d.startsWith("-"))for(let h of d.slice(1))if(h==="r")r=!0;else if(h==="c")n=!0;else if(h==="e")s=!0;else if(h==="s")o=!0;else if(h==="n")i=!0;else return O("jq",`-${h}`);else c?l.push(d):(a=d,c=!0)}}let u;if(i)u="";else if(l.length===0||l.length===1&&l[0]==="-")u=e.stdin;else try{let f=e.fs.resolvePath(e.cwd,l[0]);u=await e.fs.readFile(f)}catch{return{stdout:"",stderr:`jq: ${l[0]}: No such file or directory
|
|
316
316
|
`,exitCode:2}}try{let f;if(i)f=nt(null,a);else if(o){let p=[];for(let b of u.trim().split(`
|
|
317
317
|
`))b.trim()&&p.push(JSON.parse(b));f=nt(p,a)}else{let p=u.trim();if(p.startsWith("{")||p.startsWith("["))f=nt(JSON.parse(p),a);else{f=[];for(let b of p.split(`
|
|
318
318
|
`))b.trim()&&f.push(...nt(JSON.parse(b),a))}}let d=f.map(p=>rt(p,n,r)).join(`
|
|
319
319
|
`),h=s&&(f.length===0||f.every(p=>p==null||p===!1))?1:0;return{stdout:d?`${d}
|
|
320
320
|
`:"",stderr:"",exitCode:h}}catch(f){return{stdout:"",stderr:`jq: parse error: ${f.message}
|
|
321
|
-
`,exitCode:5}}}}});var
|
|
321
|
+
`,exitCode:5}}}}});var qi={};I(qi,{base64Command:()=>Eu});var wu,bu,Eu,Gi=C(()=>{"use strict";Y();Le();R();wu={name:"base64",summary:"base64 encode/decode data and print to standard output",usage:"base64 [OPTION]... [FILE]",options:["-d, --decode decode data","-w, --wrap=COLS wrap encoded lines after COLS character (default 76, 0 to disable)"," --help display this help and exit"]},bu={decode:{short:"d",long:"decode",type:"boolean"},wrap:{short:"w",long:"wrap",type:"number",default:76}},Eu={name:"base64",async execute(t,e){if(S(t))return x(wu);let r=M("base64",t,bu);if(!r.ok)return r.error;let n=r.result.flags.decode,s=r.result.flags.wrap,o=r.result.positional,i=await Ie(e,o,{cmdName:"base64"});if(!i.ok)return i.error;let a=i.content;try{if(n){let l=a.replace(/\s/g,"");return{stdout:Buffer.from(l,"base64").toString("utf-8"),stderr:"",exitCode:0}}let c=Buffer.from(a).toString("base64");if(s>0){let l=[];for(let u=0;u<c.length;u+=s)l.push(c.slice(u,u+s));c=l.join(`
|
|
322
322
|
`)+(c.length>0?`
|
|
323
323
|
`:"")}return{stdout:c,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`base64: invalid input
|
|
324
|
-
`,exitCode:1}}}}});var
|
|
324
|
+
`,exitCode:1}}}}});var Zi={};I(Zi,{diffCommand:()=>Cu});import*as Vi from"diff";var xu,Su,Cu,Qi=C(()=>{"use strict";Y();R();xu={name:"diff",summary:"compare files line by line",usage:"diff [OPTION]... FILE1 FILE2",options:["-u, --unified output unified diff format (default)","-q, --brief report only whether files differ","-s, --report-identical-files report when files are the same","-i, --ignore-case ignore case differences"," --help display this help and exit"]},Su={unified:{short:"u",long:"unified",type:"boolean"},brief:{short:"q",long:"brief",type:"boolean"},reportSame:{short:"s",long:"report-identical-files",type:"boolean"},ignoreCase:{short:"i",long:"ignore-case",type:"boolean"}},Cu={name:"diff",async execute(t,e){if(S(t))return x(xu);let r=M("diff",t,Su);if(!r.ok)return r.error;let n=r.result.flags.brief,s=r.result.flags.reportSame,o=r.result.flags.ignoreCase,i=r.result.positional;if(r.result.flags.unified,i.length<2)return{stdout:"",stderr:`diff: missing operand
|
|
325
325
|
`,exitCode:2};let a,c,[l,u]=i;try{a=l==="-"?e.stdin:await e.fs.readFile(e.fs.resolvePath(e.cwd,l))}catch{return{stdout:"",stderr:`diff: ${l}: No such file or directory
|
|
326
326
|
`,exitCode:2}}try{c=u==="-"?e.stdin:await e.fs.readFile(e.fs.resolvePath(e.cwd,u))}catch{return{stdout:"",stderr:`diff: ${u}: No such file or directory
|
|
327
327
|
`,exitCode:2}}let f=a,d=c;return o&&(f=f.toLowerCase(),d=d.toLowerCase()),f===d?s?{stdout:`Files ${l} and ${u} are identical
|
|
328
328
|
`,stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0}:n?{stdout:`Files ${l} and ${u} differ
|
|
329
|
-
`,stderr:"",exitCode:1}:{stdout:
|
|
330
|
-
`;break;case"p":s+=n.H<12?"AM":"PM";break;case"P":s+=n.H<12?"am":"pm";break;case"R":s+=`${ne(n.H)}:${ne(n.M)}`;break;case"s":s+=Math.floor(t.getTime()/1e3);break;case"S":s+=ne(n.S);break;case"t":s+=" ";break;case"T":s+=`${ne(n.H)}:${ne(n.M)}:${ne(n.S)}`;break;case"u":s+=n.w||7;break;case"w":s+=n.w;break;case"y":s+=ne(n.Y%100);break;case"Y":s+=n.Y;break;case"z":s+=r?"+0000":
|
|
331
|
-
`,exitCode:1};let c;return s?c=
|
|
332
|
-
`,stderr:"",exitCode:0}}}});var
|
|
329
|
+
`,stderr:"",exitCode:1}:{stdout:Vi.createTwoFilesPatch(l,u,a,c,"","",{context:3}),stderr:"",exitCode:1}}}});var Ki={};I(Ki,{dateCommand:()=>Iu});function ne(t,e=2){return String(t).padStart(e,"0")}function vu(t){let e=-t.getTimezoneOffset();return`${e>=0?"+":"-"}${ne(Math.floor(Math.abs(e)/60))}${ne(Math.abs(e)%60)}`}function vt(t,e,r){let n=r?{Y:t.getUTCFullYear(),m:t.getUTCMonth(),D:t.getUTCDate(),H:t.getUTCHours(),M:t.getUTCMinutes(),S:t.getUTCSeconds(),w:t.getUTCDay()}:{Y:t.getFullYear(),m:t.getMonth(),D:t.getDate(),H:t.getHours(),M:t.getMinutes(),S:t.getSeconds(),w:t.getDay()},s="",o=0;for(;o<e.length;){if(e[o]==="%"&&o+1<e.length){let i=e[++o];switch(i){case"%":s+="%";break;case"a":s+=$u[n.w];break;case"b":case"h":s+=Nu[n.m];break;case"d":s+=ne(n.D);break;case"e":s+=String(n.D).padStart(2," ");break;case"F":s+=`${n.Y}-${ne(n.m+1)}-${ne(n.D)}`;break;case"H":s+=ne(n.H);break;case"I":s+=ne(n.H%12||12);break;case"m":s+=ne(n.m+1);break;case"M":s+=ne(n.M);break;case"n":s+=`
|
|
330
|
+
`;break;case"p":s+=n.H<12?"AM":"PM";break;case"P":s+=n.H<12?"am":"pm";break;case"R":s+=`${ne(n.H)}:${ne(n.M)}`;break;case"s":s+=Math.floor(t.getTime()/1e3);break;case"S":s+=ne(n.S);break;case"t":s+=" ";break;case"T":s+=`${ne(n.H)}:${ne(n.M)}:${ne(n.S)}`;break;case"u":s+=n.w||7;break;case"w":s+=n.w;break;case"y":s+=ne(n.Y%100);break;case"Y":s+=n.Y;break;case"z":s+=r?"+0000":vu(t);break;case"Z":s+=r?"UTC":Intl.DateTimeFormat().resolvedOptions().timeZone;break;default:s+=`%${i}`}}else s+=e[o];o++}return s}function ku(t){let e=new Date(t);if(!Number.isNaN(e.getTime()))return e;if(/^\d+$/.test(t))return new Date(Number.parseInt(t,10)*1e3);let r=t.toLowerCase();return r==="now"||r==="today"?new Date:r==="yesterday"?new Date(Date.now()-864e5):r==="tomorrow"?new Date(Date.now()+864e5):null}var Au,$u,Nu,Iu,Xi=C(()=>{"use strict";R();Au={name:"date",summary:"display the current time in the given FORMAT",usage:"date [OPTION]... [+FORMAT]",options:["-d, --date=STRING display time described by STRING","-u, --utc print Coordinated Universal Time (UTC)","-I, --iso-8601 output date/time in ISO 8601 format","-R, --rfc-email output RFC 5322 date format"," --help display this help and exit"]},$u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Nu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Iu={name:"date",async execute(t,e){if(S(t))return x(Au);let r=!1,n=null,s=null,o=!1,i=!1;for(let l=0;l<t.length;l++){let u=t[l];if(u==="-u"||u==="--utc")r=!0;else if(u==="-d"||u==="--date")n=t[++l]??"";else if(u.startsWith("--date="))n=u.slice(7);else if(u==="-I"||u==="--iso-8601")o=!0;else if(u==="-R"||u==="--rfc-email")i=!0;else if(u.startsWith("+"))s=u.slice(1);else{if(u.startsWith("--"))return O("date",u);if(u.startsWith("-"))for(let f of u.slice(1))if(f==="u")r=!0;else if(f==="I")o=!0;else if(f==="R")i=!0;else return O("date",`-${f}`)}}let a=n!==null?ku(n):new Date;if(!a)return{stdout:"",stderr:`date: invalid date '${n}'
|
|
331
|
+
`,exitCode:1};let c;return s?c=vt(a,s,r):o?c=vt(a,"%Y-%m-%dT%H:%M:%S%z",r):i?c=vt(a,"%a, %d %b %Y %H:%M:%S %z",r):c=vt(a,"%a %b %e %H:%M:%S %Z %Y",r),{stdout:`${c}
|
|
332
|
+
`,stderr:"",exitCode:0}}}});var Yi={};I(Yi,{sleepCommand:()=>Ou});function Ru(t){let e=t.match(/^(\d+\.?\d*)(s|m|h|d)?$/);if(!e)return null;let r=parseFloat(e[1]);switch(e[2]||"s"){case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;case"d":return r*24*60*60*1e3;default:return null}}var Pu,Ou,Ji=C(()=>{"use strict";R();Pu={name:"sleep",summary:"delay for a specified amount of time",usage:"sleep NUMBER[SUFFIX]",description:`Pause for NUMBER seconds. SUFFIX may be:
|
|
333
333
|
s - seconds (default)
|
|
334
334
|
m - minutes
|
|
335
335
|
h - hours
|
|
336
336
|
d - days
|
|
337
337
|
|
|
338
|
-
NUMBER may be a decimal number.`,options:[" --help display this help and exit"]};
|
|
339
|
-
`,exitCode:1};let r=0;for(let n of t){let s=
|
|
340
|
-
`,exitCode:1};r+=s}return e.sleep?await e.sleep(r):await new Promise(n=>setTimeout(n,r)),{stdout:"",stderr:"",exitCode:0}}}});var
|
|
338
|
+
NUMBER may be a decimal number.`,options:[" --help display this help and exit"]};Ou={name:"sleep",async execute(t,e){if(S(t))return x(Pu);if(t.length===0)return{stdout:"",stderr:`sleep: missing operand
|
|
339
|
+
`,exitCode:1};let r=0;for(let n of t){let s=Ru(n);if(s===null)return{stdout:"",stderr:`sleep: invalid time interval '${n}'
|
|
340
|
+
`,exitCode:1};r+=s}return e.sleep?await e.sleep(r):await new Promise(n=>setTimeout(n,r)),{stdout:"",stderr:"",exitCode:0}}}});var eo={};I(eo,{timeoutCommand:()=>Mu});function Tu(t){let e=t.match(/^(\d+\.?\d*)(s|m|h|d)?$/);if(!e)return null;let r=parseFloat(e[1]);switch(e[2]||"s"){case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;case"d":return r*24*60*60*1e3;default:return null}}var Du,Mu,to=C(()=>{"use strict";R();Du={name:"timeout",summary:"run a command with a time limit",usage:"timeout [OPTION] DURATION COMMAND [ARG]...",description:`Start COMMAND, and kill it if still running after DURATION.
|
|
341
341
|
|
|
342
342
|
DURATION is a number with optional suffix:
|
|
343
343
|
s - seconds (default)
|
|
344
344
|
m - minutes
|
|
345
345
|
h - hours
|
|
346
|
-
d - days`,options:["-k, --kill-after=DURATION send KILL signal after DURATION if still running","-s, --signal=SIGNAL specify signal to send (default: TERM)"," --preserve-status exit with same status as COMMAND, even on timeout"," --foreground run command in foreground"," --help display this help and exit"]};
|
|
347
|
-
`,exitCode:1};let o=s[0],i=
|
|
346
|
+
d - days`,options:["-k, --kill-after=DURATION send KILL signal after DURATION if still running","-s, --signal=SIGNAL specify signal to send (default: TERM)"," --preserve-status exit with same status as COMMAND, even on timeout"," --foreground run command in foreground"," --help display this help and exit"]};Mu={name:"timeout",async execute(t,e){if(S(t))return x(Du);let r=!1,n=0;for(let d=0;d<t.length;d++){let h=t[d];if(h==="--preserve-status")r=!0,n=d+1;else if(h==="--foreground")n=d+1;else if(h==="-k"||h==="--kill-after")d++,n=d+1;else if(h.startsWith("--kill-after="))n=d+1;else if(h==="-s"||h==="--signal")d++,n=d+1;else if(h.startsWith("--signal="))n=d+1;else{if(h.startsWith("--")&&h!=="--")return O("timeout",h);if(h.startsWith("-")&&h.length>1&&h!=="--")if(h.startsWith("-k"))n=d+1;else if(h.startsWith("-s"))n=d+1;else return O("timeout",h);else{n=d;break}}}let s=t.slice(n);if(s.length===0)return{stdout:"",stderr:`timeout: missing operand
|
|
347
|
+
`,exitCode:1};let o=s[0],i=Tu(o);if(i===null)return{stdout:"",stderr:`timeout: invalid time interval '${o}'
|
|
348
348
|
`,exitCode:1};let a=s.slice(1);if(a.length===0)return{stdout:"",stderr:`timeout: missing operand
|
|
349
349
|
`,exitCode:1};if(!e.exec)return{stdout:"",stderr:`timeout: exec not available
|
|
350
|
-
`,exitCode:1};let c=a.map(d=>d.includes(" ")||d.includes(" ")?`'${d.replace(/'/g,"'\\''")}'`:d).join(" "),l=new Promise(d=>{setTimeout(()=>d({timedOut:!0}),i)}),u=e.exec(c).then(d=>({timedOut:!1,result:d})),f=await Promise.race([l,u]);return f.timedOut?{stdout:"",stderr:"",exitCode:124}:f.result}}});var
|
|
350
|
+
`,exitCode:1};let c=a.map(d=>d.includes(" ")||d.includes(" ")?`'${d.replace(/'/g,"'\\''")}'`:d).join(" "),l=new Promise(d=>{setTimeout(()=>d({timedOut:!0}),i)}),u=e.exec(c).then(d=>({timedOut:!1,result:d})),f=await Promise.race([l,u]);return f.timedOut?{stdout:"",stderr:"",exitCode:124}:f.result}}});var ro={};I(ro,{seqCommand:()=>Fu});var Fu,no=C(()=>{"use strict";Fu={name:"seq",async execute(t){let e=`
|
|
351
351
|
`,r=!1,n=[],s=0;for(;s<t.length;){let p=t[s];if(p==="-s"&&s+1<t.length){e=t[s+1],s+=2;continue}if(p==="-w"){r=!0,s++;continue}if(p==="--"){s++;break}if(p.startsWith("-")&&p!=="-"){if(p.startsWith("-s")&&p.length>2){e=p.slice(2),s++;continue}if((p==="-ws"||p==="-sw")&&(r=!0,s+1<t.length)){e=t[s+1],s+=2;continue}}n.push(p),s++}for(;s<t.length;)n.push(t[s]),s++;if(n.length===0)return{stdout:"",stderr:`seq: missing operand
|
|
352
352
|
`,exitCode:1};let o=1,i=1,a;if(n.length===1?a=parseFloat(n[0]):n.length===2?(o=parseFloat(n[0]),a=parseFloat(n[1])):(o=parseFloat(n[0]),i=parseFloat(n[1]),a=parseFloat(n[2])),Number.isNaN(o)||Number.isNaN(i)||Number.isNaN(a))return{stdout:"",stderr:`seq: invalid floating point argument: '${n.find(b=>Number.isNaN(parseFloat(b)))}'
|
|
353
353
|
`,exitCode:1};if(i===0)return{stdout:"",stderr:`seq: invalid Zero increment value: '0'
|
|
354
354
|
`,exitCode:1};let c=[],l=p=>{let b=String(p),g=b.indexOf(".");return g===-1?0:b.length-g-1},u=Math.max(l(o),l(i),l(a)),f=1e5,d=0;if(i>0)for(let p=o;p<=a+1e-10&&!(d++>f);p+=i)c.push(u>0?p.toFixed(u):String(Math.round(p)));else for(let p=o;p>=a-1e-10&&!(d++>f);p+=i)c.push(u>0?p.toFixed(u):String(Math.round(p)));if(r&&c.length>0){let p=Math.max(...c.map(b=>b.replace("-","").length));for(let b=0;b<c.length;b++){let g=c[b].startsWith("-"),w=(g?c[b].slice(1):c[b]).padStart(p,"0");c[b]=g?`-${w}`:w}}let h=c.join(e);return{stdout:h?`${h}
|
|
355
|
-
`:"",stderr:"",exitCode:0}}}});var
|
|
356
|
-
`,exitCode:2};try{let r=
|
|
355
|
+
`:"",stderr:"",exitCode:0}}}});var so={};I(so,{exprCommand:()=>Lu});function Wu(t){if(t.length===1)return t[0];let e=0;function r(){let l=n();for(;e<t.length&&t[e]==="|";){e++;let u=n();if(l!=="0"&&l!=="")return l;l=u}return l}function n(){let l=s();for(;e<t.length&&t[e]==="&";){e++;let u=s();(l==="0"||l===""||u==="0"||u==="")&&(l="0")}return l}function s(){let l=o();for(;e<t.length;){let u=t[e];if(["=","!=","<",">","<=",">="].includes(u)){e++;let f=o(),d=parseInt(l,10),h=parseInt(f,10),p=!Number.isNaN(d)&&!Number.isNaN(h),b;u==="="?b=p?d===h:l===f:u==="!="?b=p?d!==h:l!==f:u==="<"?b=p?d<h:l<f:u===">"?b=p?d>h:l>f:u==="<="?b=p?d<=h:l<=f:b=p?d>=h:l>=f,l=b?"1":"0"}else break}return l}function o(){let l=i();for(;e<t.length;){let u=t[e];if(u==="+"||u==="-"){e++;let f=i(),d=parseInt(l,10),h=parseInt(f,10);if(Number.isNaN(d)||Number.isNaN(h))throw new Error("non-integer argument");l=String(u==="+"?d+h:d-h)}else break}return l}function i(){let l=a();for(;e<t.length;){let u=t[e];if(u==="*"||u==="/"||u==="%"){e++;let f=a(),d=parseInt(l,10),h=parseInt(f,10);if(Number.isNaN(d)||Number.isNaN(h))throw new Error("non-integer argument");if((u==="/"||u==="%")&&h===0)throw new Error("division by zero");u==="*"?l=String(d*h):u==="/"?l=String(Math.trunc(d/h)):l=String(d%h)}else break}return l}function a(){let l=c();for(;e<t.length&&t[e]===":";){e++;let u=c(),f=new RegExp(`^${u}`),d=l.match(f);d?l=d[1]!==void 0?d[1]:String(d[0].length):l="0"}return l}function c(){if(e>=t.length)throw new Error("syntax error");let l=t[e];if(l==="match"){e++;let u=c(),f=c(),d=new RegExp(f),h=u.match(d);return h?h[1]!==void 0?h[1]:String(h[0].length):"0"}if(l==="substr"){e++;let u=c(),f=parseInt(c(),10),d=parseInt(c(),10);if(Number.isNaN(f)||Number.isNaN(d))throw new Error("non-integer argument");return u.substring(f-1,f-1+d)}if(l==="index"){e++;let u=c(),f=c();for(let d=0;d<u.length;d++)if(f.includes(u[d]))return String(d+1);return"0"}if(l==="length"){e++;let u=c();return String(u.length)}if(l==="("){e++;let u=r();if(e>=t.length||t[e]!==")")throw new Error("syntax error");return e++,u}return e++,l}return r()}var Lu,io=C(()=>{"use strict";Lu={name:"expr",async execute(t,e){if(t.length===0)return{stdout:"",stderr:`expr: missing operand
|
|
356
|
+
`,exitCode:2};try{let r=Wu(t),n=r==="0"||r===""?1:0;return{stdout:`${r}
|
|
357
357
|
`,stderr:"",exitCode:n}}catch(r){return{stdout:"",stderr:`expr: ${r.message}
|
|
358
|
-
`,exitCode:2}}}}});var
|
|
359
|
-
`,exitCode:1}}if(!a.trim())return{stdout:"",stderr:"",exitCode:0};try{let c=new
|
|
358
|
+
`,exitCode:2}}}}});var oo={};I(oo,{htmlToMarkdownCommand:()=>Bu});import _u from"turndown";var Hu,Bu,ao=C(()=>{"use strict";R();Hu={name:"html-to-markdown",summary:"convert HTML to Markdown (BashEnv extension)",usage:"html-to-markdown [OPTION]... [FILE]",description:["Convert HTML content to Markdown format using the turndown library.","This is a non-standard BashEnv extension command, not available in regular bash.","","Read HTML from FILE or standard input and output Markdown to standard output.","Commonly used with curl to convert web pages:"," curl -s https://example.com | html-to-markdown","","Supported HTML elements:"," - Headings (h1-h6) \u2192 # Markdown headings"," - Paragraphs (p) \u2192 Plain text with blank lines"," - Links (a) \u2192 [text](url)"," - Images (img) \u2192 "," - Bold/Strong \u2192 **text**"," - Italic/Em \u2192 _text_"," - Code (code, pre) \u2192 `inline` or fenced blocks"," - Lists (ul, ol, li) \u2192 - or 1. items"," - Blockquotes \u2192 > quoted text"," - Horizontal rules (hr) \u2192 ---"],options:["-b, --bullet=CHAR bullet character for unordered lists (-, +, or *)","-c, --code=FENCE fence style for code blocks (``` or ~~~)","-r, --hr=STRING string for horizontal rules (default: ---)"," --heading-style=STYLE"," heading style: 'atx' for # headings (default),"," 'setext' for underlined headings (h1/h2 only)"," --help display this help and exit"],examples:["echo '<h1>Hello</h1><p>World</p>' | html-to-markdown","html-to-markdown page.html","curl -s https://example.com | html-to-markdown > page.md"]},Bu={name:"html-to-markdown",async execute(t,e){if(S(t))return x(Hu);let r="-",n="```",s="---",o="atx",i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="-b"||l==="--bullet")r=t[++c]??"-";else if(l.startsWith("--bullet="))r=l.slice(9);else if(l==="-c"||l==="--code")n=t[++c]??"```";else if(l.startsWith("--code="))n=l.slice(7);else if(l==="-r"||l==="--hr")s=t[++c]??"---";else if(l.startsWith("--hr="))s=l.slice(5);else if(l.startsWith("--heading-style=")){let u=l.slice(16);(u==="setext"||u==="atx")&&(o=u)}else if(l==="-")i.push("-");else{if(l.startsWith("--"))return O("html-to-markdown",l);if(l.startsWith("-"))return O("html-to-markdown",l);i.push(l)}}let a;if(i.length===0||i.length===1&&i[0]==="-")a=e.stdin;else try{let c=e.fs.resolvePath(e.cwd,i[0]);a=await e.fs.readFile(c)}catch{return{stdout:"",stderr:`html-to-markdown: ${i[0]}: No such file or directory
|
|
359
|
+
`,exitCode:1}}if(!a.trim())return{stdout:"",stderr:"",exitCode:0};try{let c=new _u({bulletListMarker:r,codeBlockStyle:"fenced",fence:n,hr:s,headingStyle:o});return c.remove(["script","style","footer"]),{stdout:`${c.turndown(a).trim()}
|
|
360
360
|
`,stderr:"",exitCode:0}}catch(c){return{stdout:"",stderr:`html-to-markdown: conversion error: ${c.message}
|
|
361
|
-
`,exitCode:1}}}}});var
|
|
362
|
-
`);let n=[];for(let[s,o]of Object.entries(
|
|
361
|
+
`,exitCode:1}}}}});var lo={};I(lo,{helpCommand:()=>ju});function Uu(t){let e=[],r=new Set(t);e.push(`Available commands:
|
|
362
|
+
`);let n=[];for(let[s,o]of Object.entries(zu)){let i=o.filter(a=>r.has(a));if(i.length>0){e.push(` ${s}:`),e.push(` ${i.join(", ")}
|
|
363
363
|
`);for(let a of i)r.delete(a)}}for(let s of r)n.push(s);return n.length>0&&(e.push(" Other:"),e.push(` ${n.sort().join(", ")}
|
|
364
364
|
`)),e.push("Use '<command> --help' for details on a specific command."),`${e.join(`
|
|
365
365
|
`)}
|
|
366
|
-
`}var
|
|
366
|
+
`}var zu,ju,co=C(()=>{"use strict";zu={"File operations":["ls","cat","head","tail","wc","touch","mkdir","rm","cp","mv","ln","chmod","stat","readlink"],"Text processing":["grep","sed","awk","sort","uniq","cut","tr","tee","diff"],Search:["find"],"Navigation & paths":["pwd","basename","dirname","tree","du"],"Environment & shell":["echo","printf","env","printenv","export","alias","unalias","history","clear","true","false","bash","sh"],"Data processing":["xargs","jq","base64","date"],Network:["curl","html-to-markdown"]};ju={name:"help",async execute(t,e){if(t.includes("--help")||t.includes("-h"))return{stdout:`help - display available commands
|
|
367
367
|
|
|
368
368
|
Usage: help [command]
|
|
369
369
|
|
|
@@ -372,49 +372,49 @@ Options:
|
|
|
372
372
|
|
|
373
373
|
If a command name is provided, shows help for that command.
|
|
374
374
|
Otherwise, lists all available commands.
|
|
375
|
-
`,stderr:"",exitCode:0};if(t.length>0&&e.exec){let n=t[0];return e.exec(`${n} --help`)}let r=e.getRegisteredCommands?.()??[];return{stdout:
|
|
376
|
-
`),!n))break}f||(l=!1)}return{stdout:c,stderr:"",exitCode:l?0:1}}}});function
|
|
375
|
+
`,stderr:"",exitCode:0};if(t.length>0&&e.exec){let n=t[0];return e.exec(`${n} --help`)}let r=e.getRegisteredCommands?.()??[];return{stdout:Uu(r),stderr:"",exitCode:0}}}});var uo={};I(uo,{whichCommand:()=>Vu});var qu,Gu,Vu,fo=C(()=>{"use strict";Y();R();qu={name:"which",summary:"locate a command",usage:"which [-as] program ...",options:["-a List all instances of executables found","-s No output, just return 0 if found, 1 if not","--help display this help and exit"]},Gu={showAll:{short:"a",type:"boolean"},silent:{short:"s",type:"boolean"}},Vu={name:"which",async execute(t,e){if(S(t))return x(qu);let r=M("which",t,Gu);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.silent,o=r.result.positional;if(o.length===0)return{stdout:"",stderr:"",exitCode:1};let a=(e.env.PATH||"/bin:/usr/bin").split(":"),c="",l=!0;for(let u of o){let f=!1;for(let d of a){if(!d)continue;let h=`${d}/${u}`;if(await e.fs.exists(h)&&(f=!0,s||(c+=`${h}
|
|
376
|
+
`),!n))break}f||(l=!1)}return{stdout:c,stderr:"",exitCode:l?0:1}}}});function $r(t){let e=t.indexOf("=");if(e>=0){let r=t.slice(0,e),n=t.slice(e+1);return r?`${encodeURIComponent(r)}=${encodeURIComponent(n)}`:encodeURIComponent(n)}return encodeURIComponent(t)}function Nr(t){let e=t.indexOf("=");if(e<0)return null;let r=t.slice(0,e),n=t.slice(e+1),s,o,i=n.match(/;type=([^;]+)$/);i&&(o=i[1],n=n.slice(0,-i[0].length));let a=n.match(/;filename=([^;]+)/);return a&&(s=a[1],n=n.replace(a[0],"")),(n.startsWith("@")||n.startsWith("<"))&&(s=s??n.slice(1).split("/").pop()),{name:r,value:n,filename:s,contentType:o}}function ho(t,e){let r=`----CurlFormBoundary${Date.now().toString(36)}`,n=[];for(let s of t){let o=s.value;if(o.startsWith("@")||o.startsWith("<")){let a=o.slice(1);o=e.get(a)??""}let i=`--${r}\r
|
|
377
377
|
`;s.filename?(i+=`Content-Disposition: form-data; name="${s.name}"; filename="${s.filename}"\r
|
|
378
378
|
`,s.contentType&&(i+=`Content-Type: ${s.contentType}\r
|
|
379
379
|
`)):i+=`Content-Disposition: form-data; name="${s.name}"\r
|
|
380
380
|
`,i+=`\r
|
|
381
381
|
${o}\r
|
|
382
382
|
`,n.push(i)}return n.push(`--${r}--\r
|
|
383
|
-
`),{body:n.join(""),boundary:r}}var
|
|
384
|
-
`)}function
|
|
385
|
-
`),r}var
|
|
383
|
+
`),{body:n.join(""),boundary:r}}var vr=C(()=>{"use strict"});var po,mo=C(()=>{"use strict";po={name:"curl",summary:"transfer a URL",usage:"curl [OPTIONS] URL",options:["-X, --request METHOD HTTP method (GET, POST, PUT, DELETE, etc.)","-H, --header HEADER Add header (can be used multiple times)","-d, --data DATA HTTP POST data"," --data-raw DATA HTTP POST data (no @ interpretation)"," --data-binary DATA HTTP POST binary data"," --data-urlencode DATA URL-encode and POST data","-F, --form NAME=VALUE Multipart form data","-u, --user USER:PASS HTTP authentication","-A, --user-agent STR Set User-Agent header","-e, --referer URL Set Referer header","-b, --cookie DATA Send cookies (name=value or @file)","-c, --cookie-jar FILE Save cookies to file","-T, --upload-file FILE Upload file (PUT)","-o, --output FILE Write output to file","-O, --remote-name Write to file named from URL","-I, --head Show headers only (HEAD request)","-i, --include Include response headers in output","-s, --silent Silent mode (no progress)","-S, --show-error Show errors even when silent","-f, --fail Fail silently on HTTP errors (no output)","-L, --location Follow redirects (default)"," --max-redirs NUM Maximum redirects (default: 20)","-m, --max-time SECS Maximum time for request"," --connect-timeout SECS Connection timeout","-w, --write-out FMT Output format after completion","-v, --verbose Verbose output"," --help Display this help and exit","","Note: Network access must be configured via BashEnv network option."," curl is not available by default for security reasons."]}});function go(t){let e={method:"GET",headers:{},dataBinary:!1,formFields:[],useRemoteName:!1,headOnly:!1,includeHeaders:!1,silent:!1,showError:!1,failSilently:!1,followRedirects:!0,verbose:!1};for(let r=0;r<t.length;r++){let n=t[r];if(n==="-X"||n==="--request")e.method=t[++r]??"GET";else if(n.startsWith("-X"))e.method=n.slice(2);else if(n.startsWith("--request="))e.method=n.slice(10);else if(n==="-H"||n==="--header"){let s=t[++r];if(s){let o=s.indexOf(":");if(o>0){let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();e.headers[i]=a}}}else if(n.startsWith("--header=")){let s=n.slice(9),o=s.indexOf(":");if(o>0){let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();e.headers[i]=a}}else if(n==="-d"||n==="--data"||n==="--data-raw")e.data=t[++r]??"",e.method==="GET"&&(e.method="POST");else if(n.startsWith("-d"))e.data=n.slice(2),e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data="))e.data=n.slice(7),e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data-raw="))e.data=n.slice(11),e.method==="GET"&&(e.method="POST");else if(n==="--data-binary")e.data=t[++r]??"",e.dataBinary=!0,e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data-binary="))e.data=n.slice(14),e.dataBinary=!0,e.method==="GET"&&(e.method="POST");else if(n==="--data-urlencode"){let s=t[++r]??"";e.data=(e.data?`${e.data}&`:"")+$r(s),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--data-urlencode=")){let s=n.slice(17);e.data=(e.data?`${e.data}&`:"")+$r(s),e.method==="GET"&&(e.method="POST")}else if(n==="-F"||n==="--form"){let s=t[++r]??"",o=Nr(s);o&&e.formFields.push(o),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--form=")){let s=n.slice(7),o=Nr(s);o&&e.formFields.push(o),e.method==="GET"&&(e.method="POST")}else if(n==="-u"||n==="--user")e.user=t[++r];else if(n.startsWith("-u"))e.user=n.slice(2);else if(n.startsWith("--user="))e.user=n.slice(7);else if(n==="-A"||n==="--user-agent")e.headers["User-Agent"]=t[++r]??"";else if(n.startsWith("-A"))e.headers["User-Agent"]=n.slice(2);else if(n.startsWith("--user-agent="))e.headers["User-Agent"]=n.slice(13);else if(n==="-e"||n==="--referer")e.headers.Referer=t[++r]??"";else if(n.startsWith("-e"))e.headers.Referer=n.slice(2);else if(n.startsWith("--referer="))e.headers.Referer=n.slice(10);else if(n==="-b"||n==="--cookie")e.headers.Cookie=t[++r]??"";else if(n.startsWith("-b"))e.headers.Cookie=n.slice(2);else if(n.startsWith("--cookie="))e.headers.Cookie=n.slice(9);else if(n==="-c"||n==="--cookie-jar")e.cookieJar=t[++r];else if(n.startsWith("--cookie-jar="))e.cookieJar=n.slice(13);else if(n==="-T"||n==="--upload-file")e.uploadFile=t[++r],e.method==="GET"&&(e.method="PUT");else if(n.startsWith("--upload-file="))e.uploadFile=n.slice(14),e.method==="GET"&&(e.method="PUT");else if(n==="-m"||n==="--max-time"){let s=parseFloat(t[++r]??"0");!Number.isNaN(s)&&s>0&&(e.timeoutMs=s*1e3)}else if(n.startsWith("--max-time=")){let s=parseFloat(n.slice(11));!Number.isNaN(s)&&s>0&&(e.timeoutMs=s*1e3)}else if(n==="--connect-timeout"){let s=parseFloat(t[++r]??"0");!Number.isNaN(s)&&s>0&&e.timeoutMs===void 0&&(e.timeoutMs=s*1e3)}else if(n.startsWith("--connect-timeout=")){let s=parseFloat(n.slice(18));!Number.isNaN(s)&&s>0&&e.timeoutMs===void 0&&(e.timeoutMs=s*1e3)}else if(n==="-o"||n==="--output")e.outputFile=t[++r];else if(n.startsWith("--output="))e.outputFile=n.slice(9);else if(n==="-O"||n==="--remote-name")e.useRemoteName=!0;else if(n==="-I"||n==="--head")e.headOnly=!0,e.method="HEAD";else if(n==="-i"||n==="--include")e.includeHeaders=!0;else if(n==="-s"||n==="--silent")e.silent=!0;else if(n==="-S"||n==="--show-error")e.showError=!0;else if(n==="-f"||n==="--fail")e.failSilently=!0;else if(n==="-L"||n==="--location")e.followRedirects=!0;else if(n==="--max-redirs")r++;else if(!n.startsWith("--max-redirs="))if(n==="-w"||n==="--write-out")e.writeOut=t[++r];else if(n.startsWith("--write-out="))e.writeOut=n.slice(12);else if(n==="-v"||n==="--verbose")e.verbose=!0;else{if(n.startsWith("--")&&n!=="--")return O("curl",n);if(n.startsWith("-")&&n!=="-")for(let s of n.slice(1))switch(s){case"s":e.silent=!0;break;case"S":e.showError=!0;break;case"f":e.failSilently=!0;break;case"L":e.followRedirects=!0;break;case"I":e.headOnly=!0,e.method="HEAD";break;case"i":e.includeHeaders=!0;break;case"O":e.useRemoteName=!0;break;case"v":e.verbose=!0;break;default:return O("curl",`-${s}`)}else n.startsWith("-")||(e.url=n)}}return e}var yo=C(()=>{"use strict";R();vr()});function kr(t){return Object.entries(t).map(([e,r])=>`${e}: ${r}`).join(`\r
|
|
384
|
+
`)}function wo(t){try{return new URL(t).pathname.split("/").pop()||"index.html"}catch{return"index.html"}}function Ir(t,e){let r=t;return r=r.replace(/%\{http_code\}/g,String(e.status)),r=r.replace(/%\{content_type\}/g,e.headers["content-type"]||""),r=r.replace(/%\{url_effective\}/g,e.url),r=r.replace(/%\{size_download\}/g,String(e.bodyLength)),r=r.replace(/\\n/g,`
|
|
385
|
+
`),r}var bo=C(()=>{"use strict"});var Eo={};I(Eo,{curlCommand:()=>Yu});async function Zu(t,e){if(t.uploadFile){let r=e.fs.resolvePath(e.cwd,t.uploadFile);return{body:await e.fs.readFile(r)}}if(t.formFields.length>0){let r=new Map;for(let o of t.formFields)if(o.value.startsWith("@")||o.value.startsWith("<")){let i=e.fs.resolvePath(e.cwd,o.value.slice(1));try{let a=await e.fs.readFile(i);r.set(o.value.slice(1),a)}catch{r.set(o.value.slice(1),"")}}let{body:n,boundary:s}=ho(t.formFields,r);return{body:n,contentType:`multipart/form-data; boundary=${s}`}}return t.data!==void 0?{body:t.data}:{}}function Qu(t,e){let r={...t.headers};if(t.user){let n=Buffer.from(t.user).toString("base64");r.Authorization=`Basic ${n}`}return e&&!r["Content-Type"]&&(r["Content-Type"]=e),r}async function Ku(t,e,r){if(!t.cookieJar)return;let n=e["set-cookie"];if(!n)return;let s=r.fs.resolvePath(r.cwd,t.cookieJar);await r.fs.writeFile(s,n)}function Xu(t,e,r){let n="";if(t.verbose){n+=`> ${t.method} ${r}
|
|
386
386
|
`;for(let[s,o]of Object.entries(t.headers))n+=`> ${s}: ${o}
|
|
387
387
|
`;n+=`>
|
|
388
388
|
`,n+=`< HTTP/1.1 ${e.status} ${e.statusText}
|
|
389
389
|
`;for(let[s,o]of Object.entries(e.headers))n+=`< ${s}: ${o}
|
|
390
390
|
`;n+=`<
|
|
391
391
|
`}return t.includeHeaders&&!t.verbose&&(n+=`HTTP/1.1 ${e.status} ${e.statusText}\r
|
|
392
|
-
`,n+=
|
|
392
|
+
`,n+=kr(e.headers),n+=`\r
|
|
393
393
|
\r
|
|
394
394
|
`),t.headOnly?t.includeHeaders||t.verbose||(n+=`HTTP/1.1 ${e.status} ${e.statusText}\r
|
|
395
|
-
`,n+=
|
|
396
|
-
`):n+=e.body,t.writeOut&&(n+=
|
|
395
|
+
`,n+=kr(e.headers),n+=`\r
|
|
396
|
+
`):n+=e.body,t.writeOut&&(n+=Ir(t.writeOut,{status:e.status,headers:e.headers,url:e.url,bodyLength:e.body.length})),n}var Yu,xo=C(()=>{"use strict";ye();R();vr();mo();yo();bo();Yu={name:"curl",async execute(t,e){if(S(t))return x(po);let r=go(t);if("exitCode"in r)return r;let n=r;if(!n.url)return{stdout:"",stderr:`curl: no URL specified
|
|
397
397
|
`,exitCode:2};if(!e.fetch)return{stdout:"",stderr:`curl: internal error: fetch not available
|
|
398
|
-
`,exitCode:1};let s=n.url;s.match(/^https?:\/\//)||(s=`https://${s}`);try{let{body:o,contentType:i}=await
|
|
399
|
-
`:"",exitCode:22};let l=
|
|
400
|
-
`:"",exitCode:a}}}}});import{tool as ld,zodSchema as cd}from"ai";import{z as Ba}from"zod";var xo=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(Nn(),$n))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(kn(),vn))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(Rn(),Pn))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(Mn(),Tn))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(Wn(),Fn))).mkdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(_n(),Ln))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(Bn(),Hn))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(Un(),zn))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(qn(),jn))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>(Vn(),Gn))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(Kn(),Qn))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>(Yn(),Xn))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(es(),Jn))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(ss(),ns))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(os(),is))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(cs(),ls))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(ds(),fs))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(Ct(),St))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(Ct(),St))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(Ct(),St))).egrepCommand},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(vs(),Ns))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(Js(),Ys))).awkCommand},{name:"sort",load:async()=>(await Promise.resolve().then(()=>(ii(),si))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(ai(),oi))).uniqCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(ci(),li))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(di(),fi))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(mi(),pi))).trCommand},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(yi(),gi))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(Ci(),Si))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>($i(),Ai))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(vi(),Ni))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(Pi(),Ii))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(Di(),Oi))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(yr(),gr))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(yr(),gr))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(br(),wr))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(br(),wr))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(Fi(),Mi))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(Li(),Wi))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(xr(),Er))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(xr(),Er))).falseCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(Hi(),_i))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(Cr(),Sr))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(Cr(),Sr))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(Ui(),zi))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(qi(),ji))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(Zi(),Vi))).diffCommand},{name:"date",load:async()=>(await Promise.resolve().then(()=>(Ki(),Qi))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(Yi(),Xi))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>(eo(),Ji))).timeoutCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(ro(),to))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(so(),no))).exprCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>(oo(),io))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(lo(),ao))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(uo(),co))).whichCommand}],Ku=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(Eo(),bo))).curlCommand}],So=new Map;function Co(t){return{name:t.name,async execute(e,r){let n=So.get(t.name);return n||(n=await t.load(),So.set(t.name,n)),n.execute(e,r)}}}function Ao(t){return(t?xo.filter(r=>t.includes(r.name)):xo).map(Co)}function $o(){return Ku.map(Co)}var st=new TextEncoder,Xu=new TextDecoder;function No(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),r=>r.charCodeAt(0));case"hex":{let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=parseInt(t.slice(n,n+2),16);return r}case"binary":case"latin1":return Uint8Array.from(t,r=>r.charCodeAt(0));default:return st.encode(t)}}function Yu(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return Xu.decode(t)}}function Ir(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}function Ju(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var _e=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[r,n]of Object.entries(e))Ju(n)?this.writeFileSync(r,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(r,n)}normalizePath(e){if(!e||e==="/")return"/";let r=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;r.startsWith("/")||(r=`/${r}`);let n=r.split("/").filter(o=>o&&o!=="."),s=[];for(let o of n)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}dirname(e){let r=this.normalizePath(e);if(r==="/")return"/";let n=r.lastIndexOf("/");return n===0?"/":r.slice(0,n)}ensureParentDirs(e){let r=this.dirname(e);r!=="/"&&(this.data.has(r)||(this.ensureParentDirs(r),this.data.set(r,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,r,n,s){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=Ir(n),a=No(r,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,r){let n=await this.readFileBuffer(e),s=Ir(r);return Yu(n,s)}async readFileBuffer(e){let r=this.normalizePath(e),n=this.data.get(r),s=r;if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let o=new Set;for(;n&&n.type==="symlink";){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return n.content instanceof Uint8Array?n.content:st.encode(n.content)}async writeFile(e,r,n){this.writeFileSync(e,r,n)}async appendFile(e,r,n){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=Ir(n),a=No(r,i);if(o?.type==="file"){let c=o.content instanceof Uint8Array?o.content:st.encode(o.content),l=new Uint8Array(c.length+a.length);l.set(c),l.set(a,c.length),this.data.set(s,{type:"file",content:l,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,r,n)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);n=i}let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=st.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}async lstat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=st.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}resolveSymlink(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=this.dirname(e);return this.normalizePath(n==="/"?`/${r}`:`${n}/${r}`)}async mkdir(e,r){this.mkdirSync(e,r)}mkdirSync(e,r){let n=this.normalizePath(e);if(this.data.has(n)){if(this.data.get(n)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!r?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(n);if(s!=="/"&&!this.data.has(s))if(r?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let s=r==="/"?"/":`${r}/`,o=[];for(let i of this.data.keys())if(i!==r&&i.startsWith(s)){let c=i.slice(s.length).split("/")[0];c&&!o.includes(c)&&o.push(c)}return o.sort()}async rm(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s){if(r?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let o=await this.readdir(n);if(o.length>0){if(!r?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=n==="/"?`/${i}`:`${n}/${i}`;await this.rm(a,r)}}}this.data.delete(n)}async cp(e,r,n){let s=this.normalizePath(e),o=this.normalizePath(r),i=this.data.get(s);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(s);for(let c of a){let l=s==="/"?`/${c}`:`${s}/${c}`,u=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(l,u,n)}}}async mv(e,r){await this.cp(e,r,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=e==="/"?`/${r}`:`${e}/${r}`;return this.normalizePath(n)}async chmod(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=r}async symlink(e,r){let n=this.normalizePath(r);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${r}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,r){let n=this.normalizePath(e),s=this.normalizePath(r),o=this.data.get(n);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${r}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}};Z();Z();function K(t,e){return{type:"ArithmeticExpression",expression:Ae(t,e,0).expr}}function Ae(t,e,r){return ef(t,e,r)}function ef(t,e,r){let{expr:n,pos:s}=Pt(t,e,r);for(s=G(e,s);e[s]===",";){s++;let{expr:o,pos:i}=Pt(t,e,s);n={type:"ArithBinary",operator:",",left:n,right:o},s=G(e,i)}return{expr:n,pos:s}}function Pt(t,e,r){let{expr:n,pos:s}=tf(t,e,r);if(s=G(e,s),e[s]==="?"){s++;let{expr:o,pos:i}=Ae(t,e,s);if(s=G(e,i),e[s]===":"){s++;let{expr:a,pos:c}=Ae(t,e,s);return{expr:{type:"ArithTernary",condition:n,consequent:o,alternate:a},pos:c}}}return{expr:n,pos:s}}function tf(t,e,r){let{expr:n,pos:s}=vo(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:o,pos:i}=vo(t,e,s);n={type:"ArithBinary",operator:"||",left:n,right:o},s=i}return{expr:n,pos:s}}function vo(t,e,r){let{expr:n,pos:s}=ko(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:o,pos:i}=ko(t,e,s);n={type:"ArithBinary",operator:"&&",left:n,right:o},s=i}return{expr:n,pos:s}}function ko(t,e,r){let{expr:n,pos:s}=Io(t,e,r);for(;s=G(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:o,pos:i}=Io(t,e,s);n={type:"ArithBinary",operator:"|",left:n,right:o},s=i}return{expr:n,pos:s}}function Io(t,e,r){let{expr:n,pos:s}=Po(t,e,r);for(;s=G(e,s),e[s]==="^";){s++;let{expr:o,pos:i}=Po(t,e,s);n={type:"ArithBinary",operator:"^",left:n,right:o},s=i}return{expr:n,pos:s}}function Po(t,e,r){let{expr:n,pos:s}=Ro(t,e,r);for(;s=G(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:o,pos:i}=Ro(t,e,s);n={type:"ArithBinary",operator:"&",left:n,right:o},s=i}return{expr:n,pos:s}}function Ro(t,e,r){let{expr:n,pos:s}=Oo(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Oo(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Oo(t,e,r){let{expr:n,pos:s}=Pr(t,e,r);for(;;)if(s=G(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Pr(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else if(e[s]==="<"||e[s]===">"){let o=e[s];s++;let{expr:i,pos:a}=Pr(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else break;return{expr:n,pos:s}}function Pr(t,e,r){let{expr:n,pos:s}=Do(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Do(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Do(t,e,r){let{expr:n,pos:s}=To(t,e,r);for(;s=G(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let o=e[s];s++;let{expr:i,pos:a}=To(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function To(t,e,r){let{expr:n,pos:s}=It(t,e,r);for(;;)if(s=G(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:o,pos:i}=It(t,e,s);n={type:"ArithBinary",operator:"*",left:n,right:o},s=i}else if(e[s]==="/"||e[s]==="%"){let o=e[s];s++;let{expr:i,pos:a}=It(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else break;return{expr:n,pos:s}}function It(t,e,r){let{expr:n,pos:s}=Rr(t,e,r),o=G(e,s);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=It(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:n,right:i},pos:a}}return{expr:n,pos:s}}function Rr(t,e,r){let n=G(e,r);if(e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let s=e.slice(n,n+2);n+=2;let{expr:o,pos:i}=Rr(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}if(e[n]==="+"||e[n]==="-"||e[n]==="!"||e[n]==="~"){let s=e[n];n++;let{expr:o,pos:i}=Rr(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}return nf(t,e,n)}function rf(t,e){let r=t[e];return r==="$"||r==="`"}function nf(t,e,r){let{expr:n,pos:s}=Mo(t,e,r),o=[n];for(;rf(e,s);){let{expr:i,pos:a}=Mo(t,e,s);o.push(i),s=a}if(o.length>1&&(n={type:"ArithConcat",parts:o}),s=G(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let i=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:i,operand:n,prefix:!1},pos:s}}return{expr:n,pos:s}}function Mo(t,e,r){let n=G(e,r);if(e.slice(n,n+3)==="$(("){n+=3;let s=1,o=n;for(;n<e.length-1&&s>0;)e[n]==="("&&e[n+1]==="("?(s++,n+=2):e[n]===")"&&e[n+1]===")"?(s--,s>0&&(n+=2)):n++;let i=e.slice(o,n),{expr:a}=Ae(t,i,0);return n+=2,{expr:{type:"ArithNested",expression:a},pos:n}}if(e.slice(n,n+2)==="$("&&e[n+2]!=="("){n+=2;let s=1,o=n;for(;n<e.length&&s>0;)e[n]==="("?s++:e[n]===")"&&s--,s>0&&n++;let i=e.slice(o,n);return n++,{expr:{type:"ArithCommandSubst",command:i},pos:n}}if(e[n]==="`"){n++;let s=n;for(;n<e.length&&e[n]!=="`";)n++;let o=e.slice(s,n);return e[n]==="`"&&n++,{expr:{type:"ArithCommandSubst",command:o},pos:n}}if(e[n]==="("){n++;let{expr:s,pos:o}=Ae(t,e,n);return n=G(e,o),e[n]===")"&&n++,{expr:{type:"ArithGroup",expression:s},pos:n}}if(/[0-9]/.test(e[n])){let s="",o=!1;for(;n<e.length;){let a=e[n];if(o)if(/[0-9a-zA-Z@_]/.test(a))s+=a,n++;else break;else if(a==="#")o=!0,s+=a,n++;else if(/[0-9a-fA-FxX]/.test(a))s+=a,n++;else break}if(e[n]==="."&&/[0-9]/.test(e[n+1]))throw new V(`${s}.${e[n+1]}...: syntax error: invalid arithmetic operator`);if(e[n]==="["){let a=e.slice(n).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:Ze(s)},pos:n}}if(e[n]==="$"&&e[n+1]==="{"){let s=n+2,o=1,i=s;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(s,i),c=i+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let u=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:u},pos:l}}if(/[0-9]/.test(e[c])||e[c]==="x"||e[c]==="X"){let l=c;if(e[c]==="x"||e[c]==="X")for(l++;l<e.length&&/[0-9a-fA-F]/.test(e[l]);)l++;else for(;l<e.length&&/[0-9]/.test(e[l]);)l++;let u=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:u},pos:l}}return n=c,{expr:{type:"ArithBracedExpansion",content:a},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[0-9]/.test(e[n+1])){n++;let s="";for(;n<e.length&&/[0-9]/.test(e[n]);)s+=e[n],n++;return{expr:{type:"ArithVariable",name:s},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[a-zA-Z_]/.test(e[n+1])&&n++,/[a-zA-Z_]/.test(e[n])){let s="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)s+=e[n],n++;if(e[n]==="["){n++;let i;if(e[n]==="'"||e[n]==='"'){let l=e[n];for(n++,i="";n<e.length&&e[n]!==l;)i+=e[n],n++;e[n]===l&&n++,n=G(e,n),e[n]==="]"&&n++}let a;if(i===void 0){let{expr:l,pos:u}=Ae(t,e,n);a=l,n=u,e[n]==="]"&&n++}if(n=G(e,n),e[n]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:s,index:a},pos:n};let c=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let l of c)if(e.slice(n,n+l.length)===l&&e.slice(n,n+l.length+1)!=="=="){n+=l.length;let{expr:u,pos:f}=Pt(t,e,n);return{expr:{type:"ArithAssignment",operator:l,variable:s,subscript:a,stringKey:i,value:u},pos:f}}return{expr:{type:"ArithArrayElement",array:s,index:a,stringKey:i},pos:n}}n=G(e,n);let o=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let i of o)if(e.slice(n,n+i.length)===i&&e.slice(n,n+i.length+1)!=="=="){n+=i.length;let{expr:a,pos:c}=Pt(t,e,n);return{expr:{type:"ArithAssignment",operator:i,variable:s,value:a},pos:c}}return{expr:{type:"ArithVariable",name:s},pos:n}}return{expr:{type:"ArithNumber",value:0},pos:n}}function Ze(t){if(t.includes("#")){let[e,r]=t.split("#"),n=Number.parseInt(e,10);if(n<2||n>64)return Number.NaN;if(n<=36)return Number.parseInt(r,n);let s=0;for(let o of r){let i;if(o>="0"&&o<="9")i=o.charCodeAt(0)-48;else if(o>="a"&&o<="z")i=o.charCodeAt(0)-97+10;else if(o>="A"&&o<="Z")i=o.charCodeAt(0)-65+36;else if(o==="@")i=62;else if(o==="_")i=63;else return Number.NaN;if(i>=n)return Number.NaN;s=s*n+i}return s}return t.startsWith("0x")||t.startsWith("0X")?Number.parseInt(t.slice(2),16):t.startsWith("0")&&t.length>1&&/^[0-9]+$/.test(t)?/[89]/.test(t)?Number.NaN:Number.parseInt(t,8):Number.parseInt(t,10)}function G(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
|
|
401
|
-
`){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var N={script(t){return{type:"Script",statements:t}},statement(t,e=[],r=!1){return{type:"Statement",pipelines:t,operators:e,background:r}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],r=[],n=[]){return{type:"SimpleCommand",name:t,args:e,assignments:r,redirections:n}},word(t){return{type:"Word",parts:t}},literal(t){return{type:"Literal",value:t}},singleQuoted(t){return{type:"SingleQuoted",value:t}},doubleQuoted(t){return{type:"DoubleQuoted",parts:t}},escaped(t){return{type:"Escaped",value:t}},parameterExpansion(t,e=null){return{type:"ParameterExpansion",parameter:t,operation:e}},commandSubstitution(t,e=!1){return{type:"CommandSubstitution",body:t,legacy:e}},arithmeticExpansion(t){return{type:"ArithmeticExpansion",expression:t}},assignment(t,e,r=!1,n=null){return{type:"Assignment",name:t,value:e,append:r,array:n}},redirection(t,e,r=null){return{type:"Redirection",fd:r,operator:t,target:e}},hereDoc(t,e,r=!1,n=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:r,quoted:n}},ifNode(t,e=null,r=[]){return{type:"If",clauses:t,elseBody:e,redirections:r}},forNode(t,e,r,n=[]){return{type:"For",variable:t,words:e,body:r,redirections:n}},whileNode(t,e,r=[]){return{type:"While",condition:t,body:e,redirections:r}},untilNode(t,e,r=[]){return{type:"Until",condition:t,body:e,redirections:r}},caseNode(t,e,r=[]){return{type:"Case",word:t,items:e,redirections:r}},caseItem(t,e,r=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:r}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,r=[]){return{type:"FunctionDef",name:t,body:e,redirections:r}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var m;(function(t){t.EOF="EOF",t.NEWLINE="NEWLINE",t.SEMICOLON="SEMICOLON",t.AMP="AMP",t.PIPE="PIPE",t.PIPE_AMP="PIPE_AMP",t.AND_AND="AND_AND",t.OR_OR="OR_OR",t.BANG="BANG",t.LESS="LESS",t.GREAT="GREAT",t.DLESS="DLESS",t.DGREAT="DGREAT",t.LESSAND="LESSAND",t.GREATAND="GREATAND",t.LESSGREAT="LESSGREAT",t.DLESSDASH="DLESSDASH",t.CLOBBER="CLOBBER",t.TLESS="TLESS",t.AND_GREAT="AND_GREAT",t.AND_DGREAT="AND_DGREAT",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.DSEMI="DSEMI",t.SEMI_AND="SEMI_AND",t.SEMI_SEMI_AND="SEMI_SEMI_AND",t.DBRACK_START="DBRACK_START",t.DBRACK_END="DBRACK_END",t.DPAREN_START="DPAREN_START",t.DPAREN_END="DPAREN_END",t.IF="IF",t.THEN="THEN",t.ELSE="ELSE",t.ELIF="ELIF",t.FI="FI",t.FOR="FOR",t.WHILE="WHILE",t.UNTIL="UNTIL",t.DO="DO",t.DONE="DONE",t.CASE="CASE",t.ESAC="ESAC",t.IN="IN",t.FUNCTION="FUNCTION",t.SELECT="SELECT",t.TIME="TIME",t.COPROC="COPROC",t.WORD="WORD",t.NAME="NAME",t.NUMBER="NUMBER",t.ASSIGNMENT_WORD="ASSIGNMENT_WORD",t.COMMENT="COMMENT",t.HEREDOC_CONTENT="HEREDOC_CONTENT"})(m||(m={}));var
|
|
398
|
+
`,exitCode:1};let s=n.url;s.match(/^https?:\/\//)||(s=`https://${s}`);try{let{body:o,contentType:i}=await Zu(n,e),a=Qu(n,i),c=await e.fetch(s,{method:n.method,headers:Object.keys(a).length>0?a:void 0,body:o,followRedirects:n.followRedirects,timeoutMs:n.timeoutMs});if(await Ku(n,c.headers,e),n.failSilently&&c.status>=400)return{stdout:"",stderr:n.showError||!n.silent?`curl: (22) The requested URL returned error: ${c.status}
|
|
399
|
+
`:"",exitCode:22};let l=Xu(n,c,s);if(n.outputFile||n.useRemoteName){let u=n.outputFile||wo(s),f=e.fs.resolvePath(e.cwd,u);await e.fs.writeFile(f,n.headOnly?"":c.body),n.verbose||(l=""),n.writeOut&&(l=Ir(n.writeOut,{status:c.status,headers:c.headers,url:c.url,bodyLength:c.body.length}))}return{stdout:l,stderr:"",exitCode:0}}catch(o){let i=q(o),a=1;return i.includes("Network access denied")?a=7:i.includes("HTTP method")&&i.includes("not allowed")?a=3:i.includes("Redirect target not in allow-list")||i.includes("Too many redirects")?a=47:i.includes("aborted")&&(a=28),{stdout:"",stderr:!n.silent||n.showError?`curl: (${a}) ${i}
|
|
400
|
+
`:"",exitCode:a}}}}});import{tool as fd,zodSchema as dd}from"ai";import{z as ja}from"zod";var So=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(vn(),Nn))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(In(),kn))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(On(),Rn))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(Fn(),Mn))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(Wn(),Ln))).mkdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(Hn(),_n))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(zn(),Bn))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(jn(),Un))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(Gn(),qn))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>(Zn(),Vn))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(Xn(),Kn))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>(Jn(),Yn))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(ts(),es))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(is(),ss))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(as(),os))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(us(),cs))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(hs(),ds))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(St(),xt))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(St(),xt))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(St(),xt))).egrepCommand},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(ks(),vs))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(ei(),Js))).awkCommand},{name:"sort",load:async()=>(await Promise.resolve().then(()=>(oi(),ii))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(li(),ai))).uniqCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(ui(),ci))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(hi(),di))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(gi(),mi))).trCommand},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(wi(),yi))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(Ai(),Ci))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>(Ni(),$i))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(ki(),vi))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(Ri(),Pi))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(Ti(),Di))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(wr(),yr))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(wr(),yr))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(Er(),br))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(Er(),br))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(Li(),Fi))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(_i(),Wi))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(Sr(),xr))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(Sr(),xr))).falseCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(Bi(),Hi))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(Ar(),Cr))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(Ar(),Cr))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(ji(),Ui))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(Gi(),qi))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(Qi(),Zi))).diffCommand},{name:"date",load:async()=>(await Promise.resolve().then(()=>(Xi(),Ki))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(Ji(),Yi))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>(to(),eo))).timeoutCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(no(),ro))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(io(),so))).exprCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>(ao(),oo))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(co(),lo))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(fo(),uo))).whichCommand}],Ju=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(xo(),Eo))).curlCommand}],Co=new Map;function Ao(t){return{name:t.name,async execute(e,r){let n=Co.get(t.name);return n||(n=await t.load(),Co.set(t.name,n)),n.execute(e,r)}}}function $o(t){return(t?So.filter(r=>t.includes(r.name)):So).map(Ao)}function No(){return Ju.map(Ao)}function vo(t){return"load"in t&&typeof t.load=="function"}function ko(t){let e=null;return{name:t.name,async execute(r,n){return e||(e=await t.load()),e.execute(r,n)}}}var ef=new TextEncoder,tf=new TextDecoder;function Pr(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),r=>r.charCodeAt(0));case"hex":{let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=parseInt(t.slice(n,n+2),16);return r}case"binary":case"latin1":return Uint8Array.from(t,r=>r.charCodeAt(0));default:return ef.encode(t)}}function Io(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return tf.decode(t)}}function kt(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var It=new TextEncoder;function rf(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var _e=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[r,n]of Object.entries(e))rf(n)?this.writeFileSync(r,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(r,n)}normalizePath(e){if(!e||e==="/")return"/";let r=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;r.startsWith("/")||(r=`/${r}`);let n=r.split("/").filter(o=>o&&o!=="."),s=[];for(let o of n)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}dirname(e){let r=this.normalizePath(e);if(r==="/")return"/";let n=r.lastIndexOf("/");return n===0?"/":r.slice(0,n)}ensureParentDirs(e){let r=this.dirname(e);r!=="/"&&(this.data.has(r)||(this.ensureParentDirs(r),this.data.set(r,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,r,n,s){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=kt(n),a=Pr(r,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,r){let n=await this.readFileBuffer(e),s=kt(r);return Io(n,s)}async readFileBuffer(e){let r=this.normalizePath(e),n=this.data.get(r),s=r;if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let o=new Set;for(;n&&n.type==="symlink";){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return n.content instanceof Uint8Array?n.content:It.encode(n.content)}async writeFile(e,r,n){this.writeFileSync(e,r,n)}async appendFile(e,r,n){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=kt(n),a=Pr(r,i);if(o?.type==="file"){let c=o.content instanceof Uint8Array?o.content:It.encode(o.content),l=new Uint8Array(c.length+a.length);l.set(c),l.set(a,c.length),this.data.set(s,{type:"file",content:l,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,r,n)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);n=i}let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=It.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}async lstat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=It.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}resolveSymlink(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=this.dirname(e);return this.normalizePath(n==="/"?`/${r}`:`${n}/${r}`)}async mkdir(e,r){this.mkdirSync(e,r)}mkdirSync(e,r){let n=this.normalizePath(e);if(this.data.has(n)){if(this.data.get(n)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!r?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(n);if(s!=="/"&&!this.data.has(s))if(r?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let s=r==="/"?"/":`${r}/`,o=[];for(let i of this.data.keys())if(i!==r&&i.startsWith(s)){let c=i.slice(s.length).split("/")[0];c&&!o.includes(c)&&o.push(c)}return o.sort()}async rm(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s){if(r?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let o=await this.readdir(n);if(o.length>0){if(!r?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=n==="/"?`/${i}`:`${n}/${i}`;await this.rm(a,r)}}}this.data.delete(n)}async cp(e,r,n){let s=this.normalizePath(e),o=this.normalizePath(r),i=this.data.get(s);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(s);for(let c of a){let l=s==="/"?`/${c}`:`${s}/${c}`,u=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(l,u,n)}}}async mv(e,r){await this.cp(e,r,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=e==="/"?`/${r}`:`${e}/${r}`;return this.normalizePath(n)}async chmod(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=r}async symlink(e,r){let n=this.normalizePath(r);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${r}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,r){let n=this.normalizePath(e),s=this.normalizePath(r),o=this.data.get(n);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${r}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}};Z();Z();function K(t,e){return{type:"ArithmeticExpression",expression:Ae(t,e,0).expr}}function Ae(t,e,r){return nf(t,e,r)}function nf(t,e,r){let{expr:n,pos:s}=Rt(t,e,r);for(s=G(e,s);e[s]===",";){s++;let{expr:o,pos:i}=Rt(t,e,s);n={type:"ArithBinary",operator:",",left:n,right:o},s=G(e,i)}return{expr:n,pos:s}}function Rt(t,e,r){let{expr:n,pos:s}=sf(t,e,r);if(s=G(e,s),e[s]==="?"){s++;let{expr:o,pos:i}=Ae(t,e,s);if(s=G(e,i),e[s]===":"){s++;let{expr:a,pos:c}=Ae(t,e,s);return{expr:{type:"ArithTernary",condition:n,consequent:o,alternate:a},pos:c}}}return{expr:n,pos:s}}function sf(t,e,r){let{expr:n,pos:s}=Po(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:o,pos:i}=Po(t,e,s);n={type:"ArithBinary",operator:"||",left:n,right:o},s=i}return{expr:n,pos:s}}function Po(t,e,r){let{expr:n,pos:s}=Ro(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:o,pos:i}=Ro(t,e,s);n={type:"ArithBinary",operator:"&&",left:n,right:o},s=i}return{expr:n,pos:s}}function Ro(t,e,r){let{expr:n,pos:s}=Oo(t,e,r);for(;s=G(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:o,pos:i}=Oo(t,e,s);n={type:"ArithBinary",operator:"|",left:n,right:o},s=i}return{expr:n,pos:s}}function Oo(t,e,r){let{expr:n,pos:s}=Do(t,e,r);for(;s=G(e,s),e[s]==="^";){s++;let{expr:o,pos:i}=Do(t,e,s);n={type:"ArithBinary",operator:"^",left:n,right:o},s=i}return{expr:n,pos:s}}function Do(t,e,r){let{expr:n,pos:s}=To(t,e,r);for(;s=G(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:o,pos:i}=To(t,e,s);n={type:"ArithBinary",operator:"&",left:n,right:o},s=i}return{expr:n,pos:s}}function To(t,e,r){let{expr:n,pos:s}=Mo(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Mo(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Mo(t,e,r){let{expr:n,pos:s}=Rr(t,e,r);for(;;)if(s=G(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Rr(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else if(e[s]==="<"||e[s]===">"){let o=e[s];s++;let{expr:i,pos:a}=Rr(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else break;return{expr:n,pos:s}}function Rr(t,e,r){let{expr:n,pos:s}=Fo(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Fo(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Fo(t,e,r){let{expr:n,pos:s}=Lo(t,e,r);for(;s=G(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let o=e[s];s++;let{expr:i,pos:a}=Lo(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Lo(t,e,r){let{expr:n,pos:s}=Pt(t,e,r);for(;;)if(s=G(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:o,pos:i}=Pt(t,e,s);n={type:"ArithBinary",operator:"*",left:n,right:o},s=i}else if(e[s]==="/"||e[s]==="%"){let o=e[s];s++;let{expr:i,pos:a}=Pt(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else break;return{expr:n,pos:s}}function Pt(t,e,r){let{expr:n,pos:s}=Or(t,e,r),o=G(e,s);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=Pt(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:n,right:i},pos:a}}return{expr:n,pos:s}}function Or(t,e,r){let n=G(e,r);if(e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let s=e.slice(n,n+2);n+=2;let{expr:o,pos:i}=Or(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}if(e[n]==="+"||e[n]==="-"||e[n]==="!"||e[n]==="~"){let s=e[n];n++;let{expr:o,pos:i}=Or(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}return af(t,e,n)}function of(t,e){let r=t[e];return r==="$"||r==="`"}function af(t,e,r){let{expr:n,pos:s}=Wo(t,e,r),o=[n];for(;of(e,s);){let{expr:i,pos:a}=Wo(t,e,s);o.push(i),s=a}if(o.length>1&&(n={type:"ArithConcat",parts:o}),s=G(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let i=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:i,operand:n,prefix:!1},pos:s}}return{expr:n,pos:s}}function Wo(t,e,r){let n=G(e,r);if(e.slice(n,n+3)==="$(("){n+=3;let s=1,o=n;for(;n<e.length-1&&s>0;)e[n]==="("&&e[n+1]==="("?(s++,n+=2):e[n]===")"&&e[n+1]===")"?(s--,s>0&&(n+=2)):n++;let i=e.slice(o,n),{expr:a}=Ae(t,i,0);return n+=2,{expr:{type:"ArithNested",expression:a},pos:n}}if(e.slice(n,n+2)==="$("&&e[n+2]!=="("){n+=2;let s=1,o=n;for(;n<e.length&&s>0;)e[n]==="("?s++:e[n]===")"&&s--,s>0&&n++;let i=e.slice(o,n);return n++,{expr:{type:"ArithCommandSubst",command:i},pos:n}}if(e[n]==="`"){n++;let s=n;for(;n<e.length&&e[n]!=="`";)n++;let o=e.slice(s,n);return e[n]==="`"&&n++,{expr:{type:"ArithCommandSubst",command:o},pos:n}}if(e[n]==="("){n++;let{expr:s,pos:o}=Ae(t,e,n);return n=G(e,o),e[n]===")"&&n++,{expr:{type:"ArithGroup",expression:s},pos:n}}if(/[0-9]/.test(e[n])){let s="",o=!1;for(;n<e.length;){let a=e[n];if(o)if(/[0-9a-zA-Z@_]/.test(a))s+=a,n++;else break;else if(a==="#")o=!0,s+=a,n++;else if(/[0-9a-fA-FxX]/.test(a))s+=a,n++;else break}if(e[n]==="."&&/[0-9]/.test(e[n+1]))throw new V(`${s}.${e[n+1]}...: syntax error: invalid arithmetic operator`);if(e[n]==="["){let a=e.slice(n).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:Ze(s)},pos:n}}if(e[n]==="$"&&e[n+1]==="{"){let s=n+2,o=1,i=s;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(s,i),c=i+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let u=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:u},pos:l}}if(/[0-9]/.test(e[c])||e[c]==="x"||e[c]==="X"){let l=c;if(e[c]==="x"||e[c]==="X")for(l++;l<e.length&&/[0-9a-fA-F]/.test(e[l]);)l++;else for(;l<e.length&&/[0-9]/.test(e[l]);)l++;let u=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:u},pos:l}}return n=c,{expr:{type:"ArithBracedExpansion",content:a},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[0-9]/.test(e[n+1])){n++;let s="";for(;n<e.length&&/[0-9]/.test(e[n]);)s+=e[n],n++;return{expr:{type:"ArithVariable",name:s},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[a-zA-Z_]/.test(e[n+1])&&n++,/[a-zA-Z_]/.test(e[n])){let s="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)s+=e[n],n++;if(e[n]==="["){n++;let i;if(e[n]==="'"||e[n]==='"'){let l=e[n];for(n++,i="";n<e.length&&e[n]!==l;)i+=e[n],n++;e[n]===l&&n++,n=G(e,n),e[n]==="]"&&n++}let a;if(i===void 0){let{expr:l,pos:u}=Ae(t,e,n);a=l,n=u,e[n]==="]"&&n++}if(n=G(e,n),e[n]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:s,index:a},pos:n};let c=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let l of c)if(e.slice(n,n+l.length)===l&&e.slice(n,n+l.length+1)!=="=="){n+=l.length;let{expr:u,pos:f}=Rt(t,e,n);return{expr:{type:"ArithAssignment",operator:l,variable:s,subscript:a,stringKey:i,value:u},pos:f}}return{expr:{type:"ArithArrayElement",array:s,index:a,stringKey:i},pos:n}}n=G(e,n);let o=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let i of o)if(e.slice(n,n+i.length)===i&&e.slice(n,n+i.length+1)!=="=="){n+=i.length;let{expr:a,pos:c}=Rt(t,e,n);return{expr:{type:"ArithAssignment",operator:i,variable:s,value:a},pos:c}}return{expr:{type:"ArithVariable",name:s},pos:n}}return{expr:{type:"ArithNumber",value:0},pos:n}}function Ze(t){if(t.includes("#")){let[e,r]=t.split("#"),n=Number.parseInt(e,10);if(n<2||n>64)return Number.NaN;if(n<=36)return Number.parseInt(r,n);let s=0;for(let o of r){let i;if(o>="0"&&o<="9")i=o.charCodeAt(0)-48;else if(o>="a"&&o<="z")i=o.charCodeAt(0)-97+10;else if(o>="A"&&o<="Z")i=o.charCodeAt(0)-65+36;else if(o==="@")i=62;else if(o==="_")i=63;else return Number.NaN;if(i>=n)return Number.NaN;s=s*n+i}return s}return t.startsWith("0x")||t.startsWith("0X")?Number.parseInt(t.slice(2),16):t.startsWith("0")&&t.length>1&&/^[0-9]+$/.test(t)?/[89]/.test(t)?Number.NaN:Number.parseInt(t,8):Number.parseInt(t,10)}function G(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
|
|
401
|
+
`){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var N={script(t){return{type:"Script",statements:t}},statement(t,e=[],r=!1){return{type:"Statement",pipelines:t,operators:e,background:r}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],r=[],n=[]){return{type:"SimpleCommand",name:t,args:e,assignments:r,redirections:n}},word(t){return{type:"Word",parts:t}},literal(t){return{type:"Literal",value:t}},singleQuoted(t){return{type:"SingleQuoted",value:t}},doubleQuoted(t){return{type:"DoubleQuoted",parts:t}},escaped(t){return{type:"Escaped",value:t}},parameterExpansion(t,e=null){return{type:"ParameterExpansion",parameter:t,operation:e}},commandSubstitution(t,e=!1){return{type:"CommandSubstitution",body:t,legacy:e}},arithmeticExpansion(t){return{type:"ArithmeticExpansion",expression:t}},assignment(t,e,r=!1,n=null){return{type:"Assignment",name:t,value:e,append:r,array:n}},redirection(t,e,r=null){return{type:"Redirection",fd:r,operator:t,target:e}},hereDoc(t,e,r=!1,n=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:r,quoted:n}},ifNode(t,e=null,r=[]){return{type:"If",clauses:t,elseBody:e,redirections:r}},forNode(t,e,r,n=[]){return{type:"For",variable:t,words:e,body:r,redirections:n}},whileNode(t,e,r=[]){return{type:"While",condition:t,body:e,redirections:r}},untilNode(t,e,r=[]){return{type:"Until",condition:t,body:e,redirections:r}},caseNode(t,e,r=[]){return{type:"Case",word:t,items:e,redirections:r}},caseItem(t,e,r=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:r}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,r=[]){return{type:"FunctionDef",name:t,body:e,redirections:r}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var m;(function(t){t.EOF="EOF",t.NEWLINE="NEWLINE",t.SEMICOLON="SEMICOLON",t.AMP="AMP",t.PIPE="PIPE",t.PIPE_AMP="PIPE_AMP",t.AND_AND="AND_AND",t.OR_OR="OR_OR",t.BANG="BANG",t.LESS="LESS",t.GREAT="GREAT",t.DLESS="DLESS",t.DGREAT="DGREAT",t.LESSAND="LESSAND",t.GREATAND="GREATAND",t.LESSGREAT="LESSGREAT",t.DLESSDASH="DLESSDASH",t.CLOBBER="CLOBBER",t.TLESS="TLESS",t.AND_GREAT="AND_GREAT",t.AND_DGREAT="AND_DGREAT",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.DSEMI="DSEMI",t.SEMI_AND="SEMI_AND",t.SEMI_SEMI_AND="SEMI_SEMI_AND",t.DBRACK_START="DBRACK_START",t.DBRACK_END="DBRACK_END",t.DPAREN_START="DPAREN_START",t.DPAREN_END="DPAREN_END",t.IF="IF",t.THEN="THEN",t.ELSE="ELSE",t.ELIF="ELIF",t.FI="FI",t.FOR="FOR",t.WHILE="WHILE",t.UNTIL="UNTIL",t.DO="DO",t.DONE="DONE",t.CASE="CASE",t.ESAC="ESAC",t.IN="IN",t.FUNCTION="FUNCTION",t.SELECT="SELECT",t.TIME="TIME",t.COPROC="COPROC",t.WORD="WORD",t.NAME="NAME",t.NUMBER="NUMBER",t.ASSIGNMENT_WORD="ASSIGNMENT_WORD",t.COMMENT="COMMENT",t.HEREDOC_CONTENT="HEREDOC_CONTENT"})(m||(m={}));var Ot={if:m.IF,then:m.THEN,else:m.ELSE,elif:m.ELIF,fi:m.FI,for:m.FOR,while:m.WHILE,until:m.UNTIL,do:m.DO,done:m.DONE,case:m.CASE,esac:m.ESAC,in:m.IN,function:m.FUNCTION,select:m.SELECT,time:m.TIME,coproc:m.COPROC};function Ho(t){let e=t.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!e)return!1;let r=t.slice(e[0].length);if(r===""||r==="+")return!0;if(r[0]==="["){let n=0,s=0;for(;s<r.length;s++)if(r[s]==="[")n++;else if(r[s]==="]"&&(n--,n===0))break;if(n!==0||s>=r.length)return!1;let o=r.slice(s+1);return o===""||o==="+"}return!1}var lf=[[";",";","&",m.SEMI_SEMI_AND],["<","<","<",m.TLESS],["&",">",">",m.AND_DGREAT]],cf=[["[","[",m.DBRACK_START],["]","]",m.DBRACK_END],["(","(",m.DPAREN_START],[")",")",m.DPAREN_END],["&","&",m.AND_AND],["|","|",m.OR_OR],[";",";",m.DSEMI],[";","&",m.SEMI_AND],["|","&",m.PIPE_AMP],[">",">",m.DGREAT],["<","&",m.LESSAND],[">","&",m.GREATAND],["<",">",m.LESSGREAT],[">","|",m.CLOBBER],["&",">",m.AND_GREAT]],uf={"|":m.PIPE,"&":m.AMP,";":m.SEMICOLON,"(":m.LPAREN,")":m.RPAREN,"<":m.LESS,">":m.GREAT};function ff(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var Dt=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];constructor(e){this.input=e}tokenize(){let r=this.input.length,n=this.tokens,s=this.pendingHeredocs;for(;this.pos<r&&(this.skipWhitespace(),!(this.pos>=r));){if(s.length>0&&n.length>0&&n[n.length-1].type===m.NEWLINE){this.readHeredocContent();continue}let o=this.nextToken();o&&n.push(o)}return n.push({type:m.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),n}skipWhitespace(){let e=this.input,r=e.length,n=this.pos,s=this.column,o=this.line;for(;n<r;){let i=e[n];if(i===" "||i===" ")n++,s++;else if(i==="\\"&&e[n+1]===`
|
|
402
402
|
`)n+=2,o++,s=1;else break}this.pos=n,this.column=s,this.line=o}nextToken(){let e=this.input,r=this.pos,n=this.line,s=this.column,o=e[r],i=e[r+1],a=e[r+2];if(o==="#")return this.readComment(r,n,s);if(o===`
|
|
403
403
|
`)return this.pos=r+1,this.line++,this.column=1,{type:m.NEWLINE,value:`
|
|
404
|
-
`,start:r,end:r+1,line:n,column:s};if(o==="<"&&i==="<"&&a==="-")return this.pos=r+3,this.column=s+3,this.registerHeredocFromLookahead(!0),this.makeToken(m.DLESSDASH,"<<-",r,n,s);for(let[l,u,f,d]of
|
|
404
|
+
`,start:r,end:r+1,line:n,column:s};if(o==="<"&&i==="<"&&a==="-")return this.pos=r+3,this.column=s+3,this.registerHeredocFromLookahead(!0),this.makeToken(m.DLESSDASH,"<<-",r,n,s);for(let[l,u,f,d]of lf)if(o===l&&i===u&&a===f)return this.pos=r+3,this.column=s+3,this.makeToken(d,l+u+f,r,n,s);if(o==="<"&&i==="<")return this.pos=r+2,this.column=s+2,this.registerHeredocFromLookahead(!1),this.makeToken(m.DLESS,"<<",r,n,s);for(let[l,u,f]of cf)if(o===l&&i===u)return this.pos=r+2,this.column=s+2,this.makeToken(f,l+u,r,n,s);let c=uf[o];return c?(this.pos=r+1,this.column=s+1,this.makeToken(c,o,r,n,s)):o==="{"?i==="}"?(this.pos=r+2,this.column=s+2,{type:m.WORD,value:"{}",start:r,end:r+2,line:n,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(r)!==null?this.readWordWithBraceExpansion(r,n,s):this.scanLiteralBraceWord(r)!==null?this.readWordWithBraceExpansion(r,n,s):i!==void 0&&i!==" "&&i!==" "&&i!==`
|
|
405
405
|
`?this.readWord(r,n,s):(this.pos=r+1,this.column=s+1,this.makeToken(m.LBRACE,"{",r,n,s)):o==="}"?this.isWordCharFollowing(r+1)?this.readWord(r,n,s):(this.pos=r+1,this.column=s+1,this.makeToken(m.RBRACE,"}",r,n,s)):o==="!"?i==="="?(this.pos=r+2,this.column=s+2,this.makeToken(m.WORD,"!=",r,n,s)):(this.pos=r+1,this.column=s+1,this.makeToken(m.BANG,"!",r,n,s)):this.readWord(r,n,s)}makeToken(e,r,n,s,o){return{type:e,value:r,start:n,end:this.pos,line:s,column:o}}readComment(e,r,n){let s=this.input,o=s.length,i=this.pos;for(;i<o&&s[i]!==`
|
|
406
406
|
`;)i++;let a=s.slice(e,i);return this.pos=i,this.column=n+(i-e),{type:m.COMMENT,value:a,start:e,end:i,line:r,column:n}}readWord(e,r,n){let s=this.input,o=s.length,i=this.pos,a=i;for(;i<o;){let g=s[i];if(g===" "||g===" "||g===`
|
|
407
407
|
`||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"||g==="'"||g==='"'||g==="\\"||g==="$"||g==="`"||g==="{"||g==="}"||g==="~"||g==="*"||g==="?"||g==="[")break;i++}if(i>a){let g=s[i];if(i>=o||g===" "||g===" "||g===`
|
|
408
|
-
`||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"){let y=s.slice(a,i);if(this.pos=i,this.column=n+(i-a),
|
|
408
|
+
`||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"){let y=s.slice(a,i);if(this.pos=i,this.column=n+(i-a),Ot[y])return{type:Ot[y],value:y,start:e,end:i,line:r,column:n};let w=y.indexOf("=");return w>0&&Ho(y.slice(0,w))?{type:m.ASSIGNMENT_WORD,value:y,start:e,end:i,line:r,column:n}:/^[0-9]+$/.test(y)?{type:m.NUMBER,value:y,start:e,end:i,line:r,column:n}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)?{type:m.NAME,value:y,start:e,end:i,line:r,column:n,quoted:!1,singleQuoted:!1}:{type:m.WORD,value:y,start:e,end:i,line:r,column:n,quoted:!1,singleQuoted:!1}}}i=this.pos;let c=this.column,l=this.line,u="",f=!1,d=!1,h=!1,p=!1,b=s[i]==='"'||s[i]==="'";for(;i<o;){let g=s[i];if(!h&&!p&&(g===" "||g===" "||g===`
|
|
409
409
|
`||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"))break;if(g==="$"&&i+1<o&&s[i+1]==="'"&&!h&&!p){for(u+="$'",i+=2,c+=2;i<o&&s[i]!=="'";)s[i]==="\\"&&i+1<o?(u+=s[i]+s[i+1],i+=2,c+=2):(u+=s[i],i++,c++);i<o&&(u+="'",i++,c++);continue}if(g==="$"&&i+1<o&&s[i+1]==='"'&&!h&&!p){i++,c++,p=!0,f=!0,u===""&&(b=!0),i++,c++;continue}if(g==="'"&&!p){h?(h=!1,b||(u+=g)):(h=!0,b?(d=!0,f=!0):u+=g),i++,c++;continue}if(g==='"'&&!h){p?(p=!1,b||(u+=g)):(p=!0,b?f=!0:u+=g),i++,c++;continue}if(g==="\\"&&!h&&i+1<o){let y=s[i+1];if(y===`
|
|
410
410
|
`){i+=2,l++,c=1;continue}if(p){if(y==='"'||y==="\\"||y==="$"||y==="`"||y===`
|
|
411
|
-
`){y==="$"||y==="`"?u+=g+y:u+=y,i+=2,c+=2;continue}}else{y==='"'||y==="'"?u+=g+y:u+=y,i+=2,c+=2;continue}}if(g==="$"&&i+1<o&&s[i+1]==="("){u+=g,i++,c++,u+=s[i],i++,c++;let y=1,w=!1,E=!1,$=0,A=!1,P="",J=s[i]==="(";for(;y>0&&i<o;){let
|
|
412
|
-
`;)i++,c++,u+=s[i];P=""}else/[a-zA-Z_]/.test(
|
|
411
|
+
`){y==="$"||y==="`"?u+=g+y:u+=y,i+=2,c+=2;continue}}else{y==='"'||y==="'"?u+=g+y:u+=y,i+=2,c+=2;continue}}if(g==="$"&&i+1<o&&s[i+1]==="("){u+=g,i++,c++,u+=s[i],i++,c++;let y=1,w=!1,E=!1,$=0,A=!1,P="",J=s[i]==="(";for(;y>0&&i<o;){let L=s[i];if(u+=L,w)L==="'"&&(w=!1);else if(E)L==="\\"&&i+1<o?(u+=s[i+1],i++,c++):L==='"'&&(E=!1);else if(L==="'")w=!0,P="";else if(L==='"')E=!0,P="";else if(L==="\\"&&i+1<o)u+=s[i+1],i++,c++,P="";else if(L==="#"&&!J&&(P===""||/\s/.test(s[i-1]||""))){for(;i+1<o&&s[i+1]!==`
|
|
412
|
+
`;)i++,c++,u+=s[i];P=""}else/[a-zA-Z_]/.test(L)?P+=L:(P==="case"?($++,A=!1):P==="in"&&$>0?A=!0:P==="esac"&&$>0&&($--,A=!1),P="",L==="("?i>0&&s[i-1]==="$"?y++:A||y++:L===")"?A?A=!1:y--:L===";"&&$>0&&i+1<o&&s[i+1]===";"&&(A=!0));L===`
|
|
413
413
|
`&&(l++,c=0,P=""),i++,c++}continue}if(g==="$"&&i+1<o&&s[i+1]==="["){u+=g,i++,c++,u+=s[i],i++,c++;let y=1;for(;y>0&&i<o;){let w=s[i];u+=w,w==="["?y++:w==="]"?y--:w===`
|
|
414
414
|
`&&(l++,c=0),i++,c++}continue}if(g==="$"&&i+1<o&&s[i+1]==="{"){u+=g,i++,c++,u+=s[i],i++,c++;let y=1;for(;y>0&&i<o;){let w=s[i];u+=w,w==="{"?y++:w==="}"?y--:w===`
|
|
415
415
|
`&&(l++,c=0),i++,c++}continue}if(g==="$"&&i+1<o){let y=s[i+1];if(y==="#"||y==="?"||y==="$"||y==="!"||y==="@"||y==="*"||y==="-"||y>="0"&&y<="9"){u+=g+y,i+=2,c+=2;continue}}if(g==="`"){for(u+=g,i++,c++;i<o&&s[i]!=="`";){let y=s[i];u+=y,y==="\\"&&i+1<o&&(u+=s[i+1],i++,c++),y===`
|
|
416
416
|
`&&(l++,c=0),i++,c++}i<o&&(u+=s[i],i++,c++);continue}u+=g,i++,g===`
|
|
417
|
-
`?(l++,c=1):c++}if(this.pos=i,this.column=c,this.line=l,u==="")return{type:m.WORD,value:"",start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d};if(!f&&
|
|
417
|
+
`?(l++,c=1):c++}if(this.pos=i,this.column=c,this.line=l,u==="")return{type:m.WORD,value:"",start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d};if(!f&&Ot[u])return{type:Ot[u],value:u,start:e,end:i,line:r,column:n};if(!b){let g=u.indexOf("=");if(g>0&&Ho(u.slice(0,g)))return{type:m.ASSIGNMENT_WORD,value:u,start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:m.NUMBER,value:u,start:e,end:i,line:r,column:n}:ff(u)?{type:m.NAME,value:u,start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d}:{type:m.WORD,value:u,start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let r=this.pos,n=this.line,s=this.column,o="";for(;this.pos<this.input.length;){let i=this.pos,a="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
|
|
418
418
|
`;)a+=this.input[this.pos],this.pos++,this.column++;if((e.stripTabs?a.replace(/^\t+/,""):a)===e.delimiter){this.pos<this.input.length&&this.input[this.pos]===`
|
|
419
419
|
`&&(this.pos++,this.line++,this.column=1);break}o+=a,this.pos<this.input.length&&this.input[this.pos]===`
|
|
420
420
|
`&&(o+=`
|
|
@@ -422,46 +422,46 @@ ${o}\r
|
|
|
422
422
|
`||r===";"||r==="&"||r==="|"||r==="("||r===")"||r==="<"||r===">")}readWordWithBraceExpansion(e,r,n){let s=this.input,o=s.length,i=e,a=n;for(;i<o;){let l=s[i];if(l===" "||l===" "||l===`
|
|
423
423
|
`||l===";"||l==="&"||l==="|"||l==="("||l===")"||l==="<"||l===">")break;if(l==="{"){if(this.scanBraceExpansion(i)!==null){let f=1;for(i++,a++;i<o&&f>0;)s[i]==="{"?f++:s[i]==="}"&&f--,i++,a++;continue}i++,a++;continue}if(l==="}"){i++,a++;continue}if(l==="$"&&i+1<o&&s[i+1]==="("){i++,a++,i++,a++;let u=1;for(;u>0&&i<o;)s[i]==="("?u++:s[i]===")"&&u--,i++,a++;continue}if(l==="$"&&i+1<o&&s[i+1]==="{"){i++,a++,i++,a++;let u=1;for(;u>0&&i<o;)s[i]==="{"?u++:s[i]==="}"&&u--,i++,a++;continue}if(l==="`"){for(i++,a++;i<o&&s[i]!=="`";)s[i]==="\\"&&i+1<o?(i+=2,a+=2):(i++,a++);i<o&&(i++,a++);continue}i++,a++}let c=s.slice(e,i);return this.pos=i,this.column=a,{type:m.WORD,value:c,start:e,end:i,line:r,column:n,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let r=this.input,n=r.length,s=e+1,o=1,i=!1,a=!1;for(;s<n&&o>0;){let c=r[s];if(c==="{")o++,s++;else if(c==="}")o--,s++;else if(c===","&&o===1)i=!0,s++;else if(c==="."&&s+1<n&&r[s+1]===".")a=!0,s+=2;else{if(c===" "||c===" "||c===`
|
|
424
424
|
`||c===";"||c==="&"||c==="|")return null;s++}}return o===0&&(i||a)?r.slice(e,s):null}scanLiteralBraceWord(e){let r=this.input,n=r.length,s=e+1,o=1;for(;s<n&&o>0;){let i=r[s];if(i==="{")o++,s++;else if(i==="}"){if(o--,o===0)return r.slice(e,s+1);s++}else{if(i===" "||i===" "||i===`
|
|
425
|
-
`||i===";"||i==="&"||i==="|")return null;s++}}return null}};var
|
|
426
|
-
`,s+=2;break;case"t":n+=" ",s+=2;break;case"r":n+="\r",s+=2;break;case"\\":n+="\\",s+=2;break;case"'":n+="'",s+=2;break;case'"':n+='"',s+=2;break;case"a":n+="\x07",s+=2;break;case"b":n+="\b",s+=2;break;case"e":case"E":n+="\x1B",s+=2;break;case"f":n+="\f",s+=2;break;case"v":n+="\v",s+=2;break;case"x":{let a=e.slice(s+2,s+4),c=parseInt(a,16);Number.isNaN(c)?(n+="\\x",s+=2):(n+=String.fromCharCode(c),s+=4);break}case"u":{let a=e.slice(s+2,s+6),c=parseInt(a,16);Number.isNaN(c)?(n+="\\u",s+=2):(n+=String.fromCharCode(c),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",c=s+1;for(;c<e.length&&c<s+4&&/[0-7]/.test(e[c]);)a+=e[c],c++;let l=parseInt(a,8);n+=String.fromCharCode(l),s=c;break}default:n+=o,s++}else n+=o,s++}return s<e.length&&e[s]==="'"&&s++,{part:N.literal(n),endIndex:s}}function Mr(t,e){let r=e.trim();return r===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:K(t,r)}function Bo(t){let e=[],r="",n=0;for(let s=0;s<t.length;s++){let o=t[s];o==="{"?(n++,r+=o):o==="}"?(n--,r+=o):o===","&&n===0?(e.push(r),r=""):r+=o}return e.push(r),e}function Go(t,e,r,n){let s=Tr(t,e,r,"{","}");if(s===-1)return null;let o=e.slice(r+1,s),i=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(i)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:s+1};let a=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:s+1}:o.includes(",")&&n?{part:{type:"BraceExpansion",items:Bo(o).map(u=>({type:"Word",word:N.word(n(t,u,!1,!1,!1))}))},endIndex:s+1}:o.includes(",")?{part:{type:"BraceExpansion",items:Bo(o).map(u=>({type:"Word",word:N.word([N.literal(u)])}))},endIndex:s+1}:null}function Vo(t,e){let r="";for(let n of e.parts)switch(n.type){case"Literal":case"SingleQuoted":case"Escaped":r+=n.value;break;case"DoubleQuoted":r+='"';for(let s of n.parts)s.type==="Literal"||s.type==="Escaped"?r+=s.value:s.type==="ParameterExpansion"&&(r+=`\${${s.parameter}}`);r+='"';break;case"ParameterExpansion":r+=`\${${n.parameter}}`;break;case"Glob":r+=n.pattern;break;default:r+=n.type}return r}function Zo(t,e){return{[m.LESS]:"<",[m.GREAT]:">",[m.DGREAT]:">>",[m.LESSAND]:"<&",[m.GREATAND]:">&",[m.LESSGREAT]:"<>",[m.CLOBBER]:">|",[m.TLESS]:"<<<",[m.AND_GREAT]:"&>",[m.AND_DGREAT]:"&>>",[m.DLESS]:"<",[m.DLESSDASH]:"<"}[e]||">"}function Dt(t){let e=t.current(),r=e.type;if(r===m.NUMBER){let n=t.peek(1);return e.end!==n.start?!1:Ho.has(n.type)}return _o.has(r)}function Tt(t){let e=null;t.check(m.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let r=t.advance(),n=Zo(t,r.type);if(r.type===m.DLESS||r.type===m.DLESSDASH)return uf(t,n,e,r.type===m.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return N.redirection(n,s,e)}function uf(t,e,r,n){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),o=s.value,i=s.quoted||!1;(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1));let a=N.redirection(n?"<<-":"<<",N.hereDoc(o,N.word([]),n,i),r);return t.addPendingHeredoc(a,o,n,i),a}function Ko(t){let e=[],r=null,n=[],s=[];for(;t.check(m.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(ff(t));for(;Dt(t);)t.checkIterationLimit(),s.push(Tt(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(m.RBRACE))&&!t.check(m.PIPE,m.PIPE_AMP);)if(t.checkIterationLimit(),Dt(t))s.push(Tt(t));else if(t.check(m.RBRACE)){let o=t.advance();n.push(t.parseWordFromString(o.value,!1,!1))}else if(t.isWord())n.push(t.parseWord());else if(t.check(m.ASSIGNMENT_WORD)){let o=t.advance(),i=o.value,a=i.endsWith("="),c=i.endsWith("=(");if((a||c)&&(c||t.check(m.LPAREN))){let l=c?i.slice(0,-2):i.slice(0,-1);c||t.expect(m.LPAREN);let u=Fr(t);t.expect(m.RPAREN);let f=u.map(h=>Vo(t,h)),d=`${l}=(${f.join(" ")})`;n.push(t.parseWordFromString(d,!1,!1))}else n.push(t.parseWordFromString(i,o.quoted,o.singleQuoted))}else if(t.check(m.LPAREN))t.error("syntax error near unexpected token `('");else break;return N.simpleCommand(r,n,e,s)}function ff(t){let e=t.expect(m.ASSIGNMENT_WORD),r=e.value,n=r.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);n||t.error(`Invalid assignment: ${r}`);let s=n[0],o,i=s.length;if(r[i]==="["){let f=0,d=i+1;for(;i<r.length;i++)if(r[i]==="[")f++;else if(r[i]==="]"&&(f--,f===0))break;f!==0&&t.error(`Invalid assignment: ${r}`),o=r.slice(d,i),i++}let a=r[i]==="+";a&&i++,r[i]!=="="&&t.error(`Invalid assignment: ${r}`),i++;let c=r.slice(i);if(c==="("){let f=Fr(t);t.expect(m.RPAREN);let d=o!==void 0?`${s}[${o}]`:s;return N.assignment(d,null,a,f)}if(c===""&&t.check(m.LPAREN)){let f=t.current();if(e.end===f.start){t.advance();let d=Fr(t);t.expect(m.RPAREN);let h=o!==void 0?`${s}[${o}]`:s;return N.assignment(h,null,a,d)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,u=o!==void 0?`${s}[${o}]`:s;return N.assignment(u,l,a,null)}function Fr(t){let e=[];for(t.skipNewlines();!t.check(m.RPAREN,m.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function Wr(t){t.expect(m.IF);let e=[],r=t.parseCompoundList();t.expect(m.THEN);let n=t.parseCompoundList();if(n.length===0){let i=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${i}'`)}for(e.push({condition:r,body:n});t.check(m.ELIF);){t.advance();let i=t.parseCompoundList();t.expect(m.THEN);let a=t.parseCompoundList();if(a.length===0){let c=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${c}'`)}e.push({condition:i,body:a})}let s=null;t.check(m.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(m.FI);let o=t.parseOptionalRedirections();return N.ifNode(e,s,o)}function Lr(t){if(t.expect(m.FOR),t.check(m.DPAREN_START))return hf(t);t.isWord()||t.error("Expected variable name in for loop");let r=t.advance().value,n=null;if(t.skipNewlines(),t.check(m.IN))for(t.advance(),n=[];!t.check(m.SEMICOLON,m.NEWLINE,m.DO,m.EOF)&&t.isWord();)n.push(t.parseWord());t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let s=t.parseCompoundList();t.expect(m.DONE);let o=t.parseOptionalRedirections();return N.forNode(r,n,s,o)}function hf(t){t.expect(m.DPAREN_START);let e=null,r=null,n=null,s=["","",""],o=0,i=0;for(;!t.check(m.DPAREN_END,m.EOF);){let l=t.advance();if(l.type===m.SEMICOLON&&i===0){if(o++,o>2)break}else l.value==="("&&i++,l.value===")"&&i--,s[o]+=l.value}t.expect(m.DPAREN_END),s[0].trim()&&(e=K(t,s[0].trim())),s[1].trim()&&(r=K(t,s[1].trim())),s[2].trim()&&(n=K(t,s[2].trim())),t.skipNewlines(),t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let a=t.parseCompoundList();t.expect(m.DONE);let c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:r,update:n,body:a,redirections:c}}function _r(t){t.expect(m.WHILE);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return N.whileNode(e,r,n)}function Hr(t){t.expect(m.UNTIL);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return N.untilNode(e,r,n)}function Br(t){t.expect(m.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(m.IN),t.skipNewlines();let r=[];for(;!t.check(m.ESAC,m.EOF);){t.checkIterationLimit();let s=t.getPos(),o=pf(t);if(o&&r.push(o),t.skipNewlines(),t.getPos()===s&&!o)break}t.expect(m.ESAC);let n=t.parseOptionalRedirections();return N.caseNode(e,r,n)}function pf(t){t.check(m.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(m.PIPE));)t.advance();if(e.length===0)return null;t.expect(m.RPAREN),t.skipNewlines();let r=[];for(;!t.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND,m.ESAC,m.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===m.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(m.LPAREN)&&t.peek(1).type===m.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let s=t.getPos(),o=t.parseStatement();if(o&&r.push(o),t.skipSeparators(!1),t.getPos()===s&&!o)break}let n=";;";return t.check(m.DSEMI)?(t.advance(),n=";;"):t.check(m.SEMI_AND)?(t.advance(),n=";&"):t.check(m.SEMI_SEMI_AND)&&(t.advance(),n=";;&"),N.caseItem(e,r,n)}function zr(t){t.peek(1).type,m.LPAREN,t.expect(m.LPAREN),t.check(m.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(m.RPAREN);let r=t.parseOptionalRedirections();return N.subshell(e,r)}function Ur(t){t.expect(m.LBRACE);let e=t.parseCompoundList();t.expect(m.RBRACE);let r=t.parseOptionalRedirections();return N.group(e,r)}var gf=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],yf=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function qr(t){return t.skipNewlines(),wf(t)}function wf(t){let e=Xo(t);for(t.skipNewlines();t.check(m.OR_OR);){t.advance(),t.skipNewlines();let r=Xo(t);e={type:"CondOr",left:e,right:r},t.skipNewlines()}return e}function Xo(t){let e=jr(t);for(t.skipNewlines();t.check(m.AND_AND);){t.advance(),t.skipNewlines();let r=jr(t);e={type:"CondAnd",left:e,right:r},t.skipNewlines()}return e}function jr(t){return t.skipNewlines(),t.check(m.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:jr(t)}):bf(t)}function bf(t){if(t.check(m.LPAREN)){t.advance();let e=qr(t);return t.expect(m.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),r=e.value;if(gf.includes(r)&&!e.quoted&&(t.advance(),t.check(m.DBRACK_END)&&t.error(`Expected operand after ${r}`),t.isWord())){let s=t.parseWord();return{type:"CondUnary",operator:r,operand:s}}let n=t.parseWord();if(t.isWord()&&yf.includes(t.current().value)){let s=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:s,left:n,right:o}}if(t.check(m.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:n,right:s}}if(t.check(m.GREAT)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:">",left:n,right:s}}if(t.isWord()&&t.current().value==="="){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"==",left:n,right:s}}return{type:"CondWord",word:n}}t.error("Expected conditional expression")}function xf(t,e,r){let n=r+1,s=e[n];if("@*#?$!-0123456789".includes(s))return{part:N.parameterExpansion(s),endIndex:n+1};let o="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)o+=e[n],n++;return{part:N.parameterExpansion(o),endIndex:n}}function Sf(t,e,r,n=!1){let s=r+2,o=!1;e[s]==="!"&&(o=!0,s++);let i=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(i=!0,s++);let a="",c=e[s];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))a=c,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)a+=e[s],s++;if(e[s]==="["){let u=Tr(t,e,s,"[","]");a+=e.slice(s,u+1),s=u+1}a===""&&!o&&!i&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let l=null;if(o){let u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)l={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="";else if(e[s]==="*"||e[s]==="@"){let f=e[s];s++,l={type:"VarNamePrefix",prefix:a,star:f==="*"},a=""}else l={type:"Indirection"}}else if(i)if(e[s]===":")for(l={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${a}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):l={type:"Length"};if(!l&&s<e.length&&e[s]!=="}"){let u=Cf(t,e,s,a,n);l=u.operation,s=u.endIndex}if(s<e.length&&e[s]!=="}"){let u=e[s];if(!/[:\-+=?#%/^,@[]/.test(u)){let f=s;for(;f<e.length&&e[f]!=="}";)f++;let d=e.slice(r,f+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:N.parameterExpansion(a,l),endIndex:s+1}}function Cf(t,e,r,n,s=!1){let o=r,i=e[o],a=e[o+1]||"";if(i===":"){let c=a;if("-=?+".includes(c)){o+=2;let y=He(t,e,o),w=e.slice(o,y),E=Re(t,w,!1,!1,!0,!1,s),$=N.word(E.length>0?E:[N.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:$,checkEmpty:!0},endIndex:y};if(c==="=")return{operation:{type:"AssignDefault",word:$,checkEmpty:!0},endIndex:y};if(c==="?")return{operation:{type:"ErrorIfUnset",word:$,checkEmpty:!0},endIndex:y};if(c==="+")return{operation:{type:"UseAlternative",word:$,checkEmpty:!0},endIndex:y}}o++;let l=He(t,e,o),u=e.slice(o,l),f=-1,d=0,h=0;for(let g=0;g<u.length;g++){let y=u[g];if(y==="("||y==="[")d++;else if(y===")"||y==="]")d--;else if(y==="?"&&d===0)h++;else if(y===":"&&d===0)if(h>0)h--;else{f=g;break}}let p=f>=0?u.slice(0,f):u,b=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:Mr(t,p),length:b?Mr(t,b):null},endIndex:l}}if("-=?+".includes(i)){o++;let c=He(t,e,o),l=e.slice(o,c),u=Re(t,l,!1,!1,!0,!1,s),f=N.word(u.length>0?u:[N.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:c};if(i==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:c};if(i==="?")return{operation:{type:"ErrorIfUnset",word:l?f:null,checkEmpty:!1},endIndex:c};if(i==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:c}}if(i==="#"||i==="%"){let c=a===i,l=i==="#"?"prefix":"suffix";o+=c?2:1;let u=He(t,e,o),f=e.slice(o,u),d=Re(t,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:N.word(d.length>0?d:[N.literal("")]),side:l,greedy:c},endIndex:u}}if(i==="/"){let c=a==="/";o+=c?2:1;let l=null;e[o]==="#"?(l="start",o++):e[o]==="%"&&(l="end",o++);let u=Uo(t,e,o),f=e.slice(o,u),d=Re(t,f,!1,!1,!1),h=N.word(d.length>0?d:[N.literal("")]),p=null,b=u;if(e[u]==="/"){let g=u+1,y=He(t,e,g),w=e.slice(g,y),E=Re(t,w,!1,!1,!1);p=N.word(E.length>0?E:[N.literal("")]),b=y}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:c,anchor:l},endIndex:b}}if(i==="^"||i===","){let c=a===i,l=i==="^"?"upper":"lower";o+=c?2:1;let u=He(t,e,o),f=e.slice(o,u),d=f?N.word([N.literal(f)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:d},endIndex:u}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Gr(t,e,r,n=!1){let s=r+1;if(s>=e.length)return{part:N.literal("$"),endIndex:s};let o=e[s];if(o==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,r);if(o==="["){let i=1,a=s+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let c=e.slice(s+1,a),l=K(t,c);return{part:N.arithmeticExpansion(l),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,r):o==="{"?Sf(t,e,r,n):/[a-zA-Z_0-9@*#?$!-]/.test(o)?xf(t,e,r):{part:N.literal("$"),endIndex:s}}function Af(t,e){let r=[],n=0,s="",o=()=>{s&&(r.push(N.literal(s)),s="")};for(;n<e.length;){let i=e[n];if(i==="\\"&&n+1<e.length){let a=e[n+1];if(a==="$"||a==="`"){s+=a,n+=2;continue}s+=i,n++;continue}if(i==="$"){o();let{part:a,endIndex:c}=Gr(t,e,n,!0);a&&r.push(a),n=c;continue}if(i==="`"){o();let{part:a,endIndex:c}=t.parseBacktickSubstitution(e,n,!0);r.push(a),n=c;continue}s+=i,n++}return o(),r}function $f(t,e,r){let n=[],s=r,o="",i=()=>{o&&(n.push(N.literal(o)),o="")};for(;s<e.length&&e[s]!=='"';){let a=e[s];if(a==="\\"&&s+1<e.length){let c=e[s+1];if('"\\$`\n'.includes(c)){o+=c,s+=2;continue}o+=a,s++;continue}if(a==="$"){i();let{part:c,endIndex:l}=Gr(t,e,s,!0);c&&n.push(c),s=l;continue}if(a==="`"){i();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,s,!0);n.push(c),s=l;continue}o+=a,s++}return i(),{part:N.doubleQuoted(n),endIndex:s}}function Re(t,e,r=!1,n=!1,s=!1,o=!1,i=!1){if(n)return[N.singleQuoted(e)];if(r){let f=Af(t,e);return[N.doubleQuoted(f)]}let a=[],c=0,l="",u=()=>{l&&(a.push(N.literal(l)),l="")};for(;c<e.length;){let f=e[c];if(f==="\\"&&c+1<e.length){let d=e[c+1];(o?d==="$"||d==="`"||d==="\\"||d===`
|
|
425
|
+
`||i===";"||i==="&"||i==="|")return null;s++}}return null}};var Dr=1e6,Tr=1e5,Bo=1e6,zo=new Set([m.LESS,m.GREAT,m.DLESS,m.DGREAT,m.LESSAND,m.GREATAND,m.LESSGREAT,m.DLESSDASH,m.CLOBBER,m.TLESS,m.AND_GREAT,m.AND_DGREAT]),Uo=new Set([m.LESS,m.GREAT,m.DLESS,m.DGREAT,m.LESSAND,m.GREATAND,m.LESSGREAT,m.DLESSDASH,m.CLOBBER,m.TLESS]),$e=class extends Error{line;column;token;constructor(e,r,n,s=void 0){super(`Parse error at ${r}:${n}: ${e}`),this.line=r,this.column=n,this.token=s,this.name="ParseException"}};function qo(t,e,r){let n=r+1;for(;n<e.length&&/[a-zA-Z0-9_-]/.test(e[n]);)n++;return n}function Mr(t,e,r,n,s){let o=1,i=r+1;for(;i<e.length&&o>0;)e[i]===n?o++:e[i]===s&&o--,o>0&&i++;return o===0?i:-1}function He(t,e,r){let n=r,s=1;for(;n<e.length&&s>0;){let o=e[n];if(o==="\\"&&n+1<e.length){n+=2;continue}if(o==="'"){let i=e.indexOf("'",n+1);if(i!==-1){n=i+1;continue}}if(o==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++;continue}o==="{"?s++:o==="}"&&s--,s>0&&n++}return n}function Go(t,e,r){let n=r,s=!1;for(;n<e.length;){let o=e[n];if(o==="/"&&s||o==="}")break;if(o==="'"){let i=e.indexOf("'",n+1);if(i!==-1){n=i+1,s=!0;continue}}if(o==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++,s=!0;continue}o==="\\"?(n+=2,s=!0):(n++,s=!0)}return n}function Vo(t,e,r){let n=r,s="";for(;n<e.length;){let o=e[n];if(o==="*"||o==="?")s+=o,n++;else if(o==="["){let i=df(e,n);i===-1?(s+=o,n++):(s+=e.slice(n,i+1),n=i+1)}else break}return{pattern:s,endIndex:n}}function df(t,e){let r=e+1;for(r<t.length&&t[r]==="^"&&r++,r<t.length&&t[r]==="]"&&r++;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){r+=2;continue}if(n==="]")return r;if(n==='"'||n==="$"||n==="`")return-1;if(n==="'"){let s=t.indexOf("'",r+1);if(s!==-1){r=s+1;continue}}if(n==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){r=s+2;continue}}if(n==="["&&r+1<t.length&&(t[r+1]==="."||t[r+1]==="=")){let o=`${t[r+1]}]`,i=t.indexOf(o,r+2);if(i!==-1){r=i+2;continue}}r++}return-1}function Zo(t,e,r){let n="",s=r;for(;s<e.length&&e[s]!=="'";){let o=e[s];if(o==="\\"&&s+1<e.length)switch(e[s+1]){case"n":n+=`
|
|
426
|
+
`,s+=2;break;case"t":n+=" ",s+=2;break;case"r":n+="\r",s+=2;break;case"\\":n+="\\",s+=2;break;case"'":n+="'",s+=2;break;case'"':n+='"',s+=2;break;case"a":n+="\x07",s+=2;break;case"b":n+="\b",s+=2;break;case"e":case"E":n+="\x1B",s+=2;break;case"f":n+="\f",s+=2;break;case"v":n+="\v",s+=2;break;case"x":{let a=e.slice(s+2,s+4),c=parseInt(a,16);Number.isNaN(c)?(n+="\\x",s+=2):(n+=String.fromCharCode(c),s+=4);break}case"u":{let a=e.slice(s+2,s+6),c=parseInt(a,16);Number.isNaN(c)?(n+="\\u",s+=2):(n+=String.fromCharCode(c),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",c=s+1;for(;c<e.length&&c<s+4&&/[0-7]/.test(e[c]);)a+=e[c],c++;let l=parseInt(a,8);n+=String.fromCharCode(l),s=c;break}default:n+=o,s++}else n+=o,s++}return s<e.length&&e[s]==="'"&&s++,{part:N.literal(n),endIndex:s}}function Fr(t,e){let r=e.trim();return r===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:K(t,r)}function jo(t){let e=[],r="",n=0;for(let s=0;s<t.length;s++){let o=t[s];o==="{"?(n++,r+=o):o==="}"?(n--,r+=o):o===","&&n===0?(e.push(r),r=""):r+=o}return e.push(r),e}function Qo(t,e,r,n){let s=Mr(t,e,r,"{","}");if(s===-1)return null;let o=e.slice(r+1,s),i=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(i)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:s+1};let a=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:s+1}:o.includes(",")&&n?{part:{type:"BraceExpansion",items:jo(o).map(u=>({type:"Word",word:N.word(n(t,u,!1,!1,!1))}))},endIndex:s+1}:o.includes(",")?{part:{type:"BraceExpansion",items:jo(o).map(u=>({type:"Word",word:N.word([N.literal(u)])}))},endIndex:s+1}:null}function Ko(t,e){let r="";for(let n of e.parts)switch(n.type){case"Literal":case"SingleQuoted":case"Escaped":r+=n.value;break;case"DoubleQuoted":r+='"';for(let s of n.parts)s.type==="Literal"||s.type==="Escaped"?r+=s.value:s.type==="ParameterExpansion"&&(r+=`\${${s.parameter}}`);r+='"';break;case"ParameterExpansion":r+=`\${${n.parameter}}`;break;case"Glob":r+=n.pattern;break;default:r+=n.type}return r}function Xo(t,e){return{[m.LESS]:"<",[m.GREAT]:">",[m.DGREAT]:">>",[m.LESSAND]:"<&",[m.GREATAND]:">&",[m.LESSGREAT]:"<>",[m.CLOBBER]:">|",[m.TLESS]:"<<<",[m.AND_GREAT]:"&>",[m.AND_DGREAT]:"&>>",[m.DLESS]:"<",[m.DLESSDASH]:"<"}[e]||">"}function Tt(t){let e=t.current(),r=e.type;if(r===m.NUMBER){let n=t.peek(1);return e.end!==n.start?!1:Uo.has(n.type)}return zo.has(r)}function Mt(t){let e=null;t.check(m.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let r=t.advance(),n=Xo(t,r.type);if(r.type===m.DLESS||r.type===m.DLESSDASH)return hf(t,n,e,r.type===m.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return N.redirection(n,s,e)}function hf(t,e,r,n){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),o=s.value,i=s.quoted||!1;(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1));let a=N.redirection(n?"<<-":"<<",N.hereDoc(o,N.word([]),n,i),r);return t.addPendingHeredoc(a,o,n,i),a}function Jo(t){let e=[],r=null,n=[],s=[];for(;t.check(m.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(pf(t));for(;Tt(t);)t.checkIterationLimit(),s.push(Mt(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(m.RBRACE))&&!t.check(m.PIPE,m.PIPE_AMP);)if(t.checkIterationLimit(),Tt(t))s.push(Mt(t));else if(t.check(m.RBRACE)){let o=t.advance();n.push(t.parseWordFromString(o.value,!1,!1))}else if(t.isWord())n.push(t.parseWord());else if(t.check(m.ASSIGNMENT_WORD)){let o=t.advance(),i=o.value,a=i.endsWith("="),c=i.endsWith("=(");if((a||c)&&(c||t.check(m.LPAREN))){let l=c?i.slice(0,-2):i.slice(0,-1);c||t.expect(m.LPAREN);let u=Lr(t);t.expect(m.RPAREN);let f=u.map(h=>Ko(t,h)),d=`${l}=(${f.join(" ")})`;n.push(t.parseWordFromString(d,!1,!1))}else n.push(t.parseWordFromString(i,o.quoted,o.singleQuoted))}else if(t.check(m.LPAREN))t.error("syntax error near unexpected token `('");else break;return N.simpleCommand(r,n,e,s)}function pf(t){let e=t.expect(m.ASSIGNMENT_WORD),r=e.value,n=r.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);n||t.error(`Invalid assignment: ${r}`);let s=n[0],o,i=s.length;if(r[i]==="["){let f=0,d=i+1;for(;i<r.length;i++)if(r[i]==="[")f++;else if(r[i]==="]"&&(f--,f===0))break;f!==0&&t.error(`Invalid assignment: ${r}`),o=r.slice(d,i),i++}let a=r[i]==="+";a&&i++,r[i]!=="="&&t.error(`Invalid assignment: ${r}`),i++;let c=r.slice(i);if(c==="("){let f=Lr(t);t.expect(m.RPAREN);let d=o!==void 0?`${s}[${o}]`:s;return N.assignment(d,null,a,f)}if(c===""&&t.check(m.LPAREN)){let f=t.current();if(e.end===f.start){t.advance();let d=Lr(t);t.expect(m.RPAREN);let h=o!==void 0?`${s}[${o}]`:s;return N.assignment(h,null,a,d)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,u=o!==void 0?`${s}[${o}]`:s;return N.assignment(u,l,a,null)}function Lr(t){let e=[];for(t.skipNewlines();!t.check(m.RPAREN,m.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function Wr(t){t.expect(m.IF);let e=[],r=t.parseCompoundList();t.expect(m.THEN);let n=t.parseCompoundList();if(n.length===0){let i=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${i}'`)}for(e.push({condition:r,body:n});t.check(m.ELIF);){t.advance();let i=t.parseCompoundList();t.expect(m.THEN);let a=t.parseCompoundList();if(a.length===0){let c=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${c}'`)}e.push({condition:i,body:a})}let s=null;t.check(m.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(m.FI);let o=t.parseOptionalRedirections();return N.ifNode(e,s,o)}function _r(t){if(t.expect(m.FOR),t.check(m.DPAREN_START))return gf(t);t.isWord()||t.error("Expected variable name in for loop");let r=t.advance().value,n=null;if(t.skipNewlines(),t.check(m.IN))for(t.advance(),n=[];!t.check(m.SEMICOLON,m.NEWLINE,m.DO,m.EOF)&&t.isWord();)n.push(t.parseWord());t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let s=t.parseCompoundList();t.expect(m.DONE);let o=t.parseOptionalRedirections();return N.forNode(r,n,s,o)}function gf(t){t.expect(m.DPAREN_START);let e=null,r=null,n=null,s=["","",""],o=0,i=0;for(;!t.check(m.DPAREN_END,m.EOF);){let l=t.advance();if(l.type===m.SEMICOLON&&i===0){if(o++,o>2)break}else l.value==="("&&i++,l.value===")"&&i--,s[o]+=l.value}t.expect(m.DPAREN_END),s[0].trim()&&(e=K(t,s[0].trim())),s[1].trim()&&(r=K(t,s[1].trim())),s[2].trim()&&(n=K(t,s[2].trim())),t.skipNewlines(),t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let a=t.parseCompoundList();t.expect(m.DONE);let c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:r,update:n,body:a,redirections:c}}function Hr(t){t.expect(m.WHILE);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return N.whileNode(e,r,n)}function Br(t){t.expect(m.UNTIL);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return N.untilNode(e,r,n)}function zr(t){t.expect(m.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(m.IN),t.skipNewlines();let r=[];for(;!t.check(m.ESAC,m.EOF);){t.checkIterationLimit();let s=t.getPos(),o=yf(t);if(o&&r.push(o),t.skipNewlines(),t.getPos()===s&&!o)break}t.expect(m.ESAC);let n=t.parseOptionalRedirections();return N.caseNode(e,r,n)}function yf(t){t.check(m.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(m.PIPE));)t.advance();if(e.length===0)return null;t.expect(m.RPAREN),t.skipNewlines();let r=[];for(;!t.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND,m.ESAC,m.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===m.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(m.LPAREN)&&t.peek(1).type===m.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let s=t.getPos(),o=t.parseStatement();if(o&&r.push(o),t.skipSeparators(!1),t.getPos()===s&&!o)break}let n=";;";return t.check(m.DSEMI)?(t.advance(),n=";;"):t.check(m.SEMI_AND)?(t.advance(),n=";&"):t.check(m.SEMI_SEMI_AND)&&(t.advance(),n=";;&"),N.caseItem(e,r,n)}function Ur(t){t.peek(1).type,m.LPAREN,t.expect(m.LPAREN),t.check(m.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(m.RPAREN);let r=t.parseOptionalRedirections();return N.subshell(e,r)}function jr(t){t.expect(m.LBRACE);let e=t.parseCompoundList();t.expect(m.RBRACE);let r=t.parseOptionalRedirections();return N.group(e,r)}var bf=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],Ef=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function Gr(t){return t.skipNewlines(),xf(t)}function xf(t){let e=ea(t);for(t.skipNewlines();t.check(m.OR_OR);){t.advance(),t.skipNewlines();let r=ea(t);e={type:"CondOr",left:e,right:r},t.skipNewlines()}return e}function ea(t){let e=qr(t);for(t.skipNewlines();t.check(m.AND_AND);){t.advance(),t.skipNewlines();let r=qr(t);e={type:"CondAnd",left:e,right:r},t.skipNewlines()}return e}function qr(t){return t.skipNewlines(),t.check(m.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:qr(t)}):Sf(t)}function Sf(t){if(t.check(m.LPAREN)){t.advance();let e=Gr(t);return t.expect(m.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),r=e.value;if(bf.includes(r)&&!e.quoted&&(t.advance(),t.check(m.DBRACK_END)&&t.error(`Expected operand after ${r}`),t.isWord())){let s=t.parseWord();return{type:"CondUnary",operator:r,operand:s}}let n=t.parseWord();if(t.isWord()&&Ef.includes(t.current().value)){let s=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:s,left:n,right:o}}if(t.check(m.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:n,right:s}}if(t.check(m.GREAT)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:">",left:n,right:s}}if(t.isWord()&&t.current().value==="="){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"==",left:n,right:s}}return{type:"CondWord",word:n}}t.error("Expected conditional expression")}function Af(t,e,r){let n=r+1,s=e[n];if("@*#?$!-0123456789".includes(s))return{part:N.parameterExpansion(s),endIndex:n+1};let o="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)o+=e[n],n++;return{part:N.parameterExpansion(o),endIndex:n}}function $f(t,e,r,n=!1){let s=r+2,o=!1;e[s]==="!"&&(o=!0,s++);let i=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(i=!0,s++);let a="",c=e[s];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))a=c,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)a+=e[s],s++;if(e[s]==="["){let u=Mr(t,e,s,"[","]");a+=e.slice(s,u+1),s=u+1}a===""&&!o&&!i&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let l=null;if(o){let u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)l={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="";else if(e[s]==="*"||e[s]==="@"){let f=e[s];s++,l={type:"VarNamePrefix",prefix:a,star:f==="*"},a=""}else l={type:"Indirection"}}else if(i)if(e[s]===":")for(l={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${a}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):l={type:"Length"};if(!l&&s<e.length&&e[s]!=="}"){let u=Nf(t,e,s,a,n);l=u.operation,s=u.endIndex}if(s<e.length&&e[s]!=="}"){let u=e[s];if(!/[:\-+=?#%/^,@[]/.test(u)){let f=s;for(;f<e.length&&e[f]!=="}";)f++;let d=e.slice(r,f+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:N.parameterExpansion(a,l),endIndex:s+1}}function Nf(t,e,r,n,s=!1){let o=r,i=e[o],a=e[o+1]||"";if(i===":"){let c=a;if("-=?+".includes(c)){o+=2;let y=He(t,e,o),w=e.slice(o,y),E=Re(t,w,!1,!1,!0,!1,s),$=N.word(E.length>0?E:[N.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:$,checkEmpty:!0},endIndex:y};if(c==="=")return{operation:{type:"AssignDefault",word:$,checkEmpty:!0},endIndex:y};if(c==="?")return{operation:{type:"ErrorIfUnset",word:$,checkEmpty:!0},endIndex:y};if(c==="+")return{operation:{type:"UseAlternative",word:$,checkEmpty:!0},endIndex:y}}o++;let l=He(t,e,o),u=e.slice(o,l),f=-1,d=0,h=0;for(let g=0;g<u.length;g++){let y=u[g];if(y==="("||y==="[")d++;else if(y===")"||y==="]")d--;else if(y==="?"&&d===0)h++;else if(y===":"&&d===0)if(h>0)h--;else{f=g;break}}let p=f>=0?u.slice(0,f):u,b=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:Fr(t,p),length:b?Fr(t,b):null},endIndex:l}}if("-=?+".includes(i)){o++;let c=He(t,e,o),l=e.slice(o,c),u=Re(t,l,!1,!1,!0,!1,s),f=N.word(u.length>0?u:[N.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:c};if(i==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:c};if(i==="?")return{operation:{type:"ErrorIfUnset",word:l?f:null,checkEmpty:!1},endIndex:c};if(i==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:c}}if(i==="#"||i==="%"){let c=a===i,l=i==="#"?"prefix":"suffix";o+=c?2:1;let u=He(t,e,o),f=e.slice(o,u),d=Re(t,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:N.word(d.length>0?d:[N.literal("")]),side:l,greedy:c},endIndex:u}}if(i==="/"){let c=a==="/";o+=c?2:1;let l=null;e[o]==="#"?(l="start",o++):e[o]==="%"&&(l="end",o++);let u=Go(t,e,o),f=e.slice(o,u),d=Re(t,f,!1,!1,!1),h=N.word(d.length>0?d:[N.literal("")]),p=null,b=u;if(e[u]==="/"){let g=u+1,y=He(t,e,g),w=e.slice(g,y),E=Re(t,w,!1,!1,!1);p=N.word(E.length>0?E:[N.literal("")]),b=y}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:c,anchor:l},endIndex:b}}if(i==="^"||i===","){let c=a===i,l=i==="^"?"upper":"lower";o+=c?2:1;let u=He(t,e,o),f=e.slice(o,u),d=f?N.word([N.literal(f)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:d},endIndex:u}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Vr(t,e,r,n=!1){let s=r+1;if(s>=e.length)return{part:N.literal("$"),endIndex:s};let o=e[s];if(o==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,r);if(o==="["){let i=1,a=s+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let c=e.slice(s+1,a),l=K(t,c);return{part:N.arithmeticExpansion(l),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,r):o==="{"?$f(t,e,r,n):/[a-zA-Z_0-9@*#?$!-]/.test(o)?Af(t,e,r):{part:N.literal("$"),endIndex:s}}function vf(t,e){let r=[],n=0,s="",o=()=>{s&&(r.push(N.literal(s)),s="")};for(;n<e.length;){let i=e[n];if(i==="\\"&&n+1<e.length){let a=e[n+1];if(a==="$"||a==="`"){s+=a,n+=2;continue}s+=i,n++;continue}if(i==="$"){o();let{part:a,endIndex:c}=Vr(t,e,n,!0);a&&r.push(a),n=c;continue}if(i==="`"){o();let{part:a,endIndex:c}=t.parseBacktickSubstitution(e,n,!0);r.push(a),n=c;continue}s+=i,n++}return o(),r}function kf(t,e,r){let n=[],s=r,o="",i=()=>{o&&(n.push(N.literal(o)),o="")};for(;s<e.length&&e[s]!=='"';){let a=e[s];if(a==="\\"&&s+1<e.length){let c=e[s+1];if('"\\$`\n'.includes(c)){o+=c,s+=2;continue}o+=a,s++;continue}if(a==="$"){i();let{part:c,endIndex:l}=Vr(t,e,s,!0);c&&n.push(c),s=l;continue}if(a==="`"){i();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,s,!0);n.push(c),s=l;continue}o+=a,s++}return i(),{part:N.doubleQuoted(n),endIndex:s}}function Re(t,e,r=!1,n=!1,s=!1,o=!1,i=!1){if(n)return[N.singleQuoted(e)];if(r){let f=vf(t,e);return[N.doubleQuoted(f)]}let a=[],c=0,l="",u=()=>{l&&(a.push(N.literal(l)),l="")};for(;c<e.length;){let f=e[c];if(f==="\\"&&c+1<e.length){let d=e[c+1];(o?d==="$"||d==="`"||d==="\\"||d===`
|
|
427
427
|
`:d==="$"||d==="`"||d==="\\"||d==='"'||d===`
|
|
428
|
-
`)?l+=d:l+=`\\${d}`,c+=2;continue}if(f==="'"&&!i){u();let d=e.indexOf("'",c+1);if(d===-1){l+=e.slice(c);break}a.push(N.singleQuoted(e.slice(c+1,d))),c=d+1;continue}if(f==='"'){u();let{part:d,endIndex:h}
|
|
428
|
+
`)?l+=d:l+=`\\${d}`,c+=2;continue}if(f==="'"&&!i){u();let d=e.indexOf("'",c+1);if(d===-1){l+=e.slice(c);break}a.push(N.singleQuoted(e.slice(c+1,d))),c=d+1;continue}if(f==='"'){u();let{part:d,endIndex:h}=kf(t,e,c+1);a.push(d),c=h+1;continue}if(f==="$"&&e[c+1]==="'"){u();let{part:d,endIndex:h}=Zo(t,e,c+2);a.push(d),c=h;continue}if(f==="$"){u();let{part:d,endIndex:h}=Vr(t,e,c);d&&a.push(d),c=h;continue}if(f==="`"){u();let{part:d,endIndex:h}=t.parseBacktickSubstitution(e,c);a.push(d),c=h;continue}if(f==="~"){let d=c>0?e[c-1]:"";if(c===0||d==="="||s&&d===":"){let p=qo(t,e,c),b=e[p];if(b===void 0||b==="/"||b===":"){u();let g=e.slice(c+1,p)||null;a.push({type:"TildeExpansion",user:g}),c=p;continue}}}if(f==="*"||f==="?"||f==="["){u();let{pattern:d,endIndex:h}=Vo(t,e,c);a.push({type:"Glob",pattern:d}),c=h;continue}if(f==="{"&&!s){let d=Qo(t,e,c,Re);if(d){u(),a.push(d.part),c=d.endIndex;continue}}l+=f,c++}return u(),a}var ee=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Bo)throw new $e("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>Dr)throw new $e(`Input too large: ${e.length} bytes exceeds limit of ${Dr}`,1,1);let r=new Dt(e);if(this.tokens=r.tokenize(),this.tokens.length>Tr)throw new $e(`Too many tokens: ${this.tokens.length} exceeds limit of ${Tr}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseScript()}parseTokens(e){return this.tokens=e,this.pos=0,this.pendingHeredocs=[],this.parseScript()}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(e=0){return this.tokens[this.pos+e]||this.tokens[this.tokens.length-1]}advance(){let e=this.current();return this.pos<this.tokens.length-1&&this.pos++,e}getPos(){return this.pos}check(e,r,n,s,...o){let i=this.tokens[this.pos]?.type;return i===e||r!==void 0&&i===r||n!==void 0&&i===n||s!==void 0&&i===s?!0:o.length>0?o.includes(i):!1}expect(e,r){if(this.check(e))return this.advance();let n=this.current();throw new $e(r||`Expected ${e}, got ${n.type}`,n.line,n.column,n)}error(e){let r=this.current();throw new $e(e,r.line,r.column,r)}skipNewlines(){for(;this.check(m.NEWLINE,m.COMMENT);)this.check(m.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(m.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(m.SEMICOLON,m.COMMENT)){this.advance();continue}if(e&&this.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,r,n,s){this.pendingHeredocs.push({redirect:e,delimiter:r,stripTabs:n,quoted:s})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(m.HEREDOC_CONTENT)){let r=this.advance(),n;e.quoted?n=N.word([N.literal(r.value)]):n=this.parseWordFromString(r.value,!1,!1,!1,!0),e.redirect.target=N.hereDoc(e.delimiter,n,e.stripTabs,e.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(m.EOF,m.NEWLINE,m.SEMICOLON,m.AMP,m.AND_AND,m.OR_OR,m.RPAREN,m.RBRACE,m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return e===m.WORD||e===m.NAME||e===m.NUMBER||e===m.ASSIGNMENT_WORD||e===m.IF||e===m.FOR||e===m.WHILE||e===m.UNTIL||e===m.CASE||e===m.LPAREN||e===m.LBRACE||e===m.DPAREN_START||e===m.DBRACK_START||e===m.FUNCTION||e===m.BANG||e===m.IN}parseScript(){let e=[],n=0;for(this.skipNewlines();!this.check(m.EOF);){n++,n>1e4&&this.error("Parser stuck: too many iterations (>10000)"),this.checkUnexpectedToken();let s=this.pos,o=this.parseStatement();o&&e.push(o),this.skipSeparators(!1),this.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===s&&!this.check(m.EOF)&&this.advance()}return N.script(e)}checkUnexpectedToken(){let e=this.current().type,r=this.current().value;(e===m.DO||e===m.DONE||e===m.THEN||e===m.ELSE||e===m.ELIF||e===m.FI||e===m.ESAC)&&this.error(`syntax error near unexpected token \`${r}'`),(e===m.RBRACE||e===m.RPAREN)&&this.error(`syntax error near unexpected token \`${r}'`),(e===m.DSEMI||e===m.SEMI_AND||e===m.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${r}'`),e===m.SEMICOLON&&this.error(`syntax error near unexpected token \`${r}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],r=[],n=!1,s=this.parsePipeline();for(e.push(s);this.check(m.AND_AND,m.OR_OR);){let o=this.advance();r.push(o.type===m.AND_AND?"&&":"||"),this.skipNewlines();let i=this.parsePipeline();e.push(i)}return this.check(m.AMP)&&(this.advance(),n=!0),N.statement(e,r,n)}parsePipeline(){let e=0;for(;this.check(m.BANG);)this.advance(),e++;let r=e%2===1,n=[],s=this.parseCommand();for(n.push(s);this.check(m.PIPE,m.PIPE_AMP);){let o=this.advance();this.skipNewlines();let i=this.parseCommand();o.type===m.PIPE_AMP&&i.type==="SimpleCommand"&&i.redirections.unshift(N.redirection(">&",N.word([N.literal("1")]),2)),n.push(i)}return N.pipeline(n,r)}parseCommand(){return this.check(m.IF)?Wr(this):this.check(m.FOR)?_r(this):this.check(m.WHILE)?Hr(this):this.check(m.UNTIL)?Br(this):this.check(m.CASE)?zr(this):this.check(m.LPAREN)?Ur(this):this.check(m.LBRACE)?jr(this):this.check(m.DPAREN_START)?this.parseArithmeticCommand():this.check(m.DBRACK_START)?this.parseConditionalCommand():this.check(m.FUNCTION)?this.parseFunctionDef():this.check(m.NAME,m.WORD)&&this.peek(1).type===m.LPAREN&&this.peek(2).type===m.RPAREN?this.parseFunctionDef():Jo(this)}isWord(){let e=this.current().type;return e===m.WORD||e===m.NAME||e===m.NUMBER||e===m.IF||e===m.FOR||e===m.WHILE||e===m.UNTIL||e===m.CASE||e===m.FUNCTION||e===m.ELSE||e===m.ELIF||e===m.FI||e===m.THEN||e===m.DO||e===m.DONE||e===m.ESAC||e===m.IN||e===m.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,r=!1,n=!1,s=!1,o=!1){let i=Re(this,e,r,n,s,o);return N.word(i)}parseCommandSubstitution(e,r){let n=r+2,s=1,o=n,i=!1,a=!1,c=0,l=!1,u="";for(;o<e.length&&s>0;){let p=e[o];i?p==="'"&&(i=!1):a?p==="\\"&&o+1<e.length?o++:p==='"'&&(a=!1):p==="'"?(i=!0,u=""):p==='"'?(a=!0,u=""):p==="\\"&&o+1<e.length?(o++,u=""):/[a-zA-Z_]/.test(p)?u+=p:(u==="case"?(c++,l=!1):u==="in"&&c>0?l=!0:u==="esac"&&c>0&&(c--,l=!1),u="",p==="("?o>0&&e[o-1]==="$"?s++:l||s++:p===")"?l?l=!1:s--:p===";"&&c>0&&o+1<e.length&&e[o+1]===";"&&(l=!0)),s>0&&o++}s>0&&this.error("unexpected EOF while looking for matching `)'");let f=e.slice(n,o),h=new t().parse(f);return{part:N.commandSubstitution(h,!1),endIndex:o+1}}parseBacktickSubstitution(e,r,n=!1){let o=r+1,i="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let l=e[o+1];l==="$"||l==="`"||l==="\\"||l===`
|
|
429
429
|
`||n&&l==='"'?(l!==`
|
|
430
|
-
`&&(i+=l),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(i);return{part:N.commandSubstitution(c,!0),endIndex:o+1}}parseArithmeticExpansion(e,r){let n=r+3,s=1,o=0,i=n;for(;i<e.length-1&&s>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(s++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(s++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(s--,s>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(n,i),c=this.parseArithmeticExpression(a);return{part:N.arithmeticExpansion(c),endIndex:i+2}}parseArithmeticCommand(){this.expect(m.DPAREN_START);let e="",r=1,n=0,s=!1,o=!1;for(;r>0&&!this.check(m.EOF);){if(s){if(s=!1,n>0){n--,e+=")";continue}if(this.check(m.RPAREN)){r--,o=!0,this.advance();continue}if(this.check(m.DPAREN_END)){r--,o=!0;continue}e+=")";continue}this.check(m.DPAREN_START)?(r++,e+="((",this.advance()):this.check(m.DPAREN_END)?n>=2?(n-=2,e+="))",this.advance()):n===1?(n--,e+=")",s=!0,this.advance()):(r--,o=!0,r>0&&(e+="))"),this.advance()):this.check(m.LPAREN)?(n++,e+="(",this.advance()):this.check(m.RPAREN)?(n>0&&n--,e+=")",this.advance()):(e+=this.current().value,this.advance())}o||this.expect(m.DPAREN_END);let i=this.parseArithmeticExpression(e.trim()),a=this.parseOptionalRedirections();return N.arithmeticCommand(i,a)}parseConditionalCommand(){this.expect(m.DBRACK_START);let e=qr(this);this.expect(m.DBRACK_END);let r=this.parseOptionalRedirections();return N.conditionalCommand(e,r)}parseFunctionDef(){let e;this.check(m.FUNCTION)?(this.advance(),e=this.expect(m.NAME,"Expected function name").value,this.check(m.LPAREN)&&(this.advance(),this.expect(m.RPAREN))):(e=this.advance().value,this.expect(m.LPAREN),this.expect(m.RPAREN)),this.skipNewlines();let r=this.parseCompoundCommandBody(),n=this.parseOptionalRedirections();return N.functionDef(e,r,n)}parseCompoundCommandBody(){if(this.check(m.LBRACE))return Ur(this);if(this.check(m.LPAREN))return zr(this);if(this.check(m.IF))return Wr(this);if(this.check(m.FOR))return Lr(this);if(this.check(m.WHILE))return _r(this);if(this.check(m.UNTIL))return Hr(this);if(this.check(m.CASE))return Br(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(m.EOF,m.FI,m.ELSE,m.ELIF,m.THEN,m.DO,m.DONE,m.ESAC,m.RPAREN,m.RBRACE,m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,n=this.parseStatement();if(n&&e.push(n),this.skipSeparators(),this.pos===r&&!n)break}return e}parseOptionalRedirections(){let e=[];for(;Dt(this);){this.checkIterationLimit();let r=this.pos;if(e.push(Tt(this)),this.pos===r)break}return e}parseArithmeticExpression(e){return K(this,e)}};function Oe(t){return new ee().parse(t)}Z();var Qe=class{fs;cwd;constructor(e,r){this.fs=e,this.cwd=r}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,r){let n=[];for(let s=0;s<e.length;s++){let o=e[s];if((r?.[s]??!1)||!this.isGlobPattern(o))n.push(o);else{let a=await this.expand(o);a.length>0?n.push(...a):n.push(o)}}return n}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let r=[],n=e.lastIndexOf("/"),s,o;n===-1?(s=this.cwd,o=e):(s=e.slice(0,n)||"/",o=e.slice(n+1));let i=this.fs.resolvePath(this.cwd,s);try{let a=await this.fs.readdir(i);for(let c of a)if(this.matchPattern(c,o)){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async expandRecursive(e){let r=[],n=e.indexOf("**"),s=e.slice(0,n).replace(/\/$/,"")||".",i=e.slice(n+2).replace(/^\//,"");return await this.walkDirectory(s,i,r),r.sort()}async walkDirectory(e,r,n){let s=this.fs.resolvePath(this.cwd,e);try{let o=await this.fs.readdir(s);for(let i of o){let a=e==="."?i:`${e}/${i}`,c=this.fs.resolvePath(this.cwd,a);try{(await this.fs.stat(c)).isDirectory?await this.walkDirectory(a,r,n):r&&this.matchPattern(i,r)&&n.push(a)}catch{}}}catch{}}matchPattern(e,r){return this.patternToRegex(r).test(e)}patternToRegex(e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let o=n+1,i="[";for(o<e.length&&(e[o]==="^"||e[o]==="!")&&(i+="^",o++),o<e.length&&e[o]==="]"&&(i+="\\]",o++);o<e.length&&e[o]!=="]";){if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let a=e.indexOf(":]",o+2);if(a!==-1){let c=e.slice(o+2,a),l=this.posixClassToRegex(c);i+=l,o=a+2;continue}}if(e[o]==="\\"&&o+1<e.length){i+=`\\${e[o+1]}`,o+=2;continue}e[o]==="-"?i+="\\-":i+=e[o],o++}i+="]",r+=i,n=o}else if(s==="\\"&&n+1<e.length){let o=e[n+1];/[.+^${}()|\\*?[\]]/.test(o)?r+=`\\${o}`:r+=o,n++}else/[.+^${}()|]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r)}posixClassToRegex(e){return{alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9a-fA-F"}[e]||""}};Z();function pe(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return pe(t.expression);case"ArithBinary":return pe(t.left)||pe(t.right);case"ArithUnary":return pe(t.operand);case"ArithTernary":return pe(t.condition)||pe(t.consequent)||pe(t.alternate);case"ArithAssignment":return pe(t.value);case"ArithGroup":return pe(t.expression);case"ArithArrayElement":return t.index?pe(t.index):!1;case"ArithConcat":return t.parts.some(pe);default:return!1}}function Vr(t){let e=t.operation;return e?!!("word"in e&&e.word&&Ne(e.word)||e.type==="PatternReplacement"&&(e.pattern&&Ne(e.pattern)||e.replacement&&Ne(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&Ne(e.pattern)):!1}function Mt(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return pe(t.expression.expression);case"DoubleQuoted":return t.parts.some(Mt);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&Ne(e.word));case"ParameterExpansion":return Vr(t);default:return!1}}function Ne(t){return t.parts.some(Mt)}function Zr(t){if(!t.operation)return!1;let e=t.operation,r;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(r=e.word?.parts),!r)return!1;for(let n of r)if(n.type==="DoubleQuoted"||n.type==="SingleQuoted")return!0;return!1}function Yo(t){let e=!1,r=!1,n=!1,s=!1,o=!1;for(let i of t){if((i.type==="SingleQuoted"||i.type==="DoubleQuoted")&&(e=!0,i.type==="DoubleQuoted"))for(let a of i.parts)a.type==="ParameterExpansion"&&a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!a.operation&&(s=!0);i.type==="CommandSubstitution"&&(r=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(n=!0),Zr(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:r,hasArrayVar:n,hasArrayAtExpansion:s,hasParamExpansion:o}}function vf(t,e,r,n,s){let o=r??1;o===0&&(o=1);let i=Math.abs(o),a=[],c=0;n?.match(/^-?0\d/)&&(c=Math.max(c,n.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length));let l=u=>{if(c>0){let f=u<0,d=String(Math.abs(u)).padStart(c,"0");return f?`-${d}`:d}return String(u)};if(t<=e)for(let u=t,f=0;u<=e&&f<1e4;u+=i,f++)a.push(l(u));else for(let u=t,f=0;u>=e&&f<1e4;u-=i,f++)a.push(l(u));return a}function kf(t,e,r){let n=r??1;n===0&&(n=1);let s=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(n),a=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",u=e>="a"&&e<="z";if(a&&u||c&&l)return null;let f=[];if(s<=o)for(let d=s,h=0;d<=o&&h<1e4;d+=i,h++)f.push(String.fromCharCode(d));else for(let d=s,h=0;d>=o&&h<1e4;d-=i,h++)f.push(String.fromCharCode(d));return f}function it(t,e,r,n,s){let o=r!==void 0?`..${r}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:vf(t,e,r,n,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:kf(t,e,r),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function ae(t,e){let r="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")if(n+1<t.length){let o=t[n+1];/[\\^$.|+(){}[\]*?]/.test(o)?r+=`\\${o}`:r+=o,n+=2}else r+="\\\\",n++;else if(s==="*")r+=e?".*":".*?",n++;else if(s==="?")r+=".",n++;else if(s==="["){let o=If(t,n);if(o===-1)r+="\\[",n++;else{let i=t.slice(n+1,o);r+=Pf(i),n=o+1}}else/[\^$.|+(){}]/.test(s)?(r+=`\\${s}`,n++):(r+=s,n++)}return r}function If(t,e){let r=e+1;for(r<t.length&&t[r]==="^"&&r++,r<t.length&&t[r]==="]"&&r++;r<t.length;){if(t[r]==="\\"&&r+1<t.length){r+=2;continue}if(t[r]==="]")return r;if(t[r]==="'"){let n=t.indexOf("'",r+1);if(n!==-1){r=n+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let n=t.indexOf(":]",r+2);if(n!==-1){r=n+2;continue}}r++}return-1}function Pf(t){let e="[",r=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",r++);r<t.length;){if(t[r]==="'"){let s=t.indexOf("'",r+1);if(s!==-1){let o=t.slice(r+1,s);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;r=s+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){let o=t.slice(r+2,s);e+=Of(o),r=s+2;continue}}let n=t[r];n==="\\"?r+1<t.length?(e+=`\\${t[r+1]}`,r+=2):(e+="\\\\",r++):n==="-"&&r>0&&r<t.length-1?(e+="-",r++):n==="^"&&r===0?(e+="^",r++):(n==="]"&&r===0?e+="\\]":e+=n,r++)}return e+="]",e}var Rf={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9A-Fa-f"};function Of(t){return Rf[t]??""}Z();function ot(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)){let o=s.slice(r.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&n.push(i)}return n.sort((s,o)=>s-o)}function Qr(t,e){let r=`${e}_`;for(let n of Object.keys(t.state.env))n.startsWith(r)&&delete t.state.env[n]}function Kr(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)&&!s.includes("__")){let o=s.slice(r.length);n.push(o)}return n.sort()}function Jo(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Ft(t){return t.IFS??`
|
|
431
|
-
`}function
|
|
432
|
-
`?"\\n":e).join("")}function
|
|
430
|
+
`&&(i+=l),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(i);return{part:N.commandSubstitution(c,!0),endIndex:o+1}}parseArithmeticExpansion(e,r){let n=r+3,s=1,o=0,i=n;for(;i<e.length-1&&s>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(s++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(s++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(s--,s>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(n,i),c=this.parseArithmeticExpression(a);return{part:N.arithmeticExpansion(c),endIndex:i+2}}parseArithmeticCommand(){this.expect(m.DPAREN_START);let e="",r=1,n=0,s=!1,o=!1;for(;r>0&&!this.check(m.EOF);){if(s){if(s=!1,n>0){n--,e+=")";continue}if(this.check(m.RPAREN)){r--,o=!0,this.advance();continue}if(this.check(m.DPAREN_END)){r--,o=!0;continue}e+=")";continue}this.check(m.DPAREN_START)?(r++,e+="((",this.advance()):this.check(m.DPAREN_END)?n>=2?(n-=2,e+="))",this.advance()):n===1?(n--,e+=")",s=!0,this.advance()):(r--,o=!0,r>0&&(e+="))"),this.advance()):this.check(m.LPAREN)?(n++,e+="(",this.advance()):this.check(m.RPAREN)?(n>0&&n--,e+=")",this.advance()):(e+=this.current().value,this.advance())}o||this.expect(m.DPAREN_END);let i=this.parseArithmeticExpression(e.trim()),a=this.parseOptionalRedirections();return N.arithmeticCommand(i,a)}parseConditionalCommand(){this.expect(m.DBRACK_START);let e=Gr(this);this.expect(m.DBRACK_END);let r=this.parseOptionalRedirections();return N.conditionalCommand(e,r)}parseFunctionDef(){let e;this.check(m.FUNCTION)?(this.advance(),e=this.expect(m.NAME,"Expected function name").value,this.check(m.LPAREN)&&(this.advance(),this.expect(m.RPAREN))):(e=this.advance().value,this.expect(m.LPAREN),this.expect(m.RPAREN)),this.skipNewlines();let r=this.parseCompoundCommandBody(),n=this.parseOptionalRedirections();return N.functionDef(e,r,n)}parseCompoundCommandBody(){if(this.check(m.LBRACE))return jr(this);if(this.check(m.LPAREN))return Ur(this);if(this.check(m.IF))return Wr(this);if(this.check(m.FOR))return _r(this);if(this.check(m.WHILE))return Hr(this);if(this.check(m.UNTIL))return Br(this);if(this.check(m.CASE))return zr(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(m.EOF,m.FI,m.ELSE,m.ELIF,m.THEN,m.DO,m.DONE,m.ESAC,m.RPAREN,m.RBRACE,m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,n=this.parseStatement();if(n&&e.push(n),this.skipSeparators(),this.pos===r&&!n)break}return e}parseOptionalRedirections(){let e=[];for(;Tt(this);){this.checkIterationLimit();let r=this.pos;if(e.push(Mt(this)),this.pos===r)break}return e}parseArithmeticExpression(e){return K(this,e)}};function Oe(t){return new ee().parse(t)}Z();var Qe=class{fs;cwd;constructor(e,r){this.fs=e,this.cwd=r}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,r){let n=[];for(let s=0;s<e.length;s++){let o=e[s];if((r?.[s]??!1)||!this.isGlobPattern(o))n.push(o);else{let a=await this.expand(o);a.length>0?n.push(...a):n.push(o)}}return n}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let r=[],n=e.lastIndexOf("/"),s,o;n===-1?(s=this.cwd,o=e):(s=e.slice(0,n)||"/",o=e.slice(n+1));let i=this.fs.resolvePath(this.cwd,s);try{let a=await this.fs.readdir(i);for(let c of a)if(this.matchPattern(c,o)){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async expandRecursive(e){let r=[],n=e.indexOf("**"),s=e.slice(0,n).replace(/\/$/,"")||".",i=e.slice(n+2).replace(/^\//,"");return await this.walkDirectory(s,i,r),r.sort()}async walkDirectory(e,r,n){let s=this.fs.resolvePath(this.cwd,e);try{let o=await this.fs.readdir(s);for(let i of o){let a=e==="."?i:`${e}/${i}`,c=this.fs.resolvePath(this.cwd,a);try{(await this.fs.stat(c)).isDirectory?await this.walkDirectory(a,r,n):r&&this.matchPattern(i,r)&&n.push(a)}catch{}}}catch{}}matchPattern(e,r){return this.patternToRegex(r).test(e)}patternToRegex(e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let o=n+1,i="[";for(o<e.length&&(e[o]==="^"||e[o]==="!")&&(i+="^",o++),o<e.length&&e[o]==="]"&&(i+="\\]",o++);o<e.length&&e[o]!=="]";){if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let a=e.indexOf(":]",o+2);if(a!==-1){let c=e.slice(o+2,a),l=this.posixClassToRegex(c);i+=l,o=a+2;continue}}if(e[o]==="\\"&&o+1<e.length){i+=`\\${e[o+1]}`,o+=2;continue}e[o]==="-"?i+="\\-":i+=e[o],o++}i+="]",r+=i,n=o}else if(s==="\\"&&n+1<e.length){let o=e[n+1];/[.+^${}()|\\*?[\]]/.test(o)?r+=`\\${o}`:r+=o,n++}else/[.+^${}()|]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r)}posixClassToRegex(e){return{alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9a-fA-F"}[e]||""}};Z();function pe(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return pe(t.expression);case"ArithBinary":return pe(t.left)||pe(t.right);case"ArithUnary":return pe(t.operand);case"ArithTernary":return pe(t.condition)||pe(t.consequent)||pe(t.alternate);case"ArithAssignment":return pe(t.value);case"ArithGroup":return pe(t.expression);case"ArithArrayElement":return t.index?pe(t.index):!1;case"ArithConcat":return t.parts.some(pe);default:return!1}}function Zr(t){let e=t.operation;return e?!!("word"in e&&e.word&&Ne(e.word)||e.type==="PatternReplacement"&&(e.pattern&&Ne(e.pattern)||e.replacement&&Ne(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&Ne(e.pattern)):!1}function Ft(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return pe(t.expression.expression);case"DoubleQuoted":return t.parts.some(Ft);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&Ne(e.word));case"ParameterExpansion":return Zr(t);default:return!1}}function Ne(t){return t.parts.some(Ft)}function Qr(t){if(!t.operation)return!1;let e=t.operation,r;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(r=e.word?.parts),!r)return!1;for(let n of r)if(n.type==="DoubleQuoted"||n.type==="SingleQuoted")return!0;return!1}function ta(t){let e=!1,r=!1,n=!1,s=!1,o=!1;for(let i of t){if((i.type==="SingleQuoted"||i.type==="DoubleQuoted")&&(e=!0,i.type==="DoubleQuoted"))for(let a of i.parts)a.type==="ParameterExpansion"&&a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!a.operation&&(s=!0);i.type==="CommandSubstitution"&&(r=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(n=!0),Qr(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:r,hasArrayVar:n,hasArrayAtExpansion:s,hasParamExpansion:o}}function Pf(t,e,r,n,s){let o=r??1;o===0&&(o=1);let i=Math.abs(o),a=[],c=0;n?.match(/^-?0\d/)&&(c=Math.max(c,n.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length));let l=u=>{if(c>0){let f=u<0,d=String(Math.abs(u)).padStart(c,"0");return f?`-${d}`:d}return String(u)};if(t<=e)for(let u=t,f=0;u<=e&&f<1e4;u+=i,f++)a.push(l(u));else for(let u=t,f=0;u>=e&&f<1e4;u-=i,f++)a.push(l(u));return a}function Rf(t,e,r){let n=r??1;n===0&&(n=1);let s=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(n),a=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",u=e>="a"&&e<="z";if(a&&u||c&&l)return null;let f=[];if(s<=o)for(let d=s,h=0;d<=o&&h<1e4;d+=i,h++)f.push(String.fromCharCode(d));else for(let d=s,h=0;d>=o&&h<1e4;d-=i,h++)f.push(String.fromCharCode(d));return f}function st(t,e,r,n,s){let o=r!==void 0?`..${r}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:Pf(t,e,r,n,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:Rf(t,e,r),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function ae(t,e){let r="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")if(n+1<t.length){let o=t[n+1];/[\\^$.|+(){}[\]*?]/.test(o)?r+=`\\${o}`:r+=o,n+=2}else r+="\\\\",n++;else if(s==="*")r+=e?".*":".*?",n++;else if(s==="?")r+=".",n++;else if(s==="["){let o=Of(t,n);if(o===-1)r+="\\[",n++;else{let i=t.slice(n+1,o);r+=Df(i),n=o+1}}else/[\^$.|+(){}]/.test(s)?(r+=`\\${s}`,n++):(r+=s,n++)}return r}function Of(t,e){let r=e+1;for(r<t.length&&t[r]==="^"&&r++,r<t.length&&t[r]==="]"&&r++;r<t.length;){if(t[r]==="\\"&&r+1<t.length){r+=2;continue}if(t[r]==="]")return r;if(t[r]==="'"){let n=t.indexOf("'",r+1);if(n!==-1){r=n+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let n=t.indexOf(":]",r+2);if(n!==-1){r=n+2;continue}}r++}return-1}function Df(t){let e="[",r=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",r++);r<t.length;){if(t[r]==="'"){let s=t.indexOf("'",r+1);if(s!==-1){let o=t.slice(r+1,s);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;r=s+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){let o=t.slice(r+2,s);e+=Mf(o),r=s+2;continue}}let n=t[r];n==="\\"?r+1<t.length?(e+=`\\${t[r+1]}`,r+=2):(e+="\\\\",r++):n==="-"&&r>0&&r<t.length-1?(e+="-",r++):n==="^"&&r===0?(e+="^",r++):(n==="]"&&r===0?e+="\\]":e+=n,r++)}return e+="]",e}var Tf={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:" \\t\\n\\r\\f\\v",upper:"A-Z",word:"a-zA-Z0-9_",xdigit:"0-9A-Fa-f"};function Mf(t){return Tf[t]??""}Z();function it(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)){let o=s.slice(r.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&n.push(i)}return n.sort((s,o)=>s-o)}function Kr(t,e){let r=`${e}_`;for(let n of Object.keys(t.state.env))n.startsWith(r)&&delete t.state.env[n]}function Xr(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)&&!s.includes("__")){let o=s.slice(r.length);n.push(o)}return n.sort()}function ra(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Lt(t){return t.IFS??`
|
|
431
|
+
`}function na(t){return t.IFS===""}function ot(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
|
|
432
|
+
`?"\\n":e).join("")}function Ff(t,e){let r=ot(t);return new RegExp(`[${r}]+`,e)}function Lf(t){let e=ot(t);return new RegExp(`^[${e}]+`)}function Wf(t){let e=ot(t);return new RegExp(`[${e}]+$`)}function at(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function sa(t,e){if(e==="")return{words:[t],wordStarts:[0]};let r=[],n=[],s=Ff(e,"g"),o=0,i=t.match(Lf(e));i&&(o=i[0].length),s.lastIndex=o;let a=s.exec(t);for(;a!==null;)a.index>o&&(n.push(o),r.push(t.substring(o,a.index))),o=s.lastIndex,a=s.exec(t);return o<t.length&&(n.push(o),r.push(t.substring(o))),{words:r,wordStarts:n}}function ia(t,e){return e===""?t:t.replace(Wf(e),"")}function X(t,e){return t.state.associativeArrays?.has(e)?Xr(t,e).map(o=>[o,t.state.env[`${e}_${o}`]]):it(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function oa(t,e){return t.state.associativeArrays?.has(e)?Xr(t,e).length>0:it(t,e).length>0}function me(t,e,r=!0,n=!1){switch(e){case"?":return String(t.state.lastExitCode);case"$":return String(process.pid);case"#":return t.state.env["#"]||"0";case"@":return t.state.env["@"]||"";case"_":return t.state.lastArg;case"-":{let i="";return t.state.options.errexit&&(i+="e"),t.state.options.nounset&&(i+="u"),t.state.options.verbose&&(i+="v"),t.state.options.xtrace&&(i+="x"),t.state.options.pipefail&&(i+="p"),i}case"*":{let i=Number.parseInt(t.state.env["#"]||"0",10);if(i===0)return"";let a=[];for(let c=1;c<=i;c++)a.push(t.state.env[String(c)]||"");return a.join(at(t.state.env))}case"0":return t.state.env[0]||"bash";case"PWD":return t.state.env.PWD!==void 0?t.state.env.PWD:"";case"OLDPWD":return t.state.env.OLDPWD!==void 0?t.state.env.OLDPWD:""}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(e))throw new Ce(`\${${e}}`);let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let i=s[1],a=s[2];if(a==="@"||a==="*"){let f=X(t,i);if(f.length>0)return f.map(([,h])=>h).join(" ");let d=t.state.env[i];return d!==void 0?d:""}if(t.state.associativeArrays?.has(i)){let f=ra(a),d=t.state.env[`${i}_${f}`];if(d===void 0&&r&&t.state.options.nounset)throw new fe(`${i}[${a}]`);return d||""}let l;if(/^-?\d+$/.test(a))l=Number.parseInt(a,10);else try{let f=new ee,d=K(f,a);l=W(t,d.expression)}catch{let f=t.state.env[a];l=f?Number.parseInt(f,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let f=X(t,i);if(f.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
433
433
|
`,"";let h=Math.max(...f.map(([b])=>typeof b=="number"?b:0))+1+l;return h<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
434
|
-
`,""):t.state.env[`${i}_${h}`]||""}let u=t.state.env[`${i}_${l}`];if(u===void 0&&r&&t.state.options.nounset)throw new fe(`${i}[${l}]`);return u||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&r&&t.state.options.nounset)throw new fe(e);return i||""}let o=t.state.env[e];if(o===void 0&&r&&t.state.options.nounset)throw new fe(e);return o||""}async function
|
|
435
|
-
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let n=r.charCodeAt(0);n<32||n===127?e+=`\\x${n.toString(16).padStart(2,"0")}`:e+=r}}return`${e}'`}function Be(t,e,r=!1){return e.map(n=>ve(t,n,r)).join("")}async function ze(t,e,r=!1){let n=[];for(let s of e)n.push(await xe(t,s));return n.join("")}function
|
|
436
|
-
`)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?Be(t,s.word.parts,r):"";case"Length":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let u=X(t,l[1]);return String(u.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&
|
|
437
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return f}});case"K":return"";default:return i}}case"Indirection":return me(t,i);case"ArrayKeys":{let u=X(t,s.array).map(([f])=>String(f));return s.star?u.join(
|
|
438
|
-
`)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?ze(t,s.word.parts,r):"";case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=ae(f.pattern,s.greedy);else if(f.type==="Literal")l+=ae(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=le(f.value);else if(f.type==="DoubleQuoted"){let d=await ze(t,f.parts);l+=le(d)}else if(f.type==="ParameterExpansion"){let d=await xe(t,f);l+=ae(d,s.greedy)}else{let d=await xe(t,f);l+=le(d)}if(s.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return i.replace(u,"");for(let f=i.length;f>=0;f--){let d=i.slice(f);if(u.test(d))return i.slice(0,f)}return i}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=ae(d.pattern,!0);else if(d.type==="Literal")l+=ae(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=le(d.value);else if(d.type==="DoubleQuoted"){let h=await ze(t,d.parts);l+=le(h)}else if(d.type==="ParameterExpansion"){let h=await xe(t,d);l+=ae(h,!0)}else{let h=await xe(t,d);l+=le(h)}let u=s.replacement?await ze(t,s.replacement.parts):"";if(l==="")return i;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let f=s.all?"g":"";try{let d=new RegExp(l,f);if(s.all){let h="",p=0,b=d.exec(i);for(;b!==null&&!(b[0].length===0&&b.index===i.length);)h+=i.slice(p,b.index)+u,p=b.index+b[0].length,b[0].length===0&&p++,b=d.exec(i);return h+=i.slice(p),h}return i.replace(d,u)}catch{return i}}default:return
|
|
434
|
+
`,""):t.state.env[`${i}_${h}`]||""}let u=t.state.env[`${i}_${l}`];if(u===void 0&&r&&t.state.options.nounset)throw new fe(`${i}[${l}]`);return u||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&r&&t.state.options.nounset)throw new fe(e);return i||""}let o=t.state.env[e];if(o===void 0&&r&&t.state.options.nounset)throw new fe(e);return o||""}async function aa(t,e,r,n,s){let o=[];for(let u of e){let f=u.type==="ParameterExpansion"||u.type==="CommandSubstitution"||u.type==="ArithmeticExpansion";if(u.type==="ParameterExpansion"&&Qr(u)){let d=await s(t,u);o.push({value:d,splittable:!1})}else{let d=await s(t,u);o.push({value:d,splittable:f})}}if(!o.some(u=>u.splittable&&new RegExp(`[${n}]`).test(u.value))){let u=o.map(f=>f.value).join("");return u?[u]:[]}let a=new RegExp(`[${n}]+`),c=[],l="";for(let u=0;u<o.length;u++){let f=o[u];if(!f.splittable)l+=f.value;else{let d=f.value.split(a);for(let h=0;h<d.length;h++)h===0?l+=d[h]:(l!==""&&c.push(l),l=d[h])}}return l!==""&&c.push(l),c}function le(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function la(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function ca(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Yr(t){if(t==="")return"''";if(!/['\\\n\r\t\x00-\x1f\x7f]/.test(t))return`'${t}'`;let e="$'";for(let r of t)switch(r){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
|
|
435
|
+
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let n=r.charCodeAt(0);n<32||n===127?e+=`\\x${n.toString(16).padStart(2,"0")}`:e+=r}}return`${e}'`}function Be(t,e,r=!1){return e.map(n=>ve(t,n,r)).join("")}async function ze(t,e,r=!1){let n=[];for(let s of e)n.push(await xe(t,s));return n.join("")}function _f(t){return ca(t)}function ua(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!_f(e))return!1;return!0}function fa(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function da(t,e,r=!1){let n=la(e);if(n!==null)return n;switch(e.type){case"ParameterExpansion":return ya(t,e,r);case"TildeExpansion":return r?e.user===null?"~":`~${e.user}`:e.user===null?t.state.env.HOME||"/home/user":e.user==="root"?"/root":`~${e.user}`;case"Glob":return e.pattern;default:return null}}function ve(t,e,r=!1){let n=da(t,e,r);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let s=[];for(let o of e.parts)s.push(ve(t,o,!0));return s.join("")}case"ArithmeticExpansion":return String(W(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let o of e.items)if(o.type==="Range"){let i=st(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)s.push(...i.expanded);else return i.literal}else s.push(Wt(t,o.word));return s.join(" ")}default:return""}}function Wt(t,e){let r=e.parts,n=r.length;if(n===1)return ve(t,r[0]);let s=[];for(let o=0;o<n;o++)s.push(ve(t,r[o]));return s.join("")}async function U(t,e){return Ne(e)?ga(t,e):Wt(t,e)}function _t(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&_t(e.parts))return!0;return!1}function Hf(t){for(let e of t){if(e.type==="BraceExpansion"){for(let r of e.items)if(r.type==="Word"&&Ne(r.word))return!0}if(Ft(e))return!0}return!1}var ha=1e4,Ke=1e5;function pa(t,e,r={count:0}){if(r.count>Ke)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let u of s.items)if(u.type==="Range"){let f=st(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,o.push(d);else{i=!0,a=f.literal;break}}else{let f=pa(t,u.word.parts,r);for(let d of f)r.count++,o.push(d.join(""))}if(i){for(let u of n)r.count++,u.push(a);continue}if(n.length*o.length>ha||r.count>Ke)return n;let l=[];for(let u of n)for(let f of o){if(r.count++,r.count>Ke)return l.length>0?l:n;l.push([...u,f])}n=l}else{let o=ve(t,s);for(let i of n)r.count++,i.push(o)}return n}function Bf(t,e){let r=e.parts;return _t(r)?pa(t,r).map(s=>s.join("")):[Wt(t,e)]}async function ma(t,e,r={count:0}){if(r.count>Ke)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let u of s.items)if(u.type==="Range"){let f=st(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,o.push(d);else{i=!0,a=f.literal;break}}else{let f=await ma(t,u.word.parts,r);for(let d of f)r.count++,o.push(d.join(""))}if(i){for(let u of n)r.count++,u.push(a);continue}if(n.length*o.length>ha||r.count>Ke)return n;let l=[];for(let u of n)for(let f of o){if(r.count++,r.count>Ke)return l.length>0?l:n;l.push([...u,f])}n=l}else{let o=await xe(t,s);for(let i of n)r.count++,i.push(o)}return n}async function zf(t,e){let r=e.parts;return _t(r)?(await ma(t,r)).map(s=>s.join("")):[await U(t,e)]}async function lt(t,e){let r=e.parts,{hasQuoted:n,hasCommandSub:s,hasArrayVar:o,hasArrayAtExpansion:i,hasParamExpansion:a}=ta(r),l=_t(r)?Hf(r)?await zf(t,e):Bf(t,e):null;if(l&&l.length>1){let d=[];for(let h of l)if(!n&&/[*?[]/.test(h)){let b=await new Qe(t.fs,t.state.cwd).expand(h);b.length>0?d.push(...b):d.push(h)}else d.push(h);return{values:d,quoted:!1}}if(i&&r.length===1&&r[0].type==="DoubleQuoted"){let d=r[0];if(d.parts.length===1&&d.parts[0].type==="ParameterExpansion"){let p=d.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(p){let b=p[1],g=X(t,b);if(g.length>0)return{values:g.map(([,w])=>w),quoted:!0};let y=t.state.env[b];return y!==void 0?{values:[y],quoted:!0}:{values:[],quoted:!0}}}}if(!n&&o&&r.length===1&&r[0].type==="ParameterExpansion"){let d=r[0].parameter;if(d==="@"||d==="*"){let h=Number.parseInt(t.state.env["#"]||"0",10);if(h===0)return{values:[],quoted:!1};let p=[];for(let b=1;b<=h;b++)p.push(t.state.env[String(b)]||"");return{values:p,quoted:!1}}}if(!n&&(s||o||a)&&!na(t.state.env)){let d=Lt(t.state.env),h=ot(d),p=await aa(t,r,d,h,xe),b=[],g=new Qe(t.fs,t.state.cwd);for(let y of p)if(/[*?[]/.test(y)){let w=await g.expand(y);w.length>0?b.push(...w):b.push(y)}else b.push(y);return{values:b,quoted:!1}}let f=Ne(e)?await ga(t,e):Wt(t,e);if(!n&&/[*?[]/.test(f)){let h=await new Qe(t.fs,t.state.cwd).expand(f);if(h.length>0)return{values:h,quoted:!1}}return f===""&&!n?{values:[],quoted:!1}:{values:[f],quoted:n}}async function ga(t,e){let r=e.parts,n=r.length;if(n===1)return xe(t,r[0]);let s=[];for(let o=0;o<n;o++)s.push(await xe(t,r[o]));return s.join("")}async function xe(t,e){if(e.type==="ParameterExpansion"&&Zr(e))return Uf(t,e);let r=da(t,e);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let n=[];for(let s of e.parts)n.push(await xe(t,s));return n.join("")}case"CommandSubstitution":try{let n=await t.executeScript(e.body);return t.state.lastExitCode=n.exitCode,t.state.env["?"]=String(n.exitCode),n.stdout.replace(/\n+$/,"")}catch(n){if(n instanceof j)throw n;if(n instanceof z)return t.state.lastExitCode=n.exitCode,t.state.env["?"]=String(n.exitCode),n.stdout.replace(/\n+$/,"");throw n}case"ArithmeticExpansion":return String(await _(t,e.expression.expression));case"BraceExpansion":{let n=[];for(let s of e.items)if(s.type==="Range"){let o=st(s.start,s.end,s.step,s.startStr,s.endStr);if(o.expanded)n.push(...o.expanded);else return o.literal}else n.push(await U(t,s.word));return n.join(" ")}default:return""}}function ya(t,e,r=!1){let{parameter:n,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=me(t,n,!o);if(!s)return i;let a=!(n in t.state.env),c=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?Be(t,s.word.parts,r):i;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let u=Be(t,s.word.parts,r),f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(f){let[,d,h]=f,p;if(/^\d+$/.test(h))p=Number.parseInt(h,10);else{try{let g=new ee,y=K(g,h);p=W(t,y.expression)}catch{let g=t.state.env[h];p=g?Number.parseInt(g,10):0}Number.isNaN(p)&&(p=0)}t.state.env[`${d}_${p}`]=u;let b=Number.parseInt(t.state.env[`${d}__length`]||"0",10);p>=b&&(t.state.env[`${d}__length`]=String(p+1))}else t.state.env[n]=u;return u}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let u=s.word?Be(t,s.word.parts,r):`${n}: parameter null or not set`;throw new z(1,"",`bash: ${u}
|
|
436
|
+
`)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?Be(t,s.word.parts,r):"";case"Length":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let u=X(t,l[1]);return String(u.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&oa(t,n)){let u=t.state.env[`${n}_0`]||"";return String(u.length)}return String(i.length)}case"LengthSliceError":throw new Ce(n);case"Substring":{let l=s.offset?W(t,s.offset.expression):0,u=s.length?W(t,s.length.expression):void 0;if(n==="@"||n==="*"){let p=(t.state.env["@"]||"").split(" ").filter(w=>w),b=t.state.env[0]||"bash",g=l===0?[b,...p]:p,y=l===0?0:l-1;if(y<0||y>=g.length)return"";if(u!==void 0){let w=u<0?g.length+u:y+u;return g.slice(y,Math.max(y,w)).join(" ")}return g.slice(y).join(" ")}let f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(f){let b=X(t,f[1]).map(([,y])=>y),g=l;if(g<0&&(g=b.length+g,g<0))return"";if(u!==void 0){if(u<0){let y=b.length+u;return b.slice(g,Math.max(g,y)).join(" ")}return b.slice(g,g+u).join(" ")}return b.slice(g).join(" ")}let d=[...i],h=l;if(h<0&&(h=Math.max(0,d.length+h)),u!==void 0){if(u<0){let p=d.length+u;return d.slice(h,Math.max(h,p)).join("")}return d.slice(h,h+u).join("")}return d.slice(h).join("")}case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=ae(f.pattern,s.greedy);else if(f.type==="Literal")l+=ae(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=le(f.value);else if(f.type==="DoubleQuoted"){let d=Be(t,f.parts);l+=le(d)}else if(f.type==="ParameterExpansion"){let d=ve(t,f);l+=ae(d,s.greedy)}else{let d=ve(t,f);l+=le(d)}if(s.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return i.replace(u,"");for(let f=i.length;f>=0;f--){let d=i.slice(f);if(u.test(d))return i.slice(0,f)}return i}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=ae(d.pattern,!0);else if(d.type==="Literal")l+=ae(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=le(d.value);else if(d.type==="DoubleQuoted"){let h=Be(t,d.parts);l+=le(h)}else if(d.type==="ParameterExpansion"){let h=ve(t,d);l+=ae(h,!0)}else{let h=ve(t,d);l+=le(h)}let u=s.replacement?Be(t,s.replacement.parts):"";if(l==="")return i;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let f=s.all?"g":"";try{let d=new RegExp(l,f);if(s.all){let h="",p=0,b=d.exec(i);for(;b!==null&&!(b[0].length===0&&b.index===i.length);)h+=i.slice(p,b.index)+u,p=b.index+b[0].length,b[0].length===0&&p++,b=d.exec(i);return h+=i.slice(p),h}return i.replace(d,u)}catch{return i}}case"CaseModification":return s.direction==="upper"?s.all?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):s.all?i.toLowerCase():i.charAt(0).toLowerCase()+i.slice(1);case"Transform":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l&&s.operator==="Q")return X(t,l[1]).map(([,d])=>Yr(d)).join(" ");switch(s.operator){case"Q":return Yr(i);case"P":return i;case"a":return"";case"A":return`${n}=${Yr(i)}`;case"E":return i.replace(/\\([\\abefnrtv'"?])/g,(u,f)=>{switch(f){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
|
|
437
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return f}});case"K":return"";default:return i}}case"Indirection":return me(t,i);case"ArrayKeys":{let u=X(t,s.array).map(([f])=>String(f));return s.star?u.join(at(t.state.env)):u.join(" ")}case"VarNamePrefix":{let l=Object.keys(t.state.env).filter(u=>u.startsWith(s.prefix)&&!u.includes("__")).sort();return s.star?l.join(at(t.state.env)):l.join(" ")}default:return i}}async function Uf(t,e,r=!1){let{parameter:n,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=me(t,n,!o);if(!s)return i;let a=!(n in t.state.env),c=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?ze(t,s.word.parts,r):i;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let u=await ze(t,s.word.parts,r),f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(f){let[,d,h]=f,p;if(/^\d+$/.test(h))p=Number.parseInt(h,10);else{try{let g=new ee,y=K(g,h);p=await _(t,y.expression)}catch{let g=t.state.env[h];p=g?Number.parseInt(g,10):0}Number.isNaN(p)&&(p=0)}t.state.env[`${d}_${p}`]=u;let b=Number.parseInt(t.state.env[`${d}__length`]||"0",10);p>=b&&(t.state.env[`${d}__length`]=String(p+1))}else t.state.env[n]=u;return u}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let u=s.word?await ze(t,s.word.parts,r):`${n}: parameter null or not set`;throw new z(1,"",`bash: ${u}
|
|
438
|
+
`)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?ze(t,s.word.parts,r):"";case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=ae(f.pattern,s.greedy);else if(f.type==="Literal")l+=ae(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=le(f.value);else if(f.type==="DoubleQuoted"){let d=await ze(t,f.parts);l+=le(d)}else if(f.type==="ParameterExpansion"){let d=await xe(t,f);l+=ae(d,s.greedy)}else{let d=await xe(t,f);l+=le(d)}if(s.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return i.replace(u,"");for(let f=i.length;f>=0;f--){let d=i.slice(f);if(u.test(d))return i.slice(0,f)}return i}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=ae(d.pattern,!0);else if(d.type==="Literal")l+=ae(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=le(d.value);else if(d.type==="DoubleQuoted"){let h=await ze(t,d.parts);l+=le(h)}else if(d.type==="ParameterExpansion"){let h=await xe(t,d);l+=ae(h,!0)}else{let h=await xe(t,d);l+=le(h)}let u=s.replacement?await ze(t,s.replacement.parts):"";if(l==="")return i;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let f=s.all?"g":"";try{let d=new RegExp(l,f);if(s.all){let h="",p=0,b=d.exec(i);for(;b!==null&&!(b[0].length===0&&b.index===i.length);)h+=i.slice(p,b.index)+u,p=b.index+b[0].length,b[0].length===0&&p++,b=d.exec(i);return h+=i.slice(p),h}return i.replace(d,u)}catch{return i}}default:return ya(t,e,r)}}function Jr(t,e,r){switch(r){case"+":return t+e;case"-":return t-e;case"*":return t*e;case"/":return e!==0?Math.trunc(t/e):0;case"%":return e!==0?t%e:0;case"**":if(e<0)throw new V("exponent less than 0");return t**e;case"<<":return t<<e;case">>":return t>>e;case"<":return t<e?1:0;case"<=":return t<=e?1:0;case">":return t>e?1:0;case">=":return t>=e?1:0;case"==":return t===e?1:0;case"!=":return t!==e?1:0;case"&":return t&e;case"|":return t|e;case"^":return t^e;case",":return e;default:return 0}}function wa(t,e,r){switch(r){case"=":return e;case"+=":return t+e;case"-=":return t-e;case"*=":return t*e;case"/=":return e!==0?Math.trunc(t/e):0;case"%=":return e!==0?t%e:0;case"<<=":return t<<e;case">>=":return t>>e;case"&=":return t&e;case"|=":return t|e;case"^=":return t^e;default:return e}}function en(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function jf(t,e){let r=t.state.env[e];if(r!==void 0)return r;let n=t.state.env[`${e}_0`];return n!==void 0?n:me(t,e)}function Xe(t){if(!t)return 0;let e=Number.parseInt(t,10);if(!Number.isNaN(e)&&/^-?\d+$/.test(t.trim()))return e;let r=t.trim();if(!r)return 0;try{let n=new ee,{expr:s,pos:o}=Ae(n,r,0);if(o<r.length){let i=r.slice(o).trim().split(/\s+/)[0];throw new V(`${r}: syntax error in expression (error token is "${i}")`)}return s.type==="ArithNumber"?s.value:e||0}catch(n){if(n instanceof V)throw n;let s=r.split(/\s+/).slice(1)[0]||r;throw new V(`${r}: syntax error in expression (error token is "${s}")`)}}function Ht(t,e,r=new Set){if(r.has(e))return 0;r.add(e);let n=jf(t,e);if(!n)return 0;let s=Number.parseInt(n,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(n.trim()))return s;let o=n.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return Ht(t,o,r);try{let i=new ee,{expr:a}=Ae(i,o,0);return ge(t,a,r)}catch{return 0}}function ge(t,e,r){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new V("value too great for base");return e.value;case"ArithVariable":return Ht(t,e.name,r);case"ArithBinary":{if(e.operator==="||")return ge(t,e.left,r)||ge(t,e.right,r)?1:0;if(e.operator==="&&")return ge(t,e.left,r)&&ge(t,e.right,r)?1:0;let n=ge(t,e.left,r),s=ge(t,e.right,r);return Jr(n,s,e.operator)}case"ArithUnary":{let n=ge(t,e.operand,r);return en(n,e.operator)}case"ArithTernary":return ge(t,e.condition,r)?ge(t,e.consequent,r):ge(t,e.alternate,r);case"ArithGroup":return ge(t,e.expression,r);default:return W(t,e)}}function De(t,e){if(e.startsWith("#")){let f=e.slice(1),d=t.state.env[f]||"";return String(d.length)}if(e.startsWith("!")){let f=e.slice(1),d=t.state.env[f]||"";return t.state.env[d]||""}let r=[":-",":=",":?",":+","-","=","?","+"],n=-1,s="";for(let f of r){let d=e.indexOf(f);d>0&&(n===-1||d<n)&&(n=d,s=f)}if(n===-1)return me(t,e);let o=e.slice(0,n),i=e.slice(n+s.length),a=t.state.env[o],c=a===void 0,l=a==="",u=s.startsWith(":");switch(s){case":-":case"-":return c||u&&l?i:a||"";case":=":case"=":return c||u&&l?(t.state.env[o]=i,i):a||"";case":+":case"+":return!(c||u&&l)?i:"";case":?":case"?":{if(c||u&&l)throw new Error(i||`${o}: parameter null or not set`);return a||""}default:return a||""}}function W(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new V("value too great for base");return e.value;case"ArithVariable":return Ht(t,e.name);case"ArithNested":return W(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let r=De(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=De(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return Ze(s)}case"ArithDynamicNumber":{let n=De(t,e.prefix)+e.suffix;return Ze(n)}case"ArithArrayElement":{let r=t.state.associativeArrays?.has(e.array),n;if(e.stringKey!==void 0)n=`${e.array}_${e.stringKey}`;else if(r&&e.index?.type==="ArithVariable")n=`${e.array}_${e.index.name}`;else if(e.index){let o=W(t,e.index);if(o<0){let a=X(t,e.array);if(a.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
439
439
|
`,0;let l=Math.max(...a.map(([u])=>typeof u=="number"?u:0))+1+o;if(l<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
440
|
-
`,0;o=l}n=`${e.array}_${o}`;let i=t.state.env[n];if(i!==void 0)return Xe(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return Xe(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new fe(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?Xe(s):0}case"ArithDoubleSubscript":throw new V("double subscript","","");case"ArithNumberSubscript":throw new V(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return
|
|
441
|
-
`);r=n}throw new te(r)}async function
|
|
440
|
+
`,0;o=l}n=`${e.array}_${o}`;let i=t.state.env[n];if(i!==void 0)return Xe(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return Xe(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new fe(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?Xe(s):0}case"ArithDoubleSubscript":throw new V("double subscript","","");case"ArithNumberSubscript":throw new V(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return W(t,e.left)||W(t,e.right)?1:0;if(e.operator==="&&")return W(t,e.left)&&W(t,e.right)?1:0;let r=W(t,e.left),n=W(t,e.right);return Jr(r,n,e.operator)}case"ArithUnary":{let r=W(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(me(t,n),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),o;if(e.operand.stringKey!==void 0)o=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=W(t,e.operand.index);o=`${n}_${c}`}else return r;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return r}return en(r,e.operator)}case"ArithTernary":return W(t,e.condition)?W(t,e.consequent):W(t,e.alternate);case"ArithAssignment":{let r=e.variable,n=r;if(e.stringKey!==void 0)n=`${r}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(r);if(a&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(a){let c=W(t,e.subscript);n=`${r}_${c}`}else{let c=W(t,e.subscript);if(c<0){let l=X(t,r);l.length>0&&(c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+c)}n=`${r}_${c}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,o=W(t,e.value),i=wa(s,o,e.operator);return t.state.env[n]=String(i),i}case"ArithGroup":return W(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=ba(t,n);return Number.parseInt(r,10)||0}default:return 0}}function ba(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return me(t,e.name);case"ArithBracedExpansion":return De(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=ba(t,n);return r}default:return String(W(t,e))}}async function _(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new V("value too great for base");return e.value;case"ArithVariable":return Ht(t,e.name);case"ArithNested":return _(t,e.expression);case"ArithCommandSubst":{if(t.execFn){let n=(await t.execFn(e.command)).stdout.trim();return Number.parseInt(n,10)||0}return 0}case"ArithBracedExpansion":{let r=De(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=De(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return Ze(s)}case"ArithDynamicNumber":{let n=De(t,e.prefix)+e.suffix;return Ze(n)}case"ArithArrayElement":{let r=t.state.associativeArrays?.has(e.array),n;if(e.stringKey!==void 0)n=`${e.array}_${e.stringKey}`;else if(r&&e.index?.type==="ArithVariable")n=`${e.array}_${e.index.name}`;else if(e.index){let o=await _(t,e.index);n=`${e.array}_${o}`;let i=t.state.env[n];if(i!==void 0)return Xe(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return Xe(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new fe(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?Xe(s):0}case"ArithDoubleSubscript":throw new V("double subscript","","");case"ArithNumberSubscript":throw new V(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return await _(t,e.left)||await _(t,e.right)?1:0;if(e.operator==="&&")return await _(t,e.left)&&await _(t,e.right)?1:0;let r=await _(t,e.left),n=await _(t,e.right);return Jr(r,n,e.operator)}case"ArithUnary":{let r=await _(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(me(t,n),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),o;if(e.operand.stringKey!==void 0)o=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=await _(t,e.operand.index);o=`${n}_${c}`}else return r;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return r}return en(r,e.operator)}case"ArithTernary":return await _(t,e.condition)?await _(t,e.consequent):await _(t,e.alternate);case"ArithAssignment":{let r=e.variable,n=r;if(e.stringKey!==void 0)n=`${r}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(r);if(a&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(a){let c=await _(t,e.subscript);n=`${r}_${c}`}else{let c=await _(t,e.subscript);if(c<0){let l=X(t,r);l.length>0&&(c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+c)}n=`${r}_${c}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,o=await _(t,e.value),i=wa(s,o,e.operator);return t.state.env[n]=String(i),i}case"ArithGroup":return await _(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=await Ea(t,n);return Number.parseInt(r,10)||0}default:return 0}}async function Ea(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return me(t,e.name);case"ArithBracedExpansion":return De(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command)).stdout.trim():"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=await Ea(t,n);return r}default:return String(await _(t,e))}}Z();Z();var F=Object.freeze({stdout:"",stderr:"",exitCode:0});function ce(t=""){return{stdout:t,stderr:"",exitCode:0}}function D(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function k(t,e,r){return{stdout:t,stderr:e,exitCode:r}}function Q(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function ke(t,e,r="",n=""){throw new j(t,e,r,n)}function tn(t,e){if(t.state.loopDepth===0)return F;let r=1;if(e.length>0){let n=Number.parseInt(e[0],10);if(Number.isNaN(n)||n<1)throw new z(128,"",`bash: break: ${e[0]}: numeric argument required
|
|
441
|
+
`);r=n}throw new te(r)}async function rn(t,e){let r,n=!1,s=!1,o=0;for(;o<e.length;)if(e[o]==="--"){o++;break}else if(e[o]==="-L")s=!1,o++;else if(e[o]==="-P")s=!0,o++;else if(e[o].startsWith("-")&&e[o]!=="-")o++;else break;let i=e.slice(o);if(i.length===0||i[0]==="~"?r=t.state.env.HOME||"/":i[0]==="-"?(r=t.state.previousDir,n=!0):r=i[0],!r.startsWith("/")&&!r.startsWith("./")&&!r.startsWith("../")&&r!=="."&&r!==".."){let f=t.state.env.CDPATH;if(f){let d=f.split(":").filter(h=>h);for(let h of d){let p=h.startsWith("/")?`${h}/${r}`:`${t.state.cwd}/${h}/${r}`;try{if((await t.fs.stat(p)).isDirectory){r=p,n=!0;break}}catch{}}}}let c=(r.startsWith("/")?r:`${t.state.cwd}/${r}`).split("/").filter(f=>f&&f!=="."),l="";for(let f of c)if(f==="..")l=l.split("/").slice(0,-1).join("/")||"/";else{l=l?`${l}/${f}`:`/${f}`;try{if(!(await t.fs.stat(l)).isDirectory)return D(`bash: cd: ${r}: Not a directory
|
|
442
442
|
`)}catch{return D(`bash: cd: ${r}: No such file or directory
|
|
443
443
|
`)}}let u=l||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=u,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,ce(n?`${u}
|
|
444
|
-
`:"")}Z();function
|
|
445
|
-
`);r=n}throw new ie(r)}function Ue(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function
|
|
446
|
-
`):null}function
|
|
444
|
+
`:"")}Z();function nn(t,e){if(t.state.loopDepth===0)return F;if(e.length>1)throw new te(1);let r=1;if(e.length>0){let n=Number.parseInt(e[0],10);if(Number.isNaN(n)||n<1)return D(`bash: continue: ${e[0]}: numeric argument required
|
|
445
|
+
`);r=n}throw new ie(r)}function Ue(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function qf(t,e){return t.state.readonlyVars?.has(e)??!1}function Te(t,e,r="bash"){return qf(t,e)?D(`${r}: ${e}: readonly variable
|
|
446
|
+
`):null}function xa(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:sn(e[2])};if(t.includes("=")){let r=t.indexOf("=");return{name:t.slice(0,r),isArray:!1,value:t.slice(r+1)}}return{name:t,isArray:!1}}function Sa(t,e,r={}){let{name:n,isArray:s,arrayElements:o,value:i}=e,{makeReadonly:a=!1,checkReadonly:c=!0}=r;if(c){let l=Te(t,n);if(l)return l}if(s&&o){for(let l=0;l<o.length;l++)t.state.env[`${n}_${l}`]=o[l];t.state.env[`${n}__length`]=String(o.length)}else i!==void 0&&(t.state.env[n]=i);return a&&Ue(t,n),null}function on(t,e){let r=!1,n=!1,s=!1,o=!1,i=!1,a=[];for(let c=0;c<e.length;c++){let l=e[c];if(l==="-a")r=!0;else if(l==="-A")n=!0;else if(l==="-r")s=!0;else if(l==="-x")o=!0;else if(l==="-p")i=!0;else if(l==="--"){a.push(...e.slice(c+1));break}else if(l.startsWith("-"))for(let u of l.slice(1))u==="a"?r=!0:u==="A"?n=!0:u==="r"?s=!0:u==="x"?o=!0:u==="p"&&(i=!0);else a.push(l)}if(i&&a.length>0){let c="";for(let l of a){let u=t.state.env[l];if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');c+=`declare -- ${l}="${f}"
|
|
447
447
|
`}}return ce(c)}if(a.length===0&&!i){let c="",l=Object.entries(t.state.env).filter(([u])=>!u.startsWith("BASH_")).sort(([u],[f])=>u.localeCompare(f));for(let[u,f]of l){let d=f.replace(/'/g,"'\\''");c+=`declare -- ${u}='${d}'
|
|
448
|
-
`}return ce(c)}for(let c of a){let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){let u=l[1],f=l[2];if(n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u)),n&&f.includes("[")){let d=
|
|
449
|
-
`)&&!n&&!s){r&&(e.push(r),r="");continue}r+=i}return r&&e.push(r),e}function
|
|
450
|
-
`)}return ce(a)}}else if(i==="--"){s.push(...e.slice(o+1));break}else i.startsWith("-")||s.push(i)}for(let o of s){let i=
|
|
448
|
+
`}return ce(c)}for(let c of a){let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){let u=l[1],f=l[2];if(n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u)),n&&f.includes("[")){let d=Gf(f);for(let[h,p]of d)t.state.env[`${u}_${h}`]=p}else{let d=sn(f);for(let h=0;h<d.length;h++)t.state.env[`${u}_${h}`]=d[h];t.state.env[`${u}__length`]=String(d.length)}s&&Ue(t,u);continue}if(c.includes("=")){let u=c.indexOf("="),f=c.slice(0,u),d=c.slice(u+1),h=Te(t,f);if(h)return h;t.state.env[f]=d,s&&Ue(t,f)}else{let u=c;n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u));let f=Object.keys(t.state.env).some(d=>d.startsWith(`${u}_`)&&!d.startsWith(`${u}__length`));!(u in t.state.env)&&!f&&(r||n?t.state.env[`${u}__length`]="0":t.state.env[u]=""),s&&Ue(t,u)}}return F}function sn(t){let e=[],r="",n=!1,s=!1,o=!1;for(let i of t){if(o){r+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(i==="'"&&!s){n=!n;continue}if(i==='"'&&!n){s=!s;continue}if((i===" "||i===" "||i===`
|
|
449
|
+
`)&&!n&&!s){r&&(e.push(r),r="");continue}r+=i}return r&&e.push(r),e}function Gf(t){let e=[],r=0;for(;r<t.length;){for(;r<t.length&&/\s/.test(t[r]);)r++;if(r>=t.length)break;if(t[r]!=="["){r++;continue}r++;let n="";if(t[r]==="'"||t[r]==='"'){let o=t[r];for(r++;r<t.length&&t[r]!==o;)n+=t[r],r++;t[r]===o&&r++}else for(;r<t.length&&t[r]!=="]"&&t[r]!=="=";)n+=t[r],r++;for(;r<t.length&&t[r]!=="]";)r++;if(t[r]==="]"&&r++,t[r]!=="=")continue;r++;let s="";if(t[r]==="'"||t[r]==='"'){let o=t[r];for(r++;r<t.length&&t[r]!==o;)t[r]==="\\"&&r+1<t.length&&r++,s+=t[r],r++;t[r]===o&&r++}else for(;r<t.length&&!/\s/.test(t[r]);)s+=t[r],r++;e.push([n,s])}return e}function an(t,e){let r=!1,n=!1,s=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="-a")r=!0;else if(i==="-A")n=!0;else if(i==="-p"){if(e.length===1){let a="";for(let c of t.state.readonlyVars||[]){let l=t.state.env[c];l!==void 0&&(a+=`declare -r ${c}="${l}"
|
|
450
|
+
`)}return ce(a)}}else if(i==="--"){s.push(...e.slice(o+1));break}else i.startsWith("-")||s.push(i)}for(let o of s){let i=xa(o);if(i.value===void 0&&!i.isArray){Ue(t,i.name);continue}let a=Sa(t,i,{makeReadonly:!0});if(a)return a}return F}Z();async function ln(t,e){let r=e;if(r.length>0){let s=r[0];if(s==="--")r=r.slice(1);else if(s.startsWith("-")&&s!=="-"&&s.length>1)return D(`bash: eval: ${s}: invalid option
|
|
451
451
|
eval: usage: eval [arg ...]
|
|
452
452
|
`,2)}if(r.length===0)return F;let n=r.join(" ");if(n.trim()==="")return F;try{let s=Oe(n);return t.executeScript(s)}catch(s){if(s instanceof te||s instanceof ie||s instanceof re||s instanceof z)throw s;if(s.name==="ParseException")return D(`bash: eval: ${s.message}
|
|
453
|
-
`);throw s}}Z();function
|
|
454
|
-
`,r=2):r=(o%256+256)%256}throw new z(r,"",n)}function
|
|
453
|
+
`);throw s}}Z();function cn(t,e){let r,n="";if(e.length===0)r=t.state.lastExitCode;else{let s=e[0],o=Number.parseInt(s,10);s===""||Number.isNaN(o)||!/^-?\d+$/.test(s)?(n=`bash: exit: ${s}: numeric argument required
|
|
454
|
+
`,r=2):r=(o%256+256)%256}throw new z(r,"",n)}function un(t,e){let r=!1,n=[];for(let i of e)i==="-n"?r=!0:i==="-p"||i==="--"||n.push(i);if(n.length===0&&!r){let i="",a=Object.entries(t.state.env).filter(([c])=>!c.startsWith("BASH_ALIAS_")).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of a){let u=l.replace(/'/g,"'\\''");i+=`declare -x ${c}='${u}'
|
|
455
455
|
`}return ce(i)}if(r){for(let i of n){let a=i.split("=")[0];delete t.state.env[a]}return F}let s="",o=0;for(let i of n){let a,c;if(i.includes("=")){let l=i.indexOf("=");a=i.slice(0,l),c=i.slice(l+1)}else a=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${i}': not a valid identifier
|
|
456
|
-
`,o=1;continue}c!==void 0?t.state.env[a]=c:a in t.state.env||(t.state.env[a]="")}return k("",s,o)}function
|
|
457
|
-
`);let r=
|
|
458
|
-
`)}return k("","",n===0?1:0)}function
|
|
459
|
-
`);let r=t.state.localScopes[t.state.localScopes.length-1],n="",s=0;for(let o of e){let i,a;if(o.includes("=")){let c=o.indexOf("=");i=o.slice(0,c),a=
|
|
460
|
-
`,s=1;continue}r.has(i)||r.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return k("",n,s)}function
|
|
461
|
-
`,o="",i=-1,a=null,c=[],l=0,u=!1;for(;l<e.length;){let w=e[l];w==="-r"?n=!0:w==="-d"&&l+1<e.length?(s=e[l+1],l++):w==="-p"&&l+1<e.length?(o=e[l+1],l++):w==="-n"&&l+1<e.length?(i=Number.parseInt(e[l+1],10),(Number.isNaN(i)||i<0)&&(u=!0,i=0),l++):w==="-a"&&l+1<e.length?(a=e[l+1],l++):w==="-t"?l+1<e.length&&!e[l+1].startsWith("-")&&l++:w==="-s"||w.startsWith("-")||c.push(w),l++}if(u)return k("","",1);c.length===0&&a===null&&c.push("REPLY");let f=r;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let d="",h=0,p=!0;if(i>=0){for(let w=0;w<f.length&&w<i;w++){let E=f[w];if(E===s){h=w+1;break}d+=E,h=w+1}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}else{let w=f;for(h=0;;){let E=w.indexOf(s);if(E!==-1){let $=w.substring(0,E);if(h+=E+s.length,w=w.substring(E+s.length),!n&&$.endsWith("\\")){d+=$.slice(0,-1);continue}d+=$,p=!0;break}else if(w.length>0){d+=w,h+=w.length,p=!1,w="";break}else{if(d.length===0){for(let $ of c)t.state.env[$]="";return a&&
|
|
456
|
+
`,o=1;continue}c!==void 0?t.state.env[a]=c:a in t.state.env||(t.state.env[a]="")}return k("",s,o)}function Vf(t){let e=[],r="",n=0;for(let s of t){for(let o of s)o==="("?n++:o===")"&&n--;r?r+=` ${s}`:r=s,n===0&&(e.push(r),r="")}return r&&e.push(r),e}async function fn(t,e){if(e.length===0)return D(`bash: let: expression expected
|
|
457
|
+
`);let r=Vf(e),n=0;for(let s of r)try{let i=Oe(`(( ${s} ))`).statements[0];if(i&&i.pipelines.length>0&&i.pipelines[0].commands.length>0){let a=i.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(n=await _(t,a.expression.expression))}}catch(o){return D(`bash: let: ${s}: ${o.message}
|
|
458
|
+
`)}return k("","",n===0?1:0)}function Zf(t,e){let r=t.state.env.HOME||"/home/user";return e.split(":").map(o=>o==="~"?r:o==="~root"?"/root":o.startsWith("~/")?r+o.slice(1):o.startsWith("~root/")?`/root${o.slice(5)}`:o).join(":")}function dn(t,e){if(t.state.localScopes.length===0)return D(`bash: local: can only be used in a function
|
|
459
|
+
`);let r=t.state.localScopes[t.state.localScopes.length-1],n="",s=0;for(let o of e){let i,a;if(o.includes("=")){let c=o.indexOf("=");i=o.slice(0,c),a=Zf(t,o.slice(c+1))}else i=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)){n+=`bash: local: \`${o}': not a valid identifier
|
|
460
|
+
`,s=1;continue}r.has(i)||r.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return k("",n,s)}function hn(t,e,r){let n=!1,s=`
|
|
461
|
+
`,o="",i=-1,a=null,c=[],l=0,u=!1;for(;l<e.length;){let w=e[l];w==="-r"?n=!0:w==="-d"&&l+1<e.length?(s=e[l+1],l++):w==="-p"&&l+1<e.length?(o=e[l+1],l++):w==="-n"&&l+1<e.length?(i=Number.parseInt(e[l+1],10),(Number.isNaN(i)||i<0)&&(u=!0,i=0),l++):w==="-a"&&l+1<e.length?(a=e[l+1],l++):w==="-t"?l+1<e.length&&!e[l+1].startsWith("-")&&l++:w==="-s"||w.startsWith("-")||c.push(w),l++}if(u)return k("","",1);c.length===0&&a===null&&c.push("REPLY");let f=r;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let d="",h=0,p=!0;if(i>=0){for(let w=0;w<f.length&&w<i;w++){let E=f[w];if(E===s){h=w+1;break}d+=E,h=w+1}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}else{let w=f;for(h=0;;){let E=w.indexOf(s);if(E!==-1){let $=w.substring(0,E);if(h+=E+s.length,w=w.substring(E+s.length),!n&&$.endsWith("\\")){d+=$.slice(0,-1);continue}d+=$,p=!0;break}else if(w.length>0){d+=w,h+=w.length,p=!1,w="";break}else{if(d.length===0){for(let $ of c)t.state.env[$]="";return a&&Kr(t,a),k("","",1)}p=!1;break}}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}if(s===`
|
|
462
462
|
`&&d.endsWith(`
|
|
463
|
-
`)&&(d=d.slice(0,-1)),n||(d=d.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=d,k("","",p?0:1);let b=
|
|
464
|
-
`,2);r=(s%256+256)%256}throw new re(r)}function
|
|
463
|
+
`)&&(d=d.slice(0,-1)),n||(d=d.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=d,k("","",p?0:1);let b=Lt(t.state.env),{words:g,wordStarts:y}=sa(d,b);if(a){Kr(t,a);for(let w=0;w<g.length;w++)t.state.env[`${a}_${w}`]=g[w];return k("","",p?0:1)}for(let w=0;w<c.length;w++){let E=c[w];if(w<c.length-1)t.state.env[E]=g[w]??"";else if(w<y.length){let $=ia(d.substring(y[w]),b);t.state.env[E]=$}else t.state.env[E]=""}return k("","",p?0:1)}Z();function pn(t,e){if(t.state.callDepth===0&&t.state.sourceDepth===0)return D("bash: return: can only `return' from a function or sourced script\n");let r=t.state.lastExitCode;if(e.length>0){let n=e[0],s=Number.parseInt(n,10);if(n===""||Number.isNaN(s)||!/^-?\d+$/.test(n))return D(`bash: return: ${n}: numeric argument required
|
|
464
|
+
`,2);r=(s%256+256)%256}throw new re(r)}function Qf(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var Bt=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
465
465
|
Options:
|
|
466
466
|
-e Exit immediately if a command exits with non-zero status
|
|
467
467
|
+e Disable -e
|
|
@@ -477,48 +477,48 @@ Options:
|
|
|
477
477
|
+o pipefail Disable pipefail
|
|
478
478
|
-o xtrace Same as -x
|
|
479
479
|
+o xtrace Disable xtrace
|
|
480
|
-
`,
|
|
480
|
+
`,Ca={e:"errexit",u:"nounset",x:"xtrace",v:"verbose",f:null,h:null,C:null,n:null,a:null,b:null,m:null,B:null,H:null,P:null,T:null,E:null,p:null},Aa={errexit:"errexit",pipefail:"pipefail",nounset:"nounset",xtrace:"xtrace",verbose:"verbose",noclobber:null,noglob:null,noexec:null,allexport:null,notify:null,monitor:null,braceexpand:null,histexpand:null,physical:null,functrace:null,errtrace:null,privileged:null,hashall:null,posix:null,vi:null,emacs:null,ignoreeof:null,"interactive-comments":null,keyword:null,onecmd:null},$a=["errexit","nounset","pipefail","verbose","xtrace"],Na=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function va(t,e,r){e!==null&&(t.state.options[e]=r)}function Kf(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function gn(t,e){if(e.includes("--help"))return ce(Bt);if(e.length===0){let n=Object.entries(t.state.env).filter(([s])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}=${Qf(o)}`).join(`
|
|
481
481
|
`);return ce(n?`${n}
|
|
482
|
-
`:"")}let r=0;for(;r<e.length;){let n=e[r];if((n==="-o"||n==="+o")&&
|
|
483
|
-
${
|
|
482
|
+
`:"")}let r=0;for(;r<e.length;){let n=e[r];if((n==="-o"||n==="+o")&&Kf(e,r)){let s=e[r+1];if(!(s in Aa))return D(`bash: set: ${s}: invalid option name
|
|
483
|
+
${Bt}`);va(t,Aa[s],n==="-o"),r+=2;continue}if(n==="-o"){let s=$a.map(a=>`${a.padEnd(16)}${t.state.options[a]?"on":"off"}`),o=Na.map(a=>`${a.padEnd(16)}off`),i=[...s,...o].sort();return ce(`${i.join(`
|
|
484
484
|
`)}
|
|
485
|
-
`)}if(n==="+o"){let s
|
|
485
|
+
`)}if(n==="+o"){let s=$a.map(a=>`set ${t.state.options[a]?"-o":"+o"} ${a}`),o=Na.map(a=>`set +o ${a}`),i=[...s,...o].sort();return ce(`${i.join(`
|
|
486
486
|
`)}
|
|
487
|
-
`)}if(n.length>1&&(n[0]==="-"||n[0]==="+")&&n[1]!=="-"){let s=n[0]==="-";for(let o=1;o<n.length;o++){let i=n[o];if(!(i in
|
|
488
|
-
${
|
|
489
|
-
${
|
|
487
|
+
`)}if(n.length>1&&(n[0]==="-"||n[0]==="+")&&n[1]!=="-"){let s=n[0]==="-";for(let o=1;o<n.length;o++){let i=n[o];if(!(i in Ca))return D(`bash: set: ${n[0]}${i}: invalid option
|
|
488
|
+
${Bt}`);va(t,Ca[i],s)}r++;continue}if(n==="--")return mn(t,e.slice(r+1)),F;if(n==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,r+1<e.length)return mn(t,e.slice(r+1)),F;r++;continue}if(n==="+"){r++;continue}return n.startsWith("-")||n.startsWith("+")?D(`bash: set: ${n}: invalid option
|
|
489
|
+
${Bt}`):(mn(t,e.slice(r)),F)}return F}function mn(t,e){let r=1;for(;t.state.env[String(r)]!==void 0;)delete t.state.env[String(r)],r++;for(let n=0;n<e.length;n++)t.state.env[String(n+1)]=e[n];t.state.env["#"]=String(e.length),t.state.env["@"]=e.join(" "),t.state.env["*"]=e.join(" ")}function yn(t,e){let r=1;if(e.length>0){let i=Number.parseInt(e[0],10);if(Number.isNaN(i)||i<0)return D(`bash: shift: ${e[0]}: numeric argument required
|
|
490
490
|
`);r=i}let n=Number.parseInt(t.state.env["#"]||"0",10);if(r>n)return D(`bash: shift: shift count out of range
|
|
491
|
-
`);if(r===0)return F;let s=[];for(let i=1;i<=n;i++)s.push(t.state.env[String(i)]||"");let o=s.slice(r);for(let i=1;i<=n;i++)delete t.state.env[String(i)];for(let i=0;i<o.length;i++)t.state.env[String(i+1)]=o[i];return t.state.env["#"]=String(o.length),t.state.env["@"]=o.join(" "),F}Z();async function
|
|
491
|
+
`);if(r===0)return F;let s=[];for(let i=1;i<=n;i++)s.push(t.state.env[String(i)]||"");let o=s.slice(r);for(let i=1;i<=n;i++)delete t.state.env[String(i)];for(let i=0;i<o.length;i++)t.state.env[String(i+1)]=o[i];return t.state.env["#"]=String(o.length),t.state.env["@"]=o.join(" "),F}Z();async function wn(t,e){let r=e;if(r.length>0&&r[0]==="--"&&(r=r.slice(1)),r.length===0)return k("",`bash: source: filename argument required
|
|
492
492
|
`,2);let n=r[0],s=null,o=null;if(n.includes("/")){let c=t.fs.resolvePath(t.state.cwd,n);try{o=await t.fs.readFile(c),s=c}catch{}}else{let l=(t.state.env.PATH||"").split(":").filter(u=>u);for(let u of l){let f=t.fs.resolvePath(t.state.cwd,`${u}/${n}`);try{if((await t.fs.stat(f)).isDirectory)continue;o=await t.fs.readFile(f),s=f;break}catch{}}if(o===null){let u=t.fs.resolvePath(t.state.cwd,n);try{o=await t.fs.readFile(u),s=u}catch{}}}if(o===null)return D(`bash: ${n}: No such file or directory
|
|
493
493
|
`);let i={};if(r.length>1){for(let l=1;l<=9;l++)i[String(l)]=t.state.env[String(l)];i["#"]=t.state.env["#"],i["@"]=t.state.env["@"];let c=r.slice(1);t.state.env["#"]=String(c.length),t.state.env["@"]=c.join(" ");for(let l=0;l<c.length&&l<9;l++)t.state.env[String(l+1)]=c[l];for(let l=c.length+1;l<=9;l++)delete t.state.env[String(l)]}let a=()=>{if(t.state.sourceDepth--,r.length>1)for(let[c,l]of Object.entries(i))l===void 0?delete t.state.env[c]:t.state.env[c]=l};t.state.sourceDepth++;try{let c=Oe(o),l=await t.executeScript(c);return a(),l}catch(c){if(a(),c instanceof z)throw c;if(c instanceof re)return k(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return D(`bash: ${n}: ${c.message}
|
|
494
|
-
`);throw c}}function
|
|
494
|
+
`);throw c}}function bn(t,e){let r="variable",n="",s=0;for(let o of e){if(o==="-v"){r="variable";continue}if(o==="-f"){r="function";continue}if(r==="function"){t.state.functions.delete(o);continue}let i=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let a=i[1],c=i[2];if(c==="@"||c==="*"){let u=X(t,a);for(let[f]of u)delete t.state.env[`${a}_${f}`];delete t.state.env[a];continue}let l;if(/^-?\d+$/.test(c))l=Number.parseInt(c,10);else{let u=t.state.env[c];l=u?Number.parseInt(u,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let u=X(t,a),f=u.length;if(f===0){n+=`bash: unset: [${l}]: bad array subscript
|
|
495
495
|
`,s=1;continue}let d=f+l;if(d<0){n+=`bash: unset: [${l}]: bad array subscript
|
|
496
|
-
`,s=1;continue}let h=u[d][0];delete t.state.env[`${a}_${h}`];continue}delete t.state.env[`${a}_${l}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return k("",n,s)}function
|
|
497
|
-
`,2):
|
|
498
|
-
`,2):k("","",1)}if(e.length===3){let n=e[0],s=e[1],o=e[2];if(
|
|
499
|
-
`,2):Q(r.value)}async function
|
|
500
|
-
`,exitCode:1}}Z();ye();async function
|
|
501
|
-
`,exitCode:1}}return{stdout:s,stderr:o,exitCode:i}}async function
|
|
502
|
-
`);let i=[];if(e.words===null)i=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else for(let a of e.words){let c=await
|
|
496
|
+
`,s=1;continue}let h=u[d][0];delete t.state.env[`${a}_${h}`];continue}delete t.state.env[`${a}_${l}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return k("",n,s)}function En(t,e){return t.fs.resolvePath(t.state.cwd,e)}var Xf=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function zt(t){return Xf.includes(t)}async function Ut(t,e,r){let n=En(t,r);switch(e){case"-e":case"-a":return t.fs.exists(n);case"-f":return await t.fs.exists(n)?(await t.fs.stat(n)).isFile:!1;case"-d":return await t.fs.exists(n)?(await t.fs.stat(n)).isDirectory:!1;case"-r":case"-w":case"-x":return t.fs.exists(n);case"-s":return await t.fs.exists(n)?(await t.fs.stat(n)).size>0:!1;case"-L":case"-h":try{return(await t.fs.lstat(n)).isSymbolicLink}catch{return!1}case"-k":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&512)!==0:!1;case"-g":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&1024)!==0:!1;case"-u":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&2048)!==0:!1;case"-G":case"-O":return t.fs.exists(n);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].some(o=>n===o||n.endsWith(o));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(n);default:return!1}}var Yf=["-nt","-ot","-ef"];function jt(t){return Yf.includes(t)}async function qt(t,e,r,n){let s=En(t,r),o=En(t,n);switch(e){case"-nt":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,s),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var Jf=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function Gt(t){return Jf.has(t)}function Vt(t,e,r){switch(t){case"-eq":return e===r;case"-ne":return e!==r;case"-lt":return e<r;case"-le":return e<=r;case"-gt":return e>r;case"-ge":return e>=r}}function Zt(t){return t==="="||t==="=="||t==="!="}function Qt(t,e,r,n=!1){let s=n?Kt(e,r):e===r;return t==="!="?!s:s}var ed=new Set(["-z","-n"]);function Xt(t){return ed.has(t)}function Yt(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function Jt(t,e){let r=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let n=r[1],s=r[2];s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else try{let i=Function(`"use strict"; return (${s})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[s];o=i?Number.parseInt(i,10):0}if(o<0){let i=it(t,n);if(i.length===0||(o=Math.max(...i)+1+o,o<0))return!1}return`${n}_${o}`in t.state.env}return e in t.state.env}async function Me(t,e){switch(e.type){case"CondBinary":{let r=await U(t,e.left),n=await U(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(Zt(e.operator))return Qt(e.operator,r,n,!s);if(Gt(e.operator))return Vt(e.operator,Ia(t,r),Ia(t,n));if(jt(e.operator))return qt(t,e.operator,r,n);switch(e.operator){case"=~":try{let o=new RegExp(n),i=r.match(o);if(i){t.state.env.BASH_REMATCH=i[0];for(let a=1;a<i.length;a++)t.state.env[`BASH_REMATCH_${a}`]=i[a]||""}return i!==null}catch{throw new Error("syntax error in regular expression")}case"<":return r<n;case">":return r>n;default:return!1}}case"CondUnary":{let r=await U(t,e.operand);return zt(e.operator)?Ut(t,e.operator,r):Xt(e.operator)?Yt(e.operator,r):e.operator==="-v"?Jt(t,r):e.operator==="-o"?Sn(t,r):!1}case"CondNot":return!await Me(t,e.operand);case"CondAnd":return await Me(t,e.left)?await Me(t,e.right):!1;case"CondOr":return await Me(t,e.left)?!0:await Me(t,e.right);case"CondGroup":return await Me(t,e.expression);case"CondWord":return await U(t,e.word)!=="";default:return!1}}async function Ye(t,e){if(e.length===0)return k("","",1);if(e.length===1)return Q(!!e[0]);if(e.length===2){let n=e[0],s=e[1];return n==="("?D(`test: '(' without matching ')'
|
|
497
|
+
`,2):zt(n)?Q(await Ut(t,n,s)):Xt(n)?Q(Yt(n,s)):n==="!"?Q(!s):n==="-v"?Q(Jt(t,s)):n==="-o"?Q(Sn(t,s)):n==="="||n==="=="||n==="!="||n==="<"||n===">"||n==="-eq"||n==="-ne"||n==="-lt"||n==="-le"||n==="-gt"||n==="-ge"||n==="-nt"||n==="-ot"||n==="-ef"?D(`test: ${n}: unary operator expected
|
|
498
|
+
`,2):k("","",1)}if(e.length===3){let n=e[0],s=e[1],o=e[2];if(Zt(s))return Q(Qt(s,n,o));if(Gt(s)){let i=er(n),a=er(o);return!i.valid||!a.valid?k("","",2):Q(Vt(s,i.value,a.value))}if(jt(s))return Q(await qt(t,s,n,o));switch(s){case"-a":return Q(n!==""&&o!=="");case"-o":return Q(n!==""||o!=="");case">":return Q(n>o);case"<":return Q(n<o)}if(n==="!"){let i=await Ye(t,[s,o]);return k("",i.stderr,i.exitCode===0?1:i.exitCode===1?0:i.exitCode)}if(n==="("&&o===")")return Q(s!=="")}if(e.length===4){if(e[0]==="!"){let n=await Ye(t,e.slice(1));return k("",n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(e[0]==="("&&e[3]===")")return Ye(t,[e[1],e[2]])}let r=await Ra(t,e,0);return r.pos<e.length?D(`test: too many arguments
|
|
499
|
+
`,2):Q(r.value)}async function Ra(t,e,r){return td(t,e,r)}async function td(t,e,r){let{value:n,pos:s}=await ka(t,e,r);for(;e[s]==="-o";){let o=await ka(t,e,s+1);n=n||o.value,s=o.pos}return{value:n,pos:s}}async function ka(t,e,r){let{value:n,pos:s}=await xn(t,e,r);for(;e[s]==="-a";){let o=await xn(t,e,s+1);n=n&&o.value,s=o.pos}return{value:n,pos:s}}async function xn(t,e,r){if(e[r]==="!"){let{value:n,pos:s}=await xn(t,e,r+1);return{value:!n,pos:s}}return rd(t,e,r)}async function rd(t,e,r){let n=e[r];if(n==="("){let{value:o,pos:i}=await Ra(t,e,r+1);return{value:o,pos:e[i]===")"?i+1:i}}if(zt(n)){let o=e[r+1]??"";return{value:await Ut(t,n,o),pos:r+2}}if(Xt(n)){let o=e[r+1]??"";return{value:Yt(n,o),pos:r+2}}if(n==="-v"){let o=e[r+1]??"";return{value:Jt(t,o),pos:r+2}}if(n==="-o"){let o=e[r+1]??"";return{value:Sn(t,o),pos:r+2}}let s=e[r+1];if(Zt(s)){let o=n,i=e[r+2]??"";return{value:Qt(s,o,i),pos:r+3}}if(Gt(s)){let o=er(n),i=er(e[r+2]??"0");return!o.valid||!i.valid?{value:!1,pos:r+3}:{value:Vt(s,o.value,i.value),pos:r+3}}if(jt(s)){let o=n,i=e[r+2]??"";return{value:await qt(t,s,o,i),pos:r+3}}return{value:n!==void 0&&n!=="",pos:r+1}}function Kt(t,e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="\\")if(n+1<e.length){let o=e[n+1];/[\\^$.|+(){}[\]*?]/.test(o)?r+=`\\${o}`:r+=o,n++}else r+="\\\\";else if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let o=e.indexOf("]",n+1);o!==-1?(r+=e.slice(n,o+1),n=o):r+="\\["}else/[\\^$.|+(){}]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r).test(t)}function Sn(t,e){let n={errexit:()=>t.state.options.errexit===!0,nounset:()=>t.state.options.nounset===!0,pipefail:()=>t.state.options.pipefail===!0,xtrace:()=>t.state.options.xtrace===!0,e:()=>t.state.options.errexit===!0,u:()=>t.state.options.nounset===!0,x:()=>t.state.options.xtrace===!0}[e];return n?n():!1}function Ia(t,e){if(e=e.trim(),e==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(e))return Pa(e);try{let r=new ee,n=K(r,e);return W(t,n.expression)}catch{return Pa(e)}}function nd(t,e){let r=0;for(let n of t){let s;if(n>="0"&&n<="9")s=n.charCodeAt(0)-48;else if(n>="a"&&n<="z")s=n.charCodeAt(0)-97+10;else if(n>="A"&&n<="Z")s=n.charCodeAt(0)-65+36;else if(n==="@")s=62;else if(n==="_")s=63;else return Number.NaN;if(s>=e)return Number.NaN;r=r*e+s}return r}function Pa(t){if(t=t.trim(),t==="")return 0;let e=!1;t.startsWith("-")?(e=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1));let r,n=t.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(n){let s=Number.parseInt(n[1],10);s>=2&&s<=64?r=nd(n[2],s):r=0}else/^0[xX][0-9a-fA-F]+$/.test(t)?r=Number.parseInt(t,16):/^0[0-7]+$/.test(t)?r=Number.parseInt(t,8):r=Number.parseInt(t,10);return Number.isNaN(r)&&(r=0),e?-r:r}function er(t){if(t=t.trim(),t==="")return{value:0,valid:!0};let e=!1;if(t.startsWith("-")?(e=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1)),!/^\d+$/.test(t))return{value:0,valid:!1};let r=Number.parseInt(t,10);return Number.isNaN(r)?{value:0,valid:!1}:{value:e?-r:r,valid:!0}}Z();async function Cn(t,e){let r=t.state.inCondition;t.state.inCondition=!0;let n="",s="",o=0;try{for(let i of e){let a=await t.executeStatement(i);n+=a.stdout,s+=a.stderr,o=a.exitCode}}finally{t.state.inCondition=r}return{stdout:n,stderr:s,exitCode:o}}Z();ye();function ct(t,e,r,n){if(t instanceof te)return e+=t.stdout,r+=t.stderr,t.levels>1&&n>1?(t.levels--,t.stdout=e,t.stderr=r,{action:"rethrow",stdout:e,stderr:r,error:t}):{action:"break",stdout:e,stderr:r};if(t instanceof ie)return e+=t.stdout,r+=t.stderr,t.levels>1&&n>1?(t.levels--,t.stdout=e,t.stderr=r,{action:"rethrow",stdout:e,stderr:r,error:t}):{action:"continue",stdout:e,stderr:r};if(t instanceof re||t instanceof Ee||t instanceof z||t instanceof j)return t.prependOutput(e,r),{action:"rethrow",stdout:e,stderr:r,error:t};let s=q(t);return{action:"error",stdout:e,stderr:`${r}${s}
|
|
500
|
+
`,exitCode:1}}Z();ye();async function tr(t,e,r="",n=""){let s=r,o=n,i=0;try{for(let a of e){let c=await t.executeStatement(a);s+=c.stdout,o+=c.stderr,i=c.exitCode}}catch(a){if(Ct(a)||a instanceof Ee||a instanceof z||a instanceof j)throw a.prependOutput(s,o),a;return{stdout:s,stderr:`${o}${q(a)}
|
|
501
|
+
`,exitCode:1}}return{stdout:s,stderr:o,exitCode:i}}async function Oa(t,e){let r="",n="";for(let s of e.clauses){let o=await Cn(t,s.condition);if(r+=o.stdout,n+=o.stderr,o.exitCode===0)return tr(t,s.body,r,n)}return e.elseBody?tr(t,e.elseBody,r,n):k(r,n,0)}async function Da(t,e){let r="",n="",s=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return D(`bash: \`${e.variable}': not a valid identifier
|
|
502
|
+
`);let i=[];if(e.words===null)i=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else for(let a of e.words){let c=await lt(t,a);i.push(...c.values)}t.state.loopDepth++;try{for(let a of i){o++,o>t.limits.maxLoopIterations&&ke(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),t.state.env[e.variable]=a;try{for(let c of e.body){let l=await t.executeStatement(c);r+=l.stdout,n+=l.stderr,s=l.exitCode}}catch(c){let l=ct(c,r,n,t.state.loopDepth);if(r=l.stdout,n=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return k(r,n,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return k(r,n,s)}async function Ta(t,e){let r="",n="",s=0,o=0;e.init&&await _(t,e.init.expression),t.state.loopDepth++;try{for(;o++,o>t.limits.maxLoopIterations&&ke(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),!(e.condition&&await _(t,e.condition.expression)===0);){try{for(let i of e.body){let a=await t.executeStatement(i);r+=a.stdout,n+=a.stderr,s=a.exitCode}}catch(i){let a=ct(i,r,n,t.state.loopDepth);if(r=a.stdout,n=a.stderr,a.action==="break")break;if(a.action==="continue"){e.update&&await _(t,e.update.expression);continue}if(a.action==="error")return k(r,n,a.exitCode??1);throw a.error}e.update&&await _(t,e.update.expression)}}finally{t.state.loopDepth--}return k(r,n,s)}async function Ma(t,e,r=""){let n="",s="",o=0,i=0,a=r;for(let l of e.redirections)if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let u=l.target,f=await U(t,u.content);u.stripTabs&&(f=f.split(`
|
|
503
503
|
`).map(d=>d.replace(/^\t+/,"")).join(`
|
|
504
504
|
`)),a=f}else if(l.operator==="<<<"&&l.target.type==="Word")a=`${await U(t,l.target)}
|
|
505
505
|
`;else if(l.operator==="<"&&l.target.type==="Word")try{let u=await U(t,l.target),f=t.fs.resolvePath(t.state.cwd,u);a=await t.fs.readFile(f)}catch{let u=await U(t,l.target);return D(`bash: ${u}: No such file or directory
|
|
506
|
-
`)}let c=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ke(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,s);let l=0,u=!1,f=!1,d=t.state.inCondition;t.state.inCondition=!0;try{for(let h of e.condition){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,l=p.exitCode}}catch(h){if(h instanceof te){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;u=!0}else if(h instanceof ie){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;f=!0}else throw t.state.inCondition=d,h}finally{t.state.inCondition=d}if(u)break;if(!f){if(l!==0)break;try{for(let h of e.body){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,o=p.exitCode}}catch(h){let p=
|
|
506
|
+
`)}let c=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ke(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,s);let l=0,u=!1,f=!1,d=t.state.inCondition;t.state.inCondition=!0;try{for(let h of e.condition){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,l=p.exitCode}}catch(h){if(h instanceof te){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;u=!0}else if(h instanceof ie){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;f=!0}else throw t.state.inCondition=d,h}finally{t.state.inCondition=d}if(u)break;if(!f){if(l!==0)break;try{for(let h of e.body){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,o=p.exitCode}}catch(h){let p=ct(h,n,s,t.state.loopDepth);if(n=p.stdout,s=p.stderr,p.action==="break")break;if(p.action==="continue")continue;if(p.action==="error")return k(n,s,p.exitCode??1);throw p.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=c}return k(n,s,o)}async function Fa(t,e){let r="",n="",s=0,o=0;t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&ke(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let i=await Cn(t,e.condition);if(r+=i.stdout,n+=i.stderr,i.exitCode===0)break;try{for(let a of e.body){let c=await t.executeStatement(a);r+=c.stdout,n+=c.stderr,s=c.exitCode}}catch(a){let c=ct(a,r,n,t.state.loopDepth);if(r=c.stdout,n=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return k(r,n,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return k(r,n,s)}async function La(t,e){let r="",n="",s=0,o=await U(t,e.word),i=!1;for(let a=0;a<e.items.length;a++){let c=e.items[a],l=i;if(!i)for(let u of c.patterns){let f=await U(t,u);if(ua(u)&&(f=fa(f)),Kt(o,f)){l=!0;break}}if(l){let u=await tr(t,c.body,r,n);if(r=u.stdout,n=u.stderr,s=u.exitCode,c.terminator===";;")break;c.terminator===";&"?i=!0:i=!1}else i=!1}return k(r,n,s)}Z();Z();function Wa(t,e){return t.state.functions.set(e.name,e),F}async function _a(t,e,r){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,ke(`${e.name}: maximum recursion depth (${t.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),t.state.localScopes.push(new Map);let n={};for(let o=0;o<r.length;o++)n[String(o+1)]=t.state.env[String(o+1)],t.state.env[String(o+1)]=r[o];n["@"]=t.state.env["@"],n["#"]=t.state.env["#"],t.state.env["@"]=r.join(" "),t.state.env["#"]=String(r.length);let s=()=>{let o=t.state.localScopes.pop();if(o)for(let[i,a]of o)a===void 0?delete t.state.env[i]:t.state.env[i]=a;for(let[i,a]of Object.entries(n))a===void 0?delete t.state.env[i]:t.state.env[i]=a;t.state.callDepth--};try{let o=await t.executeCommand(e.body,"");return s(),o}catch(o){if(s(),o instanceof re)return k(o.stdout,o.stderr,o.exitCode);throw o}}ye();async function Ha(t,e,r){let{stdout:n,stderr:s,exitCode:o}=e;for(let i of r){if(i.target.type==="HereDoc")continue;let a=await U(t,i.target);switch(i.operator){case">":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
507
507
|
`,o=1,n="";break}}catch{}await t.fs.writeFile(l,n),n=""}else if(c===2)if(a==="/dev/null")s="";else{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
508
508
|
`,o=1;break}}catch{}await t.fs.writeFile(l,s),s=""}break}case">>":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
509
509
|
`,o=1,n="";break}}catch{}await t.fs.appendFile(l,n),n=""}else if(c===2){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
510
510
|
`,o=1;break}}catch{}await t.fs.appendFile(l,s),s=""}break}case">&":{let c=i.fd??1;a==="2"||a==="&2"?c===1&&(s+=n,n=""):(a==="1"||a==="&1")&&(n+=s,s="");break}case"&>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
|
|
511
511
|
`,o=1,n="";break}}catch{}await t.fs.writeFile(c,n+s),n="",s="";break}case"&>>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
|
|
512
|
-
`,o=1,n="";break}}catch{}await t.fs.appendFile(c,n+s),n="",s="";break}}}return k(n,s,o)}var
|
|
513
|
-
`,1);let b=Te(this.ctx,l);if(b)return b;let g=[];for(let w of c.array){let E=await
|
|
514
|
-
`,1);let d=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let b=d[1],g=d[2],y=Te(this.ctx,b);if(y)return y;let w=this.ctx.state.associativeArrays?.has(b),E;if(w){let A;if(g.startsWith("'")&&g.endsWith("'"))A=g.slice(1,-1);else if(g.startsWith('"')&&g.endsWith('"')){let P=g.slice(1,-1),
|
|
515
|
-
`,1);if(A=Math.max(...P.map(([
|
|
512
|
+
`,o=1,n="";break}}catch{}await t.fs.appendFile(c,n+s),n="",s="";break}}}return k(n,s,o)}var ut=class{ctx;constructor(e,r){this.ctx={state:r,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep}}async executeScript(e){let r="",n="",s=0;for(let o of e.statements)try{let i=await this.executeStatement(o);r+=i.stdout,n+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(i){if(i instanceof z)throw i.prependOutput(r,n),i;if(i instanceof j)throw i;if(i instanceof Ee)return r+=i.stdout,n+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof fe)return r+=i.stdout,n+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof Ce)return r+=i.stdout,n+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof te||i instanceof ie){if(this.ctx.state.loopDepth>0)throw i.prependOutput(r,n),i;r+=i.stdout,n+=i.stderr;continue}throw i instanceof re&&i.prependOutput(r,n),i}return{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ke(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let r="",n="",s=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let c=e.pipelines[a],l=a>0?e.operators[a-1]:null;if(l==="&&"&&s!==0||l==="||"&&s===0)continue;let u=await this.executePipeline(c);r+=u.stdout,n+=u.stderr,s=u.exitCode,o=a,i=c.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new Ee(s,r,n);return k(r,n,s)}async executePipeline(e){let r="",n=F,s=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],c=i===e.commands.length-1,l;try{l=await this.executeCommand(a,r)}catch(u){if(u instanceof Ce)l={stdout:u.stdout,stderr:u.stderr,exitCode:1};else if(u instanceof z&&e.commands.length>1)l={stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode};else throw u}o.push(l.exitCode),l.exitCode!==0&&(s=l.exitCode),c?n=l:(r=l.stdout,n={stdout:"",stderr:l.stderr,exitCode:l.exitCode})}for(let i of Object.keys(this.ctx.state.env))i.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[i];for(let i=0;i<o.length;i++)this.ctx.state.env[`PIPESTATUS_${i}`]=String(o[i]);return this.ctx.state.env.PIPESTATUS__length=String(o.length),this.ctx.state.options.pipefail&&s!==0&&(n={...n,exitCode:s}),e.negated&&(n={...n,exitCode:n.exitCode===0?1:0}),n}async executeCommand(e,r){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,r);case"If":return Oa(this.ctx,e);case"For":return Da(this.ctx,e);case"CStyleFor":return Ta(this.ctx,e);case"While":return Ma(this.ctx,e,r);case"Until":return Fa(this.ctx,e);case"Case":return La(this.ctx,e);case"Subshell":return this.executeSubshell(e,r);case"Group":return this.executeGroup(e,r);case"FunctionDef":return Wa(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return F}}async executeSimpleCommand(e,r){try{return await this.executeSimpleCommandInner(e,r)}catch(n){if(n instanceof V)return D(n.stderr);throw n}}async executeSimpleCommandInner(e,r){this.ctx.state.expansionStderr="";let n={};for(let c of e.assignments){let l=c.name;if(c.array){if(/\[.+\]$/.test(l))return k("",`bash: ${l}: cannot assign list to array member
|
|
513
|
+
`,1);let b=Te(this.ctx,l);if(b)return b;let g=[];for(let w of c.array){let E=await lt(this.ctx,w);g.push(...E.values)}let y=0;if(c.append){let w=X(this.ctx,l);w.length>0&&(y=Math.max(...w.map(([$])=>typeof $=="number"?$:0))+1)}else{let w=`${l}_`;for(let E of Object.keys(this.ctx.state.env))E.startsWith(w)&&!E.includes("__")&&delete this.ctx.state.env[E]}for(let w=0;w<g.length;w++)this.ctx.state.env[`${l}_${y+w}`]=g[w];c.append||(this.ctx.state.env[`${l}__length`]=String(g.length));continue}let u=c.value?await U(this.ctx,c.value):"";if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return k("",`bash: ${l}: bad array subscript
|
|
514
|
+
`,1);let d=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let b=d[1],g=d[2],y=Te(this.ctx,b);if(y)return y;let w=this.ctx.state.associativeArrays?.has(b),E;if(w){let A;if(g.startsWith("'")&&g.endsWith("'"))A=g.slice(1,-1);else if(g.startsWith('"')&&g.endsWith('"')){let P=g.slice(1,-1),L=new ee().parseWordFromString(P,!0,!1);A=await U(this.ctx,L)}else if(g.includes("$")){let J=new ee().parseWordFromString(g,!1,!1);A=await U(this.ctx,J)}else A=g;E=`${b}_${A}`}else{let A;if(/^-?\d+$/.test(g))A=Number.parseInt(g,10);else{try{let P=new ee,J=K(P,g);A=W(this.ctx,J.expression)}catch{let P=this.ctx.state.env[g];A=P?Number.parseInt(P,10):0}Number.isNaN(A)&&(A=0)}if(A<0){let P=X(this.ctx,b);if(P.length===0)return k("",`bash: ${b}[${g}]: bad array subscript
|
|
515
|
+
`,1);if(A=Math.max(...P.map(([L])=>typeof L=="number"?L:0))+1+A,A<0)return k("",`bash: ${b}[${g}]: bad array subscript
|
|
516
516
|
`,1)}E=`${b}_${A}`}let $=c.append?(this.ctx.state.env[E]||"")+u:u;e.name?(n[E]=this.ctx.state.env[E],this.ctx.state.env[E]=$):this.ctx.state.env[E]=$;continue}let h=Te(this.ctx,l);if(h)return h;let p=c.append?(this.ctx.state.env[l]||"")+u:u;e.name?(n[l]=this.ctx.state.env[l],this.ctx.state.env[l]=p):this.ctx.state.env[l]=p}if(!e.name)return k("","",this.ctx.state.lastExitCode);for(let c of e.redirections){if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let l=c.target,u=await U(this.ctx,l.content);l.stripTabs&&(u=u.split(`
|
|
517
517
|
`).map(f=>f.replace(/^\t+/,"")).join(`
|
|
518
518
|
`)),r=u;continue}if(c.operator==="<<<"&&c.target.type==="Word"){r=`${await U(this.ctx,c.target)}
|
|
519
519
|
`;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await U(this.ctx,c.target),u=this.ctx.fs.resolvePath(this.ctx.state.cwd,l);r=await this.ctx.fs.readFile(u)}catch{let l=await U(this.ctx,c.target);for(let[u,f]of Object.entries(n))f===void 0?delete this.ctx.state.env[u]:this.ctx.state.env[u]=f;return D(`bash: ${l}: No such file or directory
|
|
520
|
-
`)}}let s=await U(this.ctx,e.name),o=[],i=[];for(let c of e.args){let l=await
|
|
521
|
-
`,127)}let a=await this.runCommand(s,o,i,r);a=await
|
|
520
|
+
`)}}let s=await U(this.ctx,e.name),o=[],i=[];for(let c of e.args){let l=await lt(this.ctx,c);for(let u of l.values)o.push(u),i.push(l.quoted)}if(!s){if(e.name.parts.every(l=>l.type==="CommandSubstitution"||l.type==="ParameterExpansion"||l.type==="ArithmeticExpansion")){if(o.length>0){let l=o.shift();return i.shift(),await this.runCommand(l,o,i,r)}return k("","",this.ctx.state.lastExitCode)}return D(`bash: : command not found
|
|
521
|
+
`,127)}let a=await this.runCommand(s,o,i,r);a=await Ha(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:s;for(let[c,l]of Object.entries(n))l===void 0?delete this.ctx.state.env[c]:this.ctx.state.env[c]=l;return this.ctx.state.expansionStderr&&(a={...a,stderr:this.ctx.state.expansionStderr+a.stderr},this.ctx.state.expansionStderr=""),a}async runCommand(e,r,n,s,o=!1){if(e==="cd")return await rn(this.ctx,r);if(e==="export")return un(this.ctx,r);if(e==="unset")return bn(this.ctx,r);if(e==="exit")return cn(this.ctx,r);if(e==="local")return dn(this.ctx,r);if(e==="set")return gn(this.ctx,r);if(e==="break")return tn(this.ctx,r);if(e==="continue")return nn(this.ctx,r);if(e==="return")return pn(this.ctx,r);if(e==="eval")return ln(this.ctx,r);if(e==="shift")return yn(this.ctx,r);if(e==="source"||e===".")return wn(this.ctx,r);if(e==="read")return hn(this.ctx,r,s);if(e==="declare"||e==="typeset")return on(this.ctx,r);if(e==="readonly")return an(this.ctx,r);if(!o){let u=this.ctx.state.functions.get(e);if(u)return _a(this.ctx,u,r)}if(e===":"||e==="true")return F;if(e==="false")return Q(!1);if(e==="let")return fn(this.ctx,r);if(e==="command"){if(r.length===0)return F;let u=r;for(;u.length>0&&u[0].startsWith("-");)u=u.slice(1);if(u.length===0)return F;let[f,...d]=u;return this.runCommand(f,d,[],s,!0)}if(e==="builtin"){if(r.length===0)return F;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="shopt")return F;if(e==="exec"){if(r.length===0)return F;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="wait")return F;if(e==="type")return this.handleType(r);if(e==="[["){let u=r.lastIndexOf("]]");if(u!==-1){let f=r.slice(0,u);return Ye(this.ctx,f)}return D("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let u=r;if(e==="["){if(r[r.length-1]!=="]")return D("[: missing `]'\n",2);u=r.slice(0,-1)}return Ye(this.ctx,u)}let i=await this.resolveCommand(e);if(!i)return D(`bash: ${e}: command not found
|
|
522
522
|
`,127);let{cmd:a,path:c}=i,l={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep};try{return await a.execute(r,l)}catch(u){return D(`${e}: ${q(u)}
|
|
523
523
|
`)}}async resolveCommand(e){if(e.includes("/")){let o=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(o))return null;let i=o.split("/").pop()||e,a=this.ctx.commands.get(i);return a?{cmd:a,path:o}:null}let n=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of n){if(!o)continue;let i=`${o}/${e}`;if(await this.ctx.fs.exists(i)){let a=this.ctx.commands.get(e);if(a)return{cmd:a,path:i}}}if(!await this.ctx.fs.exists("/bin")){let o=this.ctx.commands.get(e);if(o)return{cmd:o,path:`/bin/${e}`}}return null}async findCommandInPath(e){let r=[],s=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of s){if(!o)continue;let i=`${o}/${e}`;await this.ctx.fs.exists(i)&&r.push(i)}return r}handleType(e){let r=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),n=new Set(["cd","export","unset","exit","local","set","break","continue","return","eval","shift","source",".","read","declare","typeset","readonly",":","true","false","let","command","builtin","shopt","exec","wait","type","[","test"]),s="",o="",i=0;for(let a of e)r.has(a)?s+=`${a} is a shell keyword
|
|
524
524
|
`:n.has(a)?s+=`${a} is a shell builtin
|
|
@@ -526,16 +526,16 @@ ${Ht}`):(pn(t,e.slice(r)),F)}return F}function pn(t,e){let r=1;for(;t.state.env[
|
|
|
526
526
|
`:this.ctx.commands.has(a)?s+=`${a} is /bin/${a}
|
|
527
527
|
`:(o+=`bash: type: ${a}: not found
|
|
528
528
|
`,i=1);return k(s,o,i)}async executeSubshell(e,r=""){let n={...this.ctx.state.env},s=this.ctx.state.cwd,o=this.ctx.state.loopDepth;this.ctx.state.loopDepth=0;let i=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);let a="",c="",l=0;try{for(let u of e.body){let f=await this.executeStatement(u);a+=f.stdout,c+=f.stderr,l=f.exitCode}}catch(u){if(this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.groupStdin=i,u instanceof j)throw u;if(u instanceof te||u instanceof ie)return a+=u.stdout,c+=u.stderr,k(a,c,0);if(u instanceof z)return a+=u.stdout,c+=u.stderr,k(a,c,u.exitCode);if(u instanceof re)return a+=u.stdout,c+=u.stderr,k(a,c,u.exitCode);if(u instanceof Ee)throw u.stdout=a+u.stdout,u.stderr=c+u.stderr,u;return k(a,`${c}${q(u)}
|
|
529
|
-
`,1)}return this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.groupStdin=i,k(a,c,l)}async executeGroup(e,r=""){let n="",s="",o=0,i=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);try{for(let a of e.body){let c=await this.executeStatement(a);n+=c.stdout,s+=c.stderr,o=c.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof j)throw a;if(
|
|
529
|
+
`,1)}return this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.groupStdin=i,k(a,c,l)}async executeGroup(e,r=""){let n="",s="",o=0,i=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);try{for(let a of e.body){let c=await this.executeStatement(a);n+=c.stdout,s+=c.stderr,o=c.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof j)throw a;if(Ct(a)||a instanceof Ee||a instanceof z)throw a.prependOutput(n,s),a;return k(n,`${s}${q(a)}
|
|
530
530
|
`,1)}return this.ctx.state.groupStdin=i,k(n,s,o)}async executeArithmeticCommand(e){try{let r=await _(this.ctx,e.expression.expression);return Q(r!==0)}catch(r){return D(`bash: arithmetic expression: ${r.message}
|
|
531
531
|
`)}}async executeConditionalCommand(e){try{let r=await Me(this.ctx,e.expression);return Q(r)}catch(r){return D(`bash: conditional expression: ${r.message}
|
|
532
|
-
`,2)}}};var Je={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4};function
|
|
533
|
-
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:n,OLDPWD:n,...e.env};if(this.limits=
|
|
532
|
+
`,2)}}};var Je={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4};function Ba(t){return t?{maxCallDepth:t.maxCallDepth??Je.maxCallDepth,maxCommandCount:t.maxCommandCount??Je.maxCommandCount,maxLoopIterations:t.maxLoopIterations??Je.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??Je.maxAwkIterations,maxSedIterations:t.maxSedIterations??Je.maxSedIterations}:{...Je}}function za(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function sd(t){let e=za(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function id(t,e){let r=za(t);if(!r)return!1;let n=sd(e);return!n||r.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:r.pathname.startsWith(n.pathPrefix)}function An(t,e){return!e||e.length===0?!1:e.some(r=>id(t,r))}var ft=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},dt=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},ht=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},rr=class extends Error{constructor(e,r){super(`HTTP method '${e}' not allowed. Allowed methods: ${r.join(", ")}`),this.name="MethodNotAllowedError"}};var od=20,ad=3e4,ld=["GET","HEAD"],cd=new Set(["GET","HEAD","OPTIONS"]),ud=new Set([301,302,303,307,308]);function $n(t){let e=t.maxRedirects??od,r=t.timeoutMs??ad,n=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ld;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!An(a,t.allowedUrlPrefixes??[]))throw new ft(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let c=a.toUpperCase();if(!n.includes(c))throw new rr(c,n)}async function i(a,c={}){let l=c.method?.toUpperCase()??"GET";s(a),o(l);let u=a,f=0,d=c.followRedirects??!0,h=c.timeoutMs!==void 0?Math.min(c.timeoutMs,r):r;for(;;){let p=new AbortController,b=setTimeout(()=>p.abort(),h);try{let g={method:l,headers:c.headers,signal:p.signal,redirect:"manual"};c.body&&!cd.has(l)&&(g.body=c.body);let y=await fetch(u,g);if(ud.has(y.status)&&d){let w=y.headers.get("location");if(!w)return await Ua(y,u);let E=new URL(w,u).href;if(!t.dangerouslyAllowFullInternetAccess&&!An(E,t.allowedUrlPrefixes??[]))throw new ht(E);if(f++,f>e)throw new dt(e);u=E;continue}return await Ua(y,u)}finally{clearTimeout(b)}}}return i}async function Ua(t,e){let r={};return t.headers.forEach((n,s)=>{r[s.toLowerCase()]=n}),{status:t.status,statusText:t.statusText,headers:r,body:await t.text(),url:e}}var nr=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;state;constructor(e={}){let r=e.fs??new _e(e.files);this.fs=r,this.useDefaultLayout=!e.cwd&&!e.files;let n=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
|
|
533
|
+
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:n,OLDPWD:n,...e.env};if(this.limits=Ba({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.network&&(this.secureFetch=$n(e.network)),this.sleepFn=e.sleep,this.state={env:s,cwd:n,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},r instanceof _e)try{r.mkdirSync("/bin",{recursive:!0}),r.mkdirSync("/usr/bin",{recursive:!0}),this.useDefaultLayout&&(r.mkdirSync("/home/user",{recursive:!0}),r.mkdirSync("/tmp",{recursive:!0}))}catch{}if(n!=="/"&&r instanceof _e)try{r.mkdirSync(n,{recursive:!0})}catch{}for(let o of $o(e.commands))this.registerCommand(o);if(e.network)for(let o of No())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)vo(o)?this.registerCommand(ko(o)):this.registerCommand(o)}registerCommand(e){if(this.commands.set(e.name,e),this.fs instanceof _e)try{this.fs.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
|
|
534
534
|
# Built-in command: ${e.name}
|
|
535
535
|
`)}catch{}}async exec(e,r){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
536
536
|
`,exitCode:1,env:{...this.state.env,...r?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...r?.env}};let n=r?.cwd??this.state.cwd,s={...this.state,env:{...this.state.env,...r?.env,...r?.cwd?{PWD:r.cwd}:{}},cwd:n,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},o=e;r?.rawScript||(o=e.split(`
|
|
537
537
|
`).map(a=>a.trimStart()).join(`
|
|
538
|
-
`));try{let i=Oe(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn};return await new
|
|
538
|
+
`));try{let i=Oe(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn};return await new ut(a,s).executeScript(i)}catch(i){if(i instanceof z)return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...r?.env}};if(i instanceof V)return{stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...r?.env}};if(i instanceof j)return{stdout:i.stdout,stderr:i.stderr,exitCode:j.EXIT_CODE,env:{...this.state.env,...r?.env}};if(i.name==="ParseException")return{stdout:"",stderr:`bash: syntax error: ${i.message}
|
|
539
539
|
`,exitCode:2,env:{...this.state.env,...r?.env}};if(i instanceof RangeError)return{stdout:"",stderr:`bash: ${i.message}
|
|
540
|
-
`,exitCode:1,env:{...this.state.env,...r?.env}};throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,r){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),r)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};function
|
|
541
|
-
`).trim()}var
|
|
540
|
+
`,exitCode:1,env:{...this.state.env,...r?.env}};throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,r){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),r)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};function hd(t){let e=["Execute bash commands in a virtual environment.","","This is a simulated bash environment with a virtual filesystem. Commands run in isolation without access to the host system.",""];if(t.files&&Object.keys(t.files).length>0){let r=Object.keys(t.files),n=r.slice(0,5);e.push("Available files:");for(let s of n)e.push(` ${s}`);r.length>5&&e.push(` ... and ${r.length-5} more`),e.push(""),e.push("Common operations:"),e.push(" ls -la # List files with details"),e.push(" find . -name '*.ts' # Find files by pattern"),e.push(" grep -r 'pattern' . # Search file contents"),e.push(" cat <file> # View file contents"),e.push("")}return e.push("To discover commands and their options:"),e.push(" help # List all available commands"),e.push(" <command> --help # Show options for a specific command"),e.push(""),t.commands?.length&&(e.push(`Available commands: ${t.commands.join(", ")}`),e.push("")),t.network&&(e.push("Network access via curl is enabled for this environment."),e.push("")),t.extraInstructions&&e.push(t.extraInstructions),e.join(`
|
|
541
|
+
`).trim()}var pd=ja.object({command:ja.string().describe("The bash command to execute")});function E0(t={}){let e=new nr({fs:t.fs,files:t.fs?void 0:t.files,env:t.env,cwd:t.cwd,network:t.network,commands:t.commands});return fd({description:hd(t),inputSchema:dd(pd),execute:async({command:r})=>{t.onCall?.(r);let n=await e.exec(r);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}})}export{E0 as createBashTool};
|