@jerryan/just-bash 3.11.0 → 3.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/bin/chunks/chunk-JZR2C63H.js +17 -0
- package/dist/bin/{shell/chunks/find-3QDGII35.js → chunks/find-QM4ZVJ2E.js} +1 -1
- package/dist/bin/{shell/chunks/flag-coverage-AGEO3F6X.js → chunks/flag-coverage-ERCJF44K.js} +1 -1
- package/dist/bin/just-bash.js +2 -2
- package/dist/bin/shell/chunks/chunk-JZR2C63H.js +17 -0
- package/dist/bin/{chunks/find-3QDGII35.js → shell/chunks/find-QM4ZVJ2E.js} +1 -1
- package/dist/bin/{chunks/flag-coverage-AGEO3F6X.js → shell/chunks/flag-coverage-ERCJF44K.js} +1 -1
- package/dist/bin/shell/shell.js +2 -2
- package/dist/bundle/browser.js +109 -109
- package/dist/bundle/chunks/chunk-6X2Y5CA2.js +16 -0
- package/dist/bundle/chunks/{find-3AONTPPM.js → find-BFNQSA5B.js} +1 -1
- package/dist/bundle/chunks/{flag-coverage-6YGO7STE.js → flag-coverage-7PBO3TUZ.js} +1 -1
- package/dist/bundle/index.cjs +70 -70
- package/dist/bundle/index.js +2 -2
- package/package.json +1 -1
- package/dist/bin/chunks/chunk-4NYJ4ZTO.js +0 -17
- package/dist/bin/shell/chunks/chunk-4NYJ4ZTO.js +0 -17
- package/dist/bundle/chunks/chunk-L7NEGEOJ.js +0 -16
package/dist/bundle/index.cjs
CHANGED
|
@@ -2,16 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
If this access is required by trusted host-runtime code, add "${e}" to defenseInDepth.excludeViolationTypes.`:"";return t+SF+r}var X7,SF,O1=L(()=>{"use strict";X7=new Set(["function_constructor","async_function_constructor","generator_function_constructor","async_generator_function_constructor"]);SF=`
|
|
4
4
|
|
|
5
|
-
This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`});function Y7(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function CF(t,e,...n){return Dt.run(t,()=>e(...n))}function Q7(){return!Ni&&typeof Sc?.registerHooks=="function"}function J7(t){let e=typeof t=="boolean"?{enabled:t}:t??{};if(N1(e.excludeViolationTypes),e.enabled!==void 0&&e.enabled!==!0&&e.enabled!==!1&&e.enabled!=="auto")throw new RangeError('defenseInDepth.enabled must be true, false, or "auto"');let n={...kF,...e},r=n.enabled==="auto"?"auto":n.enabled?"enabled":"disabled",s={...n,enabled:r!=="disabled",requested:r};return s.excludeViolationTypes&&(s.excludeViolationTypes=[...new Set(s.excludeViolationTypes)].sort()),s}function NF(t,e){if(t.enabled!==e.enabled||t.auditMode!==e.auditMode||t.processLifetimeIntrinsicHardening!==e.processLifetimeIntrinsicHardening||t.onViolation!==e.onViolation)return!1;let n=t.excludeViolationTypes??[],r=e.excludeViolationTypes??[];return n.length===r.length&&n.every((s,i)=>s===r[i])}var e4,AF,Ni,I1,Sc,t4,Re,Dt,vF,kF,tt,cn=L(()=>{"use strict";e4=jt(require("node:async_hooks"),1),AF=jt(require("node:module"),1);v1();k1();O1();Ni=typeof __BROWSER__<"u"&&__BROWSER__;I1=null,Sc=null,t4=null;if(!Ni)try{I1=e4.AsyncLocalStorage,Sc=AF,t4=Sc.Module??Sc.default??null}catch{}Re=class extends Error{violation;constructor(e,n){super(T1(e,n.type,n.type==="error_prepare_stack_trace"||A1().has(n.type))),this.violation=n,this.name="SecurityViolationError"}},Dt=!Ni&&I1?new I1:null,vF=1e3;kF={enabled:!0,auditMode:!1,processLifetimeIntrinsicHardening:!1};tt=class t{static instance=null;static importHooksRegistered=!1;static trustedExecutionDepth=new Map;config;refCount=0;patchFailures=[];activeExecutionIds=new Set;contextCache=new Map;originalDescriptors=[];temporaryIntrinsicDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(e){this.config=e}static getInstance(e){let n=J7(e);if(!t.instance)t.instance=new t(n);else{let r=t.instance.config;if(!NF(n,r))throw new Error("DefenseInDepthBox config conflict: all resolved defense options, including exclusions and the violation callback, must match across Bash instances. Call DefenseInDepthBox.resetInstance() between incompatible configurations.")}return t.instance}static resetInstance(){t.instance&&(t.instance.forceDeactivate(),t.instance=null),t.trustedExecutionDepth.clear()}static isInSandboxedContext(){return Dt?Dt?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(Dt)return Dt?.getStore()?.executionId}static enterTrustedScope(e){let n=t.trustedExecutionDepth.get(e)??0;t.trustedExecutionDepth.set(e,n+1)}static leaveTrustedScope(e){let n=t.trustedExecutionDepth.get(e);if(n){if(n===1){t.trustedExecutionDepth.delete(e);return}t.trustedExecutionDepth.set(e,n-1)}}static isTrustedScopeActive(e){return e?(t.trustedExecutionDepth.get(e)??0)>0:!1}static isTrustedContext(e){return!e||e.forceUntrusted?!1:e.trusted===!0||t.isTrustedScopeActive(e.executionId)}isExecutionIdActive(e){return this.activeExecutionIds.has(e)}getCachedContext(e){let n=this.contextCache.get(e);return n||(n={sandboxActive:!0,executionId:e},this.contextCache.set(e,n)),n}static bindCurrentContext(e){if(!Dt)return e;let n=Dt.getStore(),r=n?.sandboxActive===!0?n.executionId:void 0;if(!r)return e;let i=t.instance?.getCachedContext(r)??{sandboxActive:!0,executionId:r},o=n?.forceUntrusted?{...i,forceUntrusted:!0}:i;return((...a)=>{let l=t.instance;if(!(l&&!l.isExecutionIdActive(r)&&(l.recordViolation("bound_callback_after_deactivate","bound callback","Bound callback blocked after originating execution was deactivated"),!l.config.auditMode)))return CF(o,e,...a)})}isEnabled(){return this.getStatus().state==="enabled"}getStatus(){let e=Q7();return this.config.requested==="disabled"?{requested:"disabled",state:"disabled",level:"none",contextualDynamicImportProtection:e,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?"process-lifetime":"scoped-best-effort"}:!Dt||Ni?{requested:this.config.requested,state:"unsupported",level:"none",contextualDynamicImportProtection:!1,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?"process-lifetime":"scoped-best-effort",reason:"context-aware ESM loader hooks (node:module.registerHooks) are unavailable"}:{requested:this.config.requested,state:"enabled",level:this.config.auditMode?"none":e?"full":"best-effort",contextualDynamicImportProtection:e,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?"process-lifetime":"scoped-best-effort",reason:this.config.auditMode?"audit mode records violations but does not block them":e?void 0:"best-effort protection; context-aware ESM loader hooks are unavailable"}}updateConfig(e){if(this.refCount>0)throw new Error("DefenseInDepthBox configuration cannot change while protection is active");this.config=J7({...this.config,...e})}activate(){if(!Ni&&this.config.enabled&&!Dt)throw new Error("DefenseInDepthBox: enabled protection requires node:async_hooks and node:module");if(Ni||!this.config.enabled){let r=Y7(),s=!1;return{run:i=>s?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):i(),deactivate:()=>{s=!0},executionId:r}}if(this.refCount++,this.refCount===1){try{this.applyPatches()}catch(r){throw this.restorePatches(),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0,r}this.activationTime=Date.now()}let e=Y7(),n=!1;return{run:r=>n?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):(this.activeExecutionIds.add(e),Dt.run({sandboxActive:!0,executionId:e},r)),deactivate:()=>{n||(n=!0,this.activeExecutionIds.delete(e),this.contextCache.delete(e),t.trustedExecutionDepth.delete(e),this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0))},executionId:e}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}getPatchFailures(){return[...this.patchFailures]}clearViolations(){this.violations=[]}getPathForTarget(e,n){return e===globalThis?`globalThis.${n}`:e===process?`process.${n}`:e===Error?`Error.${n}`:e===Function.prototype?`Function.prototype.${n}`:e===Object.prototype?`Object.prototype.${n}`:`<object>.${n}`}static runTrusted(e){if(!Dt)return e();let n=Dt.getStore();if(!n)return e();let{executionId:r}=n;return Dt.run({...n,trusted:!0,forceUntrusted:!1},()=>{t.enterTrustedScope(r);try{let s=e();return typeof s=="object"&&s!==null&&"finally"in s&&typeof s.finally=="function"?s.finally(()=>{t.leaveTrustedScope(r)}):(t.leaveTrustedScope(r),s)}catch(s){throw t.leaveTrustedScope(r),s}})}static async runTrustedAsync(e){if(!Dt)return e();let n=Dt.getStore();if(!n)return e();let{executionId:r}=n;return await Dt.run({...n,trusted:!0,forceUntrusted:!1},async()=>{t.enterTrustedScope(r);try{return await e()}finally{t.leaveTrustedScope(r)}})}static async runUntrustedAsync(e){if(!Dt)return e();let n=Dt.getStore();return n?Dt.run({...n,trusted:!1,forceUntrusted:!0},e):e()}shouldBlock(){if(Ni||this.config.auditMode||!Dt)return!1;let e=Dt?.getStore();return!(e?.sandboxActive!==!0||t.isTrustedContext(e))}shouldAudit(){if(!this.config.auditMode||!Dt)return!1;let e=Dt.getStore();return e?.sandboxActive===!0&&!t.isTrustedContext(e)}recordViolation(e,n,r){let s={timestamp:C1(),type:e,message:r,path:n,stack:new Error().stack,executionId:Dt?.getStore()?.executionId};if(this.violations.length<vF&&this.violations.push(s),this.config.onViolation)try{this.config.onViolation(s)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return s}createBlockingProxy(e,n,r){let s=this;return new Proxy(e,{apply(i,o,a){if(s.shouldBlock()){let l=`${n} is blocked during script execution`,c=s.recordViolation(r,n,l);throw new Re(l,c)}return s.shouldAudit()&&s.recordViolation(r,n,`${n} called (audit mode)`),Reflect.apply(i,o,a)},construct(i,o,a){if(s.shouldBlock()){let l=`${n} constructor is blocked during script execution`,c=s.recordViolation(r,n,l);throw new Re(l,c)}return s.shouldAudit()&&s.recordViolation(r,n,`${n} constructor called (audit mode)`),Reflect.construct(i,o,a)}})}createBlockingObjectProxy(e,n,r,s){let i=this;return new Proxy(e,{get(o,a,l){if(i.shouldBlock()){if(s&&typeof a=="string"&&s.has(a))return Reflect.get(o,a,l);let c=`${n}.${String(a)}`,u=`${c} is blocked during script execution`,f=i.recordViolation(r,c,u);throw new Re(u,f)}if(i.shouldAudit()){let c=`${n}.${String(a)}`;i.recordViolation(r,c,`${c} accessed (audit mode)`)}return Reflect.get(o,a,l)},set(o,a,l,c){if(i.shouldBlock()){let u=`${n}.${String(a)}`,f=`${u} modification is blocked during script execution`,d=i.recordViolation(r,u,f);throw new Re(f,d)}return n==="process.env"&&a==="DEBUG"?Reflect.set(o,a,l):Reflect.set(o,a,l,c)},ownKeys(o){if(i.shouldBlock()){let a=`${n} enumeration is blocked during script execution`,l=i.recordViolation(r,n,a);throw new Re(a,l)}return Reflect.ownKeys(o)},getOwnPropertyDescriptor(o,a){if(i.shouldBlock()){let l=`${n}.${String(a)}`,c=`${l} descriptor access is blocked during script execution`,u=i.recordViolation(r,l,c);throw new Re(c,u)}return Reflect.getOwnPropertyDescriptor(o,a)},has(o,a){if(i.shouldBlock()){let l=`${n}.${String(a)}`,c=`${l} existence check is blocked during script execution`,u=i.recordViolation(r,l,c);throw new Re(c,u)}return Reflect.has(o,a)},deleteProperty(o,a){if(i.shouldBlock()){let l=`${n}.${String(a)}`,c=`${l} deletion is blocked during script execution`,u=i.recordViolation(r,l,c);throw new Re(c,u)}return Reflect.deleteProperty(o,a)},setPrototypeOf(o,a){if(i.shouldBlock()){let l=`${n} setPrototypeOf is blocked during script execution`,c=i.recordViolation(r,n,l);throw new Re(l,c)}return Reflect.setPrototypeOf(o,a)},defineProperty(o,a,l){if(i.shouldBlock()){let c=`${n}.${String(a)}`,u=`${c} defineProperty is blocked during script execution`,f=i.recordViolation(r,c,u);throw new Re(u,f)}return Reflect.defineProperty(o,a,l)}})}createReadonlyObjectProxy(e,n,r){let s=this,i=o=>{let a=`${n} ${o} is blocked during script execution`,l=s.recordViolation(r,n,a);throw new Re(a,l)};return new Proxy(e,{set(o,a,l,c){return s.shouldBlock()&&i("modification"),Reflect.set(o,a,l,c)},defineProperty(o,a,l){return s.shouldBlock()&&i("defineProperty"),Reflect.defineProperty(o,a,l)},deleteProperty(o,a){return s.shouldBlock()&&i("deletion"),Reflect.deleteProperty(o,a)},setPrototypeOf(o,a){return s.shouldBlock()&&i("setPrototypeOf"),Reflect.setPrototypeOf(o,a)},preventExtensions(o){return s.shouldBlock()&&i("preventExtensions"),Reflect.preventExtensions(o)}})}applyPatches(){this.patchFailures=[];let e=Bf(),n=new Set(this.config.excludeViolationTypes??[]),r=new Set(["process_send","process_channel","process_stdout","process_stderr"]),s=[];for(let a of e)if(!n.has(a.violationType)&&!r.has(a.violationType)){if(a.strategy==="freeze"){s.push(a);continue}this.applyPatch(a)}this.protectConstructorChain(),n.has("error_prepare_stack_trace")||this.protectErrorPrepareStackTrace(),this.protectPromiseThen(),Q7()&&this.protectDynamicImport(),this.protectModuleLoad(),this.protectModuleResolveFilename(),this.protectProcessMainModule(),this.protectProcessExecPath(),this.protectProxyRevocable();let i=["Function.prototype.constructor","Module._load","Module._resolveFilename"],o=this.patchFailures.filter(a=>i.includes(a));if(o.length>0)throw this.restorePatches(),new Error(`DefenseInDepthBox: critical patches failed: ${o.join(", ")}`);this.config.processLifetimeIntrinsicHardening||this.protectReversibleIntrinsics(s);for(let a of s)this.applyPatch(a,this.config.processLifetimeIntrinsicHardening===!0);this.config.processLifetimeIntrinsicHardening&&this.lockWellKnownSymbols()}protectReversibleIntrinsics(e){let n=new Set,r=(o,a)=>{let l=Object.getOwnPropertyDescriptor(o,a);!l||!("value"in l)||l.writable!==!0||l.configurable!==!0||(this.temporaryIntrinsicDescriptors.push({target:o,prop:a,descriptor:l}),Object.defineProperty(o,a,{...l,writable:!1}))};for(let{target:o,prop:a}of e){let l=o[a];if(!(typeof l!="object"||l===null)){n.add(l);for(let c of Reflect.ownKeys(l))r(l,c)}}let s=[];for(let o of[Array,Map,Set,RegExp,Promise])s.push([o,Symbol.species]);for(let o of[Array.prototype,String.prototype,Map.prototype,Set.prototype])s.push([o,Symbol.iterator]);s.push([Symbol.prototype,Symbol.toPrimitive],[Date.prototype,Symbol.toPrimitive],[Function.prototype,Symbol.hasInstance],[Array.prototype,Symbol.unscopables]);for(let o of[Symbol.match,Symbol.matchAll,Symbol.replace,Symbol.search,Symbol.split])s.push([RegExp.prototype,o]);for(let o of[Map.prototype,Set.prototype,Promise.prototype,ArrayBuffer.prototype])s.push([o,Symbol.toStringTag]);for(let[o,a]of s)n.add(o),r(o,a);let i=(o,a,l)=>{let c=Object.getOwnPropertyDescriptor(o,a);if(!c||!("value"in c)||typeof c.value!="function"||c.configurable!==!0)return;let u=c.value,f=this,d=function(...h){let p=h[0];if(f.shouldBlock()&&typeof p=="object"&&p!==null&&n.has(p)){let m=`${l}.${a}`,g=`${m} is blocked for protected intrinsics during script execution`,y=f.recordViolation("prototype_mutation",m,g);throw new Re(g,y)}return Reflect.apply(u,this,h)};this.temporaryIntrinsicDescriptors.push({target:o,prop:a,descriptor:c}),Object.defineProperty(o,a,{...c,value:d,writable:!1})};for(let o of["assign","defineProperties","defineProperty","freeze","preventExtensions","seal","setPrototypeOf"])i(Object,o,"Object");for(let o of["defineProperty","deleteProperty","preventExtensions","set","setPrototypeOf"])i(Reflect,o,"Reflect")}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let e=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(e){this.patchFailures.push("AsyncFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(function*(){}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(e){this.patchFailures.push("GeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(async function*(){}).constructor,n=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&e!==n&&this.patchPrototypeConstructor(e.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(e){this.patchFailures.push("AsyncGeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",e instanceof Error?e.message:e)}}protectErrorPrepareStackTrace(){let e=this;try{let n=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:n});let r=n?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return r},set(s){if(e.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",o=e.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new Re(i,o)}e.shouldAudit()&&e.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),r=s},configurable:!0})}catch(n){this.patchFailures.push("Error.prepareStackTrace"),console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",n instanceof Error?n.message:n)}}protectPromiseThen(){let e=this;try{let i=function(...o){return Dt.run(this.captured,()=>{if(!this.box.isExecutionIdActive(this.executionId)){if(this.box.recordViolation("promise_then_after_deactivate","Promise.then","Promise.then callback is blocked after defense deactivation"),this.box.config.auditMode)return Reflect.apply(this.cb,void 0,o);if(this.kind==="fulfilled")return o[0];throw o[0]}return Reflect.apply(this.cb,void 0,o)})};var n=i;let r=Object.getOwnPropertyDescriptor(Promise.prototype,"then");this.originalDescriptors.push({target:Promise.prototype,prop:"then",descriptor:r});let s=r?.value;if(typeof s!="function")return;Object.defineProperty(Promise.prototype,"then",{value:function(a,l){if(!Dt)return Reflect.apply(s,this,[a,l]);let c=Dt.getStore(),u=c?.sandboxActive===!0&&c.trusted!==!0?c.executionId:void 0;if(!u)return Reflect.apply(s,this,[a,l]);let f=e.getCachedContext(u),d=c?.forceUntrusted?{...f,forceUntrusted:!0}:f,h=(p,m)=>typeof p!="function"?p:i.bind({box:e,executionId:u,captured:d,cb:p,kind:m});return Reflect.apply(s,this,[h(a,"fulfilled"),h(l,"rejected")])},writable:!0,configurable:!0})}catch(r){this.patchFailures.push("Promise.prototype.then"),console.debug("[DefenseInDepthBox] Could not protect Promise.prototype.then:",r instanceof Error?r.message:r)}}patchPrototypeConstructor(e,n,r){let s=this;try{let i=Object.getOwnPropertyDescriptor(e,"constructor");this.originalDescriptors.push({target:e,prop:"constructor",descriptor:i});let o=i?.value;Object.defineProperty(e,"constructor",{get(){if(s.shouldBlock()){let a=`${n} access is blocked during script execution`,l=s.recordViolation(r,n,a);throw new Re(a,l)}return s.shouldAudit()&&s.recordViolation(r,n,`${n} accessed (audit mode)`),o},set(a){if(s.shouldBlock()){let l=`${n} modification is blocked during script execution`,c=s.recordViolation(r,n,l);throw new Re(l,c)}Object.defineProperty(this,"constructor",{value:a,writable:!0,configurable:!0})},configurable:!0})}catch(i){this.patchFailures.push(n),console.debug(`[DefenseInDepthBox] Could not patch ${n}:`,i instanceof Error?i.message:i)}}protectProcessMainModule(){if(typeof process>"u")return;let e=this;try{let n=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:n});let r=n?.value;r!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(e.shouldBlock()){let s="process.mainModule access is blocked during script execution",i=e.recordViolation("process_main_module","process.mainModule",s);throw new Re(s,i)}return e.shouldAudit()&&e.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),r},set(s){if(e.shouldBlock()){let i="process.mainModule modification is blocked during script execution",o=e.recordViolation("process_main_module","process.mainModule",i);throw new Re(i,o)}Object.defineProperty(process,"mainModule",{value:s,writable:!0,configurable:!0})},configurable:!0})}catch(n){this.patchFailures.push("process.mainModule"),console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",n instanceof Error?n.message:n)}}protectProcessExecPath(){if(typeof process>"u")return;let e=this;try{let n=Object.getOwnPropertyDescriptor(process,"execPath");this.originalDescriptors.push({target:process,prop:"execPath",descriptor:n});let r=n?.value??process.execPath;Object.defineProperty(process,"execPath",{get(){if(e.shouldBlock()){let s="process.execPath access is blocked during script execution",i=e.recordViolation("process_exec_path","process.execPath",s);throw new Re(s,i)}return e.shouldAudit()&&e.recordViolation("process_exec_path","process.execPath","process.execPath accessed (audit mode)"),r},set(s){if(e.shouldBlock()){let i="process.execPath modification is blocked during script execution",o=e.recordViolation("process_exec_path","process.execPath",i);throw new Re(i,o)}Object.defineProperty(process,"execPath",{value:s,writable:!0,configurable:!0})},configurable:!0})}catch(n){this.patchFailures.push("process.execPath"),console.debug("[DefenseInDepthBox] Could not protect process.execPath:",n instanceof Error?n.message:n)}}lockWellKnownSymbols(){let e=(n,r)=>{try{let s=Object.getOwnPropertyDescriptor(n,r);if(s?.configurable){if("value"in s){Object.defineProperty(n,r,{...s,configurable:!1,writable:!1});return}Object.defineProperty(n,r,{...s,configurable:!1})}}catch{}};for(let n of[Array,Map,Set,RegExp,Promise])e(n,Symbol.species);for(let n of[Array.prototype,String.prototype,Map.prototype,Set.prototype])e(n,Symbol.iterator);e(Symbol.prototype,Symbol.toPrimitive),e(Date.prototype,Symbol.toPrimitive);for(let n of[Symbol.match,Symbol.matchAll,Symbol.replace,Symbol.search,Symbol.split])e(RegExp.prototype,n);e(Function.prototype,Symbol.hasInstance),e(Array.prototype,Symbol.unscopables);for(let n of[Map.prototype,Set.prototype,Promise.prototype,ArrayBuffer.prototype])e(n,Symbol.toStringTag)}protectProxyRevocable(){let e=this;try{let n=Proxy.revocable;if(typeof n!="function")return;let r=Object.getOwnPropertyDescriptor(Proxy,"revocable");this.originalDescriptors.push({target:Proxy,prop:"revocable",descriptor:r}),Object.defineProperty(Proxy,"revocable",{value:function(i,o){if(e.shouldBlock()){let a="Proxy.revocable is blocked during script execution",l=e.recordViolation("proxy","Proxy.revocable",a);throw new Re(a,l)}return e.shouldAudit()&&e.recordViolation("proxy","Proxy.revocable","Proxy.revocable called (audit mode)"),n(i,o)},writable:!1,configurable:!0})}catch(n){this.patchFailures.push("Proxy.revocable"),console.debug("[DefenseInDepthBox] Could not protect Proxy.revocable:",n instanceof Error?n.message:n)}}protectDynamicImport(){if(!(Ni||t.importHooksRegistered))try{let e=Sc;if(!e)throw new Error("node:module is unavailable");let n=new Set;for(let i of e.builtinModules??[]){let o=i.startsWith("node:")?i.slice(5):i;n.add(o);let a=o.indexOf("/");a>0&&n.add(o.slice(0,a))}let r=i=>{if(i.startsWith("./")||i.startsWith("../")||i.startsWith("/")||i.startsWith("file:")||i.startsWith("data:")||i.startsWith("blob:")||i.startsWith("http:")||i.startsWith("https:"))return!1;let o=i.startsWith("node:")?i.slice(5):i;if(!o)return!1;if(typeof e.isBuiltin=="function"&&e.isBuiltin(o)||n.has(o))return!0;let a=o.indexOf("/");return a>0&&n.has(o.slice(0,a))},s=i=>{let o=Dt?.getStore();return i.config.auditMode===!0&&o?.sandboxActive===!0&&!t.isTrustedContext(o)};if(typeof e.registerHooks=="function"){e.registerHooks({resolve(i,o,a){let l=t.instance;if(!l)return a(i,o);if((i.startsWith("data:")||i.startsWith("blob:"))&&l.shouldBlock()){let c=`import(${i.startsWith("data:")?"data:":"blob:"})`,u=`dynamic import of ${i.startsWith("data:")?"data:":"blob:"} URLs is blocked by defense-in-depth`,f=l.recordViolation("dynamic_import_builtin",c,u);throw new Re(u,f)}if(r(i)){let c=`import(${i})`,u=`dynamic import of Node.js builtin '${i}' is blocked during script execution`;if(l.shouldBlock()){let f=l.recordViolation("dynamic_import_builtin",c,u);throw new Re(u,f)}s(l)&&l.recordViolation("dynamic_import_builtin",c,`dynamic import of Node.js builtin '${i}' called (audit mode)`)}return a(i,o)}}),t.importHooksRegistered=!0;return}throw new Error("context-aware ESM loader hooks (node:module.registerHooks) are unavailable")}catch(e){throw new Error(`DefenseInDepthBox: could not register dynamic-import hooks: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}protectModuleLoad(){this.protectModuleMethod("_load","module_load")}protectModuleResolveFilename(){this.protectModuleMethod("_resolveFilename","module_resolve_filename")}protectModuleMethod(e,n){if(Ni)return;let r=`Module.${e}`;try{let s=t4,i=s?.[e];if(!s||typeof i!="function")throw new Error("node:module Module class or method is unavailable");let o=Object.getOwnPropertyDescriptor(s,e);if(!o)throw new Error("method has no own property descriptor");if(o.configurable===!1&&o.writable===!1)throw new Error("method is non-configurable and non-writable");let a=this.createBlockingProxy(i,r,n);this.originalDescriptors.push({target:s,prop:e,descriptor:o}),Object.defineProperty(s,e,{...o,value:a});let l=Object.getOwnPropertyDescriptor(s,e);if(s[e]!==a||l?.value!==a)throw new Error("installed patch failed verification")}catch{this.patchFailures.push(r)}}applyPatch(e,n=!1){let{target:r,prop:s,violationType:i,strategy:o}=e;try{let a=r[s];if(a===void 0)return;let l=Object.getOwnPropertyDescriptor(r,s);if(this.originalDescriptors.push({target:r,prop:s,descriptor:l}),o==="freeze"){if(typeof a=="object"&&a!==null){n&&Object.freeze(a);let c=this.getPathForTarget(r,s),u=this.createReadonlyObjectProxy(a,c,i);Object.defineProperty(r,s,{...l,value:u})}}else{let c=this.getPathForTarget(r,s),u=typeof a=="function"?this.createBlockingProxy(a,c,i):this.createBlockingObjectProxy(a,c,i,e.allowedKeys);Object.defineProperty(r,s,{value:u,writable:!0,configurable:!0})}}catch(a){let l=this.getPathForTarget(r,s);this.patchFailures.push(l),console.debug(`[DefenseInDepthBox] Could not patch ${l}:`,a instanceof Error?a.message:a)}}restorePatches(){for(let e=this.temporaryIntrinsicDescriptors.length-1;e>=0;e--){let{target:n,prop:r,descriptor:s}=this.temporaryIntrinsicDescriptors[e];try{Object.defineProperty(n,r,s)}catch(i){console.debug(`[DefenseInDepthBox] Could not restore temporary intrinsic ${String(r)}:`,i instanceof Error?i.message:i)}}this.temporaryIntrinsicDescriptors=[];for(let e=this.originalDescriptors.length-1;e>=0;e--){let{target:n,prop:r,descriptor:s}=this.originalDescriptors[e];try{s?Object.defineProperty(n,r,s):delete n[r]}catch(i){let o=this.getPathForTarget(n,r);console.debug(`[DefenseInDepthBox] Could not restore ${o}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}}});function r4(t){return typeof t!="function"?t:tt.bindCurrentContext(t)}function Oi(t,e){if(e===Number.POSITIVE_INFINITY)return;let n=r4(t),r={cleared:!1,remainingMs:Math.max(0,e),timer:void 0},s=()=>{if(r.cleared)return;let i=Math.min(r.remainingMs,TF);r.timer=R1(()=>{r.cleared||(r.remainingMs-=i,r.remainingMs>0?s():n())},i)};return s(),r}function Ii(t){t&&(t.cleared=!0,t.timer!==void 0&&n4(t.timer))}var R1,n4,$re,Lre,Ti,Hr,P1,TF,Os=L(()=>{"use strict";cn();R1=globalThis.setTimeout.bind(globalThis),n4=globalThis.clearTimeout.bind(globalThis),$re=globalThis.setInterval.bind(globalThis),Lre=globalThis.clearInterval.bind(globalThis);Ti=((t,e,...n)=>R1(r4(t),e,...n)),Hr=n4,P1=((t,e,...n)=>R1(t,e,...n)),TF=2147483647});function L1(t,e,n){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(e)||e<0||t>e)throw new RangeError(`${n}: byte conversion limit exceeded (${e} bytes)`)}function j(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r<=127)e++;else if(r<=2047)e+=2;else if(r>=55296&&r<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=4,n++):e+=3}else e+=3}return e}function to(t){return t}function kt(t){return t}function fe(t,e=$1){let n=t;if(!n)return n;L1(n.length,e,"UTF-8 decode");let r=!1;for(let i=0;i<n.length;i++){let o=n.charCodeAt(i);if(o>255)return n;o>127&&(r=!0)}if(!r)return n;let s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);try{return OF.decode(s)}catch{return n}}function vr(t,e=$1){if(!t)return t;L1(j(t),e,"UTF-8 encode");let n=IF.encode(t),r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return r}function RF(t,e=$1){L1(t.byteLength,e,"byte-string conversion");let n="";for(let r=0;r<t.length;r++)n+=String.fromCharCode(t[r]);return n}async function zn(t,e){return typeof t.readFileBytes=="function"?t.readFileBytes(e):RF(await t.readFileBuffer(e))}function zf(t){return t.stdoutKind?t.stdoutKind:t.stdoutEncoding==="binary"?"bytes":"text"}function ni(t){return zf(t)==="bytes"?t.stdout:vr(t.stdout)}function F1(t){return zf(t)==="bytes"?fe(t.stdout):t.stdout}function s4(t){return{stdout:t,stdoutKind:"text"}}function i4(t){return{stdout:t,stdoutKind:"bytes",stdoutEncoding:"binary"}}var OF,IF,$1,Ri,pe=L(()=>{"use strict";OF=new TextDecoder("utf-8",{fatal:!0}),IF=new TextEncoder,$1=512*1024*1024;Ri=""});function Uf(t){return t instanceof Jn||t instanceof er||t instanceof Nn}var Bt,Jn,er,Nn,tr,nr,Pe,dt,lr,ri,Xa,v,rt,un,si,Cr,X=L(()=>{"use strict";pe();Bt=class extends Error{stdout;stderr;internalOutputAccounting={stdout:0,stderr:0};constructor(e,n="",r=""){super(e),this.stdout=n,this.stderr=r}prependOutput(e,n){this.stdout=e+this.stdout,this.stderr=n+this.stderr,this.internalOutputAccounting.stdout+=j(e),this.internalOutputAccounting.stderr+=j(n)}},Jn=class extends Bt{levels;name="BreakError";constructor(e=1,n="",r=""){super("break",n,r),this.levels=e}},er=class extends Bt{levels;name="ContinueError";constructor(e=1,n="",r=""){super("continue",n,r),this.levels=e}},Nn=class extends Bt{exitCode;name="ReturnError";constructor(e=0,n="",r=""){super("return",n,r),this.exitCode=e}},tr=class extends Bt{exitCode;name="ErrexitError";constructor(e,n="",r=""){super(`errexit: command exited with status ${e}`,n,r),this.exitCode=e}},nr=class extends Bt{varName;name="NounsetError";constructor(e,n=""){super(`${e}: unbound variable`,n,`bash: ${e}: unbound variable
|
|
5
|
+
This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`});function Y7(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function CF(t,e,...n){return Dt.run(t,()=>e(...n))}function Q7(){return!Ni&&typeof Sc?.registerHooks=="function"}function J7(t){let e=typeof t=="boolean"?{enabled:t}:t??{};if(N1(e.excludeViolationTypes),e.enabled!==void 0&&e.enabled!==!0&&e.enabled!==!1&&e.enabled!=="auto")throw new RangeError('defenseInDepth.enabled must be true, false, or "auto"');let n={...kF,...e},r=n.enabled==="auto"?"auto":n.enabled?"enabled":"disabled",s={...n,enabled:r!=="disabled",requested:r};return s.excludeViolationTypes&&(s.excludeViolationTypes=[...new Set(s.excludeViolationTypes)].sort()),s}function NF(t,e){if(t.enabled!==e.enabled||t.auditMode!==e.auditMode||t.processLifetimeIntrinsicHardening!==e.processLifetimeIntrinsicHardening||t.onViolation!==e.onViolation)return!1;let n=t.excludeViolationTypes??[],r=e.excludeViolationTypes??[];return n.length===r.length&&n.every((s,i)=>s===r[i])}var e4,AF,Ni,I1,Sc,t4,Re,Dt,vF,kF,nt,cn=L(()=>{"use strict";e4=jt(require("node:async_hooks"),1),AF=jt(require("node:module"),1);v1();k1();O1();Ni=typeof __BROWSER__<"u"&&__BROWSER__;I1=null,Sc=null,t4=null;if(!Ni)try{I1=e4.AsyncLocalStorage,Sc=AF,t4=Sc.Module??Sc.default??null}catch{}Re=class extends Error{violation;constructor(e,n){super(T1(e,n.type,n.type==="error_prepare_stack_trace"||A1().has(n.type))),this.violation=n,this.name="SecurityViolationError"}},Dt=!Ni&&I1?new I1:null,vF=1e3;kF={enabled:!0,auditMode:!1,processLifetimeIntrinsicHardening:!1};nt=class t{static instance=null;static importHooksRegistered=!1;static trustedExecutionDepth=new Map;config;refCount=0;patchFailures=[];activeExecutionIds=new Set;contextCache=new Map;originalDescriptors=[];temporaryIntrinsicDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(e){this.config=e}static getInstance(e){let n=J7(e);if(!t.instance)t.instance=new t(n);else{let r=t.instance.config;if(!NF(n,r))throw new Error("DefenseInDepthBox config conflict: all resolved defense options, including exclusions and the violation callback, must match across Bash instances. Call DefenseInDepthBox.resetInstance() between incompatible configurations.")}return t.instance}static resetInstance(){t.instance&&(t.instance.forceDeactivate(),t.instance=null),t.trustedExecutionDepth.clear()}static isInSandboxedContext(){return Dt?Dt?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(Dt)return Dt?.getStore()?.executionId}static enterTrustedScope(e){let n=t.trustedExecutionDepth.get(e)??0;t.trustedExecutionDepth.set(e,n+1)}static leaveTrustedScope(e){let n=t.trustedExecutionDepth.get(e);if(n){if(n===1){t.trustedExecutionDepth.delete(e);return}t.trustedExecutionDepth.set(e,n-1)}}static isTrustedScopeActive(e){return e?(t.trustedExecutionDepth.get(e)??0)>0:!1}static isTrustedContext(e){return!e||e.forceUntrusted?!1:e.trusted===!0||t.isTrustedScopeActive(e.executionId)}isExecutionIdActive(e){return this.activeExecutionIds.has(e)}getCachedContext(e){let n=this.contextCache.get(e);return n||(n={sandboxActive:!0,executionId:e},this.contextCache.set(e,n)),n}static bindCurrentContext(e){if(!Dt)return e;let n=Dt.getStore(),r=n?.sandboxActive===!0?n.executionId:void 0;if(!r)return e;let i=t.instance?.getCachedContext(r)??{sandboxActive:!0,executionId:r},o=n?.forceUntrusted?{...i,forceUntrusted:!0}:i;return((...a)=>{let l=t.instance;if(!(l&&!l.isExecutionIdActive(r)&&(l.recordViolation("bound_callback_after_deactivate","bound callback","Bound callback blocked after originating execution was deactivated"),!l.config.auditMode)))return CF(o,e,...a)})}isEnabled(){return this.getStatus().state==="enabled"}getStatus(){let e=Q7();return this.config.requested==="disabled"?{requested:"disabled",state:"disabled",level:"none",contextualDynamicImportProtection:e,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?"process-lifetime":"scoped-best-effort"}:!Dt||Ni?{requested:this.config.requested,state:"unsupported",level:"none",contextualDynamicImportProtection:!1,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?"process-lifetime":"scoped-best-effort",reason:"context-aware ESM loader hooks (node:module.registerHooks) are unavailable"}:{requested:this.config.requested,state:"enabled",level:this.config.auditMode?"none":e?"full":"best-effort",contextualDynamicImportProtection:e,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?"process-lifetime":"scoped-best-effort",reason:this.config.auditMode?"audit mode records violations but does not block them":e?void 0:"best-effort protection; context-aware ESM loader hooks are unavailable"}}updateConfig(e){if(this.refCount>0)throw new Error("DefenseInDepthBox configuration cannot change while protection is active");this.config=J7({...this.config,...e})}activate(){if(!Ni&&this.config.enabled&&!Dt)throw new Error("DefenseInDepthBox: enabled protection requires node:async_hooks and node:module");if(Ni||!this.config.enabled){let r=Y7(),s=!1;return{run:i=>s?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):i(),deactivate:()=>{s=!0},executionId:r}}if(this.refCount++,this.refCount===1){try{this.applyPatches()}catch(r){throw this.restorePatches(),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0,r}this.activationTime=Date.now()}let e=Y7(),n=!1;return{run:r=>n?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):(this.activeExecutionIds.add(e),Dt.run({sandboxActive:!0,executionId:e},r)),deactivate:()=>{n||(n=!0,this.activeExecutionIds.delete(e),this.contextCache.delete(e),t.trustedExecutionDepth.delete(e),this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0))},executionId:e}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}getPatchFailures(){return[...this.patchFailures]}clearViolations(){this.violations=[]}getPathForTarget(e,n){return e===globalThis?`globalThis.${n}`:e===process?`process.${n}`:e===Error?`Error.${n}`:e===Function.prototype?`Function.prototype.${n}`:e===Object.prototype?`Object.prototype.${n}`:`<object>.${n}`}static runTrusted(e){if(!Dt)return e();let n=Dt.getStore();if(!n)return e();let{executionId:r}=n;return Dt.run({...n,trusted:!0,forceUntrusted:!1},()=>{t.enterTrustedScope(r);try{let s=e();return typeof s=="object"&&s!==null&&"finally"in s&&typeof s.finally=="function"?s.finally(()=>{t.leaveTrustedScope(r)}):(t.leaveTrustedScope(r),s)}catch(s){throw t.leaveTrustedScope(r),s}})}static async runTrustedAsync(e){if(!Dt)return e();let n=Dt.getStore();if(!n)return e();let{executionId:r}=n;return await Dt.run({...n,trusted:!0,forceUntrusted:!1},async()=>{t.enterTrustedScope(r);try{return await e()}finally{t.leaveTrustedScope(r)}})}static async runUntrustedAsync(e){if(!Dt)return e();let n=Dt.getStore();return n?Dt.run({...n,trusted:!1,forceUntrusted:!0},e):e()}shouldBlock(){if(Ni||this.config.auditMode||!Dt)return!1;let e=Dt?.getStore();return!(e?.sandboxActive!==!0||t.isTrustedContext(e))}shouldAudit(){if(!this.config.auditMode||!Dt)return!1;let e=Dt.getStore();return e?.sandboxActive===!0&&!t.isTrustedContext(e)}recordViolation(e,n,r){let s={timestamp:C1(),type:e,message:r,path:n,stack:new Error().stack,executionId:Dt?.getStore()?.executionId};if(this.violations.length<vF&&this.violations.push(s),this.config.onViolation)try{this.config.onViolation(s)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return s}createBlockingProxy(e,n,r){let s=this;return new Proxy(e,{apply(i,o,a){if(s.shouldBlock()){let l=`${n} is blocked during script execution`,c=s.recordViolation(r,n,l);throw new Re(l,c)}return s.shouldAudit()&&s.recordViolation(r,n,`${n} called (audit mode)`),Reflect.apply(i,o,a)},construct(i,o,a){if(s.shouldBlock()){let l=`${n} constructor is blocked during script execution`,c=s.recordViolation(r,n,l);throw new Re(l,c)}return s.shouldAudit()&&s.recordViolation(r,n,`${n} constructor called (audit mode)`),Reflect.construct(i,o,a)}})}createBlockingObjectProxy(e,n,r,s){let i=this;return new Proxy(e,{get(o,a,l){if(i.shouldBlock()){if(s&&typeof a=="string"&&s.has(a))return Reflect.get(o,a,l);let c=`${n}.${String(a)}`,u=`${c} is blocked during script execution`,f=i.recordViolation(r,c,u);throw new Re(u,f)}if(i.shouldAudit()){let c=`${n}.${String(a)}`;i.recordViolation(r,c,`${c} accessed (audit mode)`)}return Reflect.get(o,a,l)},set(o,a,l,c){if(i.shouldBlock()){let u=`${n}.${String(a)}`,f=`${u} modification is blocked during script execution`,d=i.recordViolation(r,u,f);throw new Re(f,d)}return n==="process.env"&&a==="DEBUG"?Reflect.set(o,a,l):Reflect.set(o,a,l,c)},ownKeys(o){if(i.shouldBlock()){let a=`${n} enumeration is blocked during script execution`,l=i.recordViolation(r,n,a);throw new Re(a,l)}return Reflect.ownKeys(o)},getOwnPropertyDescriptor(o,a){if(i.shouldBlock()){let l=`${n}.${String(a)}`,c=`${l} descriptor access is blocked during script execution`,u=i.recordViolation(r,l,c);throw new Re(c,u)}return Reflect.getOwnPropertyDescriptor(o,a)},has(o,a){if(i.shouldBlock()){let l=`${n}.${String(a)}`,c=`${l} existence check is blocked during script execution`,u=i.recordViolation(r,l,c);throw new Re(c,u)}return Reflect.has(o,a)},deleteProperty(o,a){if(i.shouldBlock()){let l=`${n}.${String(a)}`,c=`${l} deletion is blocked during script execution`,u=i.recordViolation(r,l,c);throw new Re(c,u)}return Reflect.deleteProperty(o,a)},setPrototypeOf(o,a){if(i.shouldBlock()){let l=`${n} setPrototypeOf is blocked during script execution`,c=i.recordViolation(r,n,l);throw new Re(l,c)}return Reflect.setPrototypeOf(o,a)},defineProperty(o,a,l){if(i.shouldBlock()){let c=`${n}.${String(a)}`,u=`${c} defineProperty is blocked during script execution`,f=i.recordViolation(r,c,u);throw new Re(u,f)}return Reflect.defineProperty(o,a,l)}})}createReadonlyObjectProxy(e,n,r){let s=this,i=o=>{let a=`${n} ${o} is blocked during script execution`,l=s.recordViolation(r,n,a);throw new Re(a,l)};return new Proxy(e,{set(o,a,l,c){return s.shouldBlock()&&i("modification"),Reflect.set(o,a,l,c)},defineProperty(o,a,l){return s.shouldBlock()&&i("defineProperty"),Reflect.defineProperty(o,a,l)},deleteProperty(o,a){return s.shouldBlock()&&i("deletion"),Reflect.deleteProperty(o,a)},setPrototypeOf(o,a){return s.shouldBlock()&&i("setPrototypeOf"),Reflect.setPrototypeOf(o,a)},preventExtensions(o){return s.shouldBlock()&&i("preventExtensions"),Reflect.preventExtensions(o)}})}applyPatches(){this.patchFailures=[];let e=Bf(),n=new Set(this.config.excludeViolationTypes??[]),r=new Set(["process_send","process_channel","process_stdout","process_stderr"]),s=[];for(let a of e)if(!n.has(a.violationType)&&!r.has(a.violationType)){if(a.strategy==="freeze"){s.push(a);continue}this.applyPatch(a)}this.protectConstructorChain(),n.has("error_prepare_stack_trace")||this.protectErrorPrepareStackTrace(),this.protectPromiseThen(),Q7()&&this.protectDynamicImport(),this.protectModuleLoad(),this.protectModuleResolveFilename(),this.protectProcessMainModule(),this.protectProcessExecPath(),this.protectProxyRevocable();let i=["Function.prototype.constructor","Module._load","Module._resolveFilename"],o=this.patchFailures.filter(a=>i.includes(a));if(o.length>0)throw this.restorePatches(),new Error(`DefenseInDepthBox: critical patches failed: ${o.join(", ")}`);this.config.processLifetimeIntrinsicHardening||this.protectReversibleIntrinsics(s);for(let a of s)this.applyPatch(a,this.config.processLifetimeIntrinsicHardening===!0);this.config.processLifetimeIntrinsicHardening&&this.lockWellKnownSymbols()}protectReversibleIntrinsics(e){let n=new Set,r=(o,a)=>{let l=Object.getOwnPropertyDescriptor(o,a);!l||!("value"in l)||l.writable!==!0||l.configurable!==!0||(this.temporaryIntrinsicDescriptors.push({target:o,prop:a,descriptor:l}),Object.defineProperty(o,a,{...l,writable:!1}))};for(let{target:o,prop:a}of e){let l=o[a];if(!(typeof l!="object"||l===null)){n.add(l);for(let c of Reflect.ownKeys(l))r(l,c)}}let s=[];for(let o of[Array,Map,Set,RegExp,Promise])s.push([o,Symbol.species]);for(let o of[Array.prototype,String.prototype,Map.prototype,Set.prototype])s.push([o,Symbol.iterator]);s.push([Symbol.prototype,Symbol.toPrimitive],[Date.prototype,Symbol.toPrimitive],[Function.prototype,Symbol.hasInstance],[Array.prototype,Symbol.unscopables]);for(let o of[Symbol.match,Symbol.matchAll,Symbol.replace,Symbol.search,Symbol.split])s.push([RegExp.prototype,o]);for(let o of[Map.prototype,Set.prototype,Promise.prototype,ArrayBuffer.prototype])s.push([o,Symbol.toStringTag]);for(let[o,a]of s)n.add(o),r(o,a);let i=(o,a,l)=>{let c=Object.getOwnPropertyDescriptor(o,a);if(!c||!("value"in c)||typeof c.value!="function"||c.configurable!==!0)return;let u=c.value,f=this,d=function(...h){let p=h[0];if(f.shouldBlock()&&typeof p=="object"&&p!==null&&n.has(p)){let m=`${l}.${a}`,g=`${m} is blocked for protected intrinsics during script execution`,y=f.recordViolation("prototype_mutation",m,g);throw new Re(g,y)}return Reflect.apply(u,this,h)};this.temporaryIntrinsicDescriptors.push({target:o,prop:a,descriptor:c}),Object.defineProperty(o,a,{...c,value:d,writable:!1})};for(let o of["assign","defineProperties","defineProperty","freeze","preventExtensions","seal","setPrototypeOf"])i(Object,o,"Object");for(let o of["defineProperty","deleteProperty","preventExtensions","set","setPrototypeOf"])i(Reflect,o,"Reflect")}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let e=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(e){this.patchFailures.push("AsyncFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(function*(){}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(e){this.patchFailures.push("GeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(async function*(){}).constructor,n=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&e!==n&&this.patchPrototypeConstructor(e.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(e){this.patchFailures.push("AsyncGeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",e instanceof Error?e.message:e)}}protectErrorPrepareStackTrace(){let e=this;try{let n=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:n});let r=n?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return r},set(s){if(e.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",o=e.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new Re(i,o)}e.shouldAudit()&&e.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),r=s},configurable:!0})}catch(n){this.patchFailures.push("Error.prepareStackTrace"),console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",n instanceof Error?n.message:n)}}protectPromiseThen(){let e=this;try{let i=function(...o){return Dt.run(this.captured,()=>{if(!this.box.isExecutionIdActive(this.executionId)){if(this.box.recordViolation("promise_then_after_deactivate","Promise.then","Promise.then callback is blocked after defense deactivation"),this.box.config.auditMode)return Reflect.apply(this.cb,void 0,o);if(this.kind==="fulfilled")return o[0];throw o[0]}return Reflect.apply(this.cb,void 0,o)})};var n=i;let r=Object.getOwnPropertyDescriptor(Promise.prototype,"then");this.originalDescriptors.push({target:Promise.prototype,prop:"then",descriptor:r});let s=r?.value;if(typeof s!="function")return;Object.defineProperty(Promise.prototype,"then",{value:function(a,l){if(!Dt)return Reflect.apply(s,this,[a,l]);let c=Dt.getStore(),u=c?.sandboxActive===!0&&c.trusted!==!0?c.executionId:void 0;if(!u)return Reflect.apply(s,this,[a,l]);let f=e.getCachedContext(u),d=c?.forceUntrusted?{...f,forceUntrusted:!0}:f,h=(p,m)=>typeof p!="function"?p:i.bind({box:e,executionId:u,captured:d,cb:p,kind:m});return Reflect.apply(s,this,[h(a,"fulfilled"),h(l,"rejected")])},writable:!0,configurable:!0})}catch(r){this.patchFailures.push("Promise.prototype.then"),console.debug("[DefenseInDepthBox] Could not protect Promise.prototype.then:",r instanceof Error?r.message:r)}}patchPrototypeConstructor(e,n,r){let s=this;try{let i=Object.getOwnPropertyDescriptor(e,"constructor");this.originalDescriptors.push({target:e,prop:"constructor",descriptor:i});let o=i?.value;Object.defineProperty(e,"constructor",{get(){if(s.shouldBlock()){let a=`${n} access is blocked during script execution`,l=s.recordViolation(r,n,a);throw new Re(a,l)}return s.shouldAudit()&&s.recordViolation(r,n,`${n} accessed (audit mode)`),o},set(a){if(s.shouldBlock()){let l=`${n} modification is blocked during script execution`,c=s.recordViolation(r,n,l);throw new Re(l,c)}Object.defineProperty(this,"constructor",{value:a,writable:!0,configurable:!0})},configurable:!0})}catch(i){this.patchFailures.push(n),console.debug(`[DefenseInDepthBox] Could not patch ${n}:`,i instanceof Error?i.message:i)}}protectProcessMainModule(){if(typeof process>"u")return;let e=this;try{let n=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:n});let r=n?.value;r!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(e.shouldBlock()){let s="process.mainModule access is blocked during script execution",i=e.recordViolation("process_main_module","process.mainModule",s);throw new Re(s,i)}return e.shouldAudit()&&e.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),r},set(s){if(e.shouldBlock()){let i="process.mainModule modification is blocked during script execution",o=e.recordViolation("process_main_module","process.mainModule",i);throw new Re(i,o)}Object.defineProperty(process,"mainModule",{value:s,writable:!0,configurable:!0})},configurable:!0})}catch(n){this.patchFailures.push("process.mainModule"),console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",n instanceof Error?n.message:n)}}protectProcessExecPath(){if(typeof process>"u")return;let e=this;try{let n=Object.getOwnPropertyDescriptor(process,"execPath");this.originalDescriptors.push({target:process,prop:"execPath",descriptor:n});let r=n?.value??process.execPath;Object.defineProperty(process,"execPath",{get(){if(e.shouldBlock()){let s="process.execPath access is blocked during script execution",i=e.recordViolation("process_exec_path","process.execPath",s);throw new Re(s,i)}return e.shouldAudit()&&e.recordViolation("process_exec_path","process.execPath","process.execPath accessed (audit mode)"),r},set(s){if(e.shouldBlock()){let i="process.execPath modification is blocked during script execution",o=e.recordViolation("process_exec_path","process.execPath",i);throw new Re(i,o)}Object.defineProperty(process,"execPath",{value:s,writable:!0,configurable:!0})},configurable:!0})}catch(n){this.patchFailures.push("process.execPath"),console.debug("[DefenseInDepthBox] Could not protect process.execPath:",n instanceof Error?n.message:n)}}lockWellKnownSymbols(){let e=(n,r)=>{try{let s=Object.getOwnPropertyDescriptor(n,r);if(s?.configurable){if("value"in s){Object.defineProperty(n,r,{...s,configurable:!1,writable:!1});return}Object.defineProperty(n,r,{...s,configurable:!1})}}catch{}};for(let n of[Array,Map,Set,RegExp,Promise])e(n,Symbol.species);for(let n of[Array.prototype,String.prototype,Map.prototype,Set.prototype])e(n,Symbol.iterator);e(Symbol.prototype,Symbol.toPrimitive),e(Date.prototype,Symbol.toPrimitive);for(let n of[Symbol.match,Symbol.matchAll,Symbol.replace,Symbol.search,Symbol.split])e(RegExp.prototype,n);e(Function.prototype,Symbol.hasInstance),e(Array.prototype,Symbol.unscopables);for(let n of[Map.prototype,Set.prototype,Promise.prototype,ArrayBuffer.prototype])e(n,Symbol.toStringTag)}protectProxyRevocable(){let e=this;try{let n=Proxy.revocable;if(typeof n!="function")return;let r=Object.getOwnPropertyDescriptor(Proxy,"revocable");this.originalDescriptors.push({target:Proxy,prop:"revocable",descriptor:r}),Object.defineProperty(Proxy,"revocable",{value:function(i,o){if(e.shouldBlock()){let a="Proxy.revocable is blocked during script execution",l=e.recordViolation("proxy","Proxy.revocable",a);throw new Re(a,l)}return e.shouldAudit()&&e.recordViolation("proxy","Proxy.revocable","Proxy.revocable called (audit mode)"),n(i,o)},writable:!1,configurable:!0})}catch(n){this.patchFailures.push("Proxy.revocable"),console.debug("[DefenseInDepthBox] Could not protect Proxy.revocable:",n instanceof Error?n.message:n)}}protectDynamicImport(){if(!(Ni||t.importHooksRegistered))try{let e=Sc;if(!e)throw new Error("node:module is unavailable");let n=new Set;for(let i of e.builtinModules??[]){let o=i.startsWith("node:")?i.slice(5):i;n.add(o);let a=o.indexOf("/");a>0&&n.add(o.slice(0,a))}let r=i=>{if(i.startsWith("./")||i.startsWith("../")||i.startsWith("/")||i.startsWith("file:")||i.startsWith("data:")||i.startsWith("blob:")||i.startsWith("http:")||i.startsWith("https:"))return!1;let o=i.startsWith("node:")?i.slice(5):i;if(!o)return!1;if(typeof e.isBuiltin=="function"&&e.isBuiltin(o)||n.has(o))return!0;let a=o.indexOf("/");return a>0&&n.has(o.slice(0,a))},s=i=>{let o=Dt?.getStore();return i.config.auditMode===!0&&o?.sandboxActive===!0&&!t.isTrustedContext(o)};if(typeof e.registerHooks=="function"){e.registerHooks({resolve(i,o,a){let l=t.instance;if(!l)return a(i,o);if((i.startsWith("data:")||i.startsWith("blob:"))&&l.shouldBlock()){let c=`import(${i.startsWith("data:")?"data:":"blob:"})`,u=`dynamic import of ${i.startsWith("data:")?"data:":"blob:"} URLs is blocked by defense-in-depth`,f=l.recordViolation("dynamic_import_builtin",c,u);throw new Re(u,f)}if(r(i)){let c=`import(${i})`,u=`dynamic import of Node.js builtin '${i}' is blocked during script execution`;if(l.shouldBlock()){let f=l.recordViolation("dynamic_import_builtin",c,u);throw new Re(u,f)}s(l)&&l.recordViolation("dynamic_import_builtin",c,`dynamic import of Node.js builtin '${i}' called (audit mode)`)}return a(i,o)}}),t.importHooksRegistered=!0;return}throw new Error("context-aware ESM loader hooks (node:module.registerHooks) are unavailable")}catch(e){throw new Error(`DefenseInDepthBox: could not register dynamic-import hooks: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}protectModuleLoad(){this.protectModuleMethod("_load","module_load")}protectModuleResolveFilename(){this.protectModuleMethod("_resolveFilename","module_resolve_filename")}protectModuleMethod(e,n){if(Ni)return;let r=`Module.${e}`;try{let s=t4,i=s?.[e];if(!s||typeof i!="function")throw new Error("node:module Module class or method is unavailable");let o=Object.getOwnPropertyDescriptor(s,e);if(!o)throw new Error("method has no own property descriptor");if(o.configurable===!1&&o.writable===!1)throw new Error("method is non-configurable and non-writable");let a=this.createBlockingProxy(i,r,n);this.originalDescriptors.push({target:s,prop:e,descriptor:o}),Object.defineProperty(s,e,{...o,value:a});let l=Object.getOwnPropertyDescriptor(s,e);if(s[e]!==a||l?.value!==a)throw new Error("installed patch failed verification")}catch{this.patchFailures.push(r)}}applyPatch(e,n=!1){let{target:r,prop:s,violationType:i,strategy:o}=e;try{let a=r[s];if(a===void 0)return;let l=Object.getOwnPropertyDescriptor(r,s);if(this.originalDescriptors.push({target:r,prop:s,descriptor:l}),o==="freeze"){if(typeof a=="object"&&a!==null){n&&Object.freeze(a);let c=this.getPathForTarget(r,s),u=this.createReadonlyObjectProxy(a,c,i);Object.defineProperty(r,s,{...l,value:u})}}else{let c=this.getPathForTarget(r,s),u=typeof a=="function"?this.createBlockingProxy(a,c,i):this.createBlockingObjectProxy(a,c,i,e.allowedKeys);Object.defineProperty(r,s,{value:u,writable:!0,configurable:!0})}}catch(a){let l=this.getPathForTarget(r,s);this.patchFailures.push(l),console.debug(`[DefenseInDepthBox] Could not patch ${l}:`,a instanceof Error?a.message:a)}}restorePatches(){for(let e=this.temporaryIntrinsicDescriptors.length-1;e>=0;e--){let{target:n,prop:r,descriptor:s}=this.temporaryIntrinsicDescriptors[e];try{Object.defineProperty(n,r,s)}catch(i){console.debug(`[DefenseInDepthBox] Could not restore temporary intrinsic ${String(r)}:`,i instanceof Error?i.message:i)}}this.temporaryIntrinsicDescriptors=[];for(let e=this.originalDescriptors.length-1;e>=0;e--){let{target:n,prop:r,descriptor:s}=this.originalDescriptors[e];try{s?Object.defineProperty(n,r,s):delete n[r]}catch(i){let o=this.getPathForTarget(n,r);console.debug(`[DefenseInDepthBox] Could not restore ${o}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}}});function r4(t){return typeof t!="function"?t:nt.bindCurrentContext(t)}function Oi(t,e){if(e===Number.POSITIVE_INFINITY)return;let n=r4(t),r={cleared:!1,remainingMs:Math.max(0,e),timer:void 0},s=()=>{if(r.cleared)return;let i=Math.min(r.remainingMs,TF);r.timer=R1(()=>{r.cleared||(r.remainingMs-=i,r.remainingMs>0?s():n())},i)};return s(),r}function Ii(t){t&&(t.cleared=!0,t.timer!==void 0&&n4(t.timer))}var R1,n4,$re,Lre,Ti,Hr,P1,TF,Os=L(()=>{"use strict";cn();R1=globalThis.setTimeout.bind(globalThis),n4=globalThis.clearTimeout.bind(globalThis),$re=globalThis.setInterval.bind(globalThis),Lre=globalThis.clearInterval.bind(globalThis);Ti=((t,e,...n)=>R1(r4(t),e,...n)),Hr=n4,P1=((t,e,...n)=>R1(t,e,...n)),TF=2147483647});function L1(t,e,n){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(e)||e<0||t>e)throw new RangeError(`${n}: byte conversion limit exceeded (${e} bytes)`)}function j(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r<=127)e++;else if(r<=2047)e+=2;else if(r>=55296&&r<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=4,n++):e+=3}else e+=3}return e}function to(t){return t}function kt(t){return t}function fe(t,e=$1){let n=t;if(!n)return n;L1(n.length,e,"UTF-8 decode");let r=!1;for(let i=0;i<n.length;i++){let o=n.charCodeAt(i);if(o>255)return n;o>127&&(r=!0)}if(!r)return n;let s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);try{return OF.decode(s)}catch{return n}}function vr(t,e=$1){if(!t)return t;L1(j(t),e,"UTF-8 encode");let n=IF.encode(t),r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return r}function RF(t,e=$1){L1(t.byteLength,e,"byte-string conversion");let n="";for(let r=0;r<t.length;r++)n+=String.fromCharCode(t[r]);return n}async function zn(t,e){return typeof t.readFileBytes=="function"?t.readFileBytes(e):RF(await t.readFileBuffer(e))}function zf(t){return t.stdoutKind?t.stdoutKind:t.stdoutEncoding==="binary"?"bytes":"text"}function ni(t){return zf(t)==="bytes"?t.stdout:vr(t.stdout)}function F1(t){return zf(t)==="bytes"?fe(t.stdout):t.stdout}function s4(t){return{stdout:t,stdoutKind:"text"}}function i4(t){return{stdout:t,stdoutKind:"bytes",stdoutEncoding:"binary"}}var OF,IF,$1,Ri,pe=L(()=>{"use strict";OF=new TextDecoder("utf-8",{fatal:!0}),IF=new TextEncoder,$1=512*1024*1024;Ri=""});function Uf(t){return t instanceof Jn||t instanceof er||t instanceof Nn}var Bt,Jn,er,Nn,tr,nr,Pe,dt,lr,ri,Xa,v,et,un,si,Cr,X=L(()=>{"use strict";pe();Bt=class extends Error{stdout;stderr;internalOutputAccounting={stdout:0,stderr:0};constructor(e,n="",r=""){super(e),this.stdout=n,this.stderr=r}prependOutput(e,n){this.stdout=e+this.stdout,this.stderr=n+this.stderr,this.internalOutputAccounting.stdout+=j(e),this.internalOutputAccounting.stderr+=j(n)}},Jn=class extends Bt{levels;name="BreakError";constructor(e=1,n="",r=""){super("break",n,r),this.levels=e}},er=class extends Bt{levels;name="ContinueError";constructor(e=1,n="",r=""){super("continue",n,r),this.levels=e}},Nn=class extends Bt{exitCode;name="ReturnError";constructor(e=0,n="",r=""){super("return",n,r),this.exitCode=e}},tr=class extends Bt{exitCode;name="ErrexitError";constructor(e,n="",r=""){super(`errexit: command exited with status ${e}`,n,r),this.exitCode=e}},nr=class extends Bt{varName;name="NounsetError";constructor(e,n=""){super(`${e}: unbound variable`,n,`bash: ${e}: unbound variable
|
|
6
6
|
`),this.varName=e}},Pe=class extends Bt{exitCode;name="ExitError";constructor(e,n="",r=""){super("exit",n,r),this.exitCode=e}},dt=class extends Bt{name="ArithmeticError";fatal;constructor(e,n="",r="",s=!1){super(e,n,r),this.stderr=r||`bash: ${e}
|
|
7
7
|
`,this.fatal=s}},lr=class extends Bt{name="BadSubstitutionError";constructor(e,n="",r=""){super(e,n,r),this.stderr=r||`bash: ${e}: bad substitution
|
|
8
8
|
`}},ri=class extends Bt{name="GlobError";constructor(e,n="",r=""){super(`no match: ${e}`,n,r),this.stderr=r||`bash: no match: ${e}
|
|
9
9
|
`}},Xa=class extends Bt{name="BraceExpansionError";constructor(e,n="",r=""){super(e,n,r),this.stderr=r||`bash: ${e}
|
|
10
10
|
`}},v=class extends Bt{limitType;name="ExecutionLimitError";static EXIT_CODE=126;constructor(e,n,r="",s=""){super(e,r,s),this.limitType=n,this.stderr=s||`bash: ${e}
|
|
11
|
-
`}},
|
|
11
|
+
`}},et=class extends Bt{name="ExecutionAbortedError";constructor(e="",n=""){super("execution aborted",e,n)}},un=class extends Bt{commandName;name="UnresolvedCommandError";exitCode=127;constructor(e,n="",r=""){super(`unresolved command: ${e}`,n,r),this.commandName=e}},si=class extends Bt{name="SubshellExitError";constructor(e="",n=""){super("subshell exit",e,n)}};Cr=class extends Bt{exitCode;name="PosixFatalError";constructor(e,n="",r=""){super("posix fatal error",n,r),this.exitCode=e}}});function Ya(...t){let e=[...new Set(t.filter(s=>s!==void 0))];if(e.length===0)return{signal:void 0,cleanup(){}};if(e.length===1)return{signal:e[0],cleanup(){}};let n=new AbortController,r=[];for(let s of e){if(s.aborted){n.abort(s.reason);break}let i=()=>n.abort(s.reason);s.addEventListener("abort",i,{once:!0}),r.push([s,i])}return{signal:n.signal,cleanup(){for(let[s,i]of r)s.removeEventListener("abort",i)}}}async function Ac(t,e,n){if(!e)return t;if(e.aborted)throw t.catch(()=>{}),new et("",n);let r;try{return await Promise.race([t,new Promise((s,i)=>{r=()=>i(new et("",n)),e.addEventListener("abort",r,{once:!0})})])}finally{r&&e.removeEventListener("abort",r)}}var Qa=L(()=>{"use strict";X()});function cs(t,e,n){let r=n==="width"?Math.abs(t):t;if(!Number.isFinite(t)||!Number.isSafeInteger(t)||r<0||r>e)throw new v(`format ${n} limit exceeded (${e} bytes)`,"string_length")}function Ja(t,e,n,r=D1){cs(e,r,"width"),n!==-1&&cs(n,r,"precision");let s=t;n>=0&&s.length>n&&(s=s.slice(0,n));let i=Math.abs(e);if(i>s.length){if(j(s)+i-s.length>r)throw new v(`formatted value size limit exceeded (${r} bytes)`,"string_length");e<0?s=s.padEnd(i," "):s=s.padStart(i," ")}if(j(s)>r)throw new v(`formatted value size limit exceeded (${r} bytes)`,"string_length");return s}function o4(t,e,n=D1){let r=e,s=0,i=-1,o=!1;for(r<t.length&&t[r]==="-"&&(o=!0,r++);r<t.length&&/\d/.test(t[r]);)s=s*10+parseInt(t[r],10),r++;if(r<t.length&&t[r]===".")for(r++,i=0;r<t.length&&/\d/.test(t[r]);)i=i*10+parseInt(t[r],10),r++;return o&&s>0&&(s=-s),cs(s,n,"width"),i!==-1&&cs(i,n,"precision"),[s,i,r-e]}function Wf(t,e=D1){if(j(t)>e)throw new v(`escaped string size limit exceeded (${e} bytes)`,"string_length");let n="",r=0;for(;r<t.length;)if(t[r]==="\\"&&r+1<t.length)switch(t[r+1]){case"n":n+=`
|
|
12
12
|
`,r+=2;break;case"t":n+=" ",r+=2;break;case"r":n+="\r",r+=2;break;case"\\":n+="\\",r+=2;break;case"a":n+="\x07",r+=2;break;case"b":n+="\b",r+=2;break;case"f":n+="\f",r+=2;break;case"v":n+="\v",r+=2;break;case"e":case"E":n+="\x1B",r+=2;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let i="",o=r+1;for(;o<t.length&&o<r+4&&/[0-7]/.test(t[o]);)i+=t[o],o++;n+=String.fromCharCode(parseInt(i,8)),r=o;break}case"x":{let i=[],o=r;for(;o+3<t.length&&t[o]==="\\"&&t[o+1]==="x"&&/[0-9a-fA-F]{2}/.test(t.slice(o+2,o+4));)i.push(parseInt(t.slice(o+2,o+4),16)),o+=4;if(i.length>0){try{let a=new TextDecoder("utf-8",{fatal:!0});n+=a.decode(new Uint8Array(i))}catch{for(let a of i)n+=String.fromCharCode(a)}r=o}else n+=t[r],r++;break}case"u":{let i="",o=r+2;for(;o<t.length&&o<r+6&&/[0-9a-fA-F]/.test(t[o]);)i+=t[o],o++;i?(n+=String.fromCodePoint(parseInt(i,16)),r=o):(n+="\\u",r+=2);break}case"U":{let i="",o=r+2;for(;o<t.length&&o<r+10&&/[0-9a-fA-F]/.test(t[o]);)i+=t[o],o++;i?(n+=String.fromCodePoint(parseInt(i,16)),r=o):(n+="\\U",r+=2);break}default:n+=t[r],r++}else n+=t[r],r++;return n}var D1,Qt=L(()=>{"use strict";pe();X();pe();D1=10*1024*1024});var a4={};he(a4,{echoCommand:()=>$F,flagsForFuzzing:()=>_1});function PF(t){let e="",n=0;for(;n<t.length;)if(t[n]==="\\"){if(n+1>=t.length){e+="\\";break}let r=t[n+1];switch(r){case"\\":e+="\\",n+=2;break;case"n":e+=`
|
|
13
13
|
`,n+=2;break;case"t":e+=" ",n+=2;break;case"r":e+="\r",n+=2;break;case"a":e+="\x07",n+=2;break;case"b":e+="\b",n+=2;break;case"f":e+="\f",n+=2;break;case"v":e+="\v",n+=2;break;case"e":case"E":e+="\x1B",n+=2;break;case"c":return{output:e,stop:!0};case"0":{let s="",i=n+2;for(;i<t.length&&i<n+5&&/[0-7]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\0";else{let o=parseInt(s,8)%256;e+=String.fromCharCode(o)}n=i;break}case"x":{let s="",i=n+2;for(;i<t.length&&i<n+4&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\x",n+=2;else{let o=parseInt(s,16);e+=String.fromCharCode(o),n=i}break}case"u":{let s="",i=n+2;for(;i<t.length&&i<n+6&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\u",n+=2;else{let o=parseInt(s,16);e+=String.fromCodePoint(o),n=i}break}case"U":{let s="",i=n+2;for(;i<t.length&&i<n+10&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\U",n+=2;else{let o=parseInt(s,16);try{e+=String.fromCodePoint(o)}catch{e+=`\\U${s}`}n=i}break}default:e+=`\\${r}`,n+=2}}else e+=t[n],n++;return{output:e,stop:!1}}var $F,_1,M1=L(()=>{"use strict";$F={name:"echo",async execute(t,e){let n=!1,r=e.xpgEcho??!1,s=0;for(;s<t.length;){let o=t[s];if(o==="-n")n=!0,s++;else if(o==="-e")r=!0,s++;else if(o==="-E")r=!1,s++;else if(o==="-ne"||o==="-en")n=!0,r=!0,s++;else break}let i=t.slice(s).join(" ");if(r){let o=PF(i);if(i=o.output,o.stop)return{stdout:i,stderr:"",exitCode:0,internalStdinConsumed:0}}return n||(i+=`
|
|
14
|
-
`),{stdout:i,stderr:"",exitCode:0,internalStdinConsumed:0}}},_1={name:"echo",flags:[{flag:"-n",type:"boolean"},{flag:"-e",type:"boolean"},{flag:"-E",type:"boolean"}],stdinType:"none",needsArgs:!0}});function vc(t){return t instanceof v||t instanceof
|
|
14
|
+
`),{stdout:i,stderr:"",exitCode:0,internalStdinConsumed:0}}},_1={name:"echo",flags:[{flag:"-n",type:"boolean"},{flag:"-e",type:"boolean"},{flag:"-E",type:"boolean"}],stdinType:"none",needsArgs:!0}});function vc(t){return t instanceof v||t instanceof et||t instanceof Re||t instanceof un}function ke(t){if(vc(t))throw t}var Kt=L(()=>{"use strict";X();cn()});function K(t){let e=`${t.name} - ${t.summary}
|
|
15
15
|
|
|
16
16
|
`;if(e+=`Usage: ${t.usage}
|
|
17
17
|
`,t.description){if(e+=`
|
|
@@ -53,7 +53,7 @@ Notes:
|
|
|
53
53
|
`,exitCode:1,internalStdinConsumed:0};if(n=t[r+1],!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\[[^\]\n]+\])?$/.test(n)||/[;\r\\]/.test(n)||n.includes(".."))return{stdout:"",stderr:`printf: \`${n}': not a valid identifier
|
|
54
54
|
`,exitCode:2,internalStdinConsumed:0};r+=2}else{if(o.startsWith("-")&&o!=="-")break;break}}if(r>=t.length)return{stdout:"",stderr:`printf: usage: printf format [arguments]
|
|
55
55
|
`,exitCode:1,internalStdinConsumed:0};let s=t[r],i=t.slice(r+1);try{let o=Math.min(e.limits.maxStringLength,e.limits.maxOutputSize),a=Wf(s,o),l="",c=0,u=0,f=!1,d="",h=e.env.get("TZ");do{let{result:p,argsConsumed:m,error:g,errMsg:y,stopped:w}=KF(a,i,u,h,o-c),b=j(p);if(b>o-c)throw new v(`printf: output size limit exceeded (${o} bytes)`,"string_length");if(l+=p,c+=b,u+=m,g&&(f=!0,y&&(d=y)),w)break}while(u<i.length&&u>0);if(u===0&&i.length>0,n){let p=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(['"]?)(.+?)\2\]$/);if(p){let m=p[1],g=p[3];if(g=g.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(y,w)=>e.env.get(w)??""),e.assignShellVariable)await e.assignShellVariable(m,l,g);else throw new Error("printf -v array assignment requires an interpreter assignment gateway")}else if(e.assignShellVariable)await e.assignShellVariable(n,l);else{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n))throw new Error(`${n}: not a valid identifier`);e.env.set(n,l)}return{stdout:"",stderr:d,exitCode:f?1:0,internalStdinConsumed:0}}return{stdout:l,stderr:d,exitCode:f?1:0,internalStdinConsumed:0}}catch(o){if(o instanceof v||typeof o=="object"&&o!==null&&"name"in o&&o.name==="ExitError")throw o;return{stdout:"",stderr:`printf: ${Qe(o)}
|
|
56
|
-
`,exitCode:1,internalStdinConsumed:0}}}};Is=!1;W1={name:"printf",flags:[{flag:"-v",type:"value",valueHint:"string"}],stdinType:"none",needsArgs:!0}});function ro(t,e){if(!Number.isSafeInteger(t)||t<0)throw new v(`${e}: invalid bounded allocation count`,"array_elements")}function p4(t){return new v(`${t}: invalid bounded allocation count`,"array_elements")}function fn(t,e,n){ro(t,n),ro(e,n);let r=t+e;if(!Number.isSafeInteger(r))throw p4(n);return r}function kc(t,e,n){if(ro(t,n),ro(e,n),t!==0&&e>Math.floor(Number.MAX_SAFE_INTEGER/t))throw p4(n);return t*e}function m4(t,e,n,r){let s=new $e(n,r);return s.repeat(t,e),s.build()}function cr(t,e,n,r){let s=new $e(n,r);for(let i=0;i<t.length;i++)i>0&&s.append(e),s.append(t[i]);return s.build()}var $e,Nt=L(()=>{"use strict";pe();X();$e=class{maxBytes;label;createLimitError;reservedBytes;chunks=[];usedBytes=0;constructor(e,n,r=void 0,s=0){this.maxBytes=e,this.label=n,this.createLimitError=r,this.reservedBytes=s,ro(e,n),ro(s,n),s>e&&this.fail()}fail(){throw this.createLimitError?.()??new v(`${this.label}: output size limit exceeded (${this.maxBytes} bytes)`,"output_size")}get byteLength(){return this.usedBytes}get remainingBytes(){return this.maxBytes-this.reservedBytes-this.usedBytes}reserve(e){ro(e,this.label),e>this.remainingBytes&&this.fail()}append(e){let n=j(e);return this.reserve(n),e&&this.chunks.push(e),this.usedBytes+=n,this}repeat(e,n){ro(n,this.label);let r=j(e);return r!==0&&n>Math.floor(this.remainingBytes/r)&&this.fail(),this.append(e.repeat(n))}reset(){this.chunks.length=0,this.usedBytes=0}build(){return this.chunks.join("")}}});function tl(t){if(typeof t=="object"&&t!==null&&"code"in t){let e=t.code;if(typeof e=="string"&&e.length>0)return e}}function st(t,e){return tl(t)===e}function g4(t,e="EIO"){let n=tl(t),r=t instanceof Error?t.message:String(t??"unknown error");if(n!==void 0){let s=`${n}: `;return new D(n,r.startsWith(s)?r.slice(s.length):r)}return new D(e,r)}var D,bn=L(()=>{"use strict";D=class extends Error{code;bareMessage;constructor(e,n){if(e.length===0)throw new Error("FsError: code must be a non-empty errno name");super(n.startsWith(`${e}:`)?n:`${e}: ${n}`),this.code=e,this.bareMessage=n.startsWith(`${e}:`)?n.slice(e.length+(n[e.length+1]===" "?2:1)):n}}});function ce(t){if(!t||t==="/")return"/";let e=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;e.startsWith("/")||(e=`/${e}`);let n=e.split("/").filter(s=>s&&s!=="."),r=[];for(let s of n)s===".."?r.pop():r.push(s);return`/${r.join("/")}`||"/"}function ur(t,e){let n=ce(t),r=ce(e);return r===n||n==="/"||r.startsWith(`${n}/`)}function
|
|
56
|
+
`,exitCode:1,internalStdinConsumed:0}}}};Is=!1;W1={name:"printf",flags:[{flag:"-v",type:"value",valueHint:"string"}],stdinType:"none",needsArgs:!0}});function ro(t,e){if(!Number.isSafeInteger(t)||t<0)throw new v(`${e}: invalid bounded allocation count`,"array_elements")}function p4(t){return new v(`${t}: invalid bounded allocation count`,"array_elements")}function fn(t,e,n){ro(t,n),ro(e,n);let r=t+e;if(!Number.isSafeInteger(r))throw p4(n);return r}function kc(t,e,n){if(ro(t,n),ro(e,n),t!==0&&e>Math.floor(Number.MAX_SAFE_INTEGER/t))throw p4(n);return t*e}function m4(t,e,n,r){let s=new $e(n,r);return s.repeat(t,e),s.build()}function cr(t,e,n,r){let s=new $e(n,r);for(let i=0;i<t.length;i++)i>0&&s.append(e),s.append(t[i]);return s.build()}var $e,Nt=L(()=>{"use strict";pe();X();$e=class{maxBytes;label;createLimitError;reservedBytes;chunks=[];usedBytes=0;constructor(e,n,r=void 0,s=0){this.maxBytes=e,this.label=n,this.createLimitError=r,this.reservedBytes=s,ro(e,n),ro(s,n),s>e&&this.fail()}fail(){throw this.createLimitError?.()??new v(`${this.label}: output size limit exceeded (${this.maxBytes} bytes)`,"output_size")}get byteLength(){return this.usedBytes}get remainingBytes(){return this.maxBytes-this.reservedBytes-this.usedBytes}reserve(e){ro(e,this.label),e>this.remainingBytes&&this.fail()}append(e){let n=j(e);return this.reserve(n),e&&this.chunks.push(e),this.usedBytes+=n,this}repeat(e,n){ro(n,this.label);let r=j(e);return r!==0&&n>Math.floor(this.remainingBytes/r)&&this.fail(),this.append(e.repeat(n))}reset(){this.chunks.length=0,this.usedBytes=0}build(){return this.chunks.join("")}}});function tl(t){if(typeof t=="object"&&t!==null&&"code"in t){let e=t.code;if(typeof e=="string"&&e.length>0)return e}}function st(t,e){return tl(t)===e}function g4(t,e="EIO"){let n=tl(t),r=t instanceof Error?t.message:String(t??"unknown error");if(n!==void 0){let s=`${n}: `;return new D(n,r.startsWith(s)?r.slice(s.length):r)}return new D(e,r)}var D,bn=L(()=>{"use strict";D=class extends Error{code;bareMessage;constructor(e,n){if(e.length===0)throw new Error("FsError: code must be a non-empty errno name");super(n.startsWith(`${e}:`)?n:`${e}: ${n}`),this.code=e,this.bareMessage=n.startsWith(`${e}:`)?n.slice(e.length+(n[e.length+1]===" "?2:1)):n}}});function ce(t){if(!t||t==="/")return"/";let e=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;e.startsWith("/")||(e=`/${e}`);let n=e.split("/").filter(s=>s&&s!=="."),r=[];for(let s of n)s===".."?r.pop():r.push(s);return`/${r.join("/")}`||"/"}function ur(t,e){let n=ce(t),r=ce(e);return r===n||n==="/"||r.startsWith(`${n}/`)}function Ce(t,e){if(t.includes("\0"))throw new D("ENOENT",`path contains null byte, ${e} '${t}'`)}function kr(t){let e=ce(t);if(e==="/")return"/";let n=e.lastIndexOf("/");return n===0?"/":e.slice(0,n)}function sD(t){if(typeof process>"u"||process.platform!=="win32"||!/^[A-Za-z]:[\\/]/.test(t))return t;let e=t[0].toLowerCase(),n=t.slice(2).replace(/\\/g,"/");return`/${e}${n}`}function io(t,e){if(e=sD(e),e.startsWith("/"))return ce(e);let n=t==="/"?`/${e}`:`${t}/${e}`;return ce(n)}function Jo(t){return t.replace(/\\/g,"/")}function rr(t,e){return t==="/"?`/${e}`:`${t}/${e}`}function nl(t,e){if(e.startsWith("/"))return ce(e);let n=kr(t);return ce(rr(n,e))}var Nc,Rs,so,Vf,us=L(()=>{"use strict";bn();Nc=40,Rs=493,so=420,Vf=511});function y4(t,e,n){if(!t)return t;let r=t.replace(/\n\s+at\s.*/g,"");return n&&(r=r.replace(/\bfile:\/\/\/?[^\s'",)}\]:]+/g,"<path>")),r=r.replace(e?/(?:\/(?:Users|home|private|var|opt|Library|System|usr|etc|tmp|nix|snap|workspace|root|srv|mnt|app))\b[^\s'",)}\]:]*/g:/(?:\/(?:Users|home|private|var|opt|Library|System|usr|etc|tmp|nix|snap))\b[^\s'",)}\]:]*/g,"<path>"),r=r.replace(/node:internal\/[^\s'",)}\]:]+/g,"<internal>"),r=r.replace(/[A-Z]:\\[^\s'",)}\]:]+/g,"<path>"),n&&(r=r.replace(/\\\\[^\s\\]+\\[^\s'",)}\]:]+/g,"<path>")),r}function Be(t){return y4(t,!1,!1)}function Ot(t){return y4(t,!0,!0)}var Tn=L(()=>{"use strict"});function b4(t){if(t.identity!==void 0)return`identity:${t.identity}`;if(t.dev!==void 0&&t.ino!==void 0)return`inode:${String(t.dev)}:${String(t.ino)}`}function w4(t){return st(t,"ENOENT")}async function Gr(t,e,n){let r=ce(e),s;try{s=await t.stat(r)}catch(a){if(!w4(a))return{existence:"unknown"}}if(s!==void 0){let a=b4(s);try{return{existence:"existing",canonicalPath:ce(await t.realpath(r)),stableIdentity:a}}catch{return a===void 0?{existence:"unknown"}:{existence:"existing",stableIdentity:a}}}let i=[],o=r;for(;;){n?.checkpoint();let a=kr(o);if(a===o)return{existence:"unknown"};i.unshift(o.slice(a==="/"?1:a.length+1)),o=a;try{let l=ce(await t.realpath(o));return{existence:"missing",canonicalPath:i.reduce((c,u)=>rr(c,u),l)}}catch(l){if(!w4(l))return{existence:"missing"}}}}async function Hf(t,e,n){let[r,s]=await Promise.all([Gr(t,e),Gr(t,n)]);return r.existence==="unknown"||s.existence==="unknown"?"unknown":r.existence==="missing"||s.existence==="missing"?r.existence!==s.existence?"different":r.canonicalPath!==void 0&&r.canonicalPath===s.canonicalPath?"same":"unknown":r.stableIdentity!==void 0&&s.stableIdentity!==void 0?r.stableIdentity===s.stableIdentity?"same":"different":r.canonicalPath!==void 0&&r.canonicalPath===s.canonicalPath?"same":"unknown"}async function Gf(t,e,n,r){let[s,i]=await Promise.all([Gr(t,e,r),Gr(t,n,r)]);return s.existence!=="existing"||s.canonicalPath===void 0||i.existence==="unknown"||i.canonicalPath===void 0?"unknown":ur(s.canonicalPath,i.canonicalPath)?"inside":"outside"}async function ii(t,e){let n=t.budget??new xn(t),r=[{kind:"enter",path:ce(t.root),depth:0}],s=new Set;for(;r.length>0;){n.checkpoint(0);let i=r.pop();if(!i)break;if(i.kind==="leave"){t.includeLeave&&await e({path:i.path,depth:i.depth,stat:i.stat,isSymlink:i.isSymlink,phase:"leave"}),i.identity&&s.delete(i.identity);continue}n.visit(i.depth);let o=await t.fs.lstat(i.path),a=o.isSymbolicLink,l=a&&t.symlinks==="follow"?await t.fs.stat(i.path):o;if(await e({path:i.path,depth:i.depth,stat:l,isSymlink:a,phase:"enter"}),!l.isDirectory||a&&t.symlinks!=="follow")continue;let c=b4(l)??await t.fs.realpath(i.path).then(ce).catch(()=>{});if(c!==void 0){if(s.has(c))throw new q1(t.site,i.path,"symbolic-link directory cycle detected");s.add(c)}r.push({kind:"leave",path:i.path,depth:i.depth,stat:l,isSymlink:a,identity:c});let u=await t.fs.readdir(i.path);n.checkpoint(),u.sort((f,d)=>f.localeCompare(d));for(let f=u.length-1;f>=0;f--)r.push({kind:"enter",path:rr(i.path,u[f]),depth:i.depth+1})}}var q1,xn,Kr=L(()=>{"use strict";X();bn();us();Tn();q1=class extends Error{operation;virtualPath;name="FileSystemPolicyError";constructor(e,n,r){super(`${e}: ${Be(r)}`),this.operation=e,this.virtualPath=n}};xn=class{options;entries=0;discoveredEntries=1;work=0;constructor(e){this.options=e}checkpoint(e=1){if(this.options.signal?.aborted)throw new et;if(this.options.executionScope?.throwIfAborted(this.options.site),!Number.isSafeInteger(e)||e<0||e>this.options.limits.maxTraversalWork-this.work)throw new v(`${this.options.site}: ${this.options.label??"filesystem traversal work"} limit exceeded (${this.options.limits.maxTraversalWork})`,"iterations");this.work+=e,this.options.executionScope?.consumeWork(e,`${this.options.site} filesystem traversal`)}visit(e){if(this.checkpoint(),e>this.options.limits.maxTraversalDepth)throw new v(`${this.options.site}: ${this.options.label??"filesystem traversal"} depth limit exceeded (${this.options.limits.maxTraversalDepth})`,"recursion");if(++this.entries>this.options.limits.maxTraversalEntries)throw new v(`${this.options.site}: ${this.options.label??"filesystem traversal"} entry limit exceeded (${this.options.limits.maxTraversalEntries})`,"iterations")}reserve(e){if(!Number.isSafeInteger(e)||e<0||e>this.options.limits.maxTraversalEntries-this.discoveredEntries)throw new v(`${this.options.site}: ${this.options.label??"filesystem traversal"} entry limit exceeded (${this.options.limits.maxTraversalEntries})`,"iterations");this.discoveredEntries+=e}discover(e){this.reserve(e),this.checkpoint(e)}}});var A4={};he(A4,{flagsForFuzzing:()=>Z1,lsCommand:()=>lD});function sr(t,e,n){if(j(n)>t.limits.maxOutputSize-j(e))throw new v(`ls: output size limit exceeded (${t.limits.maxOutputSize} bytes)`,"output_size");return e+n}function E4(t,e){if(e>t.limits.maxArrayElements)throw new v(`ls: array element limit exceeded (${t.limits.maxArrayElements})`,"array_elements")}function iD(t,e,n){E4(t,n),e.reserve(n)}function x4(t,e){let n=new $e(t.limits.maxOutputSize,"ls");for(let r=0;r<e.length;r++)r>0&&n.append(`
|
|
57
57
|
`),n.append(e[r]);return e.length>0&&n.append(`
|
|
58
58
|
`),n.build()}function H1(t){if(t<1024)return String(t);if(t<1024*1024){let n=t/1024;return n<10?`${n.toFixed(1)}K`:`${Math.round(n)}K`}if(t<1024*1024*1024){let n=t/1048576;return n<10?`${n.toFixed(1)}M`:`${Math.round(n)}M`}let e=t/(1024*1024*1024);return e<10?`${e.toFixed(1)}G`:`${Math.round(e)}G`}function G1(t){let n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],r=String(t.getDate()).padStart(2," "),s=new Date,i=new Date(s.getTime()-4320*60*60*1e3);if(t>i){let a=String(t.getHours()).padStart(2,"0"),l=String(t.getMinutes()).padStart(2,"0");return`${n} ${r} ${a}:${l}`}let o=t.getFullYear();return`${n} ${r} ${o}`}function Tc(t){return t.isDirectory?"/":t.isSymbolicLink?"@":(t.mode&73)!==0?"*":""}function cD(t,e,n){if(!e&&!n)return"name";if(e!==n)return e?"size":"time";let r="name";for(let s of t){if(s==="--")break;if(!(!s.startsWith("-")||s.startsWith("--")))for(let i of s.slice(1))i==="S"?r="size":i==="t"&&(r="time")}return r}async function V1(t,e,n,r,s){return await K1(t,i=>e.fs.resolvePath(e.cwd,i),e,n,r,s)}async function K1(t,e,n,r,s,i){let o=[...t];if(r==="name")o.sort();else{i?.checkpoint(o.length);let a=new Map;for(let l of o)try{let c=await n.fs.lstat(e(l));a.set(l,r==="size"?c.size??0:(c.mtime??new Date(0)).getTime())}catch{a.set(l,0)}o.sort((l,c)=>{let u=(a.get(c)??0)-(a.get(l)??0);return u!==0?u:l<c?-1:l>c?1:0})}return s&&o.reverse(),o}async function S4(t,e,n,r,s,i,o,a=!1,l=!1,c="name",u=!1,f=!1,d=new xn({limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:"ls"}),h=0,p=new Set,m=!1){let g=n||r,y=e.fs.resolvePath(e.cwd,t);try{m||d.visit(h);let w=await e.fs.stat(y);if(!w.isDirectory){let I=u?Tc(await e.fs.lstat(y)):"";if(s){let T=w.size??0,$=l?H1(T).padStart(5):String(T).padStart(5),C=w.mtime??new Date(0),O=G1(C);return{stdout:`-rw-r--r-- 1 user user ${$} ${O} ${t}${I}
|
|
59
59
|
`,stderr:"",exitCode:0}}return{stdout:`${t}${I}
|
|
@@ -64,7 +64,7 @@ Notes:
|
|
|
64
64
|
`);let $=[];for(let O=0;O<T.length;O+=100){let F=T.slice(O,O+100),R=await Promise.all(F.map(async _=>{let U=y==="/"?`/${_}`:`${y}/${_}`;try{let B=await e.fs.stat(U),W=B.isDirectory?"drwxr-xr-x":"-rw-r--r--",M=u?Tc(await e.fs.lstat(U)):"",Y=B.size??0,q=l?H1(Y).padStart(5):String(Y).padStart(5),H=B.mtime??new Date(0),re=G1(H);return{name:_,line:`${W} 1 user user ${q} ${re} ${_}${M}
|
|
65
65
|
`}}catch{return{name:_,line:`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${_}
|
|
66
66
|
`}}}));$.push(...R)}let C=new Map(T.map((O,F)=>[O,F]));$.sort((O,F)=>(C.get(O.name)??0)-(C.get(F.name)??0));for(let{line:O}of $)E=sr(e,E,O)}else if(u){let I=[],T=S.filter(C=>C!=="."&&C!==".."),$=S.filter(C=>C==="."||C==="..");for(let C of $)I.push(`${C}/`);for(let C=0;C<T.length;C+=100){let O=T.slice(C,C+100),F=await Promise.all(O.map(async R=>{let _=y==="/"?`/${R}`:`${y}/${R}`;try{let U=await e.fs.lstat(_);return`${R}${Tc(U)}`}catch{return R}}));I.push(...F)}E=sr(e,E,x4(e,I))}else E=sr(e,E,x4(e,S));if(i){let I=S.filter(R=>R!=="."&&R!==".."),T=new Set(I),$=[];if(e.fs.readdirWithFileTypes){let R=await e.fs.readdirWithFileTypes(y);d.checkpoint(),E4(e,R.length),$=R.filter(_=>_.isDirectory&&T.has(_.name)).map(_=>({name:_.name,isDirectory:!0}))}else for(let R=0;R<I.length;R+=100){let _=I.slice(R,R+100),U=await Promise.all(_.map(async B=>{let W=y==="/"?`/${B}`:`${y}/${B}`;try{let M=await e.fs.stat(W);return{name:B,isDirectory:M.isDirectory}}catch{return{name:B,isDirectory:!1}}}));$.push(...U.filter(B=>B.isDirectory))}let C=await K1($.map(R=>R.name),R=>y==="/"?`/${R}`:`${y}/${R}`,e,c,a,d),O=new Map(C.map((R,_)=>[R,_]));$.sort((R,_)=>(O.get(R.name)??0)-(O.get(_.name)??0));let F=[];for(let R of $){let _=t==="."?`./${R.name}`:`${t}/${R.name}`,U=await S4(_,e,n,r,s,i,!1,a,l,c,u,!0,d,h+1,x);F.push({name:R.name,result:U})}F.sort((R,_)=>(O.get(R.name)??0)-(O.get(_.name)??0));for(let{result:R}of F)E=sr(e,E,`
|
|
67
|
-
`),E=sr(e,E,R.stdout),A=sr(e,A,R.stderr),R.exitCode!==0&&(N=R.exitCode)}return{stdout:E,stderr:A,exitCode:N}}catch(w){if(w instanceof v||w instanceof
|
|
67
|
+
`),E=sr(e,E,R.stdout),A=sr(e,A,R.stderr),R.exitCode!==0&&(N=R.exitCode)}return{stdout:E,stderr:A,exitCode:N}}catch(w){if(w instanceof v||w instanceof et)throw w;return{stdout:"",stderr:`ls: ${t}: No such file or directory
|
|
68
68
|
`,exitCode:2}}}var oD,aD,lD,Z1,X1=L(()=>{"use strict";Nt();pe();Kr();X();on();Cc();xe();oD={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","-F, --classify append indicator (one of */=>@) to entries","-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"]},aD={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"},classifyFiles:{short:"F",long:"classify",type:"boolean"},directoryOnly:{short:"d",long:"directory",type:"boolean"},sortByTime:{short:"t",type:"boolean"},onePerLine:{short:"1",type:"boolean"}},lD={name:"ls",async execute(t,e){if(Z(t))return K(oD);let n=Ye("ls",t,aD);if(!n.ok)return n.error;let r=n.result.flags.showAll,s=n.result.flags.showAlmostAll,i=n.result.flags.longFormat,o=n.result.flags.humanReadable,a=n.result.flags.recursive,l=n.result.flags.reverse,c=n.result.flags.classifyFiles,u=n.result.flags.directoryOnly,f=cD(t,n.result.flags.sortBySize,n.result.flags.sortByTime);n.result.flags.onePerLine;let d=n.result.positional;d.length===0&&d.push(".");let h="",p="",m=0,g=new xn({limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:"ls"});if(u){for(let S of await V1(d,e,f,l,g)){g.visit(0);let E=e.fs.resolvePath(e.cwd,S);try{let A=await e.fs.stat(E);if(i){let N=A.isDirectory?"drwxr-xr-x":"-rw-r--r--",I=c?Tc(await e.fs.lstat(E)):"",T=A.size??0,$=o?H1(T).padStart(5):String(T).padStart(5),C=A.mtime??new Date(0),O=G1(C);h=sr(e,h,`${N} 1 user user ${$} ${O} ${S}${I}
|
|
69
69
|
`)}else{let N=c?Tc(await e.fs.lstat(E)):"";h=sr(e,h,`${S}${N}
|
|
70
70
|
`)}}catch{p=sr(e,p,`ls: cannot access '${S}': No such file or directory
|
|
@@ -113,7 +113,7 @@ Options:
|
|
|
113
113
|
`,h=1;continue}}if(s)try{await e.fs.stat(b);continue}catch{}let x=await Hf(e.fs,y,b);if(x==="same"){d+=`cp: '${g}' and '${b}' are the same file
|
|
114
114
|
`,h=1;continue}if(x==="unknown"){d+=`cp: cannot safely determine whether '${g}' and '${b}' are the same file
|
|
115
115
|
`,h=1;continue}w.isDirectory&&await ii({fs:e.fs,root:y,limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:"cp",symlinks:"never",budget:p},()=>{}),await e.fs.cp(y,b,{recursive:r}),o&&(f+=`'${g}' -> '${b}'
|
|
116
|
-
`)}catch(y){if(y instanceof v||y instanceof
|
|
116
|
+
`)}catch(y){if(y instanceof v||y instanceof et)throw y;let w=Qe(y);st(y,"ENOENT")?d+=`cp: cannot stat '${g}': No such file or directory
|
|
117
117
|
`:st(y,"EROFS")?d+=`cp: cannot create regular file '${l}': Read-only file system
|
|
118
118
|
`:d+=`cp: cannot copy '${g}': ${w}
|
|
119
119
|
`,h=1}return{stdout:f,stderr:d,exitCode:h}}},cg={name:"cp",flags:[{flag:"-r",type:"boolean"},{flag:"-R",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-p",type:"boolean"},{flag:"-v",type:"boolean"}],needsArgs:!0,minArgs:2}});var D4={};he(D4,{flagsForFuzzing:()=>fg,mvCommand:()=>WD});var zD,UD,WD,fg,dg=L(()=>{"use strict";us();Kr();X();Un();on();xe();bn();zD={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"]},UD={force:{short:"f",long:"force",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},WD={name:"mv",async execute(t,e){if(Z(t))return K(zD);let n=Ye("mv",t,UD);if(!n.ok)return n.error;let r=n.result.flags.force,s=n.result.flags.noClobber,i=n.result.flags.verbose,o=n.result.positional;if(s&&(r=!1),o.length<2)return{stdout:"",stderr:`mv: missing destination file operand
|
|
@@ -122,7 +122,7 @@ Options:
|
|
|
122
122
|
`,d=1;continue}if(x==="unknown"){f+=`mv: cannot safely determine whether '${w}' is inside '${m}'
|
|
123
123
|
`,d=1;continue}}if(s)try{await e.fs.stat(w);continue}catch{}let b=await Hf(e.fs,g,w);if(b==="same")continue;if(b==="unknown"){f+=`mv: cannot safely determine whether '${m}' and '${w}' are the same file
|
|
124
124
|
`,d=1;continue}if(y.isDirectory&&await ii({fs:e.fs,root:g,limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:"mv",symlinks:"never",budget:h},()=>{}),await e.fs.mv(g,w),i){let x=p?`${a}/${m.split("/").pop()||m}`:a;u+=`renamed '${m}' -> '${x}'
|
|
125
|
-
`}}catch(g){if(g instanceof v||g instanceof
|
|
125
|
+
`}}catch(g){if(g instanceof v||g instanceof et)throw g;let y=Qe(g);st(g,"ENOENT")?f+=`mv: cannot stat '${m}': No such file or directory
|
|
126
126
|
`:st(g,"EROFS")?f+=`mv: cannot move '${m}' to '${a}': Read-only file system
|
|
127
127
|
`:f+=`mv: cannot move '${m}': ${y}
|
|
128
128
|
`,d=1}return{stdout:u,stderr:f,exitCode:d}}},fg={name:"mv",flags:[{flag:"-f",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-v",type:"boolean"}],needsArgs:!0,minArgs:2}});var _4={};he(_4,{flagsForFuzzing:()=>hg,lnCommand:()=>qD});var jD,qD,hg,pg=L(()=>{"use strict";Tn();xe();bn();jD={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"]},qD={name:"ln",async execute(t,e){if(Z(t))return K(jD);let n=!1,r=!1,s=!1,i=0;for(;i<t.length&&t[i].startsWith("-");){let f=t[i];if(f==="-s"||f==="--symbolic")n=!0,i++;else if(f==="-f"||f==="--force")r=!0,i++;else if(f==="-v"||f==="--verbose")s=!0,i++;else if(f==="-n"||f==="--no-dereference")i++;else if(/^-[sfvn]+$/.test(f))f.includes("s")&&(n=!0),f.includes("f")&&(r=!0),f.includes("v")&&(s=!0),i++;else if(f==="--"){i++;break}else return ae("ln",f)}let o=t.slice(i);if(o.length<2)return{stdout:"",stderr:`ln: missing file operand
|
|
@@ -144,7 +144,7 @@ Options:
|
|
|
144
144
|
`,stderr:"",exitCode:0}}},wg={name:"pwd",flags:[{flag:"-P",type:"boolean"},{flag:"-L",type:"boolean"}]}});var z4={};he(z4,{flagsForFuzzing:()=>xg,readlinkCommand:()=>XD});var ZD,XD,xg,Eg=L(()=>{"use strict";Kr();X();xe();ZD={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"]},XD={name:"readlink",async execute(t,e){if(Z(t))return K(ZD);let n=!1,r=0;for(;r<t.length&&t[r].startsWith("-");){let l=t[r];if(l==="-f"||l==="--canonicalize")n=!0,r++;else if(l==="--"){r++;break}else return ae("readlink",l)}let s=t.slice(r);if(s.length===0)return{stdout:"",stderr:`readlink: missing operand
|
|
145
145
|
`,exitCode:1};let i="",o=!1,a=new xn({limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:"readlink",label:"symlink traversal"});for(let l of s){let c=e.fs.resolvePath(e.cwd,l);try{if(n){let u=c,f=new Set;for(;a.visit(f.size),!f.has(u);){f.add(u);try{let d=await e.fs.readlink(u);if(d.startsWith("/"))u=d;else{let h=u.substring(0,u.lastIndexOf("/"))||"/";u=e.fs.resolvePath(h,d)}}catch{break}}i+=`${u}
|
|
146
146
|
`}else{let u=await e.fs.readlink(c);i+=`${u}
|
|
147
|
-
`}}catch(u){if(u instanceof v||u instanceof
|
|
147
|
+
`}}catch(u){if(u instanceof v||u instanceof et)throw u;n?i+=`${c}
|
|
148
148
|
`:o=!0}}return{stdout:i,stderr:"",exitCode:o?1:0}}},xg={name:"readlink",flags:[{flag:"-f",type:"boolean"},{flag:"-e",type:"boolean"}],needsArgs:!0}});function Kf(t,e){let n=10,r=null,s=!1,i=!1,o=!1,a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c==="-n"&&l+1<t.length){let u=t[++l];e==="tail"&&u.startsWith("+")?(o=!0,n=parseInt(u.slice(1),10)):n=parseInt(u,10)}else if(e==="tail"&&c.startsWith("-n+"))o=!0,n=parseInt(c.slice(3),10);else if(c.startsWith("-n"))n=parseInt(c.slice(2),10);else if(c==="-c"&&l+1<t.length)r=parseInt(t[++l],10);else if(c.startsWith("-c"))r=parseInt(c.slice(2),10);else if(c.startsWith("--bytes="))r=parseInt(c.slice(8),10);else if(c.startsWith("--lines="))n=parseInt(c.slice(8),10);else if(c==="-q"||c==="--quiet"||c==="--silent")s=!0;else if(c==="-v"||c==="--verbose")i=!0;else if(c.match(/^-\d+$/))n=parseInt(c.slice(1),10);else{if(c.startsWith("--"))return{ok:!1,error:ae(e,c)};if(c.startsWith("-")&&c!=="-")return{ok:!1,error:ae(e,c)};a.push(c)}}return r!==null&&(Number.isNaN(r)||r<0)?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of bytes
|
|
149
149
|
`,exitCode:1}}:Number.isNaN(n)||n<0?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of lines
|
|
150
150
|
`,exitCode:1}}:{ok:!0,options:{lines:n,bytes:r,quiet:s,verbose:i,files:a,fromLine:o}}}async function Zf(t,e,n,r){let{quiet:s,verbose:i,files:o}=e;if(o.length>t.limits.maxArrayElements)throw new v(`${n}: file operand limit exceeded (${t.limits.maxArrayElements})`,"array_elements");if(o.length===0)return{stdout:r(t.stdin),stderr:"",exitCode:0,stdoutEncoding:"binary"};let a=Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),l=new $e(a,n),c=new $e(a,n),u=0,f=0,d=i||!s&&o.length>1,h=0;for(let p=0;p<o.length;p++){let m=o[p];try{let g=t.fs.resolvePath(t.cwd,m);if((await t.fs.stat(g)).size>t.limits.maxInputBytes-f)throw new v(`${n}: aggregate input size limit exceeded (${t.limits.maxInputBytes} bytes)`,"string_length");let w=await zn(t.fs,g);if(w.length>t.limits.maxInputBytes-f)throw new v(`${n}: aggregate input size limit exceeded (${t.limits.maxInputBytes} bytes)`,"string_length");f+=w.length,t.executionScope?.consumeInput(w.length,n),d&&(h>0&&l.append(`
|
|
@@ -182,15 +182,15 @@ Modify: ${h.mtime.toISOString()}
|
|
|
182
182
|
`)-1&&e.runes[2]===V.CODES.get(`
|
|
183
183
|
`)+1&&e.runes[3]===ze.MAX_RUNE&&(e.runes=[],e.op=G.Op.ANY_CHAR_NOT_NL))}collapse(e,n){if(e.length===1)return e[0];let r=0;for(let a of e)r+=a.op===n?a.subs.length:1;let s=new Array(r).fill(null),i=0;for(let a of e)a.op===n?(s.splice(i,a.subs.length,...a.subs),i+=a.subs.length,this.reuse(a)):s[i++]=a;let o=this.newRegexp(n);if(o.subs=s,n===G.Op.ALTERNATE&&(o.subs=this.factor(o.subs),o.subs.length===1)){let a=o;o=o.subs[0],this.reuse(a)}return o}factor(e){if(e.length<2)return e;let n=0,r=e.length,s=0,i=null,o=0,a=0,l=0;for(let u=0;u<=r;u++){let f=null,d=0,h=0;if(u<r){let p=e[n+u];if(p.op===G.Op.CONCAT&&p.subs.length>0&&(p=p.subs[0]),p.op===G.Op.LITERAL&&(f=p.runes,d=p.runes.length,h=p.flags&me.FOLD_CASE),h===a){let m=0;for(;m<o&&m<d&&i[m]===f[m];)m++;if(m>0){o=m;continue}}}if(u!==l)if(u===l+1)e[s++]=e[n+l];else{let p=this.newRegexp(G.Op.LITERAL);p.flags=a,p.runes=i.slice(0,o);for(let y=l;y<u;y++)e[n+y]=this.removeLeadingString(e[n+y],o),this.checkLimits(e[n+y]);let m=this.collapse(e.slice(n+l,n+u),G.Op.ALTERNATE),g=this.newRegexp(G.Op.CONCAT);g.subs=[p,m],e[s++]=g}l=u,i=f,o=d,a=h}r=s,n=0,l=0,s=0;let c=null;for(let u=0;u<=r;u++){let f=null;if(!(u<r&&(f=t.leadingRegexp(e[n+u]),c!==null&&c.equals(f)&&(t.isCharClass(c)||c.op===G.Op.REPEAT&&c.min===c.max&&t.isCharClass(c.subs[0]))))){if(u!==l)if(u===l+1)e[s++]=e[n+l];else{let d=c;for(let m=l;m<u;m++){let g=m!==l;e[n+m]=this.removeLeadingRegexp(e[n+m],g),this.checkLimits(e[n+m])}let h=this.collapse(e.slice(n+l,n+u),G.Op.ALTERNATE),p=this.newRegexp(G.Op.CONCAT);p.subs=[d,h],e[s++]=p}l=u,c=f}}r=s,n=0,l=0,s=0;for(let u=0;u<=r;u++)if(!(u<r&&t.isCharClass(e[n+u]))){if(u!==l)if(u===l+1)e[s++]=e[n+l];else{let f=l;for(let h=l+1;h<u;h++){let p=e[n+f],m=e[n+h];(p.op<m.op||p.op===m.op&&(p.runes!==null?p.runes.length:0)<(m.runes!==null?m.runes.length:0))&&(f=h)}let d=e[n+l];e[n+l]=e[n+f],e[n+f]=d;for(let h=l+1;h<u;h++)t.mergeCharClass(e[n+l],e[n+h]),this.reuse(e[n+h]);this.cleanAlt(e[n+l]),e[s++]=e[n+l]}u<r&&(e[s++]=e[n+u]),l=u+1}r=s,n=0,l=0,s=0;for(let u=0;u<r;++u)u+1<r&&e[n+u].op===G.Op.EMPTY_MATCH&&e[n+u+1].op===G.Op.EMPTY_MATCH||(e[s++]=e[n+u]);return r=s,n=0,e.slice(n,r)}removeLeadingString(e,n){if(e.op===G.Op.CONCAT&&e.subs.length>0){let r=this.removeLeadingString(e.subs[0],n);if(e.subs[0]=r,r.op===G.Op.EMPTY_MATCH)switch(this.reuse(r),e.subs.length){case 0:case 1:e.op=G.Op.EMPTY_MATCH,e.subs=null;break;case 2:{let s=e;e=e.subs[1],this.reuse(s);break}default:e.subs=e.subs.slice(1,e.subs.length);break}return e}return e.op===G.Op.LITERAL&&(e.runes=e.runes.slice(n,e.runes.length),e.runes.length===0&&(e.op=G.Op.EMPTY_MATCH)),e}removeLeadingRegexp(e,n){if(e.op===G.Op.CONCAT&&e.subs.length>0){switch(n&&this.reuse(e.subs[0]),e.subs=e.subs.slice(1,e.subs.length),e.subs.length){case 0:{e.op=G.Op.EMPTY_MATCH,e.subs=G.emptySubs();break}case 1:{let r=e;e=e.subs[0],this.reuse(r);break}}return e}return n&&this.reuse(e),this.newRegexp(G.Op.EMPTY_MATCH)}parseInternal(){if((this.flags&me.LITERAL)!==0)return t.literalRegexp(this.wholeRegexp,this.flags);let e=-1,n=-1,r=-1,s=new qg(this.wholeRegexp);for(;s.more();){let o=-1;e:switch(s.peek()){case V.CODES.get("("):if((this.flags&me.PERL_X)!==0&&s.lookingAt("(?")){this.parsePerlFlags(s);break}this.op(G.Op.LEFT_PAREN).cap=++this.numCap,s.skip(1);break;case V.CODES.get("|"):this.parseVerticalBar(),s.skip(1);break;case V.CODES.get(")"):this.parseRightParen(),s.skip(1);break;case V.CODES.get("^"):(this.flags&me.ONE_LINE)!==0?this.op(G.Op.BEGIN_TEXT):this.op(G.Op.BEGIN_LINE),s.skip(1);break;case V.CODES.get("$"):(this.flags&me.ONE_LINE)!==0?this.op(G.Op.END_TEXT).flags|=me.WAS_DOLLAR:this.op(G.Op.END_LINE),s.skip(1);break;case V.CODES.get("."):(this.flags&me.DOT_NL)!==0?this.op(G.Op.ANY_CHAR):this.op(G.Op.ANY_CHAR_NOT_NL),s.skip(1);break;case V.CODES.get("["):this.parseClass(s);break;case V.CODES.get("*"):case V.CODES.get("+"):case V.CODES.get("?"):{o=s.pos();let a=null;switch(s.pop()){case V.CODES.get("*"):a=G.Op.STAR;break;case V.CODES.get("+"):a=G.Op.PLUS;break;case V.CODES.get("?"):a=G.Op.QUEST;break}this.repeat(a,n,r,o,s,e);break}case V.CODES.get("{"):{o=s.pos();let a=t.parseRepeat(s);if(a<0){s.rewindTo(o),this.literal(s.pop());break}n=a>>16,r=(a&ze.MAX_BMP)<<16>>16,this.repeat(G.Op.REPEAT,n,r,o,s,e);break}case V.CODES.get("\\"):{let a=s.pos();if(s.skip(1),(this.flags&me.PERL_X)!==0&&s.more())switch(s.pop()){case V.CODES.get("A"):this.op(G.Op.BEGIN_TEXT);break e;case V.CODES.get("b"):this.op(G.Op.WORD_BOUNDARY);break e;case V.CODES.get("B"):this.op(G.Op.NO_WORD_BOUNDARY);break e;case V.CODES.get("C"):throw new Pt(t.ERR_INVALID_ESCAPE,"\\C");case V.CODES.get("Q"):{let f=s.rest(),d=f.indexOf("\\E");d>=0&&(f=f.substring(0,d)),s.skipString(f),s.skipString("\\E");let h=0;for(;h<f.length;){let p=f.codePointAt(h);this.literal(p),h+=lt.charCount(p)}break e}case V.CODES.get("z"):this.op(G.Op.END_TEXT);break e;default:s.rewindTo(a);break}let l=this.newRegexp(G.Op.CHAR_CLASS);if(l.flags=this.flags,s.lookingAt("\\p")||s.lookingAt("\\P")){let u=new oi;if(this.parseUnicodeClass(s,u)){l.runes=u.toArray(),this.push(l);break e}}let c=new oi;if(this.parsePerlClassEscape(s,c)){l.runes=c.toArray(),this.push(l);break e}s.rewindTo(a),this.reuse(l),this.literal(t.parseEscape(s));break}default:this.literal(s.pop());break}e=o}if(this.concat(),this.swapVerticalBar()&&this.pop(),this.alternate(),this.stack.length!==1)throw new Pt(t.ERR_MISSING_PAREN,this.wholeRegexp);return this.stack[0].namedGroups=this.namedGroups,this.stack[0]}parsePerlFlags(e){let n=e.pos(),r=e.rest();if(r.startsWith("(?P<")||r.startsWith("(?<")){let a=r.charAt(2)==="P"?4:3,l=r.indexOf(">");if(l<0)throw new Pt(t.ERR_INVALID_NAMED_CAPTURE,r);let c=r.substring(a,l);if(e.skipString(c),e.skip(a+1),!t.isValidCaptureName(c))throw new Pt(t.ERR_INVALID_NAMED_CAPTURE,r.substring(0,l+1));let u=this.op(G.Op.LEFT_PAREN);if(u.cap=++this.numCap,this.namedGroups[c])throw new Pt(t.ERR_DUPLICATE_NAMED_CAPTURE,c);this.namedGroups[c]=this.numCap,u.name=c;return}e.skip(2);let s=this.flags,i=1,o=!1;e:for(;e.more();){let a=e.pop();switch(a){case V.CODES.get("i"):s|=me.FOLD_CASE,o=!0;break;case V.CODES.get("m"):s&=-17,o=!0;break;case V.CODES.get("s"):s|=me.DOT_NL,o=!0;break;case V.CODES.get("U"):s|=me.NON_GREEDY,o=!0;break;case V.CODES.get("-"):if(i<0)break e;i=-1,s=~s,o=!1;break;case V.CODES.get(":"):case V.CODES.get(")"):if(i<0){if(!o)break e;s=~s}a===V.CODES.get(":")&&this.op(G.Op.LEFT_PAREN),this.flags=s;return;default:break e}}throw new Pt(t.ERR_INVALID_PERL_OP,e.from(n))}parseVerticalBar(){this.concat(),this.swapVerticalBar()||this.op(G.Op.VERTICAL_BAR)}swapVerticalBar(){let e=this.stack.length;if(e>=3&&this.stack[e-2].op===G.Op.VERTICAL_BAR&&t.isCharClass(this.stack[e-1])&&t.isCharClass(this.stack[e-3])){let n=this.stack[e-1],r=this.stack[e-3];if(n.op>r.op){let s=r;r=n,n=s,this.stack[e-3]=r}return t.mergeCharClass(r,n),this.reuse(n),this.pop(),!0}if(e>=2){let n=this.stack[e-1],r=this.stack[e-2];if(r.op===G.Op.VERTICAL_BAR)return e>=3&&this.cleanAlt(this.stack[e-3]),this.stack[e-2]=n,this.stack[e-1]=r,!0}return!1}parseRightParen(){if(this.concat(),this.swapVerticalBar()&&this.pop(),this.alternate(),this.stack.length<2)throw new Pt(t.ERR_UNEXPECTED_PAREN,this.wholeRegexp);let n=this.pop(),r=this.pop();if(r.op!==G.Op.LEFT_PAREN)throw new Pt(t.ERR_UNEXPECTED_PAREN,this.wholeRegexp);this.flags=r.flags,r.cap===0?this.push(n):(r.op=G.Op.CAPTURE,r.subs=[n],this.push(r))}parsePerlClassEscape(e,n){let r=e.pos();if((this.flags&me.PERL_X)===0||!e.more()||e.pop()!==V.CODES.get("\\")||!e.more())return!1;e.pop();let s=e.from(r),i=Y4.has(s)?Y4.get(s):null;return i===null?!1:(n.appendGroup(i,(this.flags&me.FOLD_CASE)!==0),!0)}parseNamedClass(e,n){let r=e.rest(),s=r.indexOf(":]");if(s<0)return!1;let i=r.substring(0,s+2);e.skipString(i);let o=d3.has(i)?d3.get(i):null;if(o===null)throw new Pt(t.ERR_INVALID_CHAR_RANGE,i);return n.appendGroup(o,(this.flags&me.FOLD_CASE)!==0),!0}parseUnicodeClass(e,n){let r=e.pos();if((this.flags&me.UNICODE_GROUPS)===0||!e.lookingAt("\\p")&&!e.lookingAt("\\P"))return!1;e.skip(1);let s=1,i=e.pop();if(i===V.CODES.get("P")&&(s=-1),!e.more())throw e.rewindTo(r),new Pt(t.ERR_INVALID_CHAR_RANGE,e.rest());i=e.pop();let o;if(i!==V.CODES.get("{"))o=lt.runeToString(i);else{let u=e.rest(),f=u.indexOf("}");if(f<0)throw e.rewindTo(r),new Pt(t.ERR_INVALID_CHAR_RANGE,e.rest());o=u.substring(0,f),e.skipString(o),e.skip(1)}o.length!==0&&o.codePointAt(0)===V.CODES.get("^")&&(s=0-s,o=o.substring(1));let a=t.unicodeTable(o);if(a===null)throw new Pt(t.ERR_INVALID_CHAR_RANGE,e.from(r));let l=a.first,c=a.second;if((this.flags&me.FOLD_CASE)===0||c===null)n.appendTableWithSign(l,s);else{let u=new oi().appendTable(l).appendTable(c).cleanClass().toArray();n.appendClassWithSign(u,s)}return!0}parseClass(e){let n=e.pos();e.skip(1);let r=this.newRegexp(G.Op.CHAR_CLASS);r.flags=this.flags;let s=new oi,i=1;e.more()&&e.lookingAt("^")&&(i=-1,e.skip(1),(this.flags&me.CLASS_NL)===0&&s.appendRange(V.CODES.get(`
|
|
184
184
|
`),V.CODES.get(`
|
|
185
|
-
`)));let o=!0;for(;!e.more()||e.peek()!==V.CODES.get("]")||o;){if(e.more()&&e.lookingAt("-")&&(this.flags&me.PERL_X)===0&&!o){let u=e.rest();if(u==="-"||!u.startsWith("-]"))throw e.rewindTo(n),new Pt(t.ERR_INVALID_CHAR_RANGE,e.rest())}o=!1;let a=e.pos();if(e.lookingAt("[:")){if(this.parseNamedClass(e,s))continue;e.rewindTo(a)}if(this.parseUnicodeClass(e,s)||this.parsePerlClassEscape(e,s))continue;e.rewindTo(a);let l=t.parseClassChar(e,n),c=l;if(e.more()&&e.lookingAt("-")){if(e.skip(1),e.more()&&e.lookingAt("]"))e.skip(-1);else if(c=t.parseClassChar(e,n),c<l)throw new Pt(t.ERR_INVALID_CHAR_RANGE,e.from(a))}(this.flags&me.FOLD_CASE)===0?s.appendRange(l,c):s.appendFoldedRange(l,c)}e.skip(1),s.cleanClass(),i<0&&s.negateClass(),r.runes=s.toArray(),this.push(r)}},Hg=class{constructor(e){this.value=e}get(){return this.value}set(e){this.value=e}compareAndSet(e,n){return this.value===e?(this.value=n,!0):!1}},Gg=class t{static initTest(e){let n=t.compile(e),r=new t(n.expr,n.prog,n.numSubexp,n.longest);return r.cond=n.cond,r.prefix=n.prefix,r.prefixUTF8=n.prefixUTF8,r.prefixComplete=n.prefixComplete,r.prefixRune=n.prefixRune,r}static compile(e){return t.compileImpl(e,me.PERL,!1)}static compilePOSIX(e){return t.compileImpl(e,me.POSIX,!0)}static compileImpl(e,n,r){let s=Vg.parse(e,n),i=s.maxCap();s=jg.simplify(s);let o=Wg.compileRegexp(s),a=new t(e,o,i,r),[l,c]=o.prefix();return a.prefixComplete=l,a.prefix=c,a.prefixUTF8=lt.stringToUtf8ByteArray(a.prefix),a.prefix.length>0&&(a.prefixRune=a.prefix.codePointAt(0)),a.namedGroups=s.namedGroups,a}static match(e,n){return t.compile(e).match(n)}constructor(e,n,r=0,s=0){this.expr=e,this.prog=n,this.numSubexp=r,this.longest=s,this.cond=n.startCond(),this.prefix=null,this.prefixUTF8=null,this.prefixComplete=!1,this.prefixRune=0,this.pooled=new Hg,this.dfa=new zg(n)}executeEngine(e,n,r,s){if(s>0)return this.doExecuteNFA(e,n,r,s);let i=this.dfa.match(e,n,r);return i!==null?i?[]:null:this.doExecuteNFA(e,n,r,s)}numberOfCapturingGroups(){return this.numSubexp}numberOfInstructions(){return this.prog.numInst()}get(){let e;do e=this.pooled.get();while(e&&!this.pooled.compareAndSet(e,e.next));return e}reset(){this.pooled.set(null)}put(e,n){let r=this.pooled.get();do r=this.pooled.get(),!n&&r&&(e=Ic.fromMachine(e),n=!0),e.next!==r&&(e.next=r);while(!this.pooled.compareAndSet(r,e))}toString(){return this.expr}doExecuteNFA(e,n,r,s){let i=this.get(),o=!1;i?i.next!==null&&(i=Ic.fromMachine(i),o=!0):(i=Ic.fromRE2(this),o=!0),i.init(s);let a=i.match(e,n,r)?i.submatches():null;return this.put(i,o),a}match(e){return this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,0)!==null}matchWithGroup(e,n,r,s,i){return e instanceof oo||(e=sl.utf16(e)),this.matchMachineInput(e,n,r,s,i)}matchMachineInput(e,n,r,s,i){if(n>r)return[!1,null];let o=e.isUTF16Encoding()?qt.fromUTF16(e.asCharSequence(),0,r):qt.fromUTF8(e.asBytes(),0,r),a=this.executeEngine(o,n,s,2*i);return a===null?[!1,null]:[!0,a]}matchUTF8(e){return this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,0)!==null}replaceAll(e,n){return this.replaceAllFunc(e,()=>n,2*e.length+1)}replaceFirst(e,n){return this.replaceAllFunc(e,()=>n,1)}replaceAllFunc(e,n,r){let s=0,i=0,o="",a=qt.fromUTF16(e),l=0;for(;i<=e.length;){let c=this.executeEngine(a,i,me.UNANCHORED,2);if(c===null||c.length===0)break;o+=e.substring(s,c[0]),(c[1]>s||c[0]===0)&&(o+=n(e.substring(c[0],c[1])),l++),s=c[1];let u=a.step(i)&7;if(i+u>c[1]?i+=u:i+1>c[1]?i++:i=c[1],l>=r)break}return o+=e.substring(s),o}pad(e){if(e===null)return null;let n=(1+this.numSubexp)*2;if(e.length<n){let r=new Array(n).fill(-1);for(let s=0;s<e.length;s++)r[s]=e[s];e=r}return e}allMatches(e,n,r=s=>s){let s=[],i=e.endPos();n<0&&(n=i+1);let o=0,a=0,l=-1;for(;a<n&&o<=i;){let c=this.executeEngine(e,o,me.UNANCHORED,this.prog.numCap);if(c===null||c.length===0)break;let u=!0;if(c[1]===o){c[0]===l&&(u=!1);let f=e.step(o);f<0?o=i+1:o+=f&7}else o=c[1];l=c[1],u&&(s.push(r(this.pad(c))),a++)}return s}findUTF8(e){let n=this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,2);return n===null?null:e.slice(n[0],n[1])}findUTF8Index(e){let n=this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,2);return n===null?null:n.slice(0,2)}find(e){let n=this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,2);return n===null?"":e.substring(n[0],n[1])}findIndex(e){return this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,2)}findUTF8Submatch(e){let n=this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,this.prog.numCap);if(n===null)return null;let r=new Array(1+this.numSubexp).fill(null);for(let s=0;s<r.length;s++)2*s<n.length&&n[2*s]>=0&&(r[s]=e.slice(n[2*s],n[2*s+1]));return r}findUTF8SubmatchIndex(e){return this.pad(this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,this.prog.numCap))}findSubmatch(e){let n=this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,this.prog.numCap);if(n===null)return null;let r=new Array(1+this.numSubexp).fill(null);for(let s=0;s<r.length;s++)2*s<n.length&&n[2*s]>=0&&(r[s]=e.substring(n[2*s],n[2*s+1]));return r}findSubmatchIndex(e){return this.pad(this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,this.prog.numCap))}findAllUTF8(e,n){let r=this.allMatches(qt.fromUTF8(e),n,s=>e.slice(s[0],s[1]));return r.length===0?null:r}findAllUTF8Index(e,n){let r=this.allMatches(qt.fromUTF8(e),n,s=>s.slice(0,2));return r.length===0?null:r}findAll(e,n){let r=this.allMatches(qt.fromUTF16(e),n,s=>e.substring(s[0],s[1]));return r.length===0?null:r}findAllIndex(e,n){let r=this.allMatches(qt.fromUTF16(e),n,s=>s.slice(0,2));return r.length===0?null:r}findAllUTF8Submatch(e,n){let r=this.allMatches(qt.fromUTF8(e),n,s=>{let i=new Array(s.length/2|0).fill(null);for(let o=0;o<i.length;o++)s[2*o]>=0&&(i[o]=e.slice(s[2*o],s[2*o+1]));return i});return r.length===0?null:r}findAllUTF8SubmatchIndex(e,n){let r=this.allMatches(qt.fromUTF8(e),n);return r.length===0?null:r}findAllSubmatch(e,n){let r=this.allMatches(qt.fromUTF16(e),n,s=>{let i=new Array(s.length/2|0).fill(null);for(let o=0;o<i.length;o++)s[2*o]>=0&&(i[o]=e.substring(s[2*o],s[2*o+1]));return i});return r.length===0?null:r}findAllSubmatchIndex(e,n){let r=this.allMatches(qt.fromUTF16(e),n);return r.length===0?null:r}},Kg=class t{static isUpperCaseAlpha(e){return"A"<=e&&e<="Z"}static isHexadecimal(e){return"0"<=e&&e<="9"||"A"<=e&&e<="F"||"a"<=e&&e<="f"}static getUtf8CharSize(e){let n=e.charCodeAt(0);return n<128?1:n<2048?2:n<65536?3:4}static translate(e){if(typeof e!="string")return e;let n="",r=!1,s=e.length;s===0&&(n="(?:)",r=!0);let i=0;for(;i<s;){let o=e[i];if(o==="\\"){if(i+1<s)switch(o=e[i+1],o){case"\\":{n+="\\\\",i+=2;continue}case"c":{if(i+2<s){let l=e[i+2];if(t.isUpperCaseAlpha(l)){n+="\\x",n+=(l.charCodeAt(0)-64>>4).toString(16).toUpperCase(),n+=(l.charCodeAt(0)-64&15).toString(16).toUpperCase(),i+=3,r=!0;continue}}n+="\\c",i+=2;continue}case"u":{if(i+2<s){let l=e[i+2];if(t.isHexadecimal(l)){n+="\\x{"+l,i+=3;for(let c=0;c<3&&i<s&&(l=e[i],!!t.isHexadecimal(l));++i,++c)n+=l;n+="}",r=!0;continue}else if(l==="{"){n+="\\x",i+=2,r=!0;continue}}n+="\\u",i+=2;continue}default:{n+="\\";let l=t.getUtf8CharSize(o);n+=e.substring(i+1,i+1+l),i+=l+1;continue}}}else if(o==="/"){n+="\\/",i+=1,r=!0;continue}else if(o==="("&&i+2<s&&e[i+1]==="?"&&e[i+2]==="<"&&(i+3>=s||e[i+3]!=="="&&e[i+3]!=="!")){n+="(?P<",i+=3,r=!0;continue}let a=t.getUtf8CharSize(o);n+=e.substring(i,i+a),i+=a}return r?n:e}},$i=class t{static CASE_INSENSITIVE=1;static DOTALL=2;static MULTILINE=4;static DISABLE_UNICODE_GROUPS=8;static LONGEST_MATCH=16;static quote(e){return lt.quoteMeta(e)}static translateRegExp(e){return Kg.translate(e)}static compile(e,n=0){let r=e;if((n&t.CASE_INSENSITIVE)!==0&&(r=`(?i)${r}`),(n&t.DOTALL)!==0&&(r=`(?s)${r}`),(n&t.MULTILINE)!==0&&(r=`(?m)${r}`),(n&~(t.MULTILINE|t.DOTALL|t.CASE_INSENSITIVE|t.DISABLE_UNICODE_GROUPS|t.LONGEST_MATCH))!==0)throw new Dg("Flags should only be a combination of MULTILINE, DOTALL, CASE_INSENSITIVE, DISABLE_UNICODE_GROUPS, LONGEST_MATCH");let s=me.PERL;(n&t.DISABLE_UNICODE_GROUPS)!==0&&(s&=-129);let i=new t(e,n);return i.re2Input=Gg.compileImpl(r,s,(n&t.LONGEST_MATCH)!==0),i}static matches(e,n){return t.compile(e).testExact(n)}static initTest(e,n,r){if(e==null)throw new Error("pattern is null");if(r==null)throw new Error("re2 is null");let s=new t(e,n);return s.re2Input=r,s}constructor(e,n){this.patternInput=e,this.flagsInput=n}reset(){this.re2Input.reset()}flags(){return this.flagsInput}pattern(){return this.patternInput}re2(){return this.re2Input}matches(e){return this.testExact(e)}matcher(e){return Array.isArray(e)&&(e=sl.utf8(e)),new _g(this,e)}test(e){return Array.isArray(e)?this.re2Input.matchUTF8(e):this.re2Input.match(e)}testExact(e){let n=Array.isArray(e)?qt.fromUTF8(e):qt.fromUTF16(e);return this.re2Input.executeEngine(n,0,me.ANCHOR_BOTH,0)!==null}split(e,n=0){let r=this.matcher(e),s=[],i=0,o=0;for(;r.find();){if(o===0&&r.end()===0){o=r.end();continue}if(n>0&&s.length===n-1)break;if(o===r.start()){if(n===0){i+=1,o=r.end();continue}}else for(;i>0;)s.push(""),i-=1;s.push(r.substring(o,r.start())),o=r.end()}if(n===0&&o!==r.inputLength()){for(;i>0;)s.push(""),i-=1;s.push(r.substring(o,r.inputLength()))}return(n!==0||s.length===0)&&s.push(r.substring(o,r.inputLength())),s}toString(){return this.patternInput}programSize(){return this.re2Input.numberOfInstructions()}groupCount(){return this.re2Input.numberOfCapturingGroups()}namedGroups(){return this.re2Input.namedGroups}equals(e){return this===e?!0:e===null||this.constructor!==e.constructor?!1:this.flagsInput===e.flagsInput&&this.patternInput===e.patternInput}}});function f_(t){let e=0;return t.includes("i")&&(e|=$i.CASE_INSENSITIVE),t.includes("m")&&(e|=$i.MULTILINE),t.includes("s")&&(e|=$i.DOTALL),e}function m3(t){return $i.translateRegExp(t)}function p_(t,e){let n=f_(e);if(t.length>h_)return $i.compile(m3(t),n);let r=`${n} ${t}`,s=Pc.get(r);if(s!==void 0)return s;let i=$i.compile(m3(t),n);if(Pc.size>=d_){let o=Pc.keys().next().value;o!==void 0&&Pc.delete(o)}return Pc.set(r,i),i}function le(t,e="",n={}){return new Jf(t,e,n)}var c_,u_,d_,h_,Pc,Jf,Li,g3=L(()=>{"use strict";p3();Nt();X();c_=1e6,u_=64*1024*1024;d_=256,h_=1024,Pc=new Map;Jf=class{_re2;_pattern;_flags;_global;_ignoreCase;_multiline;_lastIndex=0;_nativeRegex=null;_matcher=null;_matcherInput=null;maxResults;maxOutputBytes;signal;assertResultCount(e){if(this.signal?.aborted)throw new Error("regular expression aborted");if(e>this.maxResults)throw new v(`regular expression result limit exceeded (${this.maxResults})`,"array_elements")}expandReplacement(e,n){let r=new $e(this.maxOutputBytes,"regular expression replacement"),s=this._re2.groupCount(),i=this._re2.namedGroups();for(let o=0;o<n.length;o++){let a=n[o];if(a==="\\"&&o+1<n.length){r.append(n[++o]);continue}if(a!=="$"||o+1>=n.length){r.append(a);continue}if(n[o+1]==="{"){let l=n.indexOf("}",o+2);if(l!==-1){let c=n.slice(o+2,l),u=i?.[c];if(u!==void 0){r.append(e.group(u)??""),o=l;continue}}}if(/\d/.test(n[o+1])){let l=o+1,c=0;for(;l<n.length&&/\d/.test(n[l]);){let u=c*10+Number(n[l]);if(u>s)break;c=u,l++}r.append(e.group(c)??""),o=l-1;continue}r.append(a)}return r.build()}acquireMatcher(e){return this._matcher===null?(this._matcher=this._re2.matcher(e),this._matcherInput=e,this._matcher):(this._matcherInput!==e&&(this._matcher.matcherInput.charSequence=e,this._matcherInput=e),this._matcher.reset(),this._matcher)}constructor(e,n="",r={}){if(this._pattern=e,this._flags=n,this._global=n.includes("g"),this._ignoreCase=n.includes("i"),this._multiline=n.includes("m"),this.maxResults=r.maxResults??c_,this.maxOutputBytes=r.maxOutputBytes??u_,this.signal=r.signal,!Number.isSafeInteger(this.maxResults)||this.maxResults<0||!Number.isSafeInteger(this.maxOutputBytes)||this.maxOutputBytes<0)throw new Error("invalid regular expression limits");try{this._re2=p_(e,n)}catch(s){if(s instanceof Pt){let i=s.message||"",o="";throw i.includes("(?=")||i.includes("(?!")||i.includes("(?<")||i.includes("(?<!")||e.includes("(?=")||e.includes("(?!")||e.includes("(?<=")||e.includes("(?<!")?o=" Lookahead (?=, ?!) and lookbehind (?<=, ?<!) assertions are not supported in this environment because the regex engine uses RE2 for ReDoS protection. RE2 guarantees linear-time matching but cannot support these features.":(i.includes("backreference")||/\\[1-9]/.test(e))&&(o=" Backreferences (\\1, \\2, etc.) are not supported in this environment because the regex engine uses RE2 for ReDoS protection. RE2 guarantees linear-time matching but cannot support backreferences."),new SyntaxError(`Invalid regular expression: /${e}/: ${i}${o}`)}throw s}}test(e){return this._global&&(this._lastIndex=0),this.acquireMatcher(e).find()}exec(e){let n=this.acquireMatcher(e),r=this._global?this._lastIndex:0;if(!n.find(r))return this._global&&(this._lastIndex=0),null;let s=this._re2.groupCount(),i=[];i.push(n.group(0)??"");for(let l=1;l<=s;l++){let c=n.group(l);i.push(c)}let o=i;o.index=n.start(0),o.input=e;let a=this._re2.namedGroups();if(a&&Object.keys(a).length>0){let l=Object.create(null);for(let[c,u]of Object.entries(a)){let f=n.group(u);f!==null&&(l[c]=f)}o.groups=l}return this._global&&(this._lastIndex=n.end(0),n.start(0)===n.end(0)&&this._lastIndex++),o}match(e){if(this._global&&(this._lastIndex=0),!this._global)return this.exec(e);let n=[],r=this.acquireMatcher(e),s=0;for(;r.find(s);){let i=r.group(0)??"";if(this.assertResultCount(n.length+1),n.push(i),s=r.end(0),r.start(0)===r.end(0)&&s++,s>e.length)break}return n.length>0?n:null}replace(e,n){if(this._global&&(this._lastIndex=0),typeof n=="string"){let u=this._re2.matcher(e),f=new $e(this.maxOutputBytes,"regular expression replacement"),d=0,h=0,p=0;for(;u.find(h);){this.assertResultCount(++p);let m=u.start(0),g=u.end(0);if(f.append(e.slice(d,m)),f.append(this.expandReplacement(u,n)),d=g,h=g>m?g:g+1,!this._global||h>e.length)break}return f.append(e.slice(d)),f.build()}let r=new $e(this.maxOutputBytes,"regular expression replacement"),s=this._re2.matcher(e),i=0,o=0,a=0,l=this._re2.groupCount(),c=this._re2.namedGroups();for(;s.find(o);){this.assertResultCount(++a),r.append(e.slice(i,s.start(0)));let u=[],f=s.group(0)??"";for(let p=1;p<=l;p++)u.push(s.group(p));if(u.push(s.start(0)),u.push(e),c&&Object.keys(c).length>0){let p=Object.create(null);for(let[m,g]of Object.entries(c))p[m]=s.group(g)??"";u.push(p)}let d=s.start(0),h=s.end(0);if(r.append(n(f,...u)),i=h,o=i,d===h&&o++,!this._global||o>e.length)break}return r.append(e.slice(i)),r.build()}split(e,n){if(n===0)return[];let r=n===void 0||n<0?this.maxResults:Math.min(n,this.maxResults),s=[],i=this._re2.matcher(e),o=0,a=0;for(;s.length<r&&i.find(a);)this.assertResultCount(s.length+1),s.push(e.slice(o,i.start(0))),o=i.end(0),a=i.end(0)>i.start(0)?i.end(0):i.end(0)+1;return s.length<r&&s.push(e.slice(o)),s}search(e){let n=this.acquireMatcher(e);return n.find()?n.start(0):-1}*matchAll(e){if(!this._global)throw new Error("matchAll requires global flag");this._lastIndex=0;let n=this._re2.matcher(e),r=this._re2.groupCount(),s=this._re2.namedGroups(),i=0,o=0;for(;n.find(i);){this.assertResultCount(++o);let a=[];a.push(n.group(0)??"");for(let c=1;c<=r;c++)a.push(n.group(c));let l=a;if(l.index=n.start(0),l.input=e,s&&Object.keys(s).length>0){let c=Object.create(null);for(let[u,f]of Object.entries(s)){let d=n.group(f);d!==null&&(c[u]=d)}l.groups=c}if(yield l,i=n.end(0),n.start(0)===n.end(0)&&i++,i>e.length)break}}get native(){if(!this._nativeRegex)try{this._nativeRegex=new RegExp(this._pattern,this._flags)}catch{this._nativeRegex=new RegExp("",this._flags),Object.defineProperty(this._nativeRegex,"source",{value:this._pattern,writable:!1})}return this._nativeRegex}get source(){return this._pattern}get flags(){return this._flags}get global(){return this._global}get ignoreCase(){return this._ignoreCase}get multiline(){return this._multiline}get lastIndex(){return this._lastIndex}set lastIndex(e){this._lastIndex=e}};Li=class{_regex;constructor(e){this._regex=e}test(e){return this._regex.global&&(this._regex.lastIndex=0),this._regex.test(e)}exec(e){return this._regex.exec(e)}match(e){return this._regex.global&&(this._regex.lastIndex=0),e.match(this._regex)}replace(e,n){return this._regex.global&&(this._regex.lastIndex=0),e.replace(this._regex,n)}split(e,n){return e.split(this._regex,n)}search(e){return e.search(this._regex)}*matchAll(e){if(!this._regex.global)throw new Error("matchAll requires global flag");this._regex.lastIndex=0;let n=this._regex.exec(e);for(;n!==null;)yield n,n[0].length===0&&this._regex.lastIndex++,n=this._regex.exec(e)}get native(){return this._regex}get source(){return this._regex.source}get flags(){return this._regex.flags}get global(){return this._regex.global}get ignoreCase(){return this._regex.ignoreCase}get multiline(){return this._regex.multiline}get lastIndex(){return this._regex.lastIndex}set lastIndex(e){this._regex.lastIndex=e}}});var $t=L(()=>{"use strict";g3()});function fr(t,e,n){let r=typeof n=="boolean"?{ignoreCase:n}:n??{},s=e;r.stripQuotes&&(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1));let i=r.ignoreCase?`i:${s}`:s,o=$c.get(i);if(!o){if(o=g_(s,r.ignoreCase),$c.size>=m_){let a=$c.keys().next().value;a!==void 0&&$c.delete(a)}$c.set(i,o)}return o.test(t)}function g_(t,e){let n="^";for(let r=0;r<t.length;r++){let s=t[r];if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let i=r+1;for(;i<t.length&&t[i]!=="]";)i++;n+=t.slice(r,i+1),r=i}else s==="."||s==="+"||s==="^"||s==="$"||s==="{"||s==="}"||s==="("||s===")"||s==="|"||s==="\\"?n+=`\\${s}`:n+=s}return n+="$",le(n,e?"i":"")}var m_,$c,Zg=L(()=>{"use strict";$t();m_=2048,$c=new Map});function Lc(t,e){let n=t.ignoreCase?e.toLowerCase():e,r=t.needles;for(let s=0;s<r.length;s++)if(n.indexOf(r[s])!==-1)return!0;return!1}function y3(t,e){return t.replace(/\$(&|\d+|<([^>]+)>)/g,(n,r,s)=>{if(r==="&")return e[0];if(s!==void 0)return e.groups?.[s]??"";let i=parseInt(r,10);return e[i]??""})}function na(t,e,n={}){let{invertMatch:r=!1,showLineNumbers:s=!1,countOnly:i=!1,countMatches:o=!1,filename:a="",onlyMatching:l=!1,beforeContext:c=0,afterContext:u=0,maxCount:f=0,contextSeparator:d="--",showColumn:h=!1,vimgrep:p=!1,showByteOffset:m=!1,replace:g=null,passthru:y=!1,multiline:w=!1,kResetGroup:b,preFilter:x,maxWork:S,maxMatches:E,signal:A}=n;if(w)return y_(t,e,{invertMatch:r,showLineNumbers:s,countOnly:i,countMatches:o,filename:a,onlyMatching:l,beforeContext:c,afterContext:u,maxCount:f,contextSeparator:d,showColumn:h,showByteOffset:m,replace:g,kResetGroup:b,preFilter:x,maxWork:S,maxMatches:E,signal:A});let N=0,I=(M=1)=>{if(A?.aborted)throw new rt;if(N+=M,S!==void 0&&N>S)throw new v(`search: matching work limit exceeded (${S})`,"iterations")},T=(M,Y)=>{if(E!==void 0&&M.length>=E)throw new v(`search: result limit exceeded (${E})`,"array_elements");M.push(Y)},$=1;for(let M=0;M<t.length;M++)if((M&1023)===0&&I(),t.charCodeAt(M)===10&&($++,E!==void 0&&$>E))throw new v(`search: line limit exceeded (${E})`,"array_elements");let C=t.split(`
|
|
185
|
+
`)));let o=!0;for(;!e.more()||e.peek()!==V.CODES.get("]")||o;){if(e.more()&&e.lookingAt("-")&&(this.flags&me.PERL_X)===0&&!o){let u=e.rest();if(u==="-"||!u.startsWith("-]"))throw e.rewindTo(n),new Pt(t.ERR_INVALID_CHAR_RANGE,e.rest())}o=!1;let a=e.pos();if(e.lookingAt("[:")){if(this.parseNamedClass(e,s))continue;e.rewindTo(a)}if(this.parseUnicodeClass(e,s)||this.parsePerlClassEscape(e,s))continue;e.rewindTo(a);let l=t.parseClassChar(e,n),c=l;if(e.more()&&e.lookingAt("-")){if(e.skip(1),e.more()&&e.lookingAt("]"))e.skip(-1);else if(c=t.parseClassChar(e,n),c<l)throw new Pt(t.ERR_INVALID_CHAR_RANGE,e.from(a))}(this.flags&me.FOLD_CASE)===0?s.appendRange(l,c):s.appendFoldedRange(l,c)}e.skip(1),s.cleanClass(),i<0&&s.negateClass(),r.runes=s.toArray(),this.push(r)}},Hg=class{constructor(e){this.value=e}get(){return this.value}set(e){this.value=e}compareAndSet(e,n){return this.value===e?(this.value=n,!0):!1}},Gg=class t{static initTest(e){let n=t.compile(e),r=new t(n.expr,n.prog,n.numSubexp,n.longest);return r.cond=n.cond,r.prefix=n.prefix,r.prefixUTF8=n.prefixUTF8,r.prefixComplete=n.prefixComplete,r.prefixRune=n.prefixRune,r}static compile(e){return t.compileImpl(e,me.PERL,!1)}static compilePOSIX(e){return t.compileImpl(e,me.POSIX,!0)}static compileImpl(e,n,r){let s=Vg.parse(e,n),i=s.maxCap();s=jg.simplify(s);let o=Wg.compileRegexp(s),a=new t(e,o,i,r),[l,c]=o.prefix();return a.prefixComplete=l,a.prefix=c,a.prefixUTF8=lt.stringToUtf8ByteArray(a.prefix),a.prefix.length>0&&(a.prefixRune=a.prefix.codePointAt(0)),a.namedGroups=s.namedGroups,a}static match(e,n){return t.compile(e).match(n)}constructor(e,n,r=0,s=0){this.expr=e,this.prog=n,this.numSubexp=r,this.longest=s,this.cond=n.startCond(),this.prefix=null,this.prefixUTF8=null,this.prefixComplete=!1,this.prefixRune=0,this.pooled=new Hg,this.dfa=new zg(n)}executeEngine(e,n,r,s){if(s>0)return this.doExecuteNFA(e,n,r,s);let i=this.dfa.match(e,n,r);return i!==null?i?[]:null:this.doExecuteNFA(e,n,r,s)}numberOfCapturingGroups(){return this.numSubexp}numberOfInstructions(){return this.prog.numInst()}get(){let e;do e=this.pooled.get();while(e&&!this.pooled.compareAndSet(e,e.next));return e}reset(){this.pooled.set(null)}put(e,n){let r=this.pooled.get();do r=this.pooled.get(),!n&&r&&(e=Ic.fromMachine(e),n=!0),e.next!==r&&(e.next=r);while(!this.pooled.compareAndSet(r,e))}toString(){return this.expr}doExecuteNFA(e,n,r,s){let i=this.get(),o=!1;i?i.next!==null&&(i=Ic.fromMachine(i),o=!0):(i=Ic.fromRE2(this),o=!0),i.init(s);let a=i.match(e,n,r)?i.submatches():null;return this.put(i,o),a}match(e){return this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,0)!==null}matchWithGroup(e,n,r,s,i){return e instanceof oo||(e=sl.utf16(e)),this.matchMachineInput(e,n,r,s,i)}matchMachineInput(e,n,r,s,i){if(n>r)return[!1,null];let o=e.isUTF16Encoding()?qt.fromUTF16(e.asCharSequence(),0,r):qt.fromUTF8(e.asBytes(),0,r),a=this.executeEngine(o,n,s,2*i);return a===null?[!1,null]:[!0,a]}matchUTF8(e){return this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,0)!==null}replaceAll(e,n){return this.replaceAllFunc(e,()=>n,2*e.length+1)}replaceFirst(e,n){return this.replaceAllFunc(e,()=>n,1)}replaceAllFunc(e,n,r){let s=0,i=0,o="",a=qt.fromUTF16(e),l=0;for(;i<=e.length;){let c=this.executeEngine(a,i,me.UNANCHORED,2);if(c===null||c.length===0)break;o+=e.substring(s,c[0]),(c[1]>s||c[0]===0)&&(o+=n(e.substring(c[0],c[1])),l++),s=c[1];let u=a.step(i)&7;if(i+u>c[1]?i+=u:i+1>c[1]?i++:i=c[1],l>=r)break}return o+=e.substring(s),o}pad(e){if(e===null)return null;let n=(1+this.numSubexp)*2;if(e.length<n){let r=new Array(n).fill(-1);for(let s=0;s<e.length;s++)r[s]=e[s];e=r}return e}allMatches(e,n,r=s=>s){let s=[],i=e.endPos();n<0&&(n=i+1);let o=0,a=0,l=-1;for(;a<n&&o<=i;){let c=this.executeEngine(e,o,me.UNANCHORED,this.prog.numCap);if(c===null||c.length===0)break;let u=!0;if(c[1]===o){c[0]===l&&(u=!1);let f=e.step(o);f<0?o=i+1:o+=f&7}else o=c[1];l=c[1],u&&(s.push(r(this.pad(c))),a++)}return s}findUTF8(e){let n=this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,2);return n===null?null:e.slice(n[0],n[1])}findUTF8Index(e){let n=this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,2);return n===null?null:n.slice(0,2)}find(e){let n=this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,2);return n===null?"":e.substring(n[0],n[1])}findIndex(e){return this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,2)}findUTF8Submatch(e){let n=this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,this.prog.numCap);if(n===null)return null;let r=new Array(1+this.numSubexp).fill(null);for(let s=0;s<r.length;s++)2*s<n.length&&n[2*s]>=0&&(r[s]=e.slice(n[2*s],n[2*s+1]));return r}findUTF8SubmatchIndex(e){return this.pad(this.executeEngine(qt.fromUTF8(e),0,me.UNANCHORED,this.prog.numCap))}findSubmatch(e){let n=this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,this.prog.numCap);if(n===null)return null;let r=new Array(1+this.numSubexp).fill(null);for(let s=0;s<r.length;s++)2*s<n.length&&n[2*s]>=0&&(r[s]=e.substring(n[2*s],n[2*s+1]));return r}findSubmatchIndex(e){return this.pad(this.executeEngine(qt.fromUTF16(e),0,me.UNANCHORED,this.prog.numCap))}findAllUTF8(e,n){let r=this.allMatches(qt.fromUTF8(e),n,s=>e.slice(s[0],s[1]));return r.length===0?null:r}findAllUTF8Index(e,n){let r=this.allMatches(qt.fromUTF8(e),n,s=>s.slice(0,2));return r.length===0?null:r}findAll(e,n){let r=this.allMatches(qt.fromUTF16(e),n,s=>e.substring(s[0],s[1]));return r.length===0?null:r}findAllIndex(e,n){let r=this.allMatches(qt.fromUTF16(e),n,s=>s.slice(0,2));return r.length===0?null:r}findAllUTF8Submatch(e,n){let r=this.allMatches(qt.fromUTF8(e),n,s=>{let i=new Array(s.length/2|0).fill(null);for(let o=0;o<i.length;o++)s[2*o]>=0&&(i[o]=e.slice(s[2*o],s[2*o+1]));return i});return r.length===0?null:r}findAllUTF8SubmatchIndex(e,n){let r=this.allMatches(qt.fromUTF8(e),n);return r.length===0?null:r}findAllSubmatch(e,n){let r=this.allMatches(qt.fromUTF16(e),n,s=>{let i=new Array(s.length/2|0).fill(null);for(let o=0;o<i.length;o++)s[2*o]>=0&&(i[o]=e.substring(s[2*o],s[2*o+1]));return i});return r.length===0?null:r}findAllSubmatchIndex(e,n){let r=this.allMatches(qt.fromUTF16(e),n);return r.length===0?null:r}},Kg=class t{static isUpperCaseAlpha(e){return"A"<=e&&e<="Z"}static isHexadecimal(e){return"0"<=e&&e<="9"||"A"<=e&&e<="F"||"a"<=e&&e<="f"}static getUtf8CharSize(e){let n=e.charCodeAt(0);return n<128?1:n<2048?2:n<65536?3:4}static translate(e){if(typeof e!="string")return e;let n="",r=!1,s=e.length;s===0&&(n="(?:)",r=!0);let i=0;for(;i<s;){let o=e[i];if(o==="\\"){if(i+1<s)switch(o=e[i+1],o){case"\\":{n+="\\\\",i+=2;continue}case"c":{if(i+2<s){let l=e[i+2];if(t.isUpperCaseAlpha(l)){n+="\\x",n+=(l.charCodeAt(0)-64>>4).toString(16).toUpperCase(),n+=(l.charCodeAt(0)-64&15).toString(16).toUpperCase(),i+=3,r=!0;continue}}n+="\\c",i+=2;continue}case"u":{if(i+2<s){let l=e[i+2];if(t.isHexadecimal(l)){n+="\\x{"+l,i+=3;for(let c=0;c<3&&i<s&&(l=e[i],!!t.isHexadecimal(l));++i,++c)n+=l;n+="}",r=!0;continue}else if(l==="{"){n+="\\x",i+=2,r=!0;continue}}n+="\\u",i+=2;continue}default:{n+="\\";let l=t.getUtf8CharSize(o);n+=e.substring(i+1,i+1+l),i+=l+1;continue}}}else if(o==="/"){n+="\\/",i+=1,r=!0;continue}else if(o==="("&&i+2<s&&e[i+1]==="?"&&e[i+2]==="<"&&(i+3>=s||e[i+3]!=="="&&e[i+3]!=="!")){n+="(?P<",i+=3,r=!0;continue}let a=t.getUtf8CharSize(o);n+=e.substring(i,i+a),i+=a}return r?n:e}},$i=class t{static CASE_INSENSITIVE=1;static DOTALL=2;static MULTILINE=4;static DISABLE_UNICODE_GROUPS=8;static LONGEST_MATCH=16;static quote(e){return lt.quoteMeta(e)}static translateRegExp(e){return Kg.translate(e)}static compile(e,n=0){let r=e;if((n&t.CASE_INSENSITIVE)!==0&&(r=`(?i)${r}`),(n&t.DOTALL)!==0&&(r=`(?s)${r}`),(n&t.MULTILINE)!==0&&(r=`(?m)${r}`),(n&~(t.MULTILINE|t.DOTALL|t.CASE_INSENSITIVE|t.DISABLE_UNICODE_GROUPS|t.LONGEST_MATCH))!==0)throw new Dg("Flags should only be a combination of MULTILINE, DOTALL, CASE_INSENSITIVE, DISABLE_UNICODE_GROUPS, LONGEST_MATCH");let s=me.PERL;(n&t.DISABLE_UNICODE_GROUPS)!==0&&(s&=-129);let i=new t(e,n);return i.re2Input=Gg.compileImpl(r,s,(n&t.LONGEST_MATCH)!==0),i}static matches(e,n){return t.compile(e).testExact(n)}static initTest(e,n,r){if(e==null)throw new Error("pattern is null");if(r==null)throw new Error("re2 is null");let s=new t(e,n);return s.re2Input=r,s}constructor(e,n){this.patternInput=e,this.flagsInput=n}reset(){this.re2Input.reset()}flags(){return this.flagsInput}pattern(){return this.patternInput}re2(){return this.re2Input}matches(e){return this.testExact(e)}matcher(e){return Array.isArray(e)&&(e=sl.utf8(e)),new _g(this,e)}test(e){return Array.isArray(e)?this.re2Input.matchUTF8(e):this.re2Input.match(e)}testExact(e){let n=Array.isArray(e)?qt.fromUTF8(e):qt.fromUTF16(e);return this.re2Input.executeEngine(n,0,me.ANCHOR_BOTH,0)!==null}split(e,n=0){let r=this.matcher(e),s=[],i=0,o=0;for(;r.find();){if(o===0&&r.end()===0){o=r.end();continue}if(n>0&&s.length===n-1)break;if(o===r.start()){if(n===0){i+=1,o=r.end();continue}}else for(;i>0;)s.push(""),i-=1;s.push(r.substring(o,r.start())),o=r.end()}if(n===0&&o!==r.inputLength()){for(;i>0;)s.push(""),i-=1;s.push(r.substring(o,r.inputLength()))}return(n!==0||s.length===0)&&s.push(r.substring(o,r.inputLength())),s}toString(){return this.patternInput}programSize(){return this.re2Input.numberOfInstructions()}groupCount(){return this.re2Input.numberOfCapturingGroups()}namedGroups(){return this.re2Input.namedGroups}equals(e){return this===e?!0:e===null||this.constructor!==e.constructor?!1:this.flagsInput===e.flagsInput&&this.patternInput===e.patternInput}}});function f_(t){let e=0;return t.includes("i")&&(e|=$i.CASE_INSENSITIVE),t.includes("m")&&(e|=$i.MULTILINE),t.includes("s")&&(e|=$i.DOTALL),e}function m3(t){return $i.translateRegExp(t)}function p_(t,e){let n=f_(e);if(t.length>h_)return $i.compile(m3(t),n);let r=`${n} ${t}`,s=Pc.get(r);if(s!==void 0)return s;let i=$i.compile(m3(t),n);if(Pc.size>=d_){let o=Pc.keys().next().value;o!==void 0&&Pc.delete(o)}return Pc.set(r,i),i}function le(t,e="",n={}){return new Jf(t,e,n)}var c_,u_,d_,h_,Pc,Jf,Li,g3=L(()=>{"use strict";p3();Nt();X();c_=1e6,u_=64*1024*1024;d_=256,h_=1024,Pc=new Map;Jf=class{_re2;_pattern;_flags;_global;_ignoreCase;_multiline;_lastIndex=0;_nativeRegex=null;_matcher=null;_matcherInput=null;maxResults;maxOutputBytes;signal;assertResultCount(e){if(this.signal?.aborted)throw new Error("regular expression aborted");if(e>this.maxResults)throw new v(`regular expression result limit exceeded (${this.maxResults})`,"array_elements")}expandReplacement(e,n){let r=new $e(this.maxOutputBytes,"regular expression replacement"),s=this._re2.groupCount(),i=this._re2.namedGroups();for(let o=0;o<n.length;o++){let a=n[o];if(a==="\\"&&o+1<n.length){r.append(n[++o]);continue}if(a!=="$"||o+1>=n.length){r.append(a);continue}if(n[o+1]==="{"){let l=n.indexOf("}",o+2);if(l!==-1){let c=n.slice(o+2,l),u=i?.[c];if(u!==void 0){r.append(e.group(u)??""),o=l;continue}}}if(/\d/.test(n[o+1])){let l=o+1,c=0;for(;l<n.length&&/\d/.test(n[l]);){let u=c*10+Number(n[l]);if(u>s)break;c=u,l++}r.append(e.group(c)??""),o=l-1;continue}r.append(a)}return r.build()}acquireMatcher(e){return this._matcher===null?(this._matcher=this._re2.matcher(e),this._matcherInput=e,this._matcher):(this._matcherInput!==e&&(this._matcher.matcherInput.charSequence=e,this._matcherInput=e),this._matcher.reset(),this._matcher)}constructor(e,n="",r={}){if(this._pattern=e,this._flags=n,this._global=n.includes("g"),this._ignoreCase=n.includes("i"),this._multiline=n.includes("m"),this.maxResults=r.maxResults??c_,this.maxOutputBytes=r.maxOutputBytes??u_,this.signal=r.signal,!Number.isSafeInteger(this.maxResults)||this.maxResults<0||!Number.isSafeInteger(this.maxOutputBytes)||this.maxOutputBytes<0)throw new Error("invalid regular expression limits");try{this._re2=p_(e,n)}catch(s){if(s instanceof Pt){let i=s.message||"",o="";throw i.includes("(?=")||i.includes("(?!")||i.includes("(?<")||i.includes("(?<!")||e.includes("(?=")||e.includes("(?!")||e.includes("(?<=")||e.includes("(?<!")?o=" Lookahead (?=, ?!) and lookbehind (?<=, ?<!) assertions are not supported in this environment because the regex engine uses RE2 for ReDoS protection. RE2 guarantees linear-time matching but cannot support these features.":(i.includes("backreference")||/\\[1-9]/.test(e))&&(o=" Backreferences (\\1, \\2, etc.) are not supported in this environment because the regex engine uses RE2 for ReDoS protection. RE2 guarantees linear-time matching but cannot support backreferences."),new SyntaxError(`Invalid regular expression: /${e}/: ${i}${o}`)}throw s}}test(e){return this._global&&(this._lastIndex=0),this.acquireMatcher(e).find()}exec(e){let n=this.acquireMatcher(e),r=this._global?this._lastIndex:0;if(!n.find(r))return this._global&&(this._lastIndex=0),null;let s=this._re2.groupCount(),i=[];i.push(n.group(0)??"");for(let l=1;l<=s;l++){let c=n.group(l);i.push(c)}let o=i;o.index=n.start(0),o.input=e;let a=this._re2.namedGroups();if(a&&Object.keys(a).length>0){let l=Object.create(null);for(let[c,u]of Object.entries(a)){let f=n.group(u);f!==null&&(l[c]=f)}o.groups=l}return this._global&&(this._lastIndex=n.end(0),n.start(0)===n.end(0)&&this._lastIndex++),o}match(e){if(this._global&&(this._lastIndex=0),!this._global)return this.exec(e);let n=[],r=this.acquireMatcher(e),s=0;for(;r.find(s);){let i=r.group(0)??"";if(this.assertResultCount(n.length+1),n.push(i),s=r.end(0),r.start(0)===r.end(0)&&s++,s>e.length)break}return n.length>0?n:null}replace(e,n){if(this._global&&(this._lastIndex=0),typeof n=="string"){let u=this._re2.matcher(e),f=new $e(this.maxOutputBytes,"regular expression replacement"),d=0,h=0,p=0;for(;u.find(h);){this.assertResultCount(++p);let m=u.start(0),g=u.end(0);if(f.append(e.slice(d,m)),f.append(this.expandReplacement(u,n)),d=g,h=g>m?g:g+1,!this._global||h>e.length)break}return f.append(e.slice(d)),f.build()}let r=new $e(this.maxOutputBytes,"regular expression replacement"),s=this._re2.matcher(e),i=0,o=0,a=0,l=this._re2.groupCount(),c=this._re2.namedGroups();for(;s.find(o);){this.assertResultCount(++a),r.append(e.slice(i,s.start(0)));let u=[],f=s.group(0)??"";for(let p=1;p<=l;p++)u.push(s.group(p));if(u.push(s.start(0)),u.push(e),c&&Object.keys(c).length>0){let p=Object.create(null);for(let[m,g]of Object.entries(c))p[m]=s.group(g)??"";u.push(p)}let d=s.start(0),h=s.end(0);if(r.append(n(f,...u)),i=h,o=i,d===h&&o++,!this._global||o>e.length)break}return r.append(e.slice(i)),r.build()}split(e,n){if(n===0)return[];let r=n===void 0||n<0?this.maxResults:Math.min(n,this.maxResults),s=[],i=this._re2.matcher(e),o=0,a=0;for(;s.length<r&&i.find(a);)this.assertResultCount(s.length+1),s.push(e.slice(o,i.start(0))),o=i.end(0),a=i.end(0)>i.start(0)?i.end(0):i.end(0)+1;return s.length<r&&s.push(e.slice(o)),s}search(e){let n=this.acquireMatcher(e);return n.find()?n.start(0):-1}*matchAll(e){if(!this._global)throw new Error("matchAll requires global flag");this._lastIndex=0;let n=this._re2.matcher(e),r=this._re2.groupCount(),s=this._re2.namedGroups(),i=0,o=0;for(;n.find(i);){this.assertResultCount(++o);let a=[];a.push(n.group(0)??"");for(let c=1;c<=r;c++)a.push(n.group(c));let l=a;if(l.index=n.start(0),l.input=e,s&&Object.keys(s).length>0){let c=Object.create(null);for(let[u,f]of Object.entries(s)){let d=n.group(f);d!==null&&(c[u]=d)}l.groups=c}if(yield l,i=n.end(0),n.start(0)===n.end(0)&&i++,i>e.length)break}}get native(){if(!this._nativeRegex)try{this._nativeRegex=new RegExp(this._pattern,this._flags)}catch{this._nativeRegex=new RegExp("",this._flags),Object.defineProperty(this._nativeRegex,"source",{value:this._pattern,writable:!1})}return this._nativeRegex}get source(){return this._pattern}get flags(){return this._flags}get global(){return this._global}get ignoreCase(){return this._ignoreCase}get multiline(){return this._multiline}get lastIndex(){return this._lastIndex}set lastIndex(e){this._lastIndex=e}};Li=class{_regex;constructor(e){this._regex=e}test(e){return this._regex.global&&(this._regex.lastIndex=0),this._regex.test(e)}exec(e){return this._regex.exec(e)}match(e){return this._regex.global&&(this._regex.lastIndex=0),e.match(this._regex)}replace(e,n){return this._regex.global&&(this._regex.lastIndex=0),e.replace(this._regex,n)}split(e,n){return e.split(this._regex,n)}search(e){return e.search(this._regex)}*matchAll(e){if(!this._regex.global)throw new Error("matchAll requires global flag");this._regex.lastIndex=0;let n=this._regex.exec(e);for(;n!==null;)yield n,n[0].length===0&&this._regex.lastIndex++,n=this._regex.exec(e)}get native(){return this._regex}get source(){return this._regex.source}get flags(){return this._regex.flags}get global(){return this._regex.global}get ignoreCase(){return this._regex.ignoreCase}get multiline(){return this._regex.multiline}get lastIndex(){return this._regex.lastIndex}set lastIndex(e){this._regex.lastIndex=e}}});var $t=L(()=>{"use strict";g3()});function fr(t,e,n){let r=typeof n=="boolean"?{ignoreCase:n}:n??{},s=e;r.stripQuotes&&(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1));let i=r.ignoreCase?`i:${s}`:s,o=$c.get(i);if(!o){if(o=g_(s,r.ignoreCase),$c.size>=m_){let a=$c.keys().next().value;a!==void 0&&$c.delete(a)}$c.set(i,o)}return o.test(t)}function g_(t,e){let n="^";for(let r=0;r<t.length;r++){let s=t[r];if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let i=r+1;for(;i<t.length&&t[i]!=="]";)i++;n+=t.slice(r,i+1),r=i}else s==="."||s==="+"||s==="^"||s==="$"||s==="{"||s==="}"||s==="("||s===")"||s==="|"||s==="\\"?n+=`\\${s}`:n+=s}return n+="$",le(n,e?"i":"")}var m_,$c,Zg=L(()=>{"use strict";$t();m_=2048,$c=new Map});function Lc(t,e){let n=t.ignoreCase?e.toLowerCase():e,r=t.needles;for(let s=0;s<r.length;s++)if(n.indexOf(r[s])!==-1)return!0;return!1}function y3(t,e){return t.replace(/\$(&|\d+|<([^>]+)>)/g,(n,r,s)=>{if(r==="&")return e[0];if(s!==void 0)return e.groups?.[s]??"";let i=parseInt(r,10);return e[i]??""})}function na(t,e,n={}){let{invertMatch:r=!1,showLineNumbers:s=!1,countOnly:i=!1,countMatches:o=!1,filename:a="",onlyMatching:l=!1,beforeContext:c=0,afterContext:u=0,maxCount:f=0,contextSeparator:d="--",showColumn:h=!1,vimgrep:p=!1,showByteOffset:m=!1,replace:g=null,passthru:y=!1,multiline:w=!1,kResetGroup:b,preFilter:x,maxWork:S,maxMatches:E,signal:A}=n;if(w)return y_(t,e,{invertMatch:r,showLineNumbers:s,countOnly:i,countMatches:o,filename:a,onlyMatching:l,beforeContext:c,afterContext:u,maxCount:f,contextSeparator:d,showColumn:h,showByteOffset:m,replace:g,kResetGroup:b,preFilter:x,maxWork:S,maxMatches:E,signal:A});let N=0,I=(M=1)=>{if(A?.aborted)throw new et;if(N+=M,S!==void 0&&N>S)throw new v(`search: matching work limit exceeded (${S})`,"iterations")},T=(M,Y)=>{if(E!==void 0&&M.length>=E)throw new v(`search: result limit exceeded (${E})`,"array_elements");M.push(Y)},$=1;for(let M=0;M<t.length;M++)if((M&1023)===0&&I(),t.charCodeAt(M)===10&&($++,E!==void 0&&$>E))throw new v(`search: line limit exceeded (${E})`,"array_elements");let C=t.split(`
|
|
186
186
|
`),O=C.length,F=O>0&&C[O-1]===""?O-1:O;if(i||o){let M=0,Y=(o||l)&&!r;for(let H=0;H<F;H++){I();let re=C[H];if(!(x&&!r&&!Lc(x,re)))if(e.lastIndex=0,Y)for(let se=e.exec(re);se!==null;se=e.exec(re))I(),M++,se[0].length===0&&e.lastIndex++;else e.test(re)!==r&&M++}return{output:`${a?`${a}:${M}`:String(M)}
|
|
187
187
|
`,matched:M>0,matchCount:M}}if(c===0&&u===0&&!y){let M=[],Y=!1,q=0,H=0;for(let re=0;re<F&&(I(),!(f>0&&q>=f));re++){let se=C[re],de=null;if(x&&!Lc(x,se)||(e.lastIndex=0,de=e.exec(se)),de!==null!==r)if(Y=!0,q++,l)for(let oe=de;oe!==null;oe=e.exec(se)){I();let Se=b!==void 0?oe[b]??"":oe[0],te=g!==null?y3(g,oe):Se,ne=a?`${a}:`:"";m&&(ne+=`${H+oe.index}:`),s&&(ne+=`${re+1}:`),h&&(ne+=`${oe.index+1}:`),T(M,ne+te),oe[0].length===0&&e.lastIndex++}else if(p)for(let oe=de;oe!==null;oe=e.exec(se)){I();let Se=a?`${a}:`:"";m&&(Se+=`${H+oe.index}:`),s&&(Se+=`${re+1}:`),h&&(Se+=`${oe.index+1}:`),T(M,Se+se),oe[0].length===0&&e.lastIndex++}else{let oe=de?de.index+1:1,Se=se;g!==null&&(e.lastIndex=0,Se=e.replace(se,(...ne)=>{if(ne[0].length===0)return"";let ye=ne,Le=ne[ne.length-1];return typeof Le=="object"&&Le!==null?(ye.groups=Le,ye.input=ne[ne.length-2],ye.index=ne[ne.length-3]):(ye.input=ne[ne.length-1],ye.index=ne[ne.length-2]),y3(g,ye)}));let te=a?`${a}:`:"";m&&(te+=`${H+(de?de.index:0)}:`),s&&(te+=`${re+1}:`),h&&(te+=`${oe}:`),T(M,te+Se)}H+=se.length+1}return{output:M.length>0?`${M.join(`
|
|
188
188
|
`)}
|
|
189
|
-
`:"",matched:Y,matchCount:q}}if(y){let M=[],Y=!1,q=0;for(let H=0;H<F;H++){I();let re=C[H],se;x&&!Lc(x,re)?se=!1:(e.lastIndex=0,se=e.test(re));let de=se!==r;de&&(Y=!0,q++);let
|
|
189
|
+
`:"",matched:Y,matchCount:q}}if(y){let M=[],Y=!1,q=0;for(let H=0;H<F;H++){I();let re=C[H],se;x&&!Lc(x,re)?se=!1:(e.lastIndex=0,se=e.test(re));let de=se!==r;de&&(Y=!0,q++);let Ie=de?":":"-",oe=a?`${a}${Ie}`:"";s&&(oe+=`${H+1}${Ie}`),T(M,oe+re)}return{output:M.length>0?`${M.join(`
|
|
190
190
|
`)}
|
|
191
|
-
`:"",matched:Y,matchCount:q}}let R=[],_=0,U=new Set,B=-1,W=[];for(let M=0;M<F&&(I(),!(f>0&&_>=f));M++){let Y=C[M],q;if(x&&!Lc(x,Y)?q=!1:(e.lastIndex=0,q=e.test(Y)),q!==r){if(E!==void 0&&W.length>=E)throw new v(`search: match limit exceeded (${E})`,"array_elements");W.push(M),_++}}for(let M of W){I();let Y=Math.max(0,M-c);B>=0&&Y>B+1&&T(R,d);for(let H=Y;H<M;H++)if(I(),!U.has(H)){U.add(H),B=H;let re=C[H];s&&(re=`${H+1}-${re}`),a&&(re=`${a}-${re}`),T(R,re)}if(!U.has(M)){U.add(M),B=M;let H=C[M];if(l){e.lastIndex=0;for(let re=e.exec(H);re!==null;re=e.exec(H)){I();let se=b!==void 0?re[b]??"":re[0],de=g!==null?g:se,
|
|
191
|
+
`:"",matched:Y,matchCount:q}}let R=[],_=0,U=new Set,B=-1,W=[];for(let M=0;M<F&&(I(),!(f>0&&_>=f));M++){let Y=C[M],q;if(x&&!Lc(x,Y)?q=!1:(e.lastIndex=0,q=e.test(Y)),q!==r){if(E!==void 0&&W.length>=E)throw new v(`search: match limit exceeded (${E})`,"array_elements");W.push(M),_++}}for(let M of W){I();let Y=Math.max(0,M-c);B>=0&&Y>B+1&&T(R,d);for(let H=Y;H<M;H++)if(I(),!U.has(H)){U.add(H),B=H;let re=C[H];s&&(re=`${H+1}-${re}`),a&&(re=`${a}-${re}`),T(R,re)}if(!U.has(M)){U.add(M),B=M;let H=C[M];if(l){e.lastIndex=0;for(let re=e.exec(H);re!==null;re=e.exec(H)){I();let se=b!==void 0?re[b]??"":re[0],de=g!==null?g:se,Ie=a?`${a}:`:"";s&&(Ie+=`${M+1}:`),h&&(Ie+=`${re.index+1}:`),T(R,Ie+de),re[0].length===0&&e.lastIndex++}}else{let re=H;s&&(re=`${M+1}:${re}`),a&&(re=`${a}:${re}`),T(R,re)}}let q=Math.min(F-1,M+u);for(let H=M+1;H<=q;H++)if(I(),!U.has(H)){U.add(H),B=H;let re=C[H];s&&(re=`${H+1}-${re}`),a&&(re=`${a}-${re}`),T(R,re)}}return{output:R.length>0?`${R.join(`
|
|
192
192
|
`)}
|
|
193
|
-
`:"",matched:_>0,matchCount:_}}function y_(t,e,n){let{invertMatch:r,showLineNumbers:s,countOnly:i,countMatches:o,filename:a,onlyMatching:l,beforeContext:c,afterContext:u,maxCount:f,contextSeparator:d,showColumn:h,showByteOffset:p,replace:m,kResetGroup:g,preFilter:y,maxWork:w,maxMatches:b,signal:x}=n,S=0,E=(U=1)=>{if(x?.aborted)throw new
|
|
193
|
+
`:"",matched:_>0,matchCount:_}}function y_(t,e,n){let{invertMatch:r,showLineNumbers:s,countOnly:i,countMatches:o,filename:a,onlyMatching:l,beforeContext:c,afterContext:u,maxCount:f,contextSeparator:d,showColumn:h,showByteOffset:p,replace:m,kResetGroup:g,preFilter:y,maxWork:w,maxMatches:b,signal:x}=n,S=0,E=(U=1)=>{if(x?.aborted)throw new et;if(S+=U,w!==void 0&&S>w)throw new v(`search: matching work limit exceeded (${w})`,"iterations")};if(y&&!r&&!Lc(y,t))return i||o?{output:`${a?`${a}:0`:"0"}
|
|
194
194
|
`,matched:!1,matchCount:0}:{output:"",matched:!1,matchCount:0};let A=[0];for(let U=0;U<t.length;U++)if((U&1023)===0&&E(),t[U]===`
|
|
195
195
|
`){if(b!==void 0&&A.length>=b)throw new v(`search: line index limit exceeded (${b})`,"array_elements");A.push(U+1)}let N=t.split(`
|
|
196
196
|
`),I=N.length,T=I>0&&N[I-1]===""?I-1:I,$=U=>{let B=0,W=A.length;for(;B<W;){let M=B+Math.floor((W-B)/2);A[M]<=U?B=M+1:W=M}return Math.max(0,B-1)},C=U=>{let B=$(U);return U-A[B]+1};if(i||o){let U=0,B=0,W=-1;e.lastIndex=0;for(let q=e.exec(t);q!==null&&(E(),!(f>0&&U>=f));q=e.exec(t)){if(U++,!o){let H=$(q.index),re=$(q.index+Math.max(0,q[0].length-1)),se=Math.max(H,W+1);se<=re&&(B+=re-se+1,W=re)}q[0].length===0&&e.lastIndex++}let M=o?r?0:U:r?T-B:B;return{output:`${a?`${a}:${M}`:String(M)}
|
|
@@ -201,23 +201,23 @@ Modify: ${h.mtime.toISOString()}
|
|
|
201
201
|
`:"",matched:!0,matchCount:O.length}}var w3=L(()=>{"use strict";X()});function b3(t){let e="",n=0;for(;n<t.length;){if(t.slice(n,n+7)==="[[:<:]]"){e+="\\b",n+=7;continue}if(t.slice(n,n+7)==="[[:>:]]"){e+="\\b",n+=7;continue}if(t[n]==="["){let r="[";for(n++,n<t.length&&(t[n]==="^"||t[n]==="!")&&(r+="^",n++),n<t.length&&t[n]==="]"&&(r+="\\]",n++);n<t.length&&t[n]!=="]";){if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){let i=t.slice(n+2,s),o=w_.get(i);if(o){r+=o,n=s+2;continue}}}if(t[n]==="\\"&&n+1<t.length){r+=t[n]+t[n+1],n+=2;continue}r+=t[n],n++}n<t.length&&t[n]==="]"&&(r+="]",n++),e+=r;continue}if(t[n]==="\\"&&n+1<t.length){e+=t[n]+t[n+1],n+=2;continue}e+=t[n],n++}return e}function ol(t,e){let n,r;switch(e.mode){case"fixed":n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");break;case"extended":case"perl":{if(n=b3(t),n=n.replace(/\(\?P<([^>]+)>/g,"(?<$1>"),e.mode==="perl"){n=S_(n),n=A_(n),n=v_(n);let a=T_(n);n=a.pattern,r=a.kResetGroup}break}default:n=b3(t),n=R_(n);break}e.wholeWord&&(n=`\\b(?:${n})\\b`),e.lineRegexp&&(n=`^(?:${n})$`);let s=/\\u\{[0-9A-Fa-f]+\}/.test(n),i="g"+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.multilineDotall?"s":"")+(s?"u":""),o=b_(n,e.ignoreCase??!1);return{regex:le(n,i),kResetGroup:r,preFilter:o??void 0}}function b_(t,e){let n=t;if(n.startsWith("\\b(?:")&&n.endsWith(")\\b")?n=n.slice(5,n.length-3):n.startsWith("\\b")&&n.endsWith("\\b")&&n.length>=4&&(n=n.slice(2,n.length-2)),n.length===0)return null;let r=x_(n);if(r===null)return null;let s=[];for(let i of r){let o=E_(i);if(o===null||o.length===0)return null;s.push(o)}return s.length===0?null:{needles:e?s.map(i=>i.toLowerCase()):s,ignoreCase:e}}function x_(t){let e=[],n=0,r=!1,s=0;for(let i=0;i<t.length;i++){let o=t[i];if(o==="\\"){i++;continue}if(r){o==="]"&&(r=!1);continue}if(o==="[")r=!0;else if(o==="(")n++;else if(o===")"){if(n--,n<0)return null}else o==="|"&&n===0&&(e.push(t.slice(s,i)),s=i+1)}return n!==0||r?null:(e.push(t.slice(s)),e)}function E_(t){let e=t;if(e.startsWith("^")&&(e=e.slice(1)),e.endsWith("$")){let r=0;for(let s=e.length-2;s>=0&&e[s]==="\\";s--)r++;r%2===0&&(e=e.slice(0,-1))}if(e.length===0)return null;let n="";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\"){let i=e[r+1];if(i===void 0||/[dDwWsSbBAZzGQE0-9ckpPNXRxuU]/.test(i))return null;i==="n"?n+=`
|
|
202
202
|
`:i==="t"?n+=" ":i==="r"?n+="\r":i==="f"?n+="\f":i==="v"?n+="\v":n+=i,r++;continue}if(/[.*+?^${}()|[\]]/.test(s))return null;n+=s}return n}function S_(t){let e="",n=0;for(;n<t.length;)if(t[n]==="\\"&&n+1<t.length&&t[n+1]==="Q"){n+=2;let r="";for(;n<t.length;){if(t[n]==="\\"&&n+1<t.length&&t[n+1]==="E"){n+=2;break}r+=t[n],n++}e+=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}else e+=t[n],n++;return e}function A_(t){return t.replace(/\\x\{([0-9A-Fa-f]+)\}/g,"\\u{$1}")}function v_(t){let e="",n=0;for(;n<t.length;){if(t[n]==="("&&n+1<t.length&&t[n+1]==="?"){let r=t.slice(n).match(/^\(\?([imsx]*)(-[imsx]*)?(:|$|\))/);if(r){let s=r[1]||"",i=r[2]||"",o=r[3];if(o===":"){let a=n+r[0].length-1,l=C_(t,n);if(l!==-1){let c=t.slice(a+1,l),u=k_(c,s,i);e+=`(?:${u})`,n=l+1;continue}}else if(o===")"||o===""){n+=r[0].length;continue}}}e+=t[n],n++}return e}function C_(t,e){let n=0,r=e;for(;r<t.length;){if(t[r]==="\\"){r+=2;continue}if(t[r]==="["){for(r++;r<t.length&&t[r]!=="]";)t[r]==="\\"&&r++,r++;r++;continue}if(t[r]==="(")n++;else if(t[r]===")"&&(n--,n===0))return r;r++}return-1}function k_(t,e,n){let r=t;return e.includes("i")&&(r=N_(r)),r}function N_(t){let e="",n=0;for(;n<t.length;){let r=t[n];if(r==="\\"){n+1<t.length?(e+=r+t[n+1],n+=2):(e+=r,n++);continue}if(r==="["){e+=r,n++,n<t.length&&t[n]==="^"&&(e+=t[n],n++);let s=[];for(;n<t.length&&t[n]!=="]";)if(t[n]==="\\")s.push(t[n]),n++,n<t.length&&(s.push(t[n]),n++);else if(t[n]==="-"&&s.length>0&&n+1<t.length&&t[n+1]!=="]"){let i=s[s.length-1],o=t[n+1];s.push("-"),s.push(o),/[a-z]/.test(i)&&/[a-z]/.test(o)?(s.push(i.toUpperCase()),s.push("-"),s.push(o.toUpperCase())):/[A-Z]/.test(i)&&/[A-Z]/.test(o)&&(s.push(i.toLowerCase()),s.push("-"),s.push(o.toLowerCase())),n+=2}else{let i=t[n];if(s.push(i),/[a-zA-Z]/.test(i)){let o=i===i.toLowerCase()?i.toUpperCase():i.toLowerCase();s.includes(o)||s.push(o)}n++}e+=s.join(""),n<t.length&&(e+=t[n],n++);continue}if(/[a-zA-Z]/.test(r)){let s=r.toLowerCase(),i=r.toUpperCase();e+=`[${i}${s}]`}else e+=r;n++}return e}function T_(t){let e=O_(t);if(e===-1)return{pattern:t};let n=t.slice(0,e),r=t.slice(e+2),s=I_(n);return{pattern:`(?:${n})(${r})`,kResetGroup:s+1}}function O_(t){let e=0;for(;e<t.length-1;)if(t[e]==="\\"){if(t[e+1]==="K"){let n=0,r=e-1;for(;r>=0&&t[r]==="\\";)n++,r--;if(n%2===0)return e}e+=2}else e++;return-1}function I_(t){let e=0,n=0;for(;n<t.length;){if(t[n]==="\\"){n+=2;continue}if(t[n]==="["){for(n++;n<t.length&&t[n]!=="]";)t[n]==="\\"&&n++,n++;n++;continue}if(t[n]==="(")if(n+1<t.length&&t[n+1]==="?"){if(n+2<t.length){let r=t[n+2];if(r===":"||r==="="||r==="!"){n++;continue}if(r==="<"&&n+3<t.length){let s=t[n+3];if(s==="="||s==="!"){n++;continue}e++,n++;continue}}}else e++;n++}return e}function ed(t){let e=t.replace(/\$\{0\}|\$0(?![0-9])/g,"$$&");return e=e.replace(/\$\{([^0-9}][^}]*)\}/g,"$$<$1>"),e=e.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)(?![>0-9])/g,"$$<$1>"),e}function R_(t){let e="",n=0,r=!0,s=0;for(;n<t.length;){let i=t[n];if(i==="["){for(e+=i,n++,n<t.length&&(t[n]==="^"||t[n]==="!")&&(e+=t[n],n++),n<t.length&&t[n]==="]"&&(e+=t[n],n++);n<t.length&&t[n]!=="]";)t[n]==="\\"&&n+1<t.length?(e+=t[n]+t[n+1],n+=2):(e+=t[n],n++);n<t.length&&t[n]==="]"&&(e+=t[n],n++),r=!1;continue}if(i==="\\"&&n+1<t.length){let o=t[n+1];if(o==="|"){e+="|",n+=2,r=!0;continue}if(o==="("){e+="(",n+=2,s++,r=!0;continue}if(o===")"){e+=")",n+=2,s=Math.max(0,s-1),r=!1;continue}if(o==="{"){let l=t.slice(n).match(/^\\{(\d+)(,(\d*)?)?\\}/);if(l){let c=l[1],u=l[2]!==void 0,f=l[3]||"";u?e+=`{${c},${f}}`:e+=`{${c}}`,n+=l[0].length,r=!1;continue}e+="\\{",n+=2,r=!1;continue}if(o==="}"){e+="\\}",n+=2,r=!1;continue}e+=i+o,n+=2,r=!1;continue}if(i==="*"&&r){e+="\\*",n++;continue}if(i==="^"){if(r){e+="^",n++;continue}e+="\\^",n++;continue}if(i==="$"){let o=n===t.length-1,a=n+2<t.length&&t[n+1]==="\\"&&t[n+2]===")";o||a?e+="$":e+="\\$",n++,r=!1;continue}i==="+"||i==="?"||i==="|"||i==="("||i===")"||i==="{"||i==="}"?e+=`\\${i}`:e+=i,n++,r=!1}return e}var w_,x3=L(()=>{"use strict";$t();w_=new Map([["alpha","a-zA-Z"],["digit","0-9"],["alnum","a-zA-Z0-9"],["lower","a-z"],["upper","A-Z"],["xdigit","0-9A-Fa-f"],["space"," \\t\\n\\r\\f\\v"],["blank"," \\t"],["punct","!-/:-@\\[-`{-~"],["graph","!-~"],["print"," -~"],["cntrl","\\x00-\\x1F\\x7F"],["ascii","\\x00-\\x7F"],["word","a-zA-Z0-9_"]])});var Xg=L(()=>{"use strict";w3();x3()});var nd={};he(nd,{egrepCommand:()=>z_,egrepFlagsForFuzzing:()=>e0,fgrepCommand:()=>B_,fgrepFlagsForFuzzing:()=>Jg,flagsForFuzzing:()=>Qg,grepCommand:()=>Yg});function E3(t){let e=t.limits.maxLoopIterations,n=t.limits.maxArrayElements;return Math.max(e,Math.min(n,e*10))}function ds(t){if(++t.operations>t.maxOperations)throw new v(`grep: glob operation limit exceeded (${t.maxOperations})`,"glob_operations")}function Fc(t){if(t.results>=t.maxResults)throw new v(`grep: array element limit exceeded (${t.maxResults})`,"array_elements");t.results++}function L_(t){return t.split(`
|
|
203
203
|
`)}function F_(t){if(t==="")return[];let e=t.split(`
|
|
204
|
-
`);return e[e.length-1]===""&&e.pop(),e}function D_(t,e){return t.length===1?{pattern:t[0],mode:e}:e==="fixed"?{pattern:t.map(n=>`(?:${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})`).join("|"),mode:"extended"}:e==="basic"?{pattern:t.join("\\|"),mode:e}:{pattern:t.map(n=>`(?:${n})`).join("|"),mode:e}}async function A3(t,e,n,r,s,i=0){if(i>=S3)return;let o=n.fs.resolvePath(n.cwd,t);try{if(ds(s),!(await n.fs.stat(o)).isDirectory){let c=t.split("/").pop()||"";if(e){let u=e.replace(/^\//,"");fr(c,u,{stripQuotes:!0})&&(Fc(s),r.push(t))}return}ds(s);let l=await n.fs.readdir(o);for(let c of l){let u=t==="."?c:`${t}/${c}`,f=n.fs.resolvePath(n.cwd,u);if(ds(s),(await n.fs.stat(f)).isDirectory)await A3(u,e,n,r,s,i+1);else if(e){let h=e.replace(/^\//,"");fr(c,h,{stripQuotes:!0})&&(Fc(s),r.push(u))}}}catch(a){ke(a)}}async function M_(t,e,n){let r=[],s=t.lastIndexOf("/"),i,o;if(s===-1?(i=e.cwd,o=t):(i=t.slice(0,s)||"/",o=t.slice(s+1)),t.includes("**")){let l=[],c=t.split("**"),u=c[0].replace(/\/$/,"")||".",f=c[1]||"";return await A3(u,f,e,l,n),l.map(d=>({path:d}))}let a=e.fs.resolvePath(e.cwd,i);try{if(e.fs.readdirWithFileTypes){ds(n);let l=await e.fs.readdirWithFileTypes(a);for(let c of l)if(ds(n),fr(c.name,o,{stripQuotes:!0})){let u=s===-1?c.name:`${i}/${c.name}`;Fc(n),r.push({path:u,isFile:c.isFile})}}else{ds(n);let l=await e.fs.readdir(a);for(let c of l)if(ds(n),fr(c,o,{stripQuotes:!0})){let u=s===-1?c:`${i}/${c}`;Fc(n),r.push({path:u})}}}catch(l){ke(l)}return r.sort((l,c)=>l.path.localeCompare(c.path))}async function td(t,e,n=[],r=[],s=[],i,o={operations:0,results:0,maxOperations:e.limits.maxGlobOperations,maxResults:e.limits.maxArrayElements},a=[],l=0){if(l>=S3)return a;let c=e.fs.resolvePath(e.cwd,t);try{let u,f;if(i!==void 0)u=i,f=!i;else{ds(o);let h=await e.fs.stat(c);u=h.isFile,f=h.isDirectory}if(u){let h=t.split("/").pop()||t;return r.length>0&&r.some(p=>fr(h,p,{stripQuotes:!0}))||n.length>0&&!n.some(p=>fr(h,p,{stripQuotes:!0}))||(Fc(o),a.push({path:t,isFile:!0})),a}if(!f)return a;let d=t.split("/").pop()||t;if(s.length>0&&s.some(h=>fr(d,h,{stripQuotes:!0})))return a;if(e.fs.readdirWithFileTypes){ds(o);let h=await e.fs.readdirWithFileTypes(c);for(let p of h){if(ds(o),p.name.startsWith("."))continue;let m=t==="."?p.name:`${t}/${p.name}`;await td(m,e,n,r,s,p.isFile,o,a,l+1)}}else{ds(o);let h=await e.fs.readdir(c);for(let p of h){if(ds(o),p.startsWith("."))continue;let m=t==="."?p:`${t}/${p}`;await td(m,e,n,r,s,void 0,o,a,l+1)}}}catch(u){ke(u)}return a}var P_,$_,__,Yg,S3,B_,z_,Qg,Jg,e0,Dc=L(()=>{"use strict";pe();Kt();X();Zg();xe();Xg();P_="(standard input)";$_="[^\\s\\S]";__={name:"grep",summary:"print lines that match patterns",usage:"grep [OPTION]... PATTERN [FILE]...",description:["Search for PATTERN in each FILE.","With no FILE, or when FILE is -, read standard input."],options:["-E, --extended-regexp PATTERN is an extended regular expression","-P, --perl-regexp PATTERN is a Perl 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","-x, --line-regexp match only whole lines","-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","-m NUM, --max-count=NUM stop after NUM 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","-f FILE, --file=FILE obtain patterns from FILE, one per line"," --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"]},Yg={name:"grep",async execute(t,e){let n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!1,f=!1,d=!1,h=!1,p=!1,m=!1,g=!1,y=0,w=0,b=0,x=[],S=[],E=[],A=[],N=[],I=[],T=!0;for(let te=0;te<t.length;te++){let ne=t[te];if(T&&ne==="--"){T=!1;continue}if(T&&ne==="--help")return K(__);if(T&&ne.startsWith("-")&&ne!=="-"){if(ne==="-e"&&te+1<t.length){A.push(t[++te]);continue}if(ne.startsWith("--file=")){N.push(ne.slice(7));continue}if(ne.startsWith("--include=")){x.push(ne.slice(10));continue}if(ne.startsWith("--exclude=")){S.push(ne.slice(10));continue}if(ne.startsWith("--exclude-dir=")){E.push(ne.slice(14));continue}if(ne.startsWith("--max-count=")){y=parseInt(ne.slice(12),10);continue}let
|
|
204
|
+
`);return e[e.length-1]===""&&e.pop(),e}function D_(t,e){return t.length===1?{pattern:t[0],mode:e}:e==="fixed"?{pattern:t.map(n=>`(?:${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})`).join("|"),mode:"extended"}:e==="basic"?{pattern:t.join("\\|"),mode:e}:{pattern:t.map(n=>`(?:${n})`).join("|"),mode:e}}async function A3(t,e,n,r,s,i=0){if(i>=S3)return;let o=n.fs.resolvePath(n.cwd,t);try{if(ds(s),!(await n.fs.stat(o)).isDirectory){let c=t.split("/").pop()||"";if(e){let u=e.replace(/^\//,"");fr(c,u,{stripQuotes:!0})&&(Fc(s),r.push(t))}return}ds(s);let l=await n.fs.readdir(o);for(let c of l){let u=t==="."?c:`${t}/${c}`,f=n.fs.resolvePath(n.cwd,u);if(ds(s),(await n.fs.stat(f)).isDirectory)await A3(u,e,n,r,s,i+1);else if(e){let h=e.replace(/^\//,"");fr(c,h,{stripQuotes:!0})&&(Fc(s),r.push(u))}}}catch(a){ke(a)}}async function M_(t,e,n){let r=[],s=t.lastIndexOf("/"),i,o;if(s===-1?(i=e.cwd,o=t):(i=t.slice(0,s)||"/",o=t.slice(s+1)),t.includes("**")){let l=[],c=t.split("**"),u=c[0].replace(/\/$/,"")||".",f=c[1]||"";return await A3(u,f,e,l,n),l.map(d=>({path:d}))}let a=e.fs.resolvePath(e.cwd,i);try{if(e.fs.readdirWithFileTypes){ds(n);let l=await e.fs.readdirWithFileTypes(a);for(let c of l)if(ds(n),fr(c.name,o,{stripQuotes:!0})){let u=s===-1?c.name:`${i}/${c.name}`;Fc(n),r.push({path:u,isFile:c.isFile})}}else{ds(n);let l=await e.fs.readdir(a);for(let c of l)if(ds(n),fr(c,o,{stripQuotes:!0})){let u=s===-1?c:`${i}/${c}`;Fc(n),r.push({path:u})}}}catch(l){ke(l)}return r.sort((l,c)=>l.path.localeCompare(c.path))}async function td(t,e,n=[],r=[],s=[],i,o={operations:0,results:0,maxOperations:e.limits.maxGlobOperations,maxResults:e.limits.maxArrayElements},a=[],l=0){if(l>=S3)return a;let c=e.fs.resolvePath(e.cwd,t);try{let u,f;if(i!==void 0)u=i,f=!i;else{ds(o);let h=await e.fs.stat(c);u=h.isFile,f=h.isDirectory}if(u){let h=t.split("/").pop()||t;return r.length>0&&r.some(p=>fr(h,p,{stripQuotes:!0}))||n.length>0&&!n.some(p=>fr(h,p,{stripQuotes:!0}))||(Fc(o),a.push({path:t,isFile:!0})),a}if(!f)return a;let d=t.split("/").pop()||t;if(s.length>0&&s.some(h=>fr(d,h,{stripQuotes:!0})))return a;if(e.fs.readdirWithFileTypes){ds(o);let h=await e.fs.readdirWithFileTypes(c);for(let p of h){if(ds(o),p.name.startsWith("."))continue;let m=t==="."?p.name:`${t}/${p.name}`;await td(m,e,n,r,s,p.isFile,o,a,l+1)}}else{ds(o);let h=await e.fs.readdir(c);for(let p of h){if(ds(o),p.startsWith("."))continue;let m=t==="."?p:`${t}/${p}`;await td(m,e,n,r,s,void 0,o,a,l+1)}}}catch(u){ke(u)}return a}var P_,$_,__,Yg,S3,B_,z_,Qg,Jg,e0,Dc=L(()=>{"use strict";pe();Kt();X();Zg();xe();Xg();P_="(standard input)";$_="[^\\s\\S]";__={name:"grep",summary:"print lines that match patterns",usage:"grep [OPTION]... PATTERN [FILE]...",description:["Search for PATTERN in each FILE.","With no FILE, or when FILE is -, read standard input."],options:["-E, --extended-regexp PATTERN is an extended regular expression","-P, --perl-regexp PATTERN is a Perl 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","-x, --line-regexp match only whole lines","-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","-m NUM, --max-count=NUM stop after NUM 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","-f FILE, --file=FILE obtain patterns from FILE, one per line"," --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"]},Yg={name:"grep",async execute(t,e){let n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!1,f=!1,d=!1,h=!1,p=!1,m=!1,g=!1,y=0,w=0,b=0,x=[],S=[],E=[],A=[],N=[],I=[],T=!0;for(let te=0;te<t.length;te++){let ne=t[te];if(T&&ne==="--"){T=!1;continue}if(T&&ne==="--help")return K(__);if(T&&ne.startsWith("-")&&ne!=="-"){if(ne==="-e"&&te+1<t.length){A.push(t[++te]);continue}if(ne.startsWith("--file=")){N.push(ne.slice(7));continue}if(ne.startsWith("--include=")){x.push(ne.slice(10));continue}if(ne.startsWith("--exclude=")){S.push(ne.slice(10));continue}if(ne.startsWith("--exclude-dir=")){E.push(ne.slice(14));continue}if(ne.startsWith("--max-count=")){y=parseInt(ne.slice(12),10);continue}let Oe=ne.match(/^-m(\d+)$/);if(Oe){y=parseInt(Oe[1],10);continue}if(ne==="-m"&&te+1<t.length){y=parseInt(t[++te],10);continue}let ye=ne.match(/^-([ABC])(\d+)$/);if(ye){let Ae=parseInt(ye[2],10);ye[1]==="A"?b=Ae:ye[1]==="B"?w=Ae:ye[1]==="C"&&(w=Ae,b=Ae);continue}if((ne==="-A"||ne==="-B"||ne==="-C")&&te+1<t.length){let Ae=parseInt(t[++te],10);ne==="-A"?b=Ae:ne==="-B"?w=Ae:(w=Ae,b=Ae);continue}let Le=ne.startsWith("--")?[ne]:ne.slice(1).split("");for(let Ae=0;Ae<Le.length;Ae++){let ve=Le[Ae];if(ve==="f"||ve==="--file"){let ln=ve==="f"?Le.slice(Ae+1).join(""):"";if(ln.length>0)N.push(ln);else if(te+1<t.length)N.push(t[++te]);else return{stdout:"",stderr:ve==="f"?`grep: option requires an argument -- 'f'
|
|
205
205
|
`:`grep: option '--file' requires an argument
|
|
206
|
-
`,exitCode:2};break}if(
|
|
206
|
+
`,exitCode:2};break}if(ve==="i"||ve==="--ignore-case")n=!0;else if(ve==="n"||ve==="--line-number")r=!0;else if(ve==="v"||ve==="--invert-match")s=!0;else if(ve==="c"||ve==="--count")i=!0;else if(ve==="l"||ve==="--files-with-matches")o=!0;else if(ve==="L"||ve==="--files-without-match")a=!0;else if(ve==="r"||ve==="R"||ve==="--recursive")l=!0;else if(ve==="w"||ve==="--word-regexp")c=!0;else if(ve==="x"||ve==="--line-regexp")u=!0;else if(ve==="E"||ve==="--extended-regexp")f=!0;else if(ve==="P"||ve==="--perl-regexp")d=!0;else if(ve==="F"||ve==="--fixed-strings")h=!0;else if(ve==="o"||ve==="--only-matching")p=!0;else if(ve==="h"||ve==="--no-filename")m=!0;else if(ve==="q"||ve==="--quiet"||ve==="--silent")g=!0;else{if(ve.startsWith("--"))return ae("grep",ve);if(ve.length===1)return ae("grep",`-${ve}`)}}}else I.push(ne)}if(A.length===0&&N.length===0){let te=I.shift();if(te===void 0)return{stdout:"",stderr:`grep: missing pattern
|
|
207
207
|
`,exitCode:2};A.push(te)}A=A.flatMap(L_);let $=!1;for(let te of N){let ne;if(te==="")return{stdout:"",stderr:`grep: : No such file or directory
|
|
208
208
|
`,exitCode:2};if(te==="-")ne=$?"":fe(e.stdin),$=!0;else try{let ye=e.fs.resolvePath(e.cwd,te);if((await e.fs.stat(ye)).isDirectory)return{stdout:"",stderr:`grep: ${te}: Is a directory
|
|
209
209
|
`,exitCode:2};ne=await e.fs.readFile(ye)}catch(ye){return ke(ye),{stdout:"",stderr:`grep: ${te}: No such file or directory
|
|
210
|
-
`,exitCode:2}}let
|
|
210
|
+
`,exitCode:2}}let Oe=F_(ne);if(A.length+Oe.length>e.limits.maxArrayElements)throw new v(`grep: array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");A.push(...Oe)}if(A.length===0&&!s&&!a)return{stdout:"",stderr:"",exitCode:1};let C=I,O=h?"fixed":f?"extended":d?"perl":"basic";if(O==="perl"&&new Set(A).size>1)return{stdout:"",stderr:`grep: the -P option only supports a single pattern
|
|
211
211
|
`,exitCode:2};if(A.length>1&&O!=="fixed")for(let te of A)try{ol(te,{mode:O})}catch{return{stdout:"",stderr:`grep: invalid regular expression: ${te}
|
|
212
212
|
`,exitCode:2}}let F=A.length===0?{pattern:$_,mode:"extended"}:D_(A,O),R,_,U;try{let te=ol(F.pattern,{mode:F.mode,ignoreCase:n,wholeWord:c,lineRegexp:u});R=te.regex,_=te.kResetGroup,U=te.preFilter}catch{return{stdout:"",stderr:`grep: invalid regular expression: ${A.join(`
|
|
213
213
|
`)}
|
|
214
214
|
`,exitCode:2}}if(C.length===0&&e.stdin!==void 0){let te=$?"":fe(e.stdin),ne=na(te,R,{invertMatch:s,showLineNumbers:r,countOnly:i,filename:"",onlyMatching:p,beforeContext:w,afterContext:b,maxCount:y,kResetGroup:_,preFilter:U,maxWork:E3(e),maxMatches:e.limits.maxArrayElements,signal:e.signal});return g?{stdout:"",stderr:"",exitCode:ne.matched?0:1}:{stdout:ne.output,stderr:"",exitCode:ne.matched?0:1}}if(C.length===0)return{stdout:"",stderr:`grep: no input files
|
|
215
|
-
`,exitCode:2};let B="",W="",M=!1,Y=!1,q=[],H={operations:0,results:0,maxOperations:e.limits.maxGlobOperations,maxResults:e.limits.maxArrayElements},re=te=>{if(te.length>H.maxResults-q.length)throw new v(`grep: array element limit exceeded (${H.maxResults})`,"array_elements");q.push(...te)},se=!1,de=!1;for(let te of C){if(te==="-"){if(q.length>=H.maxResults)throw new v(`grep: array element limit exceeded (${H.maxResults})`,"array_elements");q.push({path:P_,isFile:!0,isStdin:!0,stdinAtEof:se}),se=!0;continue}if(de=!0,te.includes("*")||te.includes("?")||te.includes("[")){let ne=await M_(te,e,H);if(l)for(let
|
|
216
|
-
`,isDirectory:!0};
|
|
217
|
-
`,matched:!1,matchCount:0}}}return{file:Le,result:{output:"",matched:!1,matchCount:0}}}}let ln=na(
|
|
218
|
-
`,isDirectory:!1}}}));for(let ye of
|
|
219
|
-
`:a||(B+=
|
|
220
|
-
`:i&&!o&&(B+=
|
|
215
|
+
`,exitCode:2};let B="",W="",M=!1,Y=!1,q=[],H={operations:0,results:0,maxOperations:e.limits.maxGlobOperations,maxResults:e.limits.maxArrayElements},re=te=>{if(te.length>H.maxResults-q.length)throw new v(`grep: array element limit exceeded (${H.maxResults})`,"array_elements");q.push(...te)},se=!1,de=!1;for(let te of C){if(te==="-"){if(q.length>=H.maxResults)throw new v(`grep: array element limit exceeded (${H.maxResults})`,"array_elements");q.push({path:P_,isFile:!0,isStdin:!0,stdinAtEof:se}),se=!0;continue}if(de=!0,te.includes("*")||te.includes("?")||te.includes("[")){let ne=await M_(te,e,H);if(l)for(let Oe of ne){let ye=await td(Oe.path,e,x,S,E,Oe.isFile,H);re(ye)}else re(ne)}else if(l){let ne=await td(te,e,x,S,E,void 0,H);re(ne)}else{if(q.length>=H.maxResults)throw new v(`grep: array element limit exceeded (${H.maxResults})`,"array_elements");q.push({path:te})}}let Ie=(q.length>1||l&&de)&&!m,oe=50;for(let te=0;te<q.length;te+=oe){let ne=q.slice(te,te+oe),Oe=await Promise.all(ne.map(async ye=>{let Le=ye.path,Ae=Le.split("/").pop()||Le;if(S.length>0&&!l&&!ye.isStdin&&S.some(ve=>fr(Ae,ve,{stripQuotes:!0}))||x.length>0&&!l&&!ye.isStdin&&!x.some(ve=>fr(Ae,ve,{stripQuotes:!0})))return null;try{let ve;if(ye.isStdin)ve=ye.stdinAtEof||e.stdin===void 0?"":fe(e.stdin);else{let Te=e.fs.resolvePath(e.cwd,Le),Ne=!1;if(ye.isFile===void 0?Ne=(await e.fs.stat(Te)).isDirectory:Ne=!ye.isFile,Ne)return l?null:{error:`grep: ${Le}: Is a directory
|
|
216
|
+
`,isDirectory:!0};ve=await e.fs.readFile(Te)}if(U&&!s){let Te=U.ignoreCase?ve.toLowerCase():ve;if(!U.needles.some(Ne=>Te.includes(Ne))){if(i){let Ne=Ie?`${Le}:0`:"0";return{file:Le,result:{output:`${Ne}
|
|
217
|
+
`,matched:!1,matchCount:0}}}return{file:Le,result:{output:"",matched:!1,matchCount:0}}}}let ln=na(ve,R,{invertMatch:s,showLineNumbers:r,countOnly:i,filename:Ie?Le:"",onlyMatching:p,beforeContext:w,afterContext:b,maxCount:y,kResetGroup:_,preFilter:U,maxWork:E3(e),maxMatches:e.limits.maxArrayElements,signal:e.signal});return{file:Le,result:ln}}catch(ve){return ke(ve),{error:`grep: ${Le}: No such file or directory
|
|
218
|
+
`,isDirectory:!1}}}));for(let ye of Oe){if(ye===null)continue;if("error"in ye&&ye.error){W+=ye.error,ye.isDirectory||(Y=!0);continue}if(!("file"in ye)||!ye.result)continue;let{file:Le,result:Ae}=ye;if(Ae.matched){if(M=!0,g)return{stdout:"",stderr:"",exitCode:0};o?B+=`${Le}
|
|
219
|
+
`:a||(B+=Ae.output)}else a?B+=`${Le}
|
|
220
|
+
`:i&&!o&&(B+=Ae.output)}}let Se;return Y?Se=2:Se=M?0:1,g?{stdout:"",stderr:"",exitCode:Se}:{stdout:B,stderr:W,exitCode:Se}}},S3=256;B_={name:"fgrep",async execute(t,e){return Yg.execute(["-F",...t],e)}},z_={name:"egrep",async execute(t,e){return Yg.execute(["-E",...t],e)}},Qg={name:"grep",flags:[{flag:"-E",type:"boolean"},{flag:"-F",type:"boolean"},{flag:"-P",type:"boolean"},{flag:"-i",type:"boolean"},{flag:"-v",type:"boolean"},{flag:"-w",type:"boolean"},{flag:"-x",type:"boolean"},{flag:"-c",type:"boolean"},{flag:"-l",type:"boolean"},{flag:"-L",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-h",type:"boolean"},{flag:"-o",type:"boolean"},{flag:"-q",type:"boolean"},{flag:"-r",type:"boolean"},{flag:"-m",type:"value",valueHint:"number"},{flag:"-A",type:"value",valueHint:"number"},{flag:"-B",type:"value",valueHint:"number"},{flag:"-C",type:"value",valueHint:"number"},{flag:"-e",type:"value",valueHint:"pattern"},{flag:"-f",type:"value",valueHint:"path"}],stdinType:"text",needsArgs:!0},Jg={name:"fgrep",flags:[],stdinType:"text",needsArgs:!0},e0={name:"egrep",flags:[],stdinType:"text",needsArgs:!0}});function C3(t,e){if(Array.isArray(t))throw new TypeError(`${e}: expected object, got array`);if(Object.getPrototypeOf(t)!==null)throw new TypeError(`${e}: expected null-prototype object, got prototypal object`)}function ht(t){return!v3.has(t)}function Et(t,e,n){C3(t,"safeSet"),ht(e)&&(t[e]=n)}function ra(t,e){return C3(t,"safeHasOwn"),Object.hasOwn(t,e)}function Nr(t,e={}){let n=e.maxDepth??2e3,r=e.maxElements??1e6,s=new WeakMap,i=e.elementBudget??{used:0};if(!Number.isSafeInteger(i.used)||i.used<0||i.used>r)throw new v(`query input element limit exceeded (${r})`,"array_elements");let o=()=>{if(++i.used>r)throw new v(`query input element limit exceeded (${r})`,"array_elements")},a=(u,f,d)=>{if(u===null||typeof u!="object"||u instanceof Date)return u;let h=s.get(u);if(h!==void 0)return h;if(f>n)throw new v(`query depth limit exceeded (${n})`,"recursion");let p=Array.isArray(u)?[]:Object.create(null);return s.set(u,p),d.push({source:u,target:p,depth:f}),p},l=[],c=a(t,0,l);for(;l.length>0;){let u=l.pop();if(!u)break;let{source:f,target:d,depth:h}=u;if(Array.isArray(f)&&Array.isArray(d)){if(f.length>r-i.used)throw new v(`query input element limit exceeded (${r})`,"array_elements");d.length=f.length;for(let y=f.length-1;y>=0;y--)o(),d[y]=a(f[y],h+1,l);continue}let p=f,m=d,g=Object.keys(p);if(g.length>r-i.used)throw new v(`query input element limit exceeded (${r})`,"array_elements");for(let y=0;y<g.length;y++){o();let w=g[y];m[w]=a(p[w],h+1,l)}}return c}function St(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function rd(t){return Object.assign(Object.create(null),t)}function Jt(t){return Object.assign(Object.create(null),t)}function t0(...t){return Object.assign(Object.create(null),...t)}var v3,moe,dr=L(()=>{"use strict";X();v3=new Set(["__proto__","constructor","prototype"]),moe=new Set([...v3,"__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"])});function N3(){let t=[];for(let[e,n]of Object.entries(k3).sort()){let r=[];for(let s of n.extensions)r.push(`*${s}`);for(let s of n.globs)r.push(s);t.push(`${e}: ${r.join(", ")}`)}return`${t.join(`
|
|
221
221
|
`)}
|
|
222
222
|
`}var k3,_c,n0=L(()=>{"use strict";$t();dr();k3=rd({js:{extensions:[".js",".mjs",".cjs",".jsx"],globs:[]},ts:{extensions:[".ts",".tsx",".mts",".cts"],globs:[]},html:{extensions:[".html",".htm",".xhtml"],globs:[]},css:{extensions:[".css",".scss",".sass",".less"],globs:[]},json:{extensions:[".json",".jsonc",".json5"],globs:[]},xml:{extensions:[".xml",".xsl",".xslt"],globs:[]},c:{extensions:[".c",".h"],globs:[]},cpp:{extensions:[".cpp",".cc",".cxx",".hpp",".hh",".hxx",".h"],globs:[]},rust:{extensions:[".rs"],globs:[]},go:{extensions:[".go"],globs:[]},zig:{extensions:[".zig"],globs:[]},java:{extensions:[".java"],globs:[]},kotlin:{extensions:[".kt",".kts"],globs:[]},scala:{extensions:[".scala",".sc"],globs:[]},clojure:{extensions:[".clj",".cljc",".cljs",".edn"],globs:[]},py:{extensions:[".py",".pyi",".pyw"],globs:[]},rb:{extensions:[".rb",".rake",".gemspec"],globs:["Rakefile","Gemfile"]},php:{extensions:[".php",".phtml",".php3",".php4",".php5"],globs:[]},perl:{extensions:[".pl",".pm",".pod",".t"],globs:[]},lua:{extensions:[".lua"],globs:[]},sh:{extensions:[".sh",".bash",".zsh",".fish"],globs:[".bashrc",".zshrc",".profile"]},bat:{extensions:[".bat",".cmd"],globs:[]},ps:{extensions:[".ps1",".psm1",".psd1"],globs:[]},yaml:{extensions:[".yaml",".yml"],globs:[]},toml:{extensions:[".toml"],globs:["Cargo.toml","pyproject.toml"]},ini:{extensions:[".ini",".cfg",".conf"],globs:[]},csv:{extensions:[".csv",".tsv"],globs:[]},md:{extensions:[".md",".mdx",".markdown",".mdown",".mkd"],globs:[]},markdown:{extensions:[".md",".mdx",".markdown",".mdown",".mkd"],globs:[]},rst:{extensions:[".rst"],globs:[]},txt:{extensions:[".txt",".text"],globs:[]},tex:{extensions:[".tex",".ltx",".sty",".cls"],globs:[]},sql:{extensions:[".sql"],globs:[]},graphql:{extensions:[".graphql",".gql"],globs:[]},proto:{extensions:[".proto"],globs:[]},make:{extensions:[".mk",".mak"],globs:["Makefile","GNUmakefile","makefile"]},docker:{extensions:[],globs:["Dockerfile","Dockerfile.*","*.dockerfile"]},tf:{extensions:[".tf",".tfvars"],globs:[]}}),_c=class{types;constructor(){this.types=new Map(Object.entries(k3).map(([e,n])=>[e,{extensions:[...n.extensions],globs:[...n.globs]}]))}addType(e){let n=e.indexOf(":");if(n===-1)return;let r=e.slice(0,n),s=e.slice(n+1);if(s.startsWith("include:")){let i=s.slice(8),o=this.types.get(i);if(o){let a=this.types.get(r)||{extensions:[],globs:[]};a.extensions.push(...o.extensions),a.globs.push(...o.globs),this.types.set(r,a)}}else{let i=this.types.get(r)||{extensions:[],globs:[]};if(s.startsWith("*.")&&!s.slice(2).includes("*")){let o=s.slice(1);i.extensions.includes(o)||i.extensions.push(o)}else i.globs.includes(s)||i.globs.push(s);this.types.set(r,i)}}clearType(e){let n=this.types.get(e);n&&(n.extensions=[],n.globs=[])}getType(e){return this.types.get(e)}getAllTypes(){return this.types}matchesType(e,n){let r=e.toLowerCase();for(let s of n){if(s==="all"){if(this.matchesAnyType(e))return!0;continue}let i=this.types.get(s);if(i){for(let o of i.extensions)if(r.endsWith(o))return!0;for(let o of i.globs)if(o.includes("*")){let a=o.replace(/\./g,"\\.").replace(/\*/g,".*");if(le(`^${a}$`,"i").test(e))return!0}else if(r===o.toLowerCase())return!0}}return!1}matchesAnyType(e){let n=e.toLowerCase();for(let r of this.types.values()){for(let s of r.extensions)if(n.endsWith(s))return!0;for(let s of r.globs)if(s.includes("*")){let i=s.replace(/\./g,"\\.").replace(/\*/g,".*");if(le(`^${i}$`,"i").test(e))return!0}else if(n===s.toLowerCase())return!0}return!1}}});function T3(){return{ignoreCase:!1,caseSensitive:!1,smartCase:!0,fixedStrings:!1,wordRegexp:!1,lineRegexp:!1,invertMatch:!1,multiline:!1,multilineDotall:!1,patterns:[],patternFiles:[],count:!1,countMatches:!1,files:!1,filesWithMatches:!1,filesWithoutMatch:!1,stats:!1,onlyMatching:!1,maxCount:0,lineNumber:!0,noFilename:!1,withFilename:!1,nullSeparator:!1,byteOffset:!1,column:!1,vimgrep:!1,replace:null,afterContext:0,beforeContext:0,contextSeparator:"--",quiet:!1,heading:!1,passthru:!1,includeZero:!1,sort:"path",json:!1,globs:[],iglobs:[],globCaseInsensitive:!1,types:[],typesNot:[],typeAdd:[],typeClear:[],hidden:!1,noIgnore:!1,noIgnoreDot:!1,noIgnoreVcs:!1,ignoreFiles:[],maxDepth:256,maxFilesize:512*1024*1024,followSymlinks:!1,searchZip:!1,searchBinary:!1,preprocessor:null,preprocessorGlobs:[]}}var O3=L(()=>{"use strict"});function U_(t){let e=t.match(/^(\d+)([KMG])?$/i);if(!e)return 0;let n=parseInt(e[1],10);switch((e[2]||"").toUpperCase()){case"K":return n*1024;case"M":return n*1024*1024;case"G":return n*1024*1024*1024;default:return n}}function W_(t){return/^\d+[KMG]?$/i.test(t)?null:{stdout:"",stderr:`rg: invalid --max-filesize value: ${t}
|
|
223
223
|
`,exitCode:1}}function j_(t,e){return!/^\d+$/.test(e)||!Number.isSafeInteger(Number(e))?{stdout:"",stderr:`rg: invalid --${t} value: ${e}
|
|
@@ -251,7 +251,7 @@ EXAMPLES:
|
|
|
251
251
|
rg -g '*.ts' foo Search files matching glob
|
|
252
252
|
rg --hidden foo Include hidden files
|
|
253
253
|
rg -l foo List files with matches only`,options:["-e, --regexp PATTERN search for PATTERN (can be used multiple times)","-f, --file FILE read patterns from FILE, one per line","-i, --ignore-case case-insensitive search","-s, --case-sensitive case-sensitive search (overrides smart-case)","-S, --smart-case smart case (default: case-insensitive unless pattern has uppercase)","-F, --fixed-strings treat pattern as literal string","-w, --word-regexp match whole words only","-x, --line-regexp match whole lines only","-v, --invert-match select non-matching lines","-r, --replace TEXT replace matches with TEXT","-c, --count print count of matching lines per file"," --count-matches print count of individual matches per file","-l, --files-with-matches print only file names with matches"," --files-without-match print file names without matches"," --files list files that would be searched","-o, --only-matching print only matching parts","-m, --max-count NUM stop after NUM matches per file","-q, --quiet suppress output, exit 0 on match"," --stats print search statistics","-n, --line-number print line numbers (default: on)","-N, --no-line-number do not print line numbers","-I, --no-filename suppress the prefixing of file names","-0, --null use NUL as filename separator","-b, --byte-offset show byte offset of each match"," --column show column number of first match"," --vimgrep show results in vimgrep format"," --json show results in JSON Lines format","-A NUM print NUM lines after each match","-B NUM print NUM lines before each match","-C NUM print NUM lines before and after each match"," --context-separator SEP separator for context groups (default: --)","-U, --multiline match patterns across lines","-z, --search-zip search in compressed files (gzip only)","-g, --glob GLOB include files matching GLOB","-t, --type TYPE only search files of TYPE (e.g., js, py, ts)","-T, --type-not TYPE exclude files of TYPE","-L, --follow follow symbolic links","-u, --unrestricted reduce filtering (-u: no ignore, -uu: +hidden, -uuu: +binary)","-a, --text search binary files as text"," --hidden search hidden files and directories"," --no-ignore don't respect .gitignore/.ignore files","-d, --max-depth NUM maximum search depth"," --sort TYPE sort files (path, none)"," --heading show file path above matches"," --passthru print all lines (non-matches use - separator)"," --include-zero include files with 0 matches in count output"," --type-list list all available file types"," --help display this help and exit"]},uM={handlesOwnVersion:!0,name:"rg",async execute(t,e){if(Z(t))return K(cM);if(t.includes("--version")||t.includes("-V"))return{stdout:`rg (just-bash)
|
|
254
|
-
`,stderr:"",exitCode:0};if(t.includes("--type-list"))return{stdout:N3(),stderr:"",exitCode:0};let n=P3(t);return n.success?M3({ctx:e,options:n.options,paths:n.paths,explicitLineNumbers:n.explicitLineNumbers}):n.error}},s0={name:"rg",flags:[{flag:"-i",type:"boolean"},{flag:"-s",type:"boolean"},{flag:"-S",type:"boolean"},{flag:"-F",type:"boolean"},{flag:"-w",type:"boolean"},{flag:"-x",type:"boolean"},{flag:"-v",type:"boolean"},{flag:"-c",type:"boolean"},{flag:"-l",type:"boolean"},{flag:"-o",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-N",type:"boolean"},{flag:"--hidden",type:"boolean"},{flag:"--no-ignore",type:"boolean"},{flag:"-m",type:"value",valueHint:"number"},{flag:"-A",type:"value",valueHint:"number"},{flag:"-B",type:"value",valueHint:"number"},{flag:"-C",type:"value",valueHint:"number"},{flag:"-g",type:"value",valueHint:"pattern"},{flag:"-t",type:"value",valueHint:"string"},{flag:"-T",type:"value",valueHint:"string"}],needsArgs:!0}});function Vt(t,e,n){if(!t||
|
|
254
|
+
`,stderr:"",exitCode:0};if(t.includes("--type-list"))return{stdout:N3(),stderr:"",exitCode:0};let n=P3(t);return n.success?M3({ctx:e,options:n.options,paths:n.paths,explicitLineNumbers:n.explicitLineNumbers}):n.error}},s0={name:"rg",flags:[{flag:"-i",type:"boolean"},{flag:"-s",type:"boolean"},{flag:"-S",type:"boolean"},{flag:"-F",type:"boolean"},{flag:"-w",type:"boolean"},{flag:"-x",type:"boolean"},{flag:"-v",type:"boolean"},{flag:"-c",type:"boolean"},{flag:"-l",type:"boolean"},{flag:"-o",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-N",type:"boolean"},{flag:"--hidden",type:"boolean"},{flag:"--no-ignore",type:"boolean"},{flag:"-m",type:"value",valueHint:"number"},{flag:"-A",type:"value",valueHint:"number"},{flag:"-B",type:"value",valueHint:"number"},{flag:"-C",type:"value",valueHint:"number"},{flag:"-g",type:"value",valueHint:"pattern"},{flag:"-t",type:"value",valueHint:"string"},{flag:"-T",type:"value",valueHint:"string"}],needsArgs:!0}});function Vt(t,e,n){if(!t||nt.isInSandboxedContext())return;let r=`${e} ${n} attempted outside defense context`;throw new Re(r,{timestamp:Date.now(),type:"missing_defense_context",message:r,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:nt.getCurrentExecutionId()})}async function Wn(t,e,n,r){Vt(t,e,`${n} (pre-await)`);let s=await r();return Vt(t,e,`${n} (post-await)`),s}function li(t,e,n,r){let s=((...i)=>(Vt(t,e,n),r(...i)));return t?nt.bindCurrentContext(s):s}var Zr=L(()=>{"use strict";cn()});function a0(t){let e="",n=0,r=!1;for(;n<t.length;){if(t[n]==="["&&!r){if(t[n+1]==="["&&t[n+2]===":"){let s=t.indexOf(":]]",n+3);if(s!==-1){let i=t.slice(n+3,s),o=o0.get(i);if(o){e+=`[${o}]`,n=s+3;continue}}}if(t[n+1]==="^"&&t[n+2]==="["&&t[n+3]===":"){let s=t.indexOf(":]]",n+4);if(s!==-1){let i=t.slice(n+4,s),o=o0.get(i);if(o){e+=`[^${o}]`,n=s+3;continue}}}e+="[",n++,r=!0,n<t.length&&t[n]==="^"&&(e+="^",n++),n<t.length&&t[n]==="]"&&(e+="\\]",n++);continue}if(r){if(t[n]==="]"){e+="]",n++,r=!1;continue}if(t[n]==="["&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){let i=t.slice(n+2,s),o=o0.get(i);if(o){e+=o,n=s+2;continue}}}if(t[n]==="\\"&&n+1<t.length){e+=t[n]+t[n+1],n+=2;continue}e+=t[n],n++;continue}if(t[n]==="\\"&&n+1<t.length){let s=t[n+1];if(s==="+"||s==="?"||s==="|"){e+=s,n+=2;continue}if(s==="("||s===")"){e+=s,n+=2;continue}if(s==="{"||s==="}"){e+=s,n+=2;continue}if(s==="t"){e+=" ",n+=2;continue}if(s==="n"){e+=`
|
|
255
255
|
`,n+=2;continue}if(s==="r"){e+="\r",n+=2;continue}e+=t[n]+s,n+=2;continue}if(t[n]==="+"||t[n]==="?"||t[n]==="|"||t[n]==="("||t[n]===")"){e+=`\\${t[n]}`,n++;continue}if(t[n]==="^"&&!(e===""||e.endsWith("("))){e+="\\^",n++;continue}if(t[n]==="$"){let s=n===t.length-1,i=n+2<t.length&&t[n+1]==="\\"&&t[n+2]===")";if(!s&&!i){e+="\\$",n++;continue}}e+=t[n],n++}return e}function l0(t){let e="",n=!1;for(let r=0;r<t.length;r++)t[r]==="["&&!n?(n=!0,e+="[",r++,r<t.length&&t[r]==="^"&&(e+="^",r++),r<t.length&&t[r]==="]"&&(e+="]",r++),r--):t[r]==="]"&&n?(n=!1,e+="]"):!n&&t[r]==="{"&&t[r+1]===","?(e+="{0,",r++):e+=t[r];return e}function q3(t){let e="";for(let n=0;n<t.length;n++){let r=t[n],s=r.charCodeAt(0);r==="\\"?e+="\\\\":r===" "?e+="\\t":r===`
|
|
256
256
|
`?e+=`$
|
|
257
257
|
`:r==="\r"?e+="\\r":r==="\x07"?e+="\\a":r==="\b"?e+="\\b":r==="\f"?e+="\\f":r==="\v"?e+="\\v":s<32||s>=127?e+=`\\${s.toString(8).padStart(3,"0")}`:e+=r}return`${e}$`}var o0,V3=L(()=>{"use strict";o0=new Map([["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 G3(t,e,n){return{patternSpace:"",holdSpace:"",lineNumber:0,totalLines:t,deleted:!1,printed:!1,quit:!1,quitSilent:!1,exitCode:void 0,errorMessage:void 0,appendBuffer:[],substitutionMade:!1,lineNumberOutput:[],nCommandOutput:[],restartCycle:!1,inDRestartedCycle:!1,currentFilename:e,pendingFileReads:[],pendingFileWrites:[],rangeStates:n||new Map,linesConsumedInCycle:0}}function dM(t){return typeof t=="object"&&"first"in t&&"step"in t}function hM(t){return typeof t=="object"&&"offset"in t}function al(t,e,n,r,s){if(t==="$")return e===n;if(typeof t=="number")return e===t;if(dM(t)){let{first:i,step:o}=t;return o===0?e===i:(e-i)%o===0&&e>=i}if(typeof t=="object"&&"pattern"in t)try{let i=t.pattern;i===""&&s?.lastPattern?i=s.lastPattern:i!==""&&s&&(s.lastPattern=i);let o=l0(a0(i));return le(o).test(r)}catch{return!1}return!1}function c0(t){let e=n=>n===void 0?"undefined":n==="$"?"$":typeof n=="number"?String(n):"pattern"in n?`/${n.pattern}/`:"first"in n?`${n.first}~${n.step}`:"unknown";return`${e(t.start)},${e(t.end)}`}function pM(t,e,n,r,s,i){if(!t||!t.start&&!t.end)return!0;let o=t.start,a=t.end;if(o!==void 0&&a===void 0)return al(o,e,n,r,i);if(o!==void 0&&a!==void 0){let l=typeof o=="object"&&"pattern"in o,c=typeof a=="object"&&"pattern"in a,u=hM(a);if(u&&s){let d=c0(t),h=s.get(d);if(h||(h={active:!1},s.set(d,h)),h.active){let p=h.startLine||e;return e>=p+a.offset&&(h.active=!1,s.set(d,h)),!0}else return al(o,e,n,r,i)?(h.active=!0,h.startLine=e,s.set(d,h),a.offset===0&&(h.active=!1,s.set(d,h)),!0):!1}if(!l&&!c&&!u){let d=typeof o=="number"?o:o==="$"?n:1,h=typeof a=="number"?a:n;if(d<=h)return e>=d&&e<=h;if(s){let p=c0(t),m=s.get(p);return m||(m={active:!1},s.set(p,m)),!m.completed&&e>=d?(m.completed=!0,s.set(p,m),!0):!1}return!1}if(s){let d=c0(t),h=s.get(d);if(h||(h={active:!1},s.set(d,h)),h.active)return al(a,e,n,r,i)&&(h.active=!1,typeof o=="number"&&(h.completed=!0),s.set(d,h)),!0;{if(h.completed)return!1;let p=!1;return typeof o=="number"?p=e>=o:p=al(o,e,n,r,i),p?(h.active=!0,h.startLine=e,s.set(d,h),al(a,e,n,r,i)&&(h.active=!1,typeof o=="number"&&(h.completed=!0),s.set(d,h)),!0):!1}}return al(o,e,n,r,i)}return!0}function sa(t,e,n,r,s,i){let o=pM(t,e,n,r,s,i);return t?.negated?!o:o}function mM(t,e,n,r){let s="",i=0,o=!1;for(;i<=t.length;){e.lastIndex=i;let a=e.exec(t);if(!a){s+=t.slice(i);break}if(a.index!==i){s+=t.slice(i,a.index),i=a.index,o=!1;continue}let l=a[0],c=a.slice(1);if(o&&l.length===0){if(i<t.length)s+=t[i],i++;else break;o=!1;continue}if(s+=r(l,c),o=!1,l.length===0)if(i<t.length)s+=t[i],i++;else break;else i+=l.length,o=!0}return s}function u0(t,e,n){let r="",s=0;for(;s<t.length;){if(t[s]==="\\"&&s+1<t.length){let i=t[s+1];if(i==="&"){r+="&",s+=2;continue}if(i==="n"){r+=`
|
|
@@ -473,7 +473,7 @@ Try 'comm --help' for more information.
|
|
|
473
473
|
`};n.tabStops=a,s++}else if(o==="--tabs"&&s+1<t.length){let a=bd(t[s+1]);if(!a)return{exitCode:1,stdout:"",stderr:`unexpand: invalid tab size: '${t[s+1]}'
|
|
474
474
|
`};n.tabStops=a,s+=2}else if(o.startsWith("--tabs=")){let a=bd(o.slice(7));if(!a)return{exitCode:1,stdout:"",stderr:`unexpand: invalid tab size: '${o.slice(7)}'
|
|
475
475
|
`};n.tabStops=a,s++}else if(o==="-a"||o==="--all")n.allBlanks=!0,s++;else if(o==="--"){r.push(...t.slice(s+1));break}else{if(o.startsWith("-")&&o!=="-")return ae("unexpand",o);r.push(o),s++}}let i="";if(r.length===0){let o=fe(e.stdin)??"";i=s8(o,n)}else for(let o of r){let a=e.fs.resolvePath(e.cwd,o),l=await e.fs.readFile(a);if(l===null)return{exitCode:1,stdout:i,stderr:`unexpand: ${o}: No such file or directory
|
|
476
|
-
`};i+=s8(l,n)}return{exitCode:0,stdout:i,stderr:""}}},Y0={name:"unexpand",flags:[{flag:"-t",type:"value",valueHint:"number"},{flag:"-a",type:"boolean"}],stdinType:"text",needsFiles:!0}});var l8={};he(l8,{flagsForFuzzing:()=>J0,strings:()=>gz});function mz(t){return t>=32&&t<=126||t===9}function o8(t,e){if(e===null)return"";switch(e){case"o":return`${t.toString(8).padStart(7," ")} `;case"x":return`${t.toString(16).padStart(7," ")} `;case"d":return`${t.toString(10).padStart(7," ")} `;default:return e}}function a8(t,e,n,r=!1,s){let i=[],o=0,a=0,l=typeof t=="string"&&!r?new TextEncoder().encode(t):t;if(l.length>n.maxStringLength-n.inputBytes)throw new v(`strings: aggregate input size limit exceeded (${n.maxStringLength} bytes)`,"string_length");n.inputBytes+=l.length;let c=new TextDecoder,u=(d,h)=>typeof l=="string"?l.slice(d,h):c.decode(l.subarray(d,h)),f=d=>{if(++n.iterations>n.maxIterations)throw new v(`strings: iteration limit exceeded (${n.maxIterations})`,"iterations");if(n.resultCount>=n.maxArrayElements)throw new v(`strings: array element limit exceeded (${n.maxArrayElements})`,"array_elements");let h=d.length+1;if(h>n.maxOutputSize-n.outputBytes)throw new v(`strings: output size limit exceeded (${n.maxOutputSize} bytes)`,"output_size");i.push(d),n.resultCount++,n.outputBytes+=h};for(let d=0;d<l.length;d++){if((d&4095)===0&&s?.aborted)throw new
|
|
476
|
+
`};i+=s8(l,n)}return{exitCode:0,stdout:i,stderr:""}}},Y0={name:"unexpand",flags:[{flag:"-t",type:"value",valueHint:"number"},{flag:"-a",type:"boolean"}],stdinType:"text",needsFiles:!0}});var l8={};he(l8,{flagsForFuzzing:()=>J0,strings:()=>gz});function mz(t){return t>=32&&t<=126||t===9}function o8(t,e){if(e===null)return"";switch(e){case"o":return`${t.toString(8).padStart(7," ")} `;case"x":return`${t.toString(16).padStart(7," ")} `;case"d":return`${t.toString(10).padStart(7," ")} `;default:return e}}function a8(t,e,n,r=!1,s){let i=[],o=0,a=0,l=typeof t=="string"&&!r?new TextEncoder().encode(t):t;if(l.length>n.maxStringLength-n.inputBytes)throw new v(`strings: aggregate input size limit exceeded (${n.maxStringLength} bytes)`,"string_length");n.inputBytes+=l.length;let c=new TextDecoder,u=(d,h)=>typeof l=="string"?l.slice(d,h):c.decode(l.subarray(d,h)),f=d=>{if(++n.iterations>n.maxIterations)throw new v(`strings: iteration limit exceeded (${n.maxIterations})`,"iterations");if(n.resultCount>=n.maxArrayElements)throw new v(`strings: array element limit exceeded (${n.maxArrayElements})`,"array_elements");let h=d.length+1;if(h>n.maxOutputSize-n.outputBytes)throw new v(`strings: output size limit exceeded (${n.maxOutputSize} bytes)`,"output_size");i.push(d),n.resultCount++,n.outputBytes+=h};for(let d=0;d<l.length;d++){if((d&4095)===0&&s?.aborted)throw new et;let h=typeof l=="string"?l.charCodeAt(d)&255:l[d];if(mz(h)){if(o===0&&(a=d),o>=n.maxStringLength)throw new v(`strings: string length limit exceeded (${n.maxStringLength} bytes)`,"string_length");o++}else{if(o>=e.minLength){let p=o8(a,e.offsetFormat);f(`${p}${u(a,d)}`)}o=0}}if(o>=e.minLength){let d=o8(a,e.offsetFormat);f(`${d}${u(a,l.length)}`)}return i}var pz,gz,J0,ey=L(()=>{"use strict";X();xe();pz={name:"strings",summary:"print the sequences of printable characters in files",usage:"strings [OPTION]... [FILE]...",description:"For each FILE, print the printable character sequences that are at least MIN characters long. If no FILE is specified, standard input is read.",options:["-n MIN Print sequences of at least MIN characters (default: 4)","-t FORMAT Print offset before each string (o=octal, x=hex, d=decimal)","-a Scan the entire file (default behavior)","-e ENCODING Select character encoding (s=7-bit, S=8-bit)"],examples:["strings file.bin # Extract strings (min 4 chars)","strings -n 8 file.bin # Extract strings (min 8 chars)","strings -t x file.bin # Show hex offset","echo 'hello' | strings # Read from stdin"]};gz={name:"strings",execute:async(t,e)=>{if(Z(t))return K(pz);let n={minLength:4,offsetFormat:null},r=[],s=0;for(;s<t.length;){let l=t[s];if(l==="-n"&&s+1<t.length){let c=Number.parseInt(t[s+1],10);if(Number.isNaN(c)||c<1)return{exitCode:1,stdout:"",stderr:`strings: invalid minimum string length: '${t[s+1]}'
|
|
477
477
|
`};n.minLength=c,s+=2}else if(l.match(/^-n\d+$/)){let c=Number.parseInt(l.slice(2),10);if(Number.isNaN(c)||c<1)return{exitCode:1,stdout:"",stderr:`strings: invalid minimum string length: '${l.slice(2)}'
|
|
478
478
|
`};n.minLength=c,s++}else if(l.match(/^-\d+$/)){let c=Number.parseInt(l.slice(1),10);if(Number.isNaN(c)||c<1)return{exitCode:1,stdout:"",stderr:`strings: invalid minimum string length: '${l.slice(1)}'
|
|
479
479
|
`};n.minLength=c,s++}else if(l==="-t"&&s+1<t.length){let c=t[s+1];if(c!=="o"&&c!=="x"&&c!=="d")return{exitCode:1,stdout:"",stderr:`strings: invalid radix: '${c}'
|
|
@@ -534,8 +534,8 @@ Try 'comm --help' for more information.
|
|
|
534
534
|
`:`find: invalid argument \`${_}' to \`${R}'
|
|
535
535
|
`,exitCode:1};let U=Number(_);if(!Number.isSafeInteger(U))return{stdout:"",stderr:`find: invalid argument \`${_}' to \`${R}'
|
|
536
536
|
`,exitCode:1};R==="-maxdepth"?r=U:s=U,F++}else R==="-depth"&&(i=!0)}let{expr:a,error:l}=b8(t,o);if(l)return{stdout:"",stderr:l,exitCode:1};let c=Sd(a),u=c.length>0;c.some(F=>F.type==="delete")&&(i=!0);let f=[],d=0,h=e.executionScope?new Ir(e.executionScope,"find"):void 0,p=[],m=[],g=0,y=new xn({limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:"find"}),w=F=>{if(h)h.append("stdout",F);else{let R=j(F);if(R>e.limits.maxOutputSize-g)throw new v(`find: output size limit exceeded (${e.limits.maxOutputSize} bytes)`,"output_size");F&&p.push(F),g+=R}},b=F=>{if(h)h.append("stderr",F);else{let R=j(F);if(R>e.limits.maxOutputSize-g)throw new v(`find: output size limit exceeded (${e.limits.maxOutputSize} bytes)`,"output_size");F&&m.push(F),g+=R}},x=g8(a),S=new Map;for(let F of x){let R=e.fs.resolvePath(e.cwd,F);try{let _=await e.fs.stat(R);S.set(F,_.mtime?.getTime()??Date.now())}catch{}}let E=c.some(F=>{if(F.type!=="printf")return!1;let R=F.format.replace(/%%/g,"");return/%[-+]?[0-9]*\.?[0-9]*(s|m|M|t|T)/.test(R)}),A=jc(a)||E,N=qc(a),I=Hc(a),T=Vc(a),$=typeof e.fs.readdirWithFileTypes=="function";for(let F of n){let W=function(q){let H={path:q.relativePath,name:q.name,size:q.stat?.size??0,mtime:q.stat?.mtime?.getTime()??Date.now(),mode:q.stat?.mode??420,isDirectory:q.isDirectory,depth:q.depth,startingPoint:F},re=q.unreadable===void 0?[]:[{action:{type:"diagnostic",message:`find: ${q.relativePath}: ${q.unreadable}
|
|
537
|
-
`},path:q.relativePath,printfData:H}],se=te=>i?[...re,...te]:[...te,...re];if(!(s===null||q.depth>=s))return re;let
|
|
538
|
-
`),d=1;continue}let _=Wz(),U=Date.now();async function B(q){let{path:H,depth:re,typeInfo:se}=q;if(y.visit(re),_.nodeCount++,re>(r??e.limits.maxTraversalDepth))return null;let de,
|
|
537
|
+
`},path:q.relativePath,printfData:H}],se=te=>i?[...re,...te]:[...te,...re];if(!(s===null||q.depth>=s))return re;let Ie=!0,oe=[];if(a!==null){let te=Date.now(),ne;if(T)ne=oa(a,q.name,q.relativePath,q.isFile,q.isDirectory);else{let Oe={name:q.name,relativePath:q.relativePath,isFile:q.isFile,isDirectory:q.isDirectory,isEmpty:q.isEmpty,mtime:q.stat?.mtime?.getTime()??Date.now(),size:q.stat?.size??0,mode:q.stat?.mode??420,newerRefTimes:S};ne=ms(a,Oe)}Ie=ne.matches,oe=ne.actions??[],_.evalCalls++,_.evalTime+=Date.now()-te}if(!u&&Ie&&(oe=[{type:"print"}]),oe.length===0)return re;y.checkpoint(oe.length);let Se=[];for(let te of oe)Se.push({action:te,path:q.relativePath,printfData:H});return se(Se)};var O=W;F.length>1&&F.endsWith("/")&&(F=F.slice(0,-1));let R=e.fs.resolvePath(e.cwd,F);try{await e.fs.stat(R)}catch{b(`find: ${F}: No such file or directory
|
|
538
|
+
`),d=1;continue}let _=Wz(),U=Date.now();async function B(q){let{path:H,depth:re,typeInfo:se}=q;if(y.visit(re),_.nodeCount++,re>(r??e.limits.maxTraversalDepth))return null;let de,Ie,oe;if(se&&!A)de=se.isFile,Ie=se.isDirectory;else{try{let xt=Date.now();oe=await e.fs.lstat(H),_.statCalls++,_.statTime+=Date.now()-xt}catch{return null}if(!oe)return null;de=oe.isFile,Ie=oe.isDirectory}let Se;H===R?Se=F.split("/").pop()||F:Se=H.split("/").pop()||"";let te=H===R?F:F==="."?`./${H.slice(R==="/"?R.length:R.length+1)}`:F+H.slice(R.length),ne=[],Oe=null,ye=null,Le=!1;Ie&&I&&!i&&(Le=y8(a,{name:Se,relativePath:te,isFile:de,isDirectory:Ie}).shouldPrune,Le&&_.earlyPrunes++);let ve=!(re>=(r??e.limits.maxTraversalDepth))&&!Le,ln=(ve||N)&&!Le,Te;if(Ie&&ln){let xt=Date.now();try{$&&e.fs.readdirWithFileTypes?Oe=await e.fs.readdirWithFileTypes(H):ye=await e.fs.readdir(H)}catch(Ee){let rt=Zz(Ee);if(rt===null)throw Ee;Te=rt,_.readdirCalls++,_.readdirTime+=Date.now()-xt}if(Oe!==null){y.checkpoint(),y.discover(Oe.length),ye=[];for(let Ee of Oe)ye.push(Ee.name);if(_.readdirCalls++,_.readdirTime+=Date.now()-xt,ve)for(let Ee=0;Ee<Oe.length;Ee++){let rt=Oe[Ee];ne.push({path:H==="/"?`/${rt.name}`:`${H}/${rt.name}`,depth:re+1,typeInfo:{isFile:rt.isFile,isDirectory:rt.isDirectory},resultIndex:Ee})}}else if(ye!==null&&(y.checkpoint(),y.discover(ye.length),_.readdirCalls++,_.readdirTime+=Date.now()-xt,ve))for(let Ee=0;Ee<ye.length;Ee++){let rt=ye[Ee];ne.push({path:H==="/"?`/${rt}`:`${H}/${rt}`,depth:re+1,resultIndex:Ee})}}let Ne=de?(oe?.size??0)===0:ye!==null&&ye.length===0,Ke=Le;if(!i&&a!==null&&!Le&&I){let xt=Date.now(),Ee={name:Se,relativePath:te,isFile:de,isDirectory:Ie,isEmpty:Ne,mtime:oe?.mtime?.getTime()??Date.now(),size:oe?.size??0,mode:oe?.mode??420,newerRefTimes:S};Ke=ms(a,Ee).pruned,_.evalCalls++,_.evalTime+=Date.now()-xt}return{relativePath:te,name:Se,isFile:de,isDirectory:Ie,isEmpty:Ne,stat:oe,depth:re,children:Ke?[]:ne,pruned:Ke,unreadable:Te}}async function M(){let q={effects:[]};if(i){let H=[],re=[{item:{path:R,depth:0,resultIndex:0},parentIndex:-1,childOrderInParent:0}],se=new Map,de=0;for(;de<re.length;){let Ie=Date.now(),oe=Math.min(re.length,de+E8),Se=re.slice(de,oe);de=oe;let te=await Promise.all(Se.map(ne=>B(ne.item).catch(Oe=>{if(Oe instanceof et)return null;throw Oe})));_.batchCount++,_.batchTime+=Date.now()-Ie;for(let ne=0;ne<Se.length;ne++){let Oe=te[ne],ye=Se[ne];if(!Oe)continue;let Le=H.length;if(ye.parentIndex>=0){let Ae=se.get(ye.parentIndex)||[];Ae.push(Le),se.set(ye.parentIndex,Ae)}H.push({node:Oe,parentIndex:ye.parentIndex,childIndices:[]});for(let Ae=0;Ae<Oe.children.length;Ae++)re.push({item:Oe.children[Ae],parentIndex:Le,childOrderInParent:Ae})}}for(let[Ie,oe]of se)Ie>=0&&Ie<H.length&&(H[Ie].childIndices=oe);if(H.length>0){let Ie=[{index:0,visited:!1}];for(;Ie.length>0;){y.checkpoint();let oe=Ie.pop();if(!oe)break;let Se=H[oe.index];if(Se){if(oe.visited){for(let te of W(Se.node))q.effects.push(te);continue}Ie.push({index:oe.index,visited:!0});for(let te=Se.childIndices.length-1;te>=0;te--)Ie.push({index:Se.childIndices[te],visited:!1})}}}}else{let H=new Map,re=0,se=[{item:{path:R,depth:0,resultIndex:0},orderIndex:re++}],de=new Map,Ie=0;for(;Ie<se.length;){let Se=Date.now(),te=Math.min(se.length,Ie+E8),ne=se.slice(Ie,te);Ie=te;let Oe=await Promise.all(ne.map(async({item:ye,orderIndex:Le})=>{try{let Ae=await B(ye);return Ae?{node:Ae,orderIndex:Le}:null}catch(Ae){if(Ae instanceof et)return null;throw Ae}}));_.batchCount++,_.batchTime+=Date.now()-Se;for(let ye of Oe){if(!ye)continue;let{node:Le,orderIndex:Ae}=ye,ve=W(Le);if(ve.length>0&&H.set(Ae,ve),Le.children.length>0){let ln=[];for(let Te of Le.children){let Ne=re++;ln.push(Ne),se.push({item:Te,orderIndex:Ne})}de.set(Ae,ln)}}}let oe=[0];for(;oe.length>0;){y.checkpoint();let Se=oe.pop();if(Se===void 0)break;let te=H.get(Se);if(te)for(let Oe of te)q.effects.push(Oe);let ne=de.get(Se);if(ne)for(let Oe=ne.length-1;Oe>=0;Oe--)oe.push(ne[Oe])}}return q}let Y=await M();for(let q of Y.effects)f.push(q);if(e.trace){let q=Date.now()-U;jz(e.trace,_,q),e.trace({category:"find",name:"searchPath",durationMs:q,details:{path:F,resultsFound:Y.effects.filter(H=>H.action.type!=="diagnostic").length}})}}let C=new Map;for(let F of f){let{action:R,path:_}=F;switch(R.type){case"diagnostic":b(R.message),d=1;break;case"print":w(`${_}
|
|
539
539
|
`);break;case"print0":w(`${_}\0`);break;case"printf":w(Hz(R.format,F.printfData));break;case"delete":{let U=e.fs.resolvePath(e.cwd,_);try{await e.fs.rm(U,{recursive:!1})}catch(B){let W=B instanceof Error?B.message:String(B);b(`find: cannot delete '${_}': ${W}
|
|
540
540
|
`),d=1}break}case"exec":{if(!e.exec)return{stdout:"",stderr:`find: -exec not supported in this context
|
|
541
541
|
`,exitCode:1};if(R.batchMode){let W=C.get(R)??[];W.push(_),C.set(R,W);break}let U=R.command.map(W=>W==="{}"?_:W),B=await e.exec(Fn([U[0]]),{cwd:e.cwd,signal:e.signal,args:U.slice(1)});h?h.appendResult(B):(w(B.stdout),b(B.stderr)),B.exitCode!==0&&(d=B.exitCode);break}}}for(let[F,R]of C){if(F.type!=="exec"||!e.exec||R.length===0)continue;let _=[];for(let B of F.command)B==="{}"?_.push(...R):_.push(B);let U=await e.exec(Fn([_[0]]),{cwd:e.cwd,signal:e.signal,args:_.slice(1)});h?h.appendResult(U):(w(U.stdout),b(U.stderr)),U.exitCode!==0&&(d=U.exitCode)}return h?.build(d)??{stdout:p.join(""),stderr:m.join(""),exitCode:d}}};Kz=new Map([["EACCES","Permission denied"],["EIO","Input/output error"],["ELOOP","Too many levels of symbolic links"],["ENAMETOOLONG","File name too long"],["ENOENT","No such file or directory"],["ENOTDIR","Not a directory"],["EPERM","Permission denied"]]);dy={name:"find",flags:[{flag:"-name",type:"value",valueHint:"pattern"},{flag:"-iname",type:"value",valueHint:"pattern"},{flag:"-type",type:"value",valueHint:"string"},{flag:"-maxdepth",type:"value",valueHint:"number"},{flag:"-mindepth",type:"value",valueHint:"number"},{flag:"-empty",type:"boolean"},{flag:"-print",type:"boolean"},{flag:"-print0",type:"boolean"}],needsFiles:!0}});var A8={};he(A8,{basenameCommand:()=>Qz,flagsForFuzzing:()=>py});var Yz,Qz,py,my=L(()=>{"use strict";xe();Yz={name:"basename",summary:"strip directory and suffix from filenames",usage:`basename NAME [SUFFIX]
|
|
@@ -557,7 +557,7 @@ basename OPTION... NAME...`,options:["-a, --multiple support multiple argument
|
|
|
557
557
|
${a} director${a===1?"y":"ies"}`,r.directoriesOnly||(i+=`, ${l} file${l===1?"":"s"}`),i+=`
|
|
558
558
|
`,{stdout:i,stderr:o,exitCode:o?1:0}}};wy={name:"tree",flags:[{flag:"-a",type:"boolean"},{flag:"-d",type:"boolean"},{flag:"-f",type:"boolean"},{flag:"-L",type:"value",valueHint:"number"}],needsFiles:!0}});var N8={};he(N8,{duCommand:()=>aU,flagsForFuzzing:()=>Ey});async function lU(t,e,n,r,s){let i={output:"",totalSize:0,stderr:""},o=new Map;return await ii({fs:t.fs,root:e,limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:"du",symlinks:"never",includeLeave:!0},a=>{let l=a.path.slice(e.length).replace(/^\//,""),c=l?n==="."?l:`${n}/${l}`:n,u=a.path==="/"?"/":a.path.slice(0,a.path.lastIndexOf("/"))||"/";if(a.phase==="enter"){if(a.stat.isDirectory){o.set(a.path,0);return}o.set(u,(o.get(u)??0)+a.stat.size),(r.allFiles||a.depth===s)&&!r.summarize&&(i.output+=`${xy(a.stat.size,r.humanReadable)} ${c}
|
|
559
559
|
`),a.depth===s&&(i.totalSize=a.stat.size);return}let f=o.get(a.path)??0;a.depth>s?o.set(u,(o.get(u)??0)+f):i.totalSize=f;let d=a.depth-s;(r.summarize&&d===0||!r.summarize&&(r.maxDepth===null||d<=r.maxDepth))&&(i.output+=`${xy(f,r.humanReadable)} ${c}
|
|
560
|
-
`)}),i}function xy(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 iU,oU,aU,Ey,Sy=L(()=>{"use strict";Kr();X();on();xe();iU={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"]},oU={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"}},aU={name:"du",async execute(t,e){if(Z(t))return K(iU);let n=Ye("du",t,oU);if(!n.ok)return n.error;let r={allFiles:n.result.flags.allFiles,humanReadable:n.result.flags.humanReadable,summarize:n.result.flags.summarize,grandTotal:n.result.flags.grandTotal,maxDepth:n.result.flags.maxDepth??null},s=n.result.positional;s.length===0&&s.push(".");let i="",o="",a=0;for(let l of s){let c=e.fs.resolvePath(e.cwd,l);try{await e.fs.stat(c);let u=await lU(e,c,l,r,0);i+=u.output,a+=u.totalSize,o+=u.stderr}catch(u){if(u instanceof v||u instanceof
|
|
560
|
+
`)}),i}function xy(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 iU,oU,aU,Ey,Sy=L(()=>{"use strict";Kr();X();on();xe();iU={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"]},oU={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"}},aU={name:"du",async execute(t,e){if(Z(t))return K(iU);let n=Ye("du",t,oU);if(!n.ok)return n.error;let r={allFiles:n.result.flags.allFiles,humanReadable:n.result.flags.humanReadable,summarize:n.result.flags.summarize,grandTotal:n.result.flags.grandTotal,maxDepth:n.result.flags.maxDepth??null},s=n.result.positional;s.length===0&&s.push(".");let i="",o="",a=0;for(let l of s){let c=e.fs.resolvePath(e.cwd,l);try{await e.fs.stat(c);let u=await lU(e,c,l,r,0);i+=u.output,a+=u.totalSize,o+=u.stderr}catch(u){if(u instanceof v||u instanceof et)throw u;o+=`du: cannot access '${l}': No such file or directory
|
|
561
561
|
`}}return r.grandTotal&&s.length>0&&(i+=`${xy(a,r.humanReadable)} total
|
|
562
562
|
`),{stdout:i,stderr:o,exitCode:o?1:0}}};Ey={name:"du",flags:[{flag:"-a",type:"boolean"},{flag:"-h",type:"boolean"},{flag:"-s",type:"boolean"},{flag:"-c",type:"boolean"},{flag:"--max-depth",type:"value",valueHint:"number"}],needsFiles:!0}});var Cy={};he(Cy,{envCommand:()=>uU,flagsForFuzzing:()=>Ay,printenvCommand:()=>dU,printenvFlagsForFuzzing:()=>vy});var cU,uU,fU,dU,Ay,vy,Ad=L(()=>{"use strict";pe();hs();xe();cU={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"]},uU={name:"env",async execute(t,e){if(Z(t))return K(cU);let n=!1,r=[],s=new Map,i=-1;for(let l=0;l<t.length;l++){let c=t[l];if(c==="-i"||c==="--ignore-environment")n=!0;else if(c==="-u"&&l+1<t.length)r.push(t[++l]);else if(c.startsWith("-u"))r.push(c.slice(2));else if(c.startsWith("--unset="))r.push(c.slice(8));else{if(c.startsWith("--")&&c!=="--")return ae("env",c);if(c.startsWith("-")&&c!=="-"){for(let u of c.slice(1))if(u!=="i"&&u!=="u")return ae("env",`-${u}`);c.includes("i")&&(n=!0)}else if(c.includes("=")&&i===-1){let u=c.indexOf("="),f=c.slice(0,u),d=c.slice(u+1);s.set(f,d)}else{i=l;break}}}let o;if(n)o=new Map(s);else{o=new Map(e.env);for(let l of r)o.delete(l);for(let[l,c]of s)o.set(l,c)}if(i===-1){let l=[];for(let[c,u]of o)l.push(`${c}=${u}`);return{stdout:l.join(`
|
|
563
563
|
`)+(l.length>0?`
|
|
@@ -781,7 +781,7 @@ With -d, decompress instead.`,options:["-c, --stdout write to standard outp
|
|
|
781
781
|
When no FILE is given, or when FILE is -, read from standard input.`,options:["-c, --stdout write to standard output, keep original files","-f, --force force overwrite of output file","-k, --keep keep (don't delete) input files","-l, --list list compressed file contents","-n, --no-name do not restore the original name and timestamp","-N, --name restore the original file name and timestamp","-q, --quiet suppress all warnings","-r, --recursive operate recursively on directories","-S, --suffix=SUF use suffix SUF on compressed files (default: .gz)","-t, --test test compressed file integrity","-v, --verbose verbose mode"," --help display this help and exit"]},dq={name:"zcat",summary:"decompress files to stdout",usage:"zcat [OPTION]... [FILE]...",description:`Decompress FILEs to standard output.
|
|
782
782
|
|
|
783
783
|
When no FILE is given, or when FILE is -, read from standard input.`,options:["-f, --force force; read compressed data even from a terminal","-l, --list list compressed file contents","-q, --quiet suppress all warnings","-S, --suffix=SUF use suffix SUF on compressed files (default: .gz)","-t, --test test compressed file integrity","-v, --verbose verbose mode"," --help display this help and exit"]},hq={stdout:{short:"c",long:"stdout",type:"boolean"},toStdout:{long:"to-stdout",type:"boolean"},decompress:{short:"d",long:"decompress",type:"boolean"},uncompress:{long:"uncompress",type:"boolean"},force:{short:"f",long:"force",type:"boolean"},keep:{short:"k",long:"keep",type:"boolean"},list:{short:"l",long:"list",type:"boolean"},noName:{short:"n",long:"no-name",type:"boolean"},name:{short:"N",long:"name",type:"boolean"},quiet:{short:"q",long:"quiet",type:"boolean"},recursive:{short:"r",long:"recursive",type:"boolean"},suffix:{short:"S",long:"suffix",type:"string",default:".gz"},test:{short:"t",long:"test",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"},fast:{short:"1",long:"fast",type:"boolean"},level2:{short:"2",type:"boolean"},level3:{short:"3",type:"boolean"},level4:{short:"4",type:"boolean"},level5:{short:"5",type:"boolean"},level6:{short:"6",type:"boolean"},level7:{short:"7",type:"boolean"},level8:{short:"8",type:"boolean"},best:{short:"9",long:"best",type:"boolean"}};wq={name:"gzip",async execute(t,e){return{...await Nw(t,e,"gzip"),stdoutEncoding:"binary"}}},bq={name:"gunzip",async execute(t,e){return{...await Nw(t,e,"gunzip"),stdoutEncoding:"binary"}}},xq={name:"zcat",async execute(t,e){return{...await Nw(t,e,"zcat"),stdoutEncoding:"binary"}}},Tw={name:"gzip",flags:[{flag:"-c",type:"boolean"},{flag:"-d",type:"boolean"},{flag:"-f",type:"boolean"},{flag:"-k",type:"boolean"},{flag:"-l",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-q",type:"boolean"},{flag:"-r",type:"boolean"},{flag:"-t",type:"boolean"},{flag:"-v",type:"boolean"},{flag:"-1",type:"boolean"},{flag:"-9",type:"boolean"}],stdinType:"binary",needsFiles:!0},Ow={name:"gunzip",flags:[{flag:"-c",type:"boolean"},{flag:"-f",type:"boolean"},{flag:"-k",type:"boolean"},{flag:"-q",type:"boolean"},{flag:"-v",type:"boolean"}],stdinType:"binary",needsFiles:!0},Iw={name:"zcat",flags:[{flag:"-f",type:"boolean"},{flag:"-q",type:"boolean"},{flag:"-v",type:"boolean"}],stdinType:"binary",needsFiles:!0}});function mo(t,e,n,r){r&&Xr.encodeInto(r,t.subarray(e,e+n))}function su(t,e,n,r){if(r===void 0)return;let s=r.toString(8).padStart(n-1,"0");Xr.encodeInto(s,t.subarray(e,e+n-1))}function Ui(t,e,n){let r=t.indexOf(0,e),s=r===-1||r>e+n?e+n:r;return dh.decode(t.subarray(e,s))}function $w(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=t[i];if(o===0)break;o!==32&&(r=r*8+(o-48))}return r}function lh(t,e,n){if(t[e]&128){let r=0;r=t[e]&127;for(let s=1;s<n;s++)r=r*256+t[e+s];if(!Number.isSafeInteger(r))throw new Error("TAR number too large");return r}return $w(t,e,n)}async function NC(t){if(t==null)return fh;if(t instanceof Uint8Array)return t;if(typeof t=="string")return Xr.encode(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(t instanceof Blob)return new Uint8Array(await t.arrayBuffer());throw new TypeError("Unsupported content type for entry body.")}function Lw(t,e){let{strip:n,filter:r,map:s}=e;if(!n&&!r&&!s)return t;let i={...t};if(n&&n>0){let a=SC(i.name,n);if(!a)return null;if(i.name=i.type==="directory"&&!a.endsWith("/")?`${a}/`:a,i.linkname){let l=i.linkname.startsWith("/");if(l||i.type==="link"){let c=SC(i.linkname,n);i.linkname=l?`/${c}`||"/":c}}}if(r?.(i)===!1)return null;let o=s?s(i):i;return o&&(!o.name||!o.name.trim()||o.name==="."||o.name==="/")?null:o}function Nq(){let t=new Array(ch),e=t.length-1,n=0,r=0,s=0,i=a=>{let l=t[n];a===l.length?(t[n]=fh,n=n+1&e):t[n]=l.subarray(a),s-=a,s===0&&t.length>ch&&(t=new Array(ch),e=ch-1,n=0,r=0)};function o(a,l){if(l){let h=0,p=Math.min(a,s);for(;p>0;){let m=t[n],g=Math.min(p,m.length),y=g===m.length?m:m.subarray(0,g);if(i(g),p-=g,h+=g,!l(y))break}return h}if(s<a)return null;if(a===0)return fh;let c=t[n];if(c.length>=a){let h=c.length===a?c:c.subarray(0,a);return i(a),h}let u=new Uint8Array(a),f=0,d=a;for(;d>0;){let h=t[n],p=Math.min(d,h.length);u.set(p===h.length?h:h.subarray(0,p),f),f+=p,d-=p,i(p)}return u}return{push:a=>{if(a.length===0)return;let l=r+1&e;if(l===n){let c=t.length,u=c*2,f=new Array(u),d=r-n+c&c-1;if(n<r)for(let h=0;h<d;h++)f[h]=t[n+h];else if(d>0){let h=c-n;for(let p=0;p<h;p++)f[p]=t[n+p];for(let p=0;p<r;p++)f[h+p]=t[p]}t=f,e=u-1,n=0,r=d,l=r+1&e}t[r]=a,r=l,s+=a.length},available:()=>s,peek:a=>{if(s<a)return null;if(a===0)return fh;let l=t[n];if(l.length>=a)return l.length===a?l:l.subarray(0,a);let c=new Uint8Array(a),u=0,f=n;for(;u<a;){let d=t[f],h=Math.min(a-u,d.length);h===d.length?c.set(d,u):c.set(d.subarray(0,h),u),u+=h,f=f+1&e}return c},discard:a=>{if(a>s)throw new Error("Too many bytes consumed");if(a===0)return;let l=a;for(;l>0;){let c=t[n],u=Math.min(l,c.length);i(u),l-=u}},pull:o}}function Oq(t){let e=$w(t,148,8),n=0;for(let r=0;r<t.length;r++)r>=148&&r<156?n+=Pw:n+=t[r];return e===n}function Iq(t){t.fill(Pw,148,156);let e=0;for(let n of t)e+=n;for(let n=153;n>=148;n--)t[n]=(e&7)+Tq,e>>=3;t[154]=0,t[155]=Pw}function Pq(t){let e={};Xr.encode(t.name).length>100&&TC(t.name)===null&&(e.path=t.name),t.linkname&&Xr.encode(t.linkname).length>100&&(e.linkpath=t.linkname),t.uname&&Xr.encode(t.uname).length>32&&(e.uname=t.uname),t.gname&&Xr.encode(t.gname).length>32&&(e.gname=t.gname),t.uid!=null&&t.uid>2097151&&(e.uid=String(t.uid)),t.gid!=null&&t.gid>2097151&&(e.gid=String(t.gid)),t.size!=null&&t.size>8589934591&&(e.size=String(t.size)),t.pax&&Object.assign(e,t.pax);let n=Object.entries(e);if(n.length===0)return null;let r=Xr.encode(n.map(([s,i])=>{let o=`${s}=${i}
|
|
784
|
-
`,a=Xr.encode(o).length+1,l=a+String(a).length;return l=a+String(l).length,`${l} ${o}`}).join(""));return{paxHeader:OC({name:dh.decode(Xr.encode(`PaxHeader/${t.name}`).slice(0,100)),size:r.length,type:"pax-header",mode:420,mtime:t.mtime,uname:t.uname,gname:t.gname,uid:t.uid,gid:t.gid}),paxBody:r}}function TC(t){let e=Xr.encode(t).length;if(e<=100||e>Rq)return null;for(let n=t.length-1;n>0;n--){if(t[n]!=="/")continue;let r=t.slice(0,n),s=t.slice(n+1);if(Xr.encode(r).length<=155&&Xr.encode(s).length<=100)return{prefix:r,name:s}}return null}function OC(t){let e=new Uint8Array(512),n=wa(t)?0:t.size??0,r=t.name,s="";if(!t.pax?.path){let i=TC(r);i&&(r=i.name,s=i.prefix)}return mo(e,0,100,r),su(e,100,8,t.mode??(t.type==="directory"?493:420)),su(e,108,8,t.uid??0),su(e,116,8,t.gid??0),su(e,124,12,n),su(e,136,12,Math.floor((t.mtime?.getTime()??Date.now())/1e3)),mo(e,156,1,vq[t.type??"file"]),mo(e,157,100,t.linkname),mo(e,257,6,"ustar\0"),mo(e,263,2,"00"),mo(e,265,32,t.uname),mo(e,297,32,t.gname),mo(e,345,155,s),Iq(e),e}function $q(t,e){if(e&&!Oq(t))throw new Error("Invalid tar header checksum.");let n=Ui(t,156,1),r={name:Ui(t,0,100),mode:$w(t,100,8),uid:lh(t,108,8),gid:lh(t,116,8),size:lh(t,124,12),mtime:new Date(lh(t,136,12)*1e3),type:Cq[n]||"file",linkname:Ui(t,157,100)},s=Ui(t,257,6);return s.trim()==="ustar"&&(r.uname=Ui(t,265,32),r.gname=Ui(t,297,32)),s==="ustar"&&(r.prefix=Ui(t,345,155)),r}function Lq(t){let e=Object.create(null),n=Object.create(null),r=!1,s=0;for(;s<t.length;){let i=t.indexOf(32,s);if(i===-1)break;let o=parseInt(dh.decode(t.subarray(s,i)),10);if(!(o>0))break;let a=s+o,l=dh.decode(t.subarray(i+1,a-1)),c=l.indexOf("=");if(c>0){let u=l.slice(0,c),f=l.slice(c+1);if(n[u]=f,r=!0,Object.hasOwn(AC,u)){let[d,h]=AC[u],p=h(f);(typeof p=="string"||!Number.isNaN(p))&&(e[d]=p)}}s=a}return r&&(e.pax=n),e}function vC(t,e){e.name!==void 0&&(t.name=e.name),e.linkname!==void 0&&(t.linkname=e.linkname),e.size!==void 0&&(t.size=e.size),e.mtime!==void 0&&(t.mtime=new Date(e.mtime*1e3)),e.uid!==void 0&&(t.uid=e.uid),e.gid!==void 0&&(t.gid=e.gid),e.uname!==void 0&&(t.uname=e.uname),e.gname!==void 0&&(t.gname=e.gname),e.pax&&(t.pax=Object.assign({},t.pax??{},e.pax))}function Fq(t){switch(t){case"pax-global-header":case"pax-header":return Lq;case"gnu-long-name":return e=>({name:Ui(e,0,e.length)});case"gnu-long-link-name":return e=>({linkname:Ui(e,0,e.length)});default:return}}function Dq(t){let e=OC(t),n=Pq(t);if(!n)return[e];let r=-n.paxBody.length&511,s=r>0?[kq.subarray(0,r)]:[];return[n.paxHeader,n.paxBody,...s,e]}function Fw(t={}){let e=t.strict??!1,{available:n,peek:r,push:s,discard:i,pull:o}=Nq(),a=Rw,l=!1,c=!1,u=!1,f=null,d={},h={},p={isEntryActive:()=>a===iu,isBodyComplete:()=>!f||f.remaining===0,canFinish:()=>!f||n()>=f.remaining+f.padding,bodyBytes:()=>f&&f.remaining>0?Math.min(f.remaining,n()):0,write(m){if(l)throw new Error("Archive already ended.");s(m)},end(){l=!0},readHeader(){if(a!==Rw)throw new Error("Cannot read header while an entry is active");if(!c)for(;!c;){if(n()<512){if(l){if(n()>0&&e)throw uh;c=!0;return}return null}let m=r(512);if(CC(m)){if(n()<512*2){if(l){if(e)throw uh;c=!0;return}return null}if(CC(r(512*2).subarray(512))){i(512*2),c=!0,u=!0;return}if(e)throw new Error("Invalid tar header.");i(512);continue}let g;try{g=$q(m,e)}catch(x){if(e)throw x;i(512);continue}let y=Fq(g.type);if(y){if(g.size>_q)throw new Error("Tar metadata entry exceeds maximum size.");let x=g.size+(-g.size&511);if(n()<512+x){if(l&&e)throw uh;return null}i(512);let S=y(o(x).subarray(0,g.size));h.pax&&(h={});let E=g.type==="pax-global-header"?d:h;for(let A in S)E[A]=S[A];continue}i(512);let w=g;g.prefix&&(w.name=`${g.prefix}/${w.name}`),vC(w,d),vC(w,h);let b=w.size;return wa(w)?(b=0,w.size=0):w.name.endsWith("/")&&w.type==="file"&&(w.type=kC,w.size=0),h={},f={header:w,remaining:b,padding:-b&511},a=iu,w}},streamBody(m){if(a!==iu||!f||f.remaining===0)return 0;let g=Math.min(f.remaining,n());if(g===0)return 0;let y=o(g,m);return f.remaining-=y,y},skipPadding(){if(a!==iu||!f)return!0;if(f.remaining>0)throw new Error("Body not fully consumed");return n()<f.padding?!1:(i(f.padding),f=null,a=Rw,!0)},skipEntry(){if(a!==iu||!f)return!0;let m=Math.min(f.remaining,n());return m>0&&(i(m),f.remaining-=m),f.remaining>0?!1:p.skipPadding()},validateEOF(){if(e){if(!u)throw uh;if(n()>0&&o(n()).some(m=>m!==0))throw new Error("Invalid EOF.")}}};return p}function CC(t){if(t.byteOffset%8===0){let e=new BigUint64Array(t.buffer,t.byteOffset,t.length/8);for(let n=0;n<e.length;n++)if(e[n]!==0n)return!1;return!0}for(let e=0;e<t.length;e++)if(t[e]!==0)return!1;return!0}function IC(t,e,n){let r=null,s=0,i=!1,o=a=>{let l=new Error(a);throw e(l),l};return{add(a){i&&o("No new tar entries after finalize."),r!==null&&o("Previous entry must be completed before adding a new one");let l=wa(a)?0:a.size;(!Number.isSafeInteger(l)||l<0)&&o("Invalid tar entry size.");try{let c=Dq({...a,size:l});for(let u of c)t(u);r={...a,size:l},s=0}catch(c){e(c)}},write(a){r||o("No active tar entry."),i&&o("Cannot write data after finalize.");let l=s+a.length;l>r.size&&o(`"${r.name}" exceeds given size of ${r.size} bytes.`);try{s=l,t(a)}catch(c){e(c)}},endEntry(){r||o("No active entry to end."),i&&o("Cannot end entry after finalize.");try{s!==r.size&&o(`Size mismatch for "${r.name}".`);let a=-r.size&511;a>0&&t(new Uint8Array(a)),r=null,s=0}catch(a){throw e(a),a}},finalize(){i&&o("Archive has already been finalized"),r!==null&&o("Cannot finalize while an entry is still active");try{t(Mq),i=!0,n&&n()}catch(a){e(a)}}}}var Eq,Sq,Aq,kC,vq,Cq,kq,fh,Xr,dh,wa,SC,ch,Pw,Tq,Rq,AC,Rw,iu,_q,uh,Mq,RC=L(()=>{Eq="file",Sq="link",Aq="symlink",kC="directory",vq={file:"0",link:"1",symlink:"2","character-device":"3","block-device":"4",directory:"5",fifo:"6","pax-header":"x","pax-global-header":"g","gnu-long-name":"L","gnu-long-link-name":"K"},Cq={0:Eq,1:Sq,2:Aq,3:"character-device",4:"block-device",5:kC,6:"fifo",x:"pax-header",g:"pax-global-header",L:"gnu-long-name",K:"gnu-long-link-name"},kq=new Uint8Array(512),fh=new Uint8Array(0),Xr=new TextEncoder,dh=new TextDecoder;wa=t=>t.type==="directory"||t.type==="symlink"||t.type==="link"||t.type==="character-device"||t.type==="block-device"||t.type==="fifo";SC=(t,e)=>{let n=t.split("/").filter(Boolean);return e>=n.length?"":n.slice(e).join("/")};ch=256;Pw=32,Tq=48;Rq=256;AC={path:["name",t=>t],linkpath:["linkname",t=>t],size:["size",t=>/^\d+$/.test(t)&&Number.isSafeInteger(+t)?+t:NaN],mtime:["mtime",parseFloat],uid:["uid",t=>parseInt(t,10)],gid:["gid",t=>parseInt(t,10)],uname:["uname",t=>t],gname:["gname",t=>t]};Rw=0,iu=1,_q=8*1024*1024,uh=new Error("Tar archive is truncated.");Mq=new Uint8Array(512*2)});function $C(){return new CompressionStream("gzip")}function LC(){return new DecompressionStream("gzip")}function Bq(){let t,e;return{readable:new ReadableStream({start(n){t=n,e=IC(n.enqueue.bind(n),n.error.bind(n),n.close.bind(n))}}),controller:{add(n){let r=wa(n);return e.add(n),r&&e.endEntry(),new WritableStream({write(s){e.write(s)},close(){r||e.endEntry()},abort(s){t.error(s)}})},finalize(){e.finalize()},error(n){t.error(n)}}}}async function FC(t){let e=[],n=t.getReader(),r=0;try{for(;;){let{done:o,value:a}=await n.read();if(o)break;e.push(a),r+=a.length}let s=new Uint8Array(r),i=0;for(let o of e)s.set(o,i),i+=o.length;return s}finally{n.releaseLock()}}function zq(t={}){let e=Fw(t),n=t.strict??!1,r=null,s=null,i=!1,o=!1,a=!1,l=!1,c=()=>{try{s?.close()}catch{}s=null},u=p=>{if(!l){l=!0;try{s?.error(p)}catch{}s=null;try{r.error(p)}catch{}r=null}},f=()=>{if(!l){l=!0,c();try{r.close()}catch{}r=null}},d=()=>{if(n)throw new Error("Tar archive is truncated.");f()},h=()=>{if(!(i||l||!r)){i=!0;try{for(;;){if(o){a&&(e.validateEOF(),f());break}if(e.isEntryActive()){if(a&&!e.canFinish()){d();break}if(s){if((s.desiredSize??1)<=0)break;if(e.streamBody(p=>(s.enqueue(p),(s.desiredSize??1)>0))===0&&!e.isBodyComplete()){a&&d();break}}else if(!e.skipEntry()){a&&d();break}if(e.isBodyComplete()&&(c(),!e.skipPadding())){a&&d();break}}else{if((r.desiredSize??0)<0)break;let p=e.readHeader();if(p===null){a&&f();break}if(p===void 0){if(a){e.validateEOF(),f();break}o=!0;break}r.enqueue({header:p,body:new ReadableStream({start(m){p.size===0?m.close():s=m},pull:h,cancel(){s=null,h()}})})}}}catch(p){throw u(p),p}finally{i=!1}}};return{readable:new ReadableStream({start(p){r=p},pull:h,cancel(p){p!==void 0?u(p):f()}},{highWaterMark:2}),writable:new WritableStream({write(p){try{if(o&&n&&p.some(m=>m!==0))throw new Error("Invalid EOF.");e.write(p),h()}catch(m){throw u(m),m}},close(){try{a=!0,e.end(),h()}catch(p){throw u(p),p}},abort(p){u(p)}})}}async function DC(t){let{readable:e,controller:n}=Bq();return await(async()=>{for(let r of t){let s=n.add(r.header),i="body"in r?r.body:r.data;if(!i){await s.close();continue}if(i instanceof ReadableStream)await i.pipeTo(s);else if(i instanceof Blob)await i.stream().pipeTo(s);else try{let o=await NC(i);if(o.length>0){let a=s.getWriter();await a.write(o),await a.close()}else await s.close()}catch{throw new TypeError(`Unsupported content type for entry "${r.header.name}".`)}}})().then(()=>n.finalize()).catch(r=>n.error(r)),FC(e)}async function _C(t,e={}){if(!(t instanceof ReadableStream))return Uq(t instanceof Uint8Array?t:new Uint8Array(t),e);let n=[],r=t.pipeThrough(zq(e));for await(let s of r){let i;try{i=Lw(s.header,e)}catch(o){throw await s.body.cancel(),o}if(i===null){await PC(s.body);continue}wa(i)?(await PC(s.body),n.push({header:i})):n.push({header:i,data:await FC(s.body)})}return n}function Uq(t,e){let n=Fw(e),r=e.strict??!1,s=[];for(n.write(t),n.end();;){let i=n.readHeader();if(i===void 0)break;if(i===null){if(r)throw new Error("Tar archive is truncated.");break}let o=Lw(i,e);if(o===null){let d=n.skipEntry();if(!d&&r)throw new Error("Tar archive is truncated.");if(!d)break;continue}if(wa(o)){let d=n.skipEntry();if(!d&&r)throw new Error("Tar archive is truncated.");if(s.push({header:o}),!d)break;continue}let a=i.size;if(a<0||!n.canFinish()){if(r)throw new Error("Tar archive is truncated.");a=n.bodyBytes()}let l=new Uint8Array(a),c=0;n.streamBody(d=>(l.set(d,c),c+=d.length,!0));let u=n.isBodyComplete(),f=!0;if(u&&(f=n.skipPadding(),!f&&r))throw new Error("Tar archive is truncated.");if(s.push({header:o,data:l}),!u||!f)break}return n.validateEOF(),s}var PC,MC=L(()=>{RC();PC=t=>t.pipeTo(new WritableStream)});function jq(t,e){return(t<<8^Wq[(t>>>24^e)&255])>>>0}function qq(t){let e=[],n=0;for(;n<t.length;){let r=t[n],s=1;for(;n+s<t.length&&t[n+s]===r&&s<255;)s++;s>=4?(e.push(r,r,r,r),e.push(s-4),n+=s):(e.push(r),n++)}return new Uint8Array(e)}function Vq(t){let e=t.length;if(e===0)return{transformed:new Uint8Array(0),pointer:0};let n=Hq(t),r=new Uint8Array(e),s=0;for(let i=0;i<e;i++)n[i]===0?(s=i,r[i]=t[e-1]):r[i]=t[n[i]-1];return{transformed:r,pointer:s}}function Hq(t){let e=t.length,n=new Int32Array(e),r=new Int32Array(e);for(let s=0;s<e;s++)n[s]=s,r[s]=t[s];for(let s=1;s<e;s*=2){let i=r.slice();n.sort((o,a)=>i[o]!==i[a]?i[o]-i[a]:i[(o+s)%e]-i[(a+s)%e]),r[n[0]]=0;for(let o=1;o<e;o++)i[n[o]]===i[n[o-1]]&&i[(n[o]+s)%e]===i[(n[o-1]+s)%e]?r[n[o]]=r[n[o-1]]:r[n[o]]=r[n[o-1]]+1;if(r[n[e-1]]===e-1)break}return n}function Gq(t,e){let n=[];for(let o=0;o<256;o++)e[o]&&n.push(o);let r=new Array(256).fill(-1);for(let o=0;o<n.length;o++)r[n[o]]=o;let s=new Uint16Array(t.length),i=n.slice();for(let o=0;o<t.length;o++){let a=t[o],l=0;for(;i[l]!==a;)l++;if(s[o]=l,l>0){let c=i[l];for(let u=l;u>0;u--)i[u]=i[u-1];i[0]=c}}return{encoded:s,length:t.length}}function Kq(t,e,n){let i=n+1,o=[],a=0;for(;a<e;)if(t[a]===0){let c=0;for(;a<e&&t[a]===0;)c++,a++;let u=c;for(;u>0;)u--,u&1?o.push(1):o.push(0),u>>>=1}else o.push(t[a]+1),a++;o.push(i);let l=new Uint16Array(o.length);for(let c=0;c<o.length;c++)l[c]=o[c];return{symbols:l,length:o.length,eob:i}}function BC(t,e,n){if(e<=1){let c=new Array(t.length).fill(0);for(let u=0;u<t.length;u++)t[u]>0&&(c[u]=1);return{codeLengths:c,maxLen:1,minLen:1}}let r=[];for(let c=0;c<t.length;c++)t[c]>0&&r.push({freq:t[c],symbol:c,left:null,right:null});if(r.length===0)return{codeLengths:new Array(t.length).fill(0),maxLen:0,minLen:0};if(r.length===1){let c=new Array(t.length).fill(0);return c[r[0].symbol]=1,{codeLengths:c,maxLen:1,minLen:1}}for(;r.length>1;){r.sort((f,d)=>f.freq-d.freq);let c=r.shift(),u=r.shift();r.push({freq:c.freq+u.freq,symbol:-1,left:c,right:u})}let s=new Array(t.length).fill(0);function i(c,u){if(!c.left&&!c.right){s[c.symbol]=u;return}c.left&&i(c.left,u+1),c.right&&i(c.right,u+1)}i(r[0],0);let o=!0;for(;o;){o=!1;for(let c=0;c<s.length;c++)s[c]>n&&(s[c]=n,o=!0);if(o){let c=0;for(let u=0;u<s.length;u++)s[u]>0&&(c+=1/(1<<s[u]));if(c>1)for(let u=1;u<n&&c>1;u++)for(let f=0;f<s.length&&c>1;f++)s[f]===u&&(s[f]++,c-=1/(1<<u)-1/(1<<u+1));o=!1;for(let u=0;u<s.length;u++)if(s[u]>n){o=!0;break}}}let a=n,l=0;for(let c=0;c<s.length;c++)s[c]>0&&(s[c]<a&&(a=s[c]),s[c]>l&&(l=s[c]));return{codeLengths:s,maxLen:l,minLen:a}}function Zq(t,e){let n=new Array(e).fill(0),r=t.slice(0,e),s=Math.max(...r,0),i=new Array(s+1).fill(0);for(let l=0;l<e;l++)r[l]>0&&i[r[l]]++;let o=new Array(s+1).fill(0),a=0;for(let l=1;l<=s;l++)a=a+i[l-1]<<1,o[l]=a;for(let l=0;l<e;l++)r[l]>0&&(n[l]=o[r[l]]++);return{codes:n,lengths:r}}function Xq(t,e,n){t.writeBits(24,3227993),t.writeBits(24,2511705),t.writeBits(32,n),t.writeBit(0);let r=qq(e),{transformed:s,pointer:i}=Vq(r);t.writeBits(24,i);let o=new Array(256).fill(!1);for(let I=0;I<s.length;I++)o[s[I]]=!0;let a=new Array(16).fill(!1);for(let I=0;I<16;I++)for(let T=0;T<16;T++)if(o[I*16+T]){a[I]=!0;break}for(let I=0;I<16;I++)t.writeBit(a[I]?1:0);for(let I=0;I<16;I++)if(a[I])for(let T=0;T<16;T++)t.writeBit(o[I*16+T]?1:0);let l=0;for(let I=0;I<256;I++)o[I]&&l++;let{encoded:c,length:u}=Gq(s,o),{symbols:f,length:d}=Kq(c,u,l),h=l+2,p=50,m=Math.ceil(d/p),g;d<200?g=2:d<600?g=3:d<1200?g=4:d<2400?g=5:g=6,g>m&&(g=Math.max(2,m));let y=[];for(let I=0;I<g;I++)y.push(new Array(h).fill(0));let w=new Int32Array(m);for(let I=0;I<m;I++)w[I]=I%g;for(let I=0;I<m;I++){let T=I*p,$=Math.min(T+p,d),C=w[I];for(let O=T;O<$;O++)y[C][f[O]]++}function b(I){for(let T=0;T<h;T++)I[T]<1&&(I[T]=1)}let x=[];for(let I=0;I<g;I++)b(y[I]),x.push(BC(y[I],h,20));for(let I=0;I<4;I++){for(let T=0;T<g;T++)y[T].fill(0);for(let T=0;T<m;T++){let $=T*p,C=Math.min($+p,d),O=0,F=1/0;for(let R=0;R<g;R++){let _=0;for(let U=$;U<C;U++)_+=x[R].codeLengths[f[U]]||20;_<F&&(F=_,O=R)}w[T]=O;for(let R=$;R<C;R++)y[O][f[R]]++}for(let T=0;T<g;T++)b(y[T]),x[T]=BC(y[T],h,20)}t.writeBits(3,g),t.writeBits(15,m);let S=[],E=[];for(let I=0;I<g;I++)E.push(I);for(let I=0;I<m;I++){let T=w[I],$=0;for(;E[$]!==T;)$++;if(S.push($),$>0){let C=E[$];for(let O=$;O>0;O--)E[O]=E[O-1];E[0]=C}}for(let I=0;I<m;I++){for(let T=0;T<S[I];T++)t.writeBit(1);t.writeBit(0)}for(let I=0;I<g;I++){let T=x[I].codeLengths,$=T[0];t.writeBits(5,$);for(let C=0;C<h;C++){let O=T[C];for(;$<O;)t.writeBit(1),t.writeBit(0),$++;for(;$>O;)t.writeBit(1),t.writeBit(1),$--;t.writeBit(0)}}for(let I=0;I<g;I++){let{codes:T,lengths:$}=Zq(x[I].codeLengths,h);x[I]=Object.assign(x[I],{_codes:T,_lengths:$})}let A=0,N=0;for(let I=0;I<d;I++){(N===0||N>=p)&&(I>0&&A++,N=0);let T=w[A],$=x[T],C=f[I],O=$._lengths[C],F=$._codes[C];O>0&&t.writeBits(O,F),N++}}function zC(t,e=9,n=Yq,r=Number.MAX_SAFE_INTEGER){if(e<1||e>9)throw new Error("Block size level must be 1-9");if(t.length>n)throw new Error(`Input too large for bzip2 compression (${t.length} bytes, max ${n})`);let s=e*1e5,i=new Dw(r);i.writeBits(8,66),i.writeBits(8,90),i.writeBits(8,104),i.writeBits(8,48+e);let o=0,a=0;for(;a<t.length;){let l=Math.min(a+s,t.length),c=t.subarray(a,l),u=4294967295;for(let f=0;f<c.length;f++)u=jq(u,c[f]);u=~u>>>0,o=(o<<1|o>>>31)>>>0,o=(o^u)>>>0,Xq(i,c,u),a=l}return i.writeBits(24,1536581),i.writeBits(24,3690640),i.writeBits(32,o),i.finish()}var Wq,Dw,Yq,UC=L(()=>{"use strict";Wq=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e<<24;for(let r=0;r<8;r++)n=n&2147483648?n<<1^79764919:n<<1;t[e]=n>>>0}return t})();Dw=class{maxOutputBytes;buffer=[];current=0;bitCount=0;constructor(e=Number.MAX_SAFE_INTEGER){if(this.maxOutputBytes=e,!Number.isSafeInteger(e)||e<0)throw new Error("Invalid bzip2 output limit")}pushByte(e){if(this.buffer.length>=this.maxOutputBytes)throw new Error(`bzip2 output exceeds limit (${this.maxOutputBytes} bytes)`);this.buffer.push(e)}writeBits(e,n){for(let r=e-1;r>=0;r--)this.current=this.current<<1|n>>>r&1,this.bitCount++,this.bitCount===8&&(this.pushByte(this.current),this.current=0,this.bitCount=0)}writeBit(e){this.current=this.current<<1|e&1,this.bitCount++,this.bitCount===8&&(this.pushByte(this.current),this.current=0,this.bitCount=0)}finish(){return this.bitCount>0&&this.pushByte(this.current<<8-this.bitCount),new Uint8Array(this.buffer)}};Yq=10*1024*1024});async function jC(){if(hh)return hh;if(ph)throw ph;try{return hh=await tt.runTrustedAsync(()=>import("node-liblzma")),hh}catch{throw ph=new Error("xz compression requires node-liblzma which failed to load. Install liblzma-dev (apt) or xz (brew) and reinstall dependencies."),ph}}async function qC(){if(mh)return mh;if(gh)throw gh;try{return mh=await tt.runTrustedAsync(()=>import("@mongodb-js/zstd")),mh}catch{throw gh=new Error("zstd compression requires @mongodb-js/zstd which is not installed. Install it with: npm install @mongodb-js/zstd"),gh}}function ou(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Archive limits must be positive safe integers");return n}function hi(t){return{maxArchiveSize:ou(t?.maxArchiveSize,_w),maxEntries:ou(t?.maxEntries,Qq),maxEntrySize:ou(t?.maxEntrySize,_w),maxCompressedSize:ou(t?.maxCompressedSize,t?.maxArchiveSize??_w),maxExpansionRatio:ou(t?.maxExpansionRatio,1e4),signal:t?.signal,executionScope:t?.executionScope,allowTrustedWholeBufferCodecs:t?.allowTrustedWholeBufferCodecs??!0}}function Jq(t,e){if(t.length>e.maxEntries)throw new Error(`Too many archive entries (max ${e.maxEntries})`);let n=s=>{if(!Number.isSafeInteger(s)||s<0||s>e.maxArchiveSize-r)throw new Error(`Archive too large (max ${e.maxArchiveSize} bytes)`);r+=s},r=Fr*2;for(let s of t){e.signal?.throwIfAborted();let i=s.isDirectory||s.isSymlink?0:typeof s.content=="string"?j(s.content):s.content?.length??0;if(i>e.maxEntrySize)throw new Error(`Archive entry too large (max ${e.maxEntrySize} bytes)`);let o=s.isDirectory&&!s.name.endsWith("/")?`${s.name}/`:s.name,a=j(o),l=j(s.linkTarget??"");if(a>e.maxArchiveSize||l>e.maxArchiveSize)throw new Error(`Archive too large (max ${e.maxArchiveSize} bytes)`);let c=0;if(a>100&&(c+=a+64),l>100&&(c+=l+64),!Number.isSafeInteger(c))throw new Error(`Archive too large (max ${e.maxArchiveSize} bytes)`);let u=Math.ceil(i/Fr)*Fr;if(n(Fr+u),c>0){let f=Math.ceil(c/Fr)*Fr;n(Fr+f)}}return r}function yh(t,e,n){return t.executionScope?.reserveBytes(e,n,`tar: ${e}`)}function eV(t){let e=t.subarray(124,136);if((e[0]&128)!==0){let s=e[0]&127;for(let i=1;i<e.length;i++)if(s=s*256+e[i],!Number.isSafeInteger(s))return;return s}let n=new TextDecoder("ascii").decode(e).replace(/\0.*$/,"").trim();if(n==="")return 0;if(!/^[0-7]+$/.test(n))return;let r=Number.parseInt(n,8);return Number.isSafeInteger(r)?r:void 0}function tV(t,e){let n=0,r=0;for(;n+Fr<=t.length;){e.signal?.throwIfAborted();let s=t.subarray(n,n+Fr);if(s.every(a=>a===0))return;if(r++,r>e.maxEntries)return`Too many entries (max ${e.maxEntries})`;let i=eV(s);if(i===void 0)return"Invalid tar archive format";if(i>e.maxEntrySize)return`Archive entry too large (max ${e.maxEntrySize} bytes)`;let o=Math.ceil(i/Fr)*Fr;if(!Number.isSafeInteger(o)||(n+=Fr+o,n>t.length))return"Invalid tar archive format"}return n===t.length?void 0:"Invalid tar archive format"}function nV(t){let e="file";t.isDirectory?e="directory":t.isSymlink&&(e="symlink");let n=t.name;t.isDirectory&&!n.endsWith("/")&&(n+="/");let r;t.content!==void 0&&(typeof t.content=="string"?r=new TextEncoder().encode(t.content):r=t.content);let s=t.isDirectory||t.isSymlink?0:r?.length??0;return{header:{name:n,mode:t.mode??(t.isDirectory?493:420),uid:t.uid??0,gid:t.gid??0,size:s,mtime:t.mtime??new Date,type:e,linkname:t.linkTarget??"",uname:"user",gname:"user"},body:r}}async function go(t,e){let n=hi(e),r=Jq(t,n),s=yh(n,"archive construction",r);try{let i=t.map(nV),o=await DC(i);if(n.signal?.throwIfAborted(),o.length>n.maxArchiveSize)throw new Error(`Archive too large (max ${n.maxArchiveSize} bytes)`);return o}finally{s?.release()}}async function VC(t,e){let n=hi(e),r=await go(t,n),s=yh(n,"gzip input",r.byteLength),i=new di({maxInputBytes:n.maxArchiveSize,maxOutputBytes:n.maxCompressedSize,signal:n.signal,label:"gzip archive"});i.acceptInput(r.length);let l=new ReadableStream({start(d){d.enqueue(r),d.close()}}).pipeThrough($C()).getReader(),c=[],u=[],f=0;try{for(;;){let{done:h,value:p}=await l.read();if(h)break;try{i.acceptOutput(p.length);let m=yh(n,"gzip chunks",p.byteLength);m&&u.push(m)}catch(m){throw await l.cancel(),m}f+=p.length,c.push(p)}let d=yh(n,"gzip result",f);try{let h=new Uint8Array(f),p=0;for(let m of c)h.set(m,p),p+=m.length;return h}finally{d?.release()}}finally{for(let d of u)d.release();s?.release()}}async function Wi(t,e){let n=hi(e);if(t.length>n.maxArchiveSize)return{entries:[],error:`Archive too large (max ${n.maxArchiveSize} bytes)`};if(t.length<Fr||t.length%Fr!==0)return{entries:[],error:"Invalid tar archive format"};let r=tV(t,n);if(r)return{entries:[],error:r};try{let s=await _C(t),i=[];for(let o of s){if(n.signal?.throwIfAborted(),i.length>=n.maxEntries)return{entries:[],error:`Too many entries (max ${n.maxEntries})`};let a=o.data??new Uint8Array(0);if(o.header.size>n.maxEntrySize||a.length>n.maxEntrySize)return{entries:[],error:`Archive entry too large (max ${n.maxEntrySize} bytes)`};let l="file";switch(o.header.type){case"directory":l="directory";break;case"symlink":l="symlink";break;case"link":l="hardlink";break;case"file":l="file";break;default:l="other"}i.push({name:o.header.name,mode:o.header.mode??420,uid:o.header.uid??0,gid:o.header.gid??0,size:o.header.size,mtime:o.header.mtime??new Date,type:l,linkTarget:o.header.linkname||void 0,content:a})}return{entries:i}}catch(s){let i=s instanceof Error?s.message:"Unknown error";return{entries:[],error:i}}}async function Mw(t,e){let n=hi(e);if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=new di({maxInputBytes:n.maxCompressedSize,maxOutputBytes:n.maxArchiveSize,maxExpansionRatio:n.maxExpansionRatio,signal:n.signal,label:"gzip archive"});r.acceptInput(t.length);let o=new ReadableStream({start(f){f.enqueue(t),f.close()}}).pipeThrough(LC()).getReader(),a=[],l=0;for(;;){let{done:f,value:d}=await o.read();if(f)break;try{r.acceptOutput(d.length)}catch(h){throw await o.cancel(),h}l+=d.length,a.push(d)}let c=new Uint8Array(l),u=0;for(let f of a)c.set(f,u),u+=f.length;return Wi(c,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return{entries:[],error:`Decompression failed: ${s}`}}}function Bw(t){return t.length>=2&&t[0]===31&&t[1]===139}function zw(t){return t.length>=3&&t[0]===66&&t[1]===90&&t[2]===104}function Uw(t){return t.length>=6&&t[0]===253&&t[1]===55&&t[2]===122&&t[3]===88&&t[4]===90&&t[5]===0}async function rV(t,e){let n=new di({maxInputBytes:e.maxCompressedSize,maxOutputBytes:e.maxArchiveSize,maxExpansionRatio:e.maxExpansionRatio,signal:e.signal,label:"bzip2 archive"});n.acceptInput(t.length);let r=Math.min(64*1024,e.maxArchiveSize),s=[],i=Buffer.allocUnsafe(r),o=0,a=0,l={writeByte(c){n.acceptOutput(1),o===i.length&&(s.push(i),i=Buffer.allocUnsafe(r),o=0),i[o++]=c,a++}};return WC.default.decode(Buffer.from(t),l),o>0&&s.push(i.subarray(0,o)),new Uint8Array(Buffer.concat(s,a))}async function sV(t,e){let n=new di({maxInputBytes:e.maxArchiveSize,maxOutputBytes:e.maxCompressedSize,signal:e.signal,label:"bzip2 archive"});n.acceptInput(t.length);let r=await zC(t,9,e.maxArchiveSize,e.maxCompressedSize);return n.acceptOutput(r.length),r}async function iV(t){let n=(await jC()).unxzSync(Buffer.from(t));return new Uint8Array(n)}async function oV(t){let n=(await jC()).xzSync(Buffer.from(t));return new Uint8Array(n)}async function HC(t,e){let n=hi(e),r=await go(t,n);return sV(r,n)}async function GC(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)throw new Error("xz compression is disabled by configuration. Enable native and trusted whole-buffer codecs to use it.");let r=await go(t,n),s=await oV(r);if(n.signal?.throwIfAborted(),s.length>n.maxCompressedSize)throw new Error(`xz archive: output exceeds limit (${n.maxCompressedSize} bytes)`);return s}async function Ww(t,e){let n=hi({...e,maxArchiveSize:e?.maxDecompressedSize??e?.maxArchiveSize});if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=await rV(t,n);return Wi(r,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return s===`bzip2 archive: output exceeds limit (${n.maxArchiveSize} bytes)`?{entries:[],error:`Decompressed archive too large (max ${n.maxArchiveSize} bytes)`}:{entries:[],error:s}}}async function jw(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)return{entries:[],error:"xz decompression is disabled by configuration. Enable native and trusted whole-buffer codecs, or decompress the archive externally before extraction."};if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=await iV(t);return n.signal?.throwIfAborted(),r.length>n.maxArchiveSize?{entries:[],error:`Trusted xz codec produced data over limit (${n.maxArchiveSize} bytes)`}:Wi(r,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return{entries:[],error:s}}}function qw(t){return t.length>=4&&t[0]===40&&t[1]===181&&t[2]===47&&t[3]===253}async function aV(t){let n=await(await qC()).compress(Buffer.from(t),3);return new Uint8Array(n)}async function lV(t){let n=await(await qC()).decompress(Buffer.from(t));return new Uint8Array(n)}async function KC(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)throw new Error("zstd compression is disabled by configuration. Enable native and trusted whole-buffer codecs to use it.");let r=await go(t,n),s=await aV(r);if(n.signal?.throwIfAborted(),s.length>n.maxCompressedSize)throw new Error(`zstd archive: output exceeds limit (${n.maxCompressedSize} bytes)`);return s}async function Vw(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)return{entries:[],error:"zstd decompression is disabled by configuration. Enable native and trusted whole-buffer codecs, or decompress the archive externally before extraction."};if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=await lV(t);return n.signal?.throwIfAborted(),r.length>n.maxArchiveSize?{entries:[],error:`Trusted zstd codec produced data over limit (${n.maxArchiveSize} bytes)`}:Wi(r,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return{entries:[],error:s}}}var WC,hh,ph,mh,gh,_w,Fr,Qq,ZC=L(()=>{"use strict";MC();WC=jt(require("seek-bzip"),1);pe();cn();Cw();UC();hh=null,ph=null;mh=null,gh=null;_w=1024*1024*1024,Fr=512,Qq=1e6});function XC(t){let e=t.length>0&&t[0]!==""&&!t[0].startsWith("-")?cV(t):t,n={create:!1,append:!1,update:!1,extract:!1,list:!1,file:"",autoCompress:!1,gzip:!1,bzip2:!1,xz:!1,zstd:!1,verbose:!1,toStdout:!1,keepOldFiles:!1,touch:!1,directory:"",preserve:!1,absoluteNames:!1,strip:0,exclude:[],filesFrom:"",excludeFrom:"",wildcards:!1},r=[],s=0;for(;s<e.length;){let i=e[s];if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2){if(/^-\d+$/.test(i)){r.push(i),s++;continue}for(let o=1;o<i.length;o++){let a=i[o];switch(a){case"c":n.create=!0;break;case"r":n.append=!0;break;case"u":n.update=!0;break;case"x":n.extract=!0;break;case"t":n.list=!0;break;case"a":n.autoCompress=!0;break;case"z":n.gzip=!0;break;case"j":n.bzip2=!0;break;case"J":n.xz=!0;break;case"v":n.verbose=!0;break;case"O":n.toStdout=!0;break;case"k":n.keepOldFiles=!0;break;case"m":n.touch=!0;break;case"p":n.preserve=!0;break;case"P":n.absoluteNames=!0;break;case"f":if(o<i.length-1)n.file=i.substring(o+1),o=i.length;else{if(s++,s>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'f'
|
|
784
|
+
`,a=Xr.encode(o).length+1,l=a+String(a).length;return l=a+String(l).length,`${l} ${o}`}).join(""));return{paxHeader:OC({name:dh.decode(Xr.encode(`PaxHeader/${t.name}`).slice(0,100)),size:r.length,type:"pax-header",mode:420,mtime:t.mtime,uname:t.uname,gname:t.gname,uid:t.uid,gid:t.gid}),paxBody:r}}function TC(t){let e=Xr.encode(t).length;if(e<=100||e>Rq)return null;for(let n=t.length-1;n>0;n--){if(t[n]!=="/")continue;let r=t.slice(0,n),s=t.slice(n+1);if(Xr.encode(r).length<=155&&Xr.encode(s).length<=100)return{prefix:r,name:s}}return null}function OC(t){let e=new Uint8Array(512),n=wa(t)?0:t.size??0,r=t.name,s="";if(!t.pax?.path){let i=TC(r);i&&(r=i.name,s=i.prefix)}return mo(e,0,100,r),su(e,100,8,t.mode??(t.type==="directory"?493:420)),su(e,108,8,t.uid??0),su(e,116,8,t.gid??0),su(e,124,12,n),su(e,136,12,Math.floor((t.mtime?.getTime()??Date.now())/1e3)),mo(e,156,1,vq[t.type??"file"]),mo(e,157,100,t.linkname),mo(e,257,6,"ustar\0"),mo(e,263,2,"00"),mo(e,265,32,t.uname),mo(e,297,32,t.gname),mo(e,345,155,s),Iq(e),e}function $q(t,e){if(e&&!Oq(t))throw new Error("Invalid tar header checksum.");let n=Ui(t,156,1),r={name:Ui(t,0,100),mode:$w(t,100,8),uid:lh(t,108,8),gid:lh(t,116,8),size:lh(t,124,12),mtime:new Date(lh(t,136,12)*1e3),type:Cq[n]||"file",linkname:Ui(t,157,100)},s=Ui(t,257,6);return s.trim()==="ustar"&&(r.uname=Ui(t,265,32),r.gname=Ui(t,297,32)),s==="ustar"&&(r.prefix=Ui(t,345,155)),r}function Lq(t){let e=Object.create(null),n=Object.create(null),r=!1,s=0;for(;s<t.length;){let i=t.indexOf(32,s);if(i===-1)break;let o=parseInt(dh.decode(t.subarray(s,i)),10);if(!(o>0))break;let a=s+o,l=dh.decode(t.subarray(i+1,a-1)),c=l.indexOf("=");if(c>0){let u=l.slice(0,c),f=l.slice(c+1);if(n[u]=f,r=!0,Object.hasOwn(AC,u)){let[d,h]=AC[u],p=h(f);(typeof p=="string"||!Number.isNaN(p))&&(e[d]=p)}}s=a}return r&&(e.pax=n),e}function vC(t,e){e.name!==void 0&&(t.name=e.name),e.linkname!==void 0&&(t.linkname=e.linkname),e.size!==void 0&&(t.size=e.size),e.mtime!==void 0&&(t.mtime=new Date(e.mtime*1e3)),e.uid!==void 0&&(t.uid=e.uid),e.gid!==void 0&&(t.gid=e.gid),e.uname!==void 0&&(t.uname=e.uname),e.gname!==void 0&&(t.gname=e.gname),e.pax&&(t.pax=Object.assign({},t.pax??{},e.pax))}function Fq(t){switch(t){case"pax-global-header":case"pax-header":return Lq;case"gnu-long-name":return e=>({name:Ui(e,0,e.length)});case"gnu-long-link-name":return e=>({linkname:Ui(e,0,e.length)});default:return}}function Dq(t){let e=OC(t),n=Pq(t);if(!n)return[e];let r=-n.paxBody.length&511,s=r>0?[kq.subarray(0,r)]:[];return[n.paxHeader,n.paxBody,...s,e]}function Fw(t={}){let e=t.strict??!1,{available:n,peek:r,push:s,discard:i,pull:o}=Nq(),a=Rw,l=!1,c=!1,u=!1,f=null,d={},h={},p={isEntryActive:()=>a===iu,isBodyComplete:()=>!f||f.remaining===0,canFinish:()=>!f||n()>=f.remaining+f.padding,bodyBytes:()=>f&&f.remaining>0?Math.min(f.remaining,n()):0,write(m){if(l)throw new Error("Archive already ended.");s(m)},end(){l=!0},readHeader(){if(a!==Rw)throw new Error("Cannot read header while an entry is active");if(!c)for(;!c;){if(n()<512){if(l){if(n()>0&&e)throw uh;c=!0;return}return null}let m=r(512);if(CC(m)){if(n()<512*2){if(l){if(e)throw uh;c=!0;return}return null}if(CC(r(512*2).subarray(512))){i(512*2),c=!0,u=!0;return}if(e)throw new Error("Invalid tar header.");i(512);continue}let g;try{g=$q(m,e)}catch(x){if(e)throw x;i(512);continue}let y=Fq(g.type);if(y){if(g.size>_q)throw new Error("Tar metadata entry exceeds maximum size.");let x=g.size+(-g.size&511);if(n()<512+x){if(l&&e)throw uh;return null}i(512);let S=y(o(x).subarray(0,g.size));h.pax&&(h={});let E=g.type==="pax-global-header"?d:h;for(let A in S)E[A]=S[A];continue}i(512);let w=g;g.prefix&&(w.name=`${g.prefix}/${w.name}`),vC(w,d),vC(w,h);let b=w.size;return wa(w)?(b=0,w.size=0):w.name.endsWith("/")&&w.type==="file"&&(w.type=kC,w.size=0),h={},f={header:w,remaining:b,padding:-b&511},a=iu,w}},streamBody(m){if(a!==iu||!f||f.remaining===0)return 0;let g=Math.min(f.remaining,n());if(g===0)return 0;let y=o(g,m);return f.remaining-=y,y},skipPadding(){if(a!==iu||!f)return!0;if(f.remaining>0)throw new Error("Body not fully consumed");return n()<f.padding?!1:(i(f.padding),f=null,a=Rw,!0)},skipEntry(){if(a!==iu||!f)return!0;let m=Math.min(f.remaining,n());return m>0&&(i(m),f.remaining-=m),f.remaining>0?!1:p.skipPadding()},validateEOF(){if(e){if(!u)throw uh;if(n()>0&&o(n()).some(m=>m!==0))throw new Error("Invalid EOF.")}}};return p}function CC(t){if(t.byteOffset%8===0){let e=new BigUint64Array(t.buffer,t.byteOffset,t.length/8);for(let n=0;n<e.length;n++)if(e[n]!==0n)return!1;return!0}for(let e=0;e<t.length;e++)if(t[e]!==0)return!1;return!0}function IC(t,e,n){let r=null,s=0,i=!1,o=a=>{let l=new Error(a);throw e(l),l};return{add(a){i&&o("No new tar entries after finalize."),r!==null&&o("Previous entry must be completed before adding a new one");let l=wa(a)?0:a.size;(!Number.isSafeInteger(l)||l<0)&&o("Invalid tar entry size.");try{let c=Dq({...a,size:l});for(let u of c)t(u);r={...a,size:l},s=0}catch(c){e(c)}},write(a){r||o("No active tar entry."),i&&o("Cannot write data after finalize.");let l=s+a.length;l>r.size&&o(`"${r.name}" exceeds given size of ${r.size} bytes.`);try{s=l,t(a)}catch(c){e(c)}},endEntry(){r||o("No active entry to end."),i&&o("Cannot end entry after finalize.");try{s!==r.size&&o(`Size mismatch for "${r.name}".`);let a=-r.size&511;a>0&&t(new Uint8Array(a)),r=null,s=0}catch(a){throw e(a),a}},finalize(){i&&o("Archive has already been finalized"),r!==null&&o("Cannot finalize while an entry is still active");try{t(Mq),i=!0,n&&n()}catch(a){e(a)}}}}var Eq,Sq,Aq,kC,vq,Cq,kq,fh,Xr,dh,wa,SC,ch,Pw,Tq,Rq,AC,Rw,iu,_q,uh,Mq,RC=L(()=>{Eq="file",Sq="link",Aq="symlink",kC="directory",vq={file:"0",link:"1",symlink:"2","character-device":"3","block-device":"4",directory:"5",fifo:"6","pax-header":"x","pax-global-header":"g","gnu-long-name":"L","gnu-long-link-name":"K"},Cq={0:Eq,1:Sq,2:Aq,3:"character-device",4:"block-device",5:kC,6:"fifo",x:"pax-header",g:"pax-global-header",L:"gnu-long-name",K:"gnu-long-link-name"},kq=new Uint8Array(512),fh=new Uint8Array(0),Xr=new TextEncoder,dh=new TextDecoder;wa=t=>t.type==="directory"||t.type==="symlink"||t.type==="link"||t.type==="character-device"||t.type==="block-device"||t.type==="fifo";SC=(t,e)=>{let n=t.split("/").filter(Boolean);return e>=n.length?"":n.slice(e).join("/")};ch=256;Pw=32,Tq=48;Rq=256;AC={path:["name",t=>t],linkpath:["linkname",t=>t],size:["size",t=>/^\d+$/.test(t)&&Number.isSafeInteger(+t)?+t:NaN],mtime:["mtime",parseFloat],uid:["uid",t=>parseInt(t,10)],gid:["gid",t=>parseInt(t,10)],uname:["uname",t=>t],gname:["gname",t=>t]};Rw=0,iu=1,_q=8*1024*1024,uh=new Error("Tar archive is truncated.");Mq=new Uint8Array(512*2)});function $C(){return new CompressionStream("gzip")}function LC(){return new DecompressionStream("gzip")}function Bq(){let t,e;return{readable:new ReadableStream({start(n){t=n,e=IC(n.enqueue.bind(n),n.error.bind(n),n.close.bind(n))}}),controller:{add(n){let r=wa(n);return e.add(n),r&&e.endEntry(),new WritableStream({write(s){e.write(s)},close(){r||e.endEntry()},abort(s){t.error(s)}})},finalize(){e.finalize()},error(n){t.error(n)}}}}async function FC(t){let e=[],n=t.getReader(),r=0;try{for(;;){let{done:o,value:a}=await n.read();if(o)break;e.push(a),r+=a.length}let s=new Uint8Array(r),i=0;for(let o of e)s.set(o,i),i+=o.length;return s}finally{n.releaseLock()}}function zq(t={}){let e=Fw(t),n=t.strict??!1,r=null,s=null,i=!1,o=!1,a=!1,l=!1,c=()=>{try{s?.close()}catch{}s=null},u=p=>{if(!l){l=!0;try{s?.error(p)}catch{}s=null;try{r.error(p)}catch{}r=null}},f=()=>{if(!l){l=!0,c();try{r.close()}catch{}r=null}},d=()=>{if(n)throw new Error("Tar archive is truncated.");f()},h=()=>{if(!(i||l||!r)){i=!0;try{for(;;){if(o){a&&(e.validateEOF(),f());break}if(e.isEntryActive()){if(a&&!e.canFinish()){d();break}if(s){if((s.desiredSize??1)<=0)break;if(e.streamBody(p=>(s.enqueue(p),(s.desiredSize??1)>0))===0&&!e.isBodyComplete()){a&&d();break}}else if(!e.skipEntry()){a&&d();break}if(e.isBodyComplete()&&(c(),!e.skipPadding())){a&&d();break}}else{if((r.desiredSize??0)<0)break;let p=e.readHeader();if(p===null){a&&f();break}if(p===void 0){if(a){e.validateEOF(),f();break}o=!0;break}r.enqueue({header:p,body:new ReadableStream({start(m){p.size===0?m.close():s=m},pull:h,cancel(){s=null,h()}})})}}}catch(p){throw u(p),p}finally{i=!1}}};return{readable:new ReadableStream({start(p){r=p},pull:h,cancel(p){p!==void 0?u(p):f()}},{highWaterMark:2}),writable:new WritableStream({write(p){try{if(o&&n&&p.some(m=>m!==0))throw new Error("Invalid EOF.");e.write(p),h()}catch(m){throw u(m),m}},close(){try{a=!0,e.end(),h()}catch(p){throw u(p),p}},abort(p){u(p)}})}}async function DC(t){let{readable:e,controller:n}=Bq();return await(async()=>{for(let r of t){let s=n.add(r.header),i="body"in r?r.body:r.data;if(!i){await s.close();continue}if(i instanceof ReadableStream)await i.pipeTo(s);else if(i instanceof Blob)await i.stream().pipeTo(s);else try{let o=await NC(i);if(o.length>0){let a=s.getWriter();await a.write(o),await a.close()}else await s.close()}catch{throw new TypeError(`Unsupported content type for entry "${r.header.name}".`)}}})().then(()=>n.finalize()).catch(r=>n.error(r)),FC(e)}async function _C(t,e={}){if(!(t instanceof ReadableStream))return Uq(t instanceof Uint8Array?t:new Uint8Array(t),e);let n=[],r=t.pipeThrough(zq(e));for await(let s of r){let i;try{i=Lw(s.header,e)}catch(o){throw await s.body.cancel(),o}if(i===null){await PC(s.body);continue}wa(i)?(await PC(s.body),n.push({header:i})):n.push({header:i,data:await FC(s.body)})}return n}function Uq(t,e){let n=Fw(e),r=e.strict??!1,s=[];for(n.write(t),n.end();;){let i=n.readHeader();if(i===void 0)break;if(i===null){if(r)throw new Error("Tar archive is truncated.");break}let o=Lw(i,e);if(o===null){let d=n.skipEntry();if(!d&&r)throw new Error("Tar archive is truncated.");if(!d)break;continue}if(wa(o)){let d=n.skipEntry();if(!d&&r)throw new Error("Tar archive is truncated.");if(s.push({header:o}),!d)break;continue}let a=i.size;if(a<0||!n.canFinish()){if(r)throw new Error("Tar archive is truncated.");a=n.bodyBytes()}let l=new Uint8Array(a),c=0;n.streamBody(d=>(l.set(d,c),c+=d.length,!0));let u=n.isBodyComplete(),f=!0;if(u&&(f=n.skipPadding(),!f&&r))throw new Error("Tar archive is truncated.");if(s.push({header:o,data:l}),!u||!f)break}return n.validateEOF(),s}var PC,MC=L(()=>{RC();PC=t=>t.pipeTo(new WritableStream)});function jq(t,e){return(t<<8^Wq[(t>>>24^e)&255])>>>0}function qq(t){let e=[],n=0;for(;n<t.length;){let r=t[n],s=1;for(;n+s<t.length&&t[n+s]===r&&s<255;)s++;s>=4?(e.push(r,r,r,r),e.push(s-4),n+=s):(e.push(r),n++)}return new Uint8Array(e)}function Vq(t){let e=t.length;if(e===0)return{transformed:new Uint8Array(0),pointer:0};let n=Hq(t),r=new Uint8Array(e),s=0;for(let i=0;i<e;i++)n[i]===0?(s=i,r[i]=t[e-1]):r[i]=t[n[i]-1];return{transformed:r,pointer:s}}function Hq(t){let e=t.length,n=new Int32Array(e),r=new Int32Array(e);for(let s=0;s<e;s++)n[s]=s,r[s]=t[s];for(let s=1;s<e;s*=2){let i=r.slice();n.sort((o,a)=>i[o]!==i[a]?i[o]-i[a]:i[(o+s)%e]-i[(a+s)%e]),r[n[0]]=0;for(let o=1;o<e;o++)i[n[o]]===i[n[o-1]]&&i[(n[o]+s)%e]===i[(n[o-1]+s)%e]?r[n[o]]=r[n[o-1]]:r[n[o]]=r[n[o-1]]+1;if(r[n[e-1]]===e-1)break}return n}function Gq(t,e){let n=[];for(let o=0;o<256;o++)e[o]&&n.push(o);let r=new Array(256).fill(-1);for(let o=0;o<n.length;o++)r[n[o]]=o;let s=new Uint16Array(t.length),i=n.slice();for(let o=0;o<t.length;o++){let a=t[o],l=0;for(;i[l]!==a;)l++;if(s[o]=l,l>0){let c=i[l];for(let u=l;u>0;u--)i[u]=i[u-1];i[0]=c}}return{encoded:s,length:t.length}}function Kq(t,e,n){let i=n+1,o=[],a=0;for(;a<e;)if(t[a]===0){let c=0;for(;a<e&&t[a]===0;)c++,a++;let u=c;for(;u>0;)u--,u&1?o.push(1):o.push(0),u>>>=1}else o.push(t[a]+1),a++;o.push(i);let l=new Uint16Array(o.length);for(let c=0;c<o.length;c++)l[c]=o[c];return{symbols:l,length:o.length,eob:i}}function BC(t,e,n){if(e<=1){let c=new Array(t.length).fill(0);for(let u=0;u<t.length;u++)t[u]>0&&(c[u]=1);return{codeLengths:c,maxLen:1,minLen:1}}let r=[];for(let c=0;c<t.length;c++)t[c]>0&&r.push({freq:t[c],symbol:c,left:null,right:null});if(r.length===0)return{codeLengths:new Array(t.length).fill(0),maxLen:0,minLen:0};if(r.length===1){let c=new Array(t.length).fill(0);return c[r[0].symbol]=1,{codeLengths:c,maxLen:1,minLen:1}}for(;r.length>1;){r.sort((f,d)=>f.freq-d.freq);let c=r.shift(),u=r.shift();r.push({freq:c.freq+u.freq,symbol:-1,left:c,right:u})}let s=new Array(t.length).fill(0);function i(c,u){if(!c.left&&!c.right){s[c.symbol]=u;return}c.left&&i(c.left,u+1),c.right&&i(c.right,u+1)}i(r[0],0);let o=!0;for(;o;){o=!1;for(let c=0;c<s.length;c++)s[c]>n&&(s[c]=n,o=!0);if(o){let c=0;for(let u=0;u<s.length;u++)s[u]>0&&(c+=1/(1<<s[u]));if(c>1)for(let u=1;u<n&&c>1;u++)for(let f=0;f<s.length&&c>1;f++)s[f]===u&&(s[f]++,c-=1/(1<<u)-1/(1<<u+1));o=!1;for(let u=0;u<s.length;u++)if(s[u]>n){o=!0;break}}}let a=n,l=0;for(let c=0;c<s.length;c++)s[c]>0&&(s[c]<a&&(a=s[c]),s[c]>l&&(l=s[c]));return{codeLengths:s,maxLen:l,minLen:a}}function Zq(t,e){let n=new Array(e).fill(0),r=t.slice(0,e),s=Math.max(...r,0),i=new Array(s+1).fill(0);for(let l=0;l<e;l++)r[l]>0&&i[r[l]]++;let o=new Array(s+1).fill(0),a=0;for(let l=1;l<=s;l++)a=a+i[l-1]<<1,o[l]=a;for(let l=0;l<e;l++)r[l]>0&&(n[l]=o[r[l]]++);return{codes:n,lengths:r}}function Xq(t,e,n){t.writeBits(24,3227993),t.writeBits(24,2511705),t.writeBits(32,n),t.writeBit(0);let r=qq(e),{transformed:s,pointer:i}=Vq(r);t.writeBits(24,i);let o=new Array(256).fill(!1);for(let I=0;I<s.length;I++)o[s[I]]=!0;let a=new Array(16).fill(!1);for(let I=0;I<16;I++)for(let T=0;T<16;T++)if(o[I*16+T]){a[I]=!0;break}for(let I=0;I<16;I++)t.writeBit(a[I]?1:0);for(let I=0;I<16;I++)if(a[I])for(let T=0;T<16;T++)t.writeBit(o[I*16+T]?1:0);let l=0;for(let I=0;I<256;I++)o[I]&&l++;let{encoded:c,length:u}=Gq(s,o),{symbols:f,length:d}=Kq(c,u,l),h=l+2,p=50,m=Math.ceil(d/p),g;d<200?g=2:d<600?g=3:d<1200?g=4:d<2400?g=5:g=6,g>m&&(g=Math.max(2,m));let y=[];for(let I=0;I<g;I++)y.push(new Array(h).fill(0));let w=new Int32Array(m);for(let I=0;I<m;I++)w[I]=I%g;for(let I=0;I<m;I++){let T=I*p,$=Math.min(T+p,d),C=w[I];for(let O=T;O<$;O++)y[C][f[O]]++}function b(I){for(let T=0;T<h;T++)I[T]<1&&(I[T]=1)}let x=[];for(let I=0;I<g;I++)b(y[I]),x.push(BC(y[I],h,20));for(let I=0;I<4;I++){for(let T=0;T<g;T++)y[T].fill(0);for(let T=0;T<m;T++){let $=T*p,C=Math.min($+p,d),O=0,F=1/0;for(let R=0;R<g;R++){let _=0;for(let U=$;U<C;U++)_+=x[R].codeLengths[f[U]]||20;_<F&&(F=_,O=R)}w[T]=O;for(let R=$;R<C;R++)y[O][f[R]]++}for(let T=0;T<g;T++)b(y[T]),x[T]=BC(y[T],h,20)}t.writeBits(3,g),t.writeBits(15,m);let S=[],E=[];for(let I=0;I<g;I++)E.push(I);for(let I=0;I<m;I++){let T=w[I],$=0;for(;E[$]!==T;)$++;if(S.push($),$>0){let C=E[$];for(let O=$;O>0;O--)E[O]=E[O-1];E[0]=C}}for(let I=0;I<m;I++){for(let T=0;T<S[I];T++)t.writeBit(1);t.writeBit(0)}for(let I=0;I<g;I++){let T=x[I].codeLengths,$=T[0];t.writeBits(5,$);for(let C=0;C<h;C++){let O=T[C];for(;$<O;)t.writeBit(1),t.writeBit(0),$++;for(;$>O;)t.writeBit(1),t.writeBit(1),$--;t.writeBit(0)}}for(let I=0;I<g;I++){let{codes:T,lengths:$}=Zq(x[I].codeLengths,h);x[I]=Object.assign(x[I],{_codes:T,_lengths:$})}let A=0,N=0;for(let I=0;I<d;I++){(N===0||N>=p)&&(I>0&&A++,N=0);let T=w[A],$=x[T],C=f[I],O=$._lengths[C],F=$._codes[C];O>0&&t.writeBits(O,F),N++}}function zC(t,e=9,n=Yq,r=Number.MAX_SAFE_INTEGER){if(e<1||e>9)throw new Error("Block size level must be 1-9");if(t.length>n)throw new Error(`Input too large for bzip2 compression (${t.length} bytes, max ${n})`);let s=e*1e5,i=new Dw(r);i.writeBits(8,66),i.writeBits(8,90),i.writeBits(8,104),i.writeBits(8,48+e);let o=0,a=0;for(;a<t.length;){let l=Math.min(a+s,t.length),c=t.subarray(a,l),u=4294967295;for(let f=0;f<c.length;f++)u=jq(u,c[f]);u=~u>>>0,o=(o<<1|o>>>31)>>>0,o=(o^u)>>>0,Xq(i,c,u),a=l}return i.writeBits(24,1536581),i.writeBits(24,3690640),i.writeBits(32,o),i.finish()}var Wq,Dw,Yq,UC=L(()=>{"use strict";Wq=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e<<24;for(let r=0;r<8;r++)n=n&2147483648?n<<1^79764919:n<<1;t[e]=n>>>0}return t})();Dw=class{maxOutputBytes;buffer=[];current=0;bitCount=0;constructor(e=Number.MAX_SAFE_INTEGER){if(this.maxOutputBytes=e,!Number.isSafeInteger(e)||e<0)throw new Error("Invalid bzip2 output limit")}pushByte(e){if(this.buffer.length>=this.maxOutputBytes)throw new Error(`bzip2 output exceeds limit (${this.maxOutputBytes} bytes)`);this.buffer.push(e)}writeBits(e,n){for(let r=e-1;r>=0;r--)this.current=this.current<<1|n>>>r&1,this.bitCount++,this.bitCount===8&&(this.pushByte(this.current),this.current=0,this.bitCount=0)}writeBit(e){this.current=this.current<<1|e&1,this.bitCount++,this.bitCount===8&&(this.pushByte(this.current),this.current=0,this.bitCount=0)}finish(){return this.bitCount>0&&this.pushByte(this.current<<8-this.bitCount),new Uint8Array(this.buffer)}};Yq=10*1024*1024});async function jC(){if(hh)return hh;if(ph)throw ph;try{return hh=await nt.runTrustedAsync(()=>import("node-liblzma")),hh}catch{throw ph=new Error("xz compression requires node-liblzma which failed to load. Install liblzma-dev (apt) or xz (brew) and reinstall dependencies."),ph}}async function qC(){if(mh)return mh;if(gh)throw gh;try{return mh=await nt.runTrustedAsync(()=>import("@mongodb-js/zstd")),mh}catch{throw gh=new Error("zstd compression requires @mongodb-js/zstd which is not installed. Install it with: npm install @mongodb-js/zstd"),gh}}function ou(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Archive limits must be positive safe integers");return n}function hi(t){return{maxArchiveSize:ou(t?.maxArchiveSize,_w),maxEntries:ou(t?.maxEntries,Qq),maxEntrySize:ou(t?.maxEntrySize,_w),maxCompressedSize:ou(t?.maxCompressedSize,t?.maxArchiveSize??_w),maxExpansionRatio:ou(t?.maxExpansionRatio,1e4),signal:t?.signal,executionScope:t?.executionScope,allowTrustedWholeBufferCodecs:t?.allowTrustedWholeBufferCodecs??!0}}function Jq(t,e){if(t.length>e.maxEntries)throw new Error(`Too many archive entries (max ${e.maxEntries})`);let n=s=>{if(!Number.isSafeInteger(s)||s<0||s>e.maxArchiveSize-r)throw new Error(`Archive too large (max ${e.maxArchiveSize} bytes)`);r+=s},r=Fr*2;for(let s of t){e.signal?.throwIfAborted();let i=s.isDirectory||s.isSymlink?0:typeof s.content=="string"?j(s.content):s.content?.length??0;if(i>e.maxEntrySize)throw new Error(`Archive entry too large (max ${e.maxEntrySize} bytes)`);let o=s.isDirectory&&!s.name.endsWith("/")?`${s.name}/`:s.name,a=j(o),l=j(s.linkTarget??"");if(a>e.maxArchiveSize||l>e.maxArchiveSize)throw new Error(`Archive too large (max ${e.maxArchiveSize} bytes)`);let c=0;if(a>100&&(c+=a+64),l>100&&(c+=l+64),!Number.isSafeInteger(c))throw new Error(`Archive too large (max ${e.maxArchiveSize} bytes)`);let u=Math.ceil(i/Fr)*Fr;if(n(Fr+u),c>0){let f=Math.ceil(c/Fr)*Fr;n(Fr+f)}}return r}function yh(t,e,n){return t.executionScope?.reserveBytes(e,n,`tar: ${e}`)}function eV(t){let e=t.subarray(124,136);if((e[0]&128)!==0){let s=e[0]&127;for(let i=1;i<e.length;i++)if(s=s*256+e[i],!Number.isSafeInteger(s))return;return s}let n=new TextDecoder("ascii").decode(e).replace(/\0.*$/,"").trim();if(n==="")return 0;if(!/^[0-7]+$/.test(n))return;let r=Number.parseInt(n,8);return Number.isSafeInteger(r)?r:void 0}function tV(t,e){let n=0,r=0;for(;n+Fr<=t.length;){e.signal?.throwIfAborted();let s=t.subarray(n,n+Fr);if(s.every(a=>a===0))return;if(r++,r>e.maxEntries)return`Too many entries (max ${e.maxEntries})`;let i=eV(s);if(i===void 0)return"Invalid tar archive format";if(i>e.maxEntrySize)return`Archive entry too large (max ${e.maxEntrySize} bytes)`;let o=Math.ceil(i/Fr)*Fr;if(!Number.isSafeInteger(o)||(n+=Fr+o,n>t.length))return"Invalid tar archive format"}return n===t.length?void 0:"Invalid tar archive format"}function nV(t){let e="file";t.isDirectory?e="directory":t.isSymlink&&(e="symlink");let n=t.name;t.isDirectory&&!n.endsWith("/")&&(n+="/");let r;t.content!==void 0&&(typeof t.content=="string"?r=new TextEncoder().encode(t.content):r=t.content);let s=t.isDirectory||t.isSymlink?0:r?.length??0;return{header:{name:n,mode:t.mode??(t.isDirectory?493:420),uid:t.uid??0,gid:t.gid??0,size:s,mtime:t.mtime??new Date,type:e,linkname:t.linkTarget??"",uname:"user",gname:"user"},body:r}}async function go(t,e){let n=hi(e),r=Jq(t,n),s=yh(n,"archive construction",r);try{let i=t.map(nV),o=await DC(i);if(n.signal?.throwIfAborted(),o.length>n.maxArchiveSize)throw new Error(`Archive too large (max ${n.maxArchiveSize} bytes)`);return o}finally{s?.release()}}async function VC(t,e){let n=hi(e),r=await go(t,n),s=yh(n,"gzip input",r.byteLength),i=new di({maxInputBytes:n.maxArchiveSize,maxOutputBytes:n.maxCompressedSize,signal:n.signal,label:"gzip archive"});i.acceptInput(r.length);let l=new ReadableStream({start(d){d.enqueue(r),d.close()}}).pipeThrough($C()).getReader(),c=[],u=[],f=0;try{for(;;){let{done:h,value:p}=await l.read();if(h)break;try{i.acceptOutput(p.length);let m=yh(n,"gzip chunks",p.byteLength);m&&u.push(m)}catch(m){throw await l.cancel(),m}f+=p.length,c.push(p)}let d=yh(n,"gzip result",f);try{let h=new Uint8Array(f),p=0;for(let m of c)h.set(m,p),p+=m.length;return h}finally{d?.release()}}finally{for(let d of u)d.release();s?.release()}}async function Wi(t,e){let n=hi(e);if(t.length>n.maxArchiveSize)return{entries:[],error:`Archive too large (max ${n.maxArchiveSize} bytes)`};if(t.length<Fr||t.length%Fr!==0)return{entries:[],error:"Invalid tar archive format"};let r=tV(t,n);if(r)return{entries:[],error:r};try{let s=await _C(t),i=[];for(let o of s){if(n.signal?.throwIfAborted(),i.length>=n.maxEntries)return{entries:[],error:`Too many entries (max ${n.maxEntries})`};let a=o.data??new Uint8Array(0);if(o.header.size>n.maxEntrySize||a.length>n.maxEntrySize)return{entries:[],error:`Archive entry too large (max ${n.maxEntrySize} bytes)`};let l="file";switch(o.header.type){case"directory":l="directory";break;case"symlink":l="symlink";break;case"link":l="hardlink";break;case"file":l="file";break;default:l="other"}i.push({name:o.header.name,mode:o.header.mode??420,uid:o.header.uid??0,gid:o.header.gid??0,size:o.header.size,mtime:o.header.mtime??new Date,type:l,linkTarget:o.header.linkname||void 0,content:a})}return{entries:i}}catch(s){let i=s instanceof Error?s.message:"Unknown error";return{entries:[],error:i}}}async function Mw(t,e){let n=hi(e);if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=new di({maxInputBytes:n.maxCompressedSize,maxOutputBytes:n.maxArchiveSize,maxExpansionRatio:n.maxExpansionRatio,signal:n.signal,label:"gzip archive"});r.acceptInput(t.length);let o=new ReadableStream({start(f){f.enqueue(t),f.close()}}).pipeThrough(LC()).getReader(),a=[],l=0;for(;;){let{done:f,value:d}=await o.read();if(f)break;try{r.acceptOutput(d.length)}catch(h){throw await o.cancel(),h}l+=d.length,a.push(d)}let c=new Uint8Array(l),u=0;for(let f of a)c.set(f,u),u+=f.length;return Wi(c,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return{entries:[],error:`Decompression failed: ${s}`}}}function Bw(t){return t.length>=2&&t[0]===31&&t[1]===139}function zw(t){return t.length>=3&&t[0]===66&&t[1]===90&&t[2]===104}function Uw(t){return t.length>=6&&t[0]===253&&t[1]===55&&t[2]===122&&t[3]===88&&t[4]===90&&t[5]===0}async function rV(t,e){let n=new di({maxInputBytes:e.maxCompressedSize,maxOutputBytes:e.maxArchiveSize,maxExpansionRatio:e.maxExpansionRatio,signal:e.signal,label:"bzip2 archive"});n.acceptInput(t.length);let r=Math.min(64*1024,e.maxArchiveSize),s=[],i=Buffer.allocUnsafe(r),o=0,a=0,l={writeByte(c){n.acceptOutput(1),o===i.length&&(s.push(i),i=Buffer.allocUnsafe(r),o=0),i[o++]=c,a++}};return WC.default.decode(Buffer.from(t),l),o>0&&s.push(i.subarray(0,o)),new Uint8Array(Buffer.concat(s,a))}async function sV(t,e){let n=new di({maxInputBytes:e.maxArchiveSize,maxOutputBytes:e.maxCompressedSize,signal:e.signal,label:"bzip2 archive"});n.acceptInput(t.length);let r=await zC(t,9,e.maxArchiveSize,e.maxCompressedSize);return n.acceptOutput(r.length),r}async function iV(t){let n=(await jC()).unxzSync(Buffer.from(t));return new Uint8Array(n)}async function oV(t){let n=(await jC()).xzSync(Buffer.from(t));return new Uint8Array(n)}async function HC(t,e){let n=hi(e),r=await go(t,n);return sV(r,n)}async function GC(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)throw new Error("xz compression is disabled by configuration. Enable native and trusted whole-buffer codecs to use it.");let r=await go(t,n),s=await oV(r);if(n.signal?.throwIfAborted(),s.length>n.maxCompressedSize)throw new Error(`xz archive: output exceeds limit (${n.maxCompressedSize} bytes)`);return s}async function Ww(t,e){let n=hi({...e,maxArchiveSize:e?.maxDecompressedSize??e?.maxArchiveSize});if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=await rV(t,n);return Wi(r,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return s===`bzip2 archive: output exceeds limit (${n.maxArchiveSize} bytes)`?{entries:[],error:`Decompressed archive too large (max ${n.maxArchiveSize} bytes)`}:{entries:[],error:s}}}async function jw(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)return{entries:[],error:"xz decompression is disabled by configuration. Enable native and trusted whole-buffer codecs, or decompress the archive externally before extraction."};if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=await iV(t);return n.signal?.throwIfAborted(),r.length>n.maxArchiveSize?{entries:[],error:`Trusted xz codec produced data over limit (${n.maxArchiveSize} bytes)`}:Wi(r,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return{entries:[],error:s}}}function qw(t){return t.length>=4&&t[0]===40&&t[1]===181&&t[2]===47&&t[3]===253}async function aV(t){let n=await(await qC()).compress(Buffer.from(t),3);return new Uint8Array(n)}async function lV(t){let n=await(await qC()).decompress(Buffer.from(t));return new Uint8Array(n)}async function KC(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)throw new Error("zstd compression is disabled by configuration. Enable native and trusted whole-buffer codecs to use it.");let r=await go(t,n),s=await aV(r);if(n.signal?.throwIfAborted(),s.length>n.maxCompressedSize)throw new Error(`zstd archive: output exceeds limit (${n.maxCompressedSize} bytes)`);return s}async function Vw(t,e){let n=hi(e);if(e?.allowNativeCodecs===!1||!n.allowTrustedWholeBufferCodecs)return{entries:[],error:"zstd decompression is disabled by configuration. Enable native and trusted whole-buffer codecs, or decompress the archive externally before extraction."};if(t.length>n.maxCompressedSize)return{entries:[],error:`Archive too large (max ${n.maxCompressedSize} bytes)`};try{let r=await lV(t);return n.signal?.throwIfAborted(),r.length>n.maxArchiveSize?{entries:[],error:`Trusted zstd codec produced data over limit (${n.maxArchiveSize} bytes)`}:Wi(r,n)}catch(r){let s=r instanceof Error?r.message:"Unknown error";return{entries:[],error:s}}}var WC,hh,ph,mh,gh,_w,Fr,Qq,ZC=L(()=>{"use strict";MC();WC=jt(require("seek-bzip"),1);pe();cn();Cw();UC();hh=null,ph=null;mh=null,gh=null;_w=1024*1024*1024,Fr=512,Qq=1e6});function XC(t){let e=t.length>0&&t[0]!==""&&!t[0].startsWith("-")?cV(t):t,n={create:!1,append:!1,update:!1,extract:!1,list:!1,file:"",autoCompress:!1,gzip:!1,bzip2:!1,xz:!1,zstd:!1,verbose:!1,toStdout:!1,keepOldFiles:!1,touch:!1,directory:"",preserve:!1,absoluteNames:!1,strip:0,exclude:[],filesFrom:"",excludeFrom:"",wildcards:!1},r=[],s=0;for(;s<e.length;){let i=e[s];if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2){if(/^-\d+$/.test(i)){r.push(i),s++;continue}for(let o=1;o<i.length;o++){let a=i[o];switch(a){case"c":n.create=!0;break;case"r":n.append=!0;break;case"u":n.update=!0;break;case"x":n.extract=!0;break;case"t":n.list=!0;break;case"a":n.autoCompress=!0;break;case"z":n.gzip=!0;break;case"j":n.bzip2=!0;break;case"J":n.xz=!0;break;case"v":n.verbose=!0;break;case"O":n.toStdout=!0;break;case"k":n.keepOldFiles=!0;break;case"m":n.touch=!0;break;case"p":n.preserve=!0;break;case"P":n.absoluteNames=!0;break;case"f":if(o<i.length-1)n.file=i.substring(o+1),o=i.length;else{if(s++,s>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'f'
|
|
785
785
|
`,exitCode:2}};n.file=e[s]}break;case"C":if(o<i.length-1)n.directory=i.substring(o+1),o=i.length;else{if(s++,s>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'C'
|
|
786
786
|
`,exitCode:2}};n.directory=e[s]}break;case"T":if(o<i.length-1)n.filesFrom=i.substring(o+1),o=i.length;else{if(s++,s>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'T'
|
|
787
787
|
`,exitCode:2}};n.filesFrom=e[s]}break;case"X":if(o<i.length-1)n.excludeFrom=i.substring(o+1),o=i.length;else{if(s++,s>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'X'
|
|
@@ -852,14 +852,14 @@ When no FILE is given, or when FILE is -, read from standard input.`,options:["-
|
|
|
852
852
|
`:`
|
|
853
853
|
`,r=e.whitespace?" = ":"=",s=[],i=e.sort?Object.keys(t).sort():Object.keys(t),o=0;e.align&&(o=qi(i.filter(c=>t[c]===null||Array.isArray(t[c])||typeof t[c]!="object").map(c=>Array.isArray(t[c])?`${c}[]`:c).concat([""]).reduce((c,u)=>qi(c).length>=qi(u).length?c:u)).length);let a="",l=e.bracketedArray?"[]":"";for(let c of i){let u=t[c];if(u&&Array.isArray(u))for(let f of u)a+=qi(`${c}${l}`).padEnd(o," ")+r+qi(f)+n;else u&&typeof u=="object"?s.push(c):a+=qi(c).padEnd(o," ")+r+qi(u)+n}e.section&&a.length&&(a="["+qi(e.section)+"]"+(e.newline?n+n:n)+a);for(let c of s){let u=s5(c,".").join("\\."),f=(e.section?e.section+".":"")+u,d=Ob(t[c],{...e,section:f});a.length&&d.length&&(a+=n),a+=d}return a};function s5(t,e){var n=0,r=0,s=0,i=[];do if(s=t.indexOf(e,n),s!==-1){if(n=s+e.length,s>0&&t[s-1]==="\\")continue;i.push(t.slice(r,s)),r=s+e.length}while(s!==-1);return i.push(t.slice(r)),i}var r5=(t,e={})=>{e.bracketedArray=e.bracketedArray!==!1;let n=Object.create(null),r=n,s=null,i=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=t.split(/[\r\n]+/g),a={};for(let c of o){if(!c||c.match(/^\s*[;#]/)||c.match(/^\s*$/))continue;let u=c.match(i);if(!u)continue;if(u[1]!==void 0){if(s=$h(u[1]),s==="__proto__"){r=Object.create(null);continue}r=n[s]=n[s]||Object.create(null);continue}let f=$h(u[2]),d;e.bracketedArray?d=f.length>2&&f.slice(-2)==="[]":(a[f]=(a?.[f]||0)+1,d=a[f]>1);let h=d&&f.endsWith("[]")?f.slice(0,-2):f;if(h==="__proto__")continue;let p=u[3]?$h(u[4]):!0,m=p==="true"||p==="false"||p==="null"?JSON.parse(p):p;d&&(Tb.call(r,h)?Array.isArray(r[h])||(r[h]=[r[h]]):r[h]=[]),Array.isArray(r[h])?r[h].push(m):r[h]=m}let l=[];for(let c of Object.keys(n)){if(!Tb.call(n,c)||typeof n[c]!="object"||Array.isArray(n[c]))continue;let u=s5(c,".");r=n;let f=u.pop(),d=f.replace(/\\\./g,".");for(let h of u)h!=="__proto__"&&((!Tb.call(r,h)||typeof r[h]!="object")&&(r[h]=Object.create(null)),r=r[h]);r===n&&d===f||(r[d]=n[c],l.push(c))}for(let c of l)delete n[c];return n},i5=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),qi=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&i5(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),$h=t=>{if(t=(t||"").trim(),i5(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let e=!1,n="";for(let r=0,s=t.length;r<s;r++){let i=t.charAt(r);if(e)"\\;#".indexOf(i)!==-1?n+=i:n+="\\"+i,e=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?e=!0:n+=i}}return e&&(n+="\\"),n.trim()}return t};o5.exports={parse:r5,decode:r5,stringify:Ob,encode:Ob,safe:qi,unsafe:$h}});var Pb=ge((Ib,Rb)=>{(function(t,e){typeof define=="function"&&define.amd?define([],e):typeof Rb=="object"&&typeof Ib<"u"?Rb.exports=e():t.Papa=e()})(Ib,function t(){"use strict";var e=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof e<"u"?e:{}})();function n(){var C=e.URL||e.webkitURL||null,O=t.toString();return a.BLOB_URL||(a.BLOB_URL=C.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",O,")();"],{type:"text/javascript"})))}var r=!e.document&&!!e.postMessage,s=e.IS_PAPA_WORKER||!1,i={},o=0,a={};a.parse=c,a.unparse=u,a.RECORD_SEP="",a.UNIT_SEP="",a.BYTE_ORDER_MARK="\uFEFF",a.BAD_DELIMITERS=["\r",`
|
|
854
854
|
`,'"',a.BYTE_ORDER_MARK],a.WORKERS_SUPPORTED=!r&&!!e.Worker,a.NODE_STREAM_INPUT=1,a.LocalChunkSize=1024*1024*10,a.RemoteChunkSize=1024*1024*5,a.DefaultDelimiter=",",a.Parser=b,a.ParserHandle=y,a.NetworkStreamer=d,a.FileStreamer=h,a.StringStreamer=p,a.ReadableStreamStreamer=m,typeof PAPA_BROWSER_CONTEXT>"u"&&(a.DuplexStreamStreamer=g),s&&(e.onmessage=N);function l(C){return C.charCodeAt(0)===65279?C.slice(1):C}function c(C,O){O=O||{};var F=O.dynamicTyping||!1;if($(F)&&(O.dynamicTypingFunction=F,F={}),O.dynamicTyping=F,O.transform=$(O.transform)?O.transform:!1,O.worker&&a.WORKERS_SUPPORTED){var R=x();R.userStep=O.step,R.userChunk=O.chunk,R.userComplete=O.complete,R.userError=O.error,O.step=$(O.step),O.chunk=$(O.chunk),O.complete=$(O.complete),O.error=$(O.error),delete O.worker,R.postMessage({input:C,config:O,workerId:R.id});return}var _=null;return C===a.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u"?(_=new g(O),_.getStream()):(typeof C=="string"?(C=l(C),O.download?_=new d(O):_=new p(O)):C.readable===!0&&$(C.read)&&$(C.on)?_=new m(O):(e.File&&C instanceof File||C instanceof Object)&&(_=new h(O)),_.stream(C))}function u(C,O){var F=!1,R=!0,_=",",U=`\r
|
|
855
|
-
`,B='"',W=B+B,M=!1,Y=null,q=!1;re();var H=new RegExp(w(B),"g");if(typeof C=="string"&&(C=JSON.parse(C)),Array.isArray(C)){if(!C.length||Array.isArray(C[0]))return se(null,C,M);if(typeof C[0]=="object")return se(Y||Object.keys(C[0]),C,M)}else if(typeof C=="object")return typeof C.data=="string"&&(C.data=JSON.parse(C.data)),Array.isArray(C.data)&&(C.fields||(C.fields=C.meta&&C.meta.fields||Y),C.fields||(C.fields=Array.isArray(C.data[0])?C.fields:typeof C.data[0]=="object"?Object.keys(C.data[0]):[]),!Array.isArray(C.data[0])&&typeof C.data[0]!="object"&&(C.data=[C.data])),se(C.fields||[],C.data||[],M);throw new Error("Unable to serialize unrecognized input");function re(){if(typeof O=="object"){if(typeof O.delimiter=="string"&&!a.BAD_DELIMITERS.filter(function(oe){return O.delimiter.indexOf(oe)!==-1}).length&&(_=O.delimiter),(typeof O.quotes=="boolean"||typeof O.quotes=="function"||Array.isArray(O.quotes))&&(F=O.quotes),(typeof O.skipEmptyLines=="boolean"||typeof O.skipEmptyLines=="string")&&(M=O.skipEmptyLines),typeof O.newline=="string"&&(U=O.newline),typeof O.quoteChar=="string"&&(B=O.quoteChar,W=B+B),typeof O.header=="boolean"&&(R=O.header),Array.isArray(O.columns)){if(O.columns.length===0)throw new Error("Option columns is empty");Y=O.columns}O.escapeChar!==void 0&&(W=O.escapeChar+B),O.escapeFormulae instanceof RegExp?q=O.escapeFormulae:typeof O.escapeFormulae=="boolean"&&O.escapeFormulae&&(q=/^[=+\-@\t\r].*$/)}}function se(oe,Se,te){var ne="";typeof oe=="string"&&(oe=JSON.parse(oe)),typeof Se=="string"&&(Se=JSON.parse(Se));var Ie=Array.isArray(oe)&&oe.length>0,ye=!Array.isArray(Se[0]);if(Ie&&R){for(var Le=0;Le<oe.length;Le++)Le>0&&(ne+=_),ne+=de(oe[Le],Le);Se.length>0&&(ne+=U)}for(var Ce=0;Ce<Se.length;Ce++){var Ae=Ie?oe.length:Se[Ce].length,ln=!1,Te=Ie?Object.keys(Se[Ce]).length===0:Se[Ce].length===0;if(te&&!Ie&&(ln=te==="greedy"?Se[Ce].join("").trim()==="":Se[Ce].length===1&&Se[Ce][0].length===0),te==="greedy"&&Ie){for(var Ne=[],Ke=0;Ke<Ae;Ke++){var xt=ye?oe[Ke]:Ke;Ne.push(Se[Ce][xt])}ln=Ne.join("").trim()===""}if(!ln){for(var Ee=0;Ee<Ae;Ee++){Ee>0&&!Te&&(ne+=_);var nt=Ie&&ye?oe[Ee]:Ee;ne+=de(Se[Ce][nt],Ee)}Ce<Se.length-1&&(!te||Ae>0&&!Te)&&(ne+=U)}}return ne}function de(oe,Se){if(typeof oe>"u"||oe===null)return"";if(oe.constructor===Date)return isNaN(oe.getTime())?"":oe.toISOString();var te=!1;q&&typeof oe=="string"&&q.test(oe)&&(oe="'"+oe,te=!0);var ne=oe.toString(),Ie=ne.replace(H,W);return te=te||F===!0||typeof F=="function"&&F(oe,Se)||Array.isArray(F)&&F[Se]||Oe(Ie,a.BAD_DELIMITERS)||Ie.indexOf(_)>-1||ne.indexOf(B)>-1||Ie.charAt(0)===" "||Ie.charAt(Ie.length-1)===" ",te?B+Ie+B:Ie}function Oe(oe,Se){for(var te=0;te<Se.length;te++)if(oe.indexOf(Se[te])>-1)return!0;return!1}}function f(C){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},O.call(this,C),this.parseChunk=function(F,R){let _=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&_>0){let q=this._config.newline;if(!q){let re=this._config.quoteChar||'"';q=this._handle.guessLineEndings(F,re)}F=[...F.split(q).slice(_)].join(q)}if(this.isFirstChunk&&$(this._config.beforeFirstChunk)){var U=this._config.beforeFirstChunk(F);U!==void 0&&(F=U)}this.isFirstChunk=!1,this._halted=!1;var B=this._partialLine+F;this._partialLine="";var W=this._handle.parse(B,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var M=W.meta.cursor;this._finished||(this._partialLine=B.substring(M-this._baseIndex),this._baseIndex=M),W&&W.data&&(this._rowCount+=W.data.length);var Y=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(s)e.postMessage({results:W,workerId:a.WORKER_ID,finished:Y});else if($(this._config.chunk)&&!R){if(this._config.chunk(W,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}W=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(W.data),this._completeResults.errors=this._completeResults.errors.concat(W.errors),this._completeResults.meta=W.meta),!this._completed&&Y&&$(this._config.complete)&&(!W||!W.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!Y&&(!W||!W.meta.paused)&&this._nextChunk(),W},this._sendError=function(F){$(this._config.error)?this._config.error(F):s&&this._config.error&&e.postMessage({workerId:a.WORKER_ID,error:F,finished:!1})};function O(F){var R=I(F);R.chunkSize=parseInt(R.chunkSize),!F.step&&!F.chunk&&(R.chunkSize=null),this._handle=new y(R),this._handle.streamer=this,this._config=R}}function d(C){C=C||{},C.chunkSize||(C.chunkSize=a.RemoteChunkSize),f.call(this,C);var O;r?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(R){this._input=R,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(O=new XMLHttpRequest,this._config.withCredentials&&(O.withCredentials=this._config.withCredentials),r||(O.onload=T(this._chunkLoaded,this),O.onerror=T(this._chunkError,this)),O.open(this._config.downloadRequestBody?"POST":"GET",this._input,!r),this._config.downloadRequestHeaders){var R=this._config.downloadRequestHeaders;for(var _ in R)O.setRequestHeader(_,R[_])}if(this._config.chunkSize){var U=this._start+this._config.chunkSize-1;O.setRequestHeader("Range","bytes="+this._start+"-"+U)}try{O.send(this._config.downloadRequestBody)}catch(B){this._chunkError(B.message)}r&&O.status===0&&this._chunkError()},this._chunkLoaded=function(){if(O.readyState===4){if(O.status<200||O.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:O.responseText.length,this._finished=!this._config.chunkSize||this._start>=F(O),this.parseChunk(O.responseText)}},this._chunkError=function(R){var _=O.statusText||R;this._sendError(new Error(_))};function F(R){var _=R.getResponseHeader("Content-Range");return _===null?-1:parseInt(_.substring(_.lastIndexOf("/")+1))}}d.prototype=Object.create(f.prototype),d.prototype.constructor=d;function h(C){C=C||{},C.chunkSize||(C.chunkSize=a.LocalChunkSize),f.call(this,C);var O,F,R=typeof FileReader<"u";this.stream=function(_){this._input=_,F=_.slice||_.webkitSlice||_.mozSlice,R?(O=new FileReader,O.onload=T(this._chunkLoaded,this),O.onerror=T(this._chunkError,this)):O=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){!this._finished&&(!this._config.preview||this._rowCount<this._config.preview)&&this._readChunk()},this._readChunk=function(){var _=this._input;if(this._config.chunkSize){var U=Math.min(this._start+this._config.chunkSize,this._input.size);_=F.call(_,this._start,U)}var B=O.readAsText(_,this._config.encoding);R||this._chunkLoaded({target:{result:B}})},this._chunkLoaded=function(_){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(_.target.result)},this._chunkError=function(){this._sendError(O.error)}}h.prototype=Object.create(f.prototype),h.prototype.constructor=h;function p(C){C=C||{},f.call(this,C);var O;this.stream=function(F){return O=F,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var F=this._config.chunkSize,R;return F?(R=O.substring(0,F),O=O.substring(F)):(R=O,O=""),this._finished=!O,this.parseChunk(R)}}}p.prototype=Object.create(p.prototype),p.prototype.constructor=p;function m(C){C=C||{},f.call(this,C);var O=[],F=!0,R=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(_){this._input=_,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){R&&O.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),O.length?this.parseChunk(O.shift()):F=!0},this._streamData=T(function(_){try{O.push(typeof _=="string"?_:_.toString(this._config.encoding)),F&&(F=!1,this._checkIsFinished(),this.parseChunk(O.shift()))}catch(U){this._streamError(U)}},this),this._streamError=T(function(_){this._streamCleanUp(),this._sendError(_)},this),this._streamEnd=T(function(){this._streamCleanUp(),R=!0,this._streamData("")},this),this._streamCleanUp=T(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}m.prototype=Object.create(f.prototype),m.prototype.constructor=m;function g(C){var O=require("stream").Duplex,F=I(C),R=!0,_=!1,U=[],B=null;this._onCsvData=function(W){var M=W.data;!B.push(M)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){B.push(null)},F.step=T(this._onCsvData,this),F.complete=T(this._onCsvComplete,this),f.call(this,F),this._nextChunk=function(){_&&U.length===1&&(this._finished=!0),U.length?U.shift()():R=!0},this._addToParseQueue=function(W,M){U.push(T(function(){if(this.parseChunk(typeof W=="string"?W:W.toString(F.encoding)),$(M))return M()},this)),R&&(R=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(W,M,Y){this._addToParseQueue(W,Y)},this._onWriteComplete=function(){_=!0,this._addToParseQueue("")},this.getStream=function(){return B},B=new O({readableObjectMode:!0,decodeStrings:!1,read:T(this._onRead,this),write:T(this._onWrite,this)}),B.once("finish",T(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(g.prototype=Object.create(f.prototype),g.prototype.constructor=g);function y(C){var O=Math.pow(2,53),F=-O,R=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,_=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,U=this,B=0,W=0,M,Y,q=!1,H=!1,re,se=[],de={data:[],errors:[],meta:{}};if($(C.step)){var Oe=C.step;C.step=function(Te){if(de=Te,ne())te();else{if(te(),de.data.length===0)return;B+=Te.data.length,C.preview&&B>C.preview?Y.abort():(de.data=de.data[0],Oe(de,U))}}}this.parse=function(Te,Ne,Ke){var xt=C.quoteChar||'"';if(C.newline||(C.newline=this.guessLineEndings(Te,xt)),re=!1,C.delimiter)$(C.delimiter)&&(C.delimiter=C.delimiter(Te),de.meta.delimiter=C.delimiter);else{var Ee=Ae(Te,C.newline,C.skipEmptyLines,C.comments,C.delimitersToGuess);Ee.successful?C.delimiter=Ee.bestDelimiter:(re=!0,C.delimiter=a.DefaultDelimiter),de.meta.delimiter=C.delimiter}var nt=I(C);return C.preview&&C.header&&nt.preview++,M=Te,Y=new b(nt),de=Y.parse(M,Ne,Ke),te(),q?{meta:{paused:!0}}:de||{meta:{paused:!1}}},this.paused=function(){return q},this.pause=function(){q=!0,Y.abort(),M=$(C.chunk)?"":M.substring(Y.getCharIndex())},this.resume=function(){U.streamer._halted?(q=!1,U.streamer.parseChunk(M,!0)):setTimeout(U.resume,3)},this.aborted=function(){return H},this.abort=function(){H=!0,Y.abort(),de.meta.aborted=!0,$(C.complete)&&C.complete(de),M=""},this.guessLineEndings=function(Te,Ne){Te=Te.substring(0,1024*1024);var Ke=new RegExp(w(Ne)+"([^]*?)"+w(Ne),"gm");Te=Te.replace(Ke,"");var xt=Te.split("\r"),Ee=Te.split(`
|
|
856
|
-
`),
|
|
855
|
+
`,B='"',W=B+B,M=!1,Y=null,q=!1;re();var H=new RegExp(w(B),"g");if(typeof C=="string"&&(C=JSON.parse(C)),Array.isArray(C)){if(!C.length||Array.isArray(C[0]))return se(null,C,M);if(typeof C[0]=="object")return se(Y||Object.keys(C[0]),C,M)}else if(typeof C=="object")return typeof C.data=="string"&&(C.data=JSON.parse(C.data)),Array.isArray(C.data)&&(C.fields||(C.fields=C.meta&&C.meta.fields||Y),C.fields||(C.fields=Array.isArray(C.data[0])?C.fields:typeof C.data[0]=="object"?Object.keys(C.data[0]):[]),!Array.isArray(C.data[0])&&typeof C.data[0]!="object"&&(C.data=[C.data])),se(C.fields||[],C.data||[],M);throw new Error("Unable to serialize unrecognized input");function re(){if(typeof O=="object"){if(typeof O.delimiter=="string"&&!a.BAD_DELIMITERS.filter(function(oe){return O.delimiter.indexOf(oe)!==-1}).length&&(_=O.delimiter),(typeof O.quotes=="boolean"||typeof O.quotes=="function"||Array.isArray(O.quotes))&&(F=O.quotes),(typeof O.skipEmptyLines=="boolean"||typeof O.skipEmptyLines=="string")&&(M=O.skipEmptyLines),typeof O.newline=="string"&&(U=O.newline),typeof O.quoteChar=="string"&&(B=O.quoteChar,W=B+B),typeof O.header=="boolean"&&(R=O.header),Array.isArray(O.columns)){if(O.columns.length===0)throw new Error("Option columns is empty");Y=O.columns}O.escapeChar!==void 0&&(W=O.escapeChar+B),O.escapeFormulae instanceof RegExp?q=O.escapeFormulae:typeof O.escapeFormulae=="boolean"&&O.escapeFormulae&&(q=/^[=+\-@\t\r].*$/)}}function se(oe,Se,te){var ne="";typeof oe=="string"&&(oe=JSON.parse(oe)),typeof Se=="string"&&(Se=JSON.parse(Se));var Oe=Array.isArray(oe)&&oe.length>0,ye=!Array.isArray(Se[0]);if(Oe&&R){for(var Le=0;Le<oe.length;Le++)Le>0&&(ne+=_),ne+=de(oe[Le],Le);Se.length>0&&(ne+=U)}for(var Ae=0;Ae<Se.length;Ae++){var ve=Oe?oe.length:Se[Ae].length,ln=!1,Te=Oe?Object.keys(Se[Ae]).length===0:Se[Ae].length===0;if(te&&!Oe&&(ln=te==="greedy"?Se[Ae].join("").trim()==="":Se[Ae].length===1&&Se[Ae][0].length===0),te==="greedy"&&Oe){for(var Ne=[],Ke=0;Ke<ve;Ke++){var xt=ye?oe[Ke]:Ke;Ne.push(Se[Ae][xt])}ln=Ne.join("").trim()===""}if(!ln){for(var Ee=0;Ee<ve;Ee++){Ee>0&&!Te&&(ne+=_);var rt=Oe&&ye?oe[Ee]:Ee;ne+=de(Se[Ae][rt],Ee)}Ae<Se.length-1&&(!te||ve>0&&!Te)&&(ne+=U)}}return ne}function de(oe,Se){if(typeof oe>"u"||oe===null)return"";if(oe.constructor===Date)return isNaN(oe.getTime())?"":oe.toISOString();var te=!1;q&&typeof oe=="string"&&q.test(oe)&&(oe="'"+oe,te=!0);var ne=oe.toString(),Oe=ne.replace(H,W);return te=te||F===!0||typeof F=="function"&&F(oe,Se)||Array.isArray(F)&&F[Se]||Ie(Oe,a.BAD_DELIMITERS)||Oe.indexOf(_)>-1||ne.indexOf(B)>-1||Oe.charAt(0)===" "||Oe.charAt(Oe.length-1)===" ",te?B+Oe+B:Oe}function Ie(oe,Se){for(var te=0;te<Se.length;te++)if(oe.indexOf(Se[te])>-1)return!0;return!1}}function f(C){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},O.call(this,C),this.parseChunk=function(F,R){let _=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&_>0){let q=this._config.newline;if(!q){let re=this._config.quoteChar||'"';q=this._handle.guessLineEndings(F,re)}F=[...F.split(q).slice(_)].join(q)}if(this.isFirstChunk&&$(this._config.beforeFirstChunk)){var U=this._config.beforeFirstChunk(F);U!==void 0&&(F=U)}this.isFirstChunk=!1,this._halted=!1;var B=this._partialLine+F;this._partialLine="";var W=this._handle.parse(B,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var M=W.meta.cursor;this._finished||(this._partialLine=B.substring(M-this._baseIndex),this._baseIndex=M),W&&W.data&&(this._rowCount+=W.data.length);var Y=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(s)e.postMessage({results:W,workerId:a.WORKER_ID,finished:Y});else if($(this._config.chunk)&&!R){if(this._config.chunk(W,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}W=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(W.data),this._completeResults.errors=this._completeResults.errors.concat(W.errors),this._completeResults.meta=W.meta),!this._completed&&Y&&$(this._config.complete)&&(!W||!W.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!Y&&(!W||!W.meta.paused)&&this._nextChunk(),W},this._sendError=function(F){$(this._config.error)?this._config.error(F):s&&this._config.error&&e.postMessage({workerId:a.WORKER_ID,error:F,finished:!1})};function O(F){var R=I(F);R.chunkSize=parseInt(R.chunkSize),!F.step&&!F.chunk&&(R.chunkSize=null),this._handle=new y(R),this._handle.streamer=this,this._config=R}}function d(C){C=C||{},C.chunkSize||(C.chunkSize=a.RemoteChunkSize),f.call(this,C);var O;r?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(R){this._input=R,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(O=new XMLHttpRequest,this._config.withCredentials&&(O.withCredentials=this._config.withCredentials),r||(O.onload=T(this._chunkLoaded,this),O.onerror=T(this._chunkError,this)),O.open(this._config.downloadRequestBody?"POST":"GET",this._input,!r),this._config.downloadRequestHeaders){var R=this._config.downloadRequestHeaders;for(var _ in R)O.setRequestHeader(_,R[_])}if(this._config.chunkSize){var U=this._start+this._config.chunkSize-1;O.setRequestHeader("Range","bytes="+this._start+"-"+U)}try{O.send(this._config.downloadRequestBody)}catch(B){this._chunkError(B.message)}r&&O.status===0&&this._chunkError()},this._chunkLoaded=function(){if(O.readyState===4){if(O.status<200||O.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:O.responseText.length,this._finished=!this._config.chunkSize||this._start>=F(O),this.parseChunk(O.responseText)}},this._chunkError=function(R){var _=O.statusText||R;this._sendError(new Error(_))};function F(R){var _=R.getResponseHeader("Content-Range");return _===null?-1:parseInt(_.substring(_.lastIndexOf("/")+1))}}d.prototype=Object.create(f.prototype),d.prototype.constructor=d;function h(C){C=C||{},C.chunkSize||(C.chunkSize=a.LocalChunkSize),f.call(this,C);var O,F,R=typeof FileReader<"u";this.stream=function(_){this._input=_,F=_.slice||_.webkitSlice||_.mozSlice,R?(O=new FileReader,O.onload=T(this._chunkLoaded,this),O.onerror=T(this._chunkError,this)):O=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){!this._finished&&(!this._config.preview||this._rowCount<this._config.preview)&&this._readChunk()},this._readChunk=function(){var _=this._input;if(this._config.chunkSize){var U=Math.min(this._start+this._config.chunkSize,this._input.size);_=F.call(_,this._start,U)}var B=O.readAsText(_,this._config.encoding);R||this._chunkLoaded({target:{result:B}})},this._chunkLoaded=function(_){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(_.target.result)},this._chunkError=function(){this._sendError(O.error)}}h.prototype=Object.create(f.prototype),h.prototype.constructor=h;function p(C){C=C||{},f.call(this,C);var O;this.stream=function(F){return O=F,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var F=this._config.chunkSize,R;return F?(R=O.substring(0,F),O=O.substring(F)):(R=O,O=""),this._finished=!O,this.parseChunk(R)}}}p.prototype=Object.create(p.prototype),p.prototype.constructor=p;function m(C){C=C||{},f.call(this,C);var O=[],F=!0,R=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(_){this._input=_,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){R&&O.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),O.length?this.parseChunk(O.shift()):F=!0},this._streamData=T(function(_){try{O.push(typeof _=="string"?_:_.toString(this._config.encoding)),F&&(F=!1,this._checkIsFinished(),this.parseChunk(O.shift()))}catch(U){this._streamError(U)}},this),this._streamError=T(function(_){this._streamCleanUp(),this._sendError(_)},this),this._streamEnd=T(function(){this._streamCleanUp(),R=!0,this._streamData("")},this),this._streamCleanUp=T(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}m.prototype=Object.create(f.prototype),m.prototype.constructor=m;function g(C){var O=require("stream").Duplex,F=I(C),R=!0,_=!1,U=[],B=null;this._onCsvData=function(W){var M=W.data;!B.push(M)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){B.push(null)},F.step=T(this._onCsvData,this),F.complete=T(this._onCsvComplete,this),f.call(this,F),this._nextChunk=function(){_&&U.length===1&&(this._finished=!0),U.length?U.shift()():R=!0},this._addToParseQueue=function(W,M){U.push(T(function(){if(this.parseChunk(typeof W=="string"?W:W.toString(F.encoding)),$(M))return M()},this)),R&&(R=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(W,M,Y){this._addToParseQueue(W,Y)},this._onWriteComplete=function(){_=!0,this._addToParseQueue("")},this.getStream=function(){return B},B=new O({readableObjectMode:!0,decodeStrings:!1,read:T(this._onRead,this),write:T(this._onWrite,this)}),B.once("finish",T(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(g.prototype=Object.create(f.prototype),g.prototype.constructor=g);function y(C){var O=Math.pow(2,53),F=-O,R=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,_=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,U=this,B=0,W=0,M,Y,q=!1,H=!1,re,se=[],de={data:[],errors:[],meta:{}};if($(C.step)){var Ie=C.step;C.step=function(Te){if(de=Te,ne())te();else{if(te(),de.data.length===0)return;B+=Te.data.length,C.preview&&B>C.preview?Y.abort():(de.data=de.data[0],Ie(de,U))}}}this.parse=function(Te,Ne,Ke){var xt=C.quoteChar||'"';if(C.newline||(C.newline=this.guessLineEndings(Te,xt)),re=!1,C.delimiter)$(C.delimiter)&&(C.delimiter=C.delimiter(Te),de.meta.delimiter=C.delimiter);else{var Ee=ve(Te,C.newline,C.skipEmptyLines,C.comments,C.delimitersToGuess);Ee.successful?C.delimiter=Ee.bestDelimiter:(re=!0,C.delimiter=a.DefaultDelimiter),de.meta.delimiter=C.delimiter}var rt=I(C);return C.preview&&C.header&&rt.preview++,M=Te,Y=new b(rt),de=Y.parse(M,Ne,Ke),te(),q?{meta:{paused:!0}}:de||{meta:{paused:!1}}},this.paused=function(){return q},this.pause=function(){q=!0,Y.abort(),M=$(C.chunk)?"":M.substring(Y.getCharIndex())},this.resume=function(){U.streamer._halted?(q=!1,U.streamer.parseChunk(M,!0)):setTimeout(U.resume,3)},this.aborted=function(){return H},this.abort=function(){H=!0,Y.abort(),de.meta.aborted=!0,$(C.complete)&&C.complete(de),M=""},this.guessLineEndings=function(Te,Ne){Te=Te.substring(0,1024*1024);var Ke=new RegExp(w(Ne)+"([^]*?)"+w(Ne),"gm");Te=Te.replace(Ke,"");var xt=Te.split("\r"),Ee=Te.split(`
|
|
856
|
+
`),rt=Ee.length>1&&Ee[0].length<xt[0].length;if(xt.length===1||rt)return`
|
|
857
857
|
`;for(var Ln=0,wn=0;wn<xt.length;wn++)xt[wn][0]===`
|
|
858
858
|
`&&Ln++;return Ln>=xt.length/2?`\r
|
|
859
|
-
`:"\r"};function oe(Te){return C.skipEmptyLines==="greedy"?Te.join("").trim()==="":Te.length===1&&Te[0].length===0}function Se(Te){if(R.test(Te)){var Ne=parseFloat(Te);if(Ne>F&&Ne<O)return!0}return!1}function te(){return de&&re&&(ln("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),re=!1),C.skipEmptyLines&&(de.data=de.data.filter(function(Te){return!oe(Te)})),ne()&&
|
|
859
|
+
`:"\r"};function oe(Te){return C.skipEmptyLines==="greedy"?Te.join("").trim()==="":Te.length===1&&Te[0].length===0}function Se(Te){if(R.test(Te)){var Ne=parseFloat(Te);if(Ne>F&&Ne<O)return!0}return!1}function te(){return de&&re&&(ln("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),re=!1),C.skipEmptyLines&&(de.data=de.data.filter(function(Te){return!oe(Te)})),ne()&&Oe(),Ae()}function ne(){return C.header&&se.length===0}function Oe(){if(!de)return;function Te(Ke,xt){Ke=l(Ke),$(C.transformHeader)&&(Ke=C.transformHeader(Ke,xt)),se.push(Ke)}if(Array.isArray(de.data[0])){for(var Ne=0;ne()&&Ne<de.data.length;Ne++)de.data[Ne].forEach(Te);de.data.splice(0,1)}else de.data.forEach(Te)}function ye(Te){return C.dynamicTypingFunction&&C.dynamicTyping[Te]===void 0&&(C.dynamicTyping[Te]=C.dynamicTypingFunction(Te)),(C.dynamicTyping[Te]||C.dynamicTyping)===!0}function Le(Te,Ne){return ye(Te)?Ne==="true"||Ne==="TRUE"?!0:Ne==="false"||Ne==="FALSE"?!1:Se(Ne)?parseFloat(Ne):_.test(Ne)?new Date(Ne):Ne===""?null:Ne:Ne}function Ae(){if(!de||!C.header&&!C.dynamicTyping&&!C.transform)return de;function Te(Ke,xt){var Ee=C.header?{}:[],rt;for(rt=0;rt<Ke.length;rt++){var Ln=rt,wn=Ke[rt];C.header&&(Ln=rt>=se.length?"__parsed_extra":se[rt]),C.transform&&(wn=C.transform(wn,Ln)),wn=Le(Ln,wn),Ln==="__parsed_extra"?(Ee[Ln]=Ee[Ln]||[],Ee[Ln].push(wn)):Ee[Ln]=wn}return C.header&&(rt>se.length?ln("FieldMismatch","TooManyFields","Too many fields: expected "+se.length+" fields but parsed "+rt,W+xt):rt<se.length&&ln("FieldMismatch","TooFewFields","Too few fields: expected "+se.length+" fields but parsed "+rt,W+xt)),Ee}var Ne=1;return!de.data.length||Array.isArray(de.data[0])?(de.data=de.data.map(Te),Ne=de.data.length):de.data=Te(de.data,0),C.header&&de.meta&&(de.meta.fields=se),W+=Ne,de}function ve(Te,Ne,Ke,xt,Ee){var rt,Ln,wn,Ka;Ee=Ee||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var Yi=0;Yi<Ee.length;Yi++){var xc=Ee[Yi],Qi=0,Ji=0,Qn=0;wn=void 0;for(var ei=new b({comments:xt,delimiter:xc,newline:Ne,preview:10}).parse(Te),Bn=0;Bn<ei.data.length;Bn++){if(Ke&&oe(ei.data[Bn])){Qn++;continue}var Ar=ei.data[Bn].length;if(Ji+=Ar,typeof wn>"u"){wn=Ar;continue}else Ar>0&&(Qi+=Math.abs(Ar-wn),wn=Ar)}ei.data.length>0&&(Ji/=ei.data.length-Qn),Ji>1.99&&(typeof Ln>"u"||Qi<Ln||Qi===Ln&&Ji>Ka)&&(Ln=Qi,rt=xc,Ka=Ji)}return C.delimiter=rt,{successful:!!rt,bestDelimiter:rt}}function ln(Te,Ne,Ke,xt){var Ee={type:Te,code:Ne,message:Ke};xt!==void 0&&(Ee.row=xt),de.errors.push(Ee)}}function w(C){return C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b(C){C=C||{};var O=C.delimiter,F=C.newline,R=C.comments,_=C.step,U=C.preview,B=C.fastMode,W,M=null,Y=!1;C.quoteChar===void 0||C.quoteChar===null?W='"':W=C.quoteChar;var q=W;if(C.escapeChar!==void 0&&(q=C.escapeChar),(typeof O!="string"||a.BAD_DELIMITERS.indexOf(O)>-1)&&(O=","),R===O)throw new Error("Comment character same as delimiter");R===!0?R="#":(typeof R!="string"||a.BAD_DELIMITERS.indexOf(R)>-1)&&(R=!1),F!==`
|
|
860
860
|
`&&F!=="\r"&&F!==`\r
|
|
861
861
|
`&&(F=`
|
|
862
|
-
`);var H=0,re=!1;this.parse=function(se,de,
|
|
862
|
+
`);var H=0,re=!1;this.parse=function(se,de,Ie){if(typeof se!="string")throw new Error("Input must be a string");var oe=se.length,Se=O.length,te=F.length,ne=R.length,Oe=$(_);H=0;var ye=[],Le=[],Ae=[],ve=0;if(!se)return Qn();if(B||B!==!1&&se.indexOf(W)===-1){for(var ln=se.split(F),Te=0;Te<ln.length;Te++){if(Ae=ln[Te],H+=Ae.length,Te!==ln.length-1)H+=F.length;else if(Ie)return Qn();if(!(R&&Ae.substring(0,ne)===R)){if(Oe){if(ye=[],Yi(Ae.split(O)),ei(),re)return Qn()}else Yi(Ae.split(O));if(U&&Te>=U)return ye=ye.slice(0,U),Qn(!0)}}return Qn()}for(var Ne=se.indexOf(O,H),Ke=se.indexOf(F,H),xt=new RegExp(w(q)+w(W),"g"),Ee=se.indexOf(W,H);;){if(se[H]===W){for(Ee=H,H++;;){if(Ee=se.indexOf(W,Ee+1),Ee===-1)return Ie||Le.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:ye.length,index:H}),Qi();if(Ee===oe-1){var rt=se.substring(H,Ee).replace(xt,W);return Qi(rt)}if(W===q&&se[Ee+1]===q){Ee++;continue}if(!(W!==q&&Ee!==0&&se[Ee-1]===q)){Ne!==-1&&Ne<Ee+1&&(Ne=se.indexOf(O,Ee+1)),Ke!==-1&&Ke<Ee+1&&(Ke=se.indexOf(F,Ee+1));var Ln=Ke===-1?Ne:Math.min(Ne,Ke),wn=xc(Ln);if(se.substr(Ee+1+wn,Se)===O){Ae.push(se.substring(H,Ee).replace(xt,W)),H=Ee+1+wn+Se,se[Ee+1+wn+Se]!==W&&(Ee=se.indexOf(W,H)),Ne=se.indexOf(O,H),Ke=se.indexOf(F,H);break}var Ka=xc(Ke);if(se.substring(Ee+1+Ka,Ee+1+Ka+te)===F){if(Ae.push(se.substring(H,Ee).replace(xt,W)),Ji(Ee+1+Ka+te),Ne=se.indexOf(O,H),Ee=se.indexOf(W,H),Oe&&(ei(),re))return Qn();if(U&&ye.length>=U)return Qn(!0);break}Le.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:ye.length,index:H}),Ee++}}continue}if(R&&Ae.length===0&&se.substring(H,H+ne)===R){if(Ke===-1)return Qn();H=Ke+te,Ke=se.indexOf(F,H),Ne=se.indexOf(O,H);continue}if(Ne!==-1&&(Ne<Ke||Ke===-1)){Ae.push(se.substring(H,Ne)),H=Ne+Se,Ne=se.indexOf(O,H);continue}if(Ke!==-1){if(Ae.push(se.substring(H,Ke)),Ji(Ke+te),Oe&&(ei(),re))return Qn();if(U&&ye.length>=U)return Qn(!0);continue}break}return Qi();function Yi(Bn){ye.push(Bn),ve=H}function xc(Bn){var Ar=0;if(Bn!==-1){var eo=se.substring(Ee+1,Bn);eo&&eo.trim()===""&&(Ar=eo.length)}return Ar}function Qi(Bn){return Ie||(typeof Bn>"u"&&(Bn=se.substring(H)),Ae.push(Bn),H=oe,Yi(Ae),Oe&&ei()),Qn()}function Ji(Bn){H=Bn,Yi(Ae),Ae=[],Ke=se.indexOf(F,H)}function Qn(Bn){if(C.header&&!de&&ye.length&&!Y){let Ar=ye[0],eo=Object.create(null),E1=new Set(Ar),G7=!1;for(let Za=0;Za<Ar.length;Za++){let ti=l(Ar[Za]);if($(C.transformHeader)&&(ti=C.transformHeader(ti,Za)),!eo[ti])eo[ti]=1,Ar[Za]=ti;else{let Ec,K7=eo[ti];do Ec=`${ti}_${K7}`,K7++;while(E1.has(Ec));E1.add(Ec),Ar[Za]=Ec,eo[ti]++,G7=!0,M===null&&(M={}),M[Ec]=ti}E1.add(ti)}G7&&console.warn("Duplicate headers found and renamed."),Y=!0}return{data:ye,errors:Le,meta:{delimiter:O,linebreak:F,aborted:re,truncated:!!Bn,cursor:ve+(de||0),renamedHeaders:M}}}function ei(){_(Qn()),ye=[],Le=[]}},this.abort=function(){re=!0},this.getCharIndex=function(){return H}}function x(){if(!a.WORKERS_SUPPORTED)return!1;var C=n(),O=new e.Worker(C);return O.onmessage=S,O.id=o++,i[O.id]=O,O}function S(C){var O=C.data,F=i[O.workerId],R=!1;if(O.error)F.userError(O.error,O.file);else if(O.results&&O.results.data){var _=function(){R=!0,E(O.workerId,{data:[],errors:[],meta:{aborted:!0}})},U={abort:_,pause:A,resume:A};if($(F.userStep)){for(var B=0;B<O.results.data.length&&(F.userStep({data:O.results.data[B],errors:O.results.errors,meta:O.results.meta},U),!R);B++);delete O.results}else $(F.userChunk)&&(F.userChunk(O.results,U,O.file),delete O.results)}O.finished&&!R&&E(O.workerId,O.results)}function E(C,O){var F=i[C];$(F.userComplete)&&F.userComplete(O),F.terminate(),delete i[C]}function A(){throw new Error("Not implemented.")}function N(C){var O=C.data;if(typeof a.WORKER_ID>"u"&&O&&(a.WORKER_ID=O.workerId),typeof O.input=="string")e.postMessage({workerId:a.WORKER_ID,results:a.parse(O.input,O.config),finished:!0});else if(e.File&&O.input instanceof File||O.input instanceof Object){var F=a.parse(O.input,O.config);F&&e.postMessage({workerId:a.WORKER_ID,results:F,finished:!0})}}function I(C){if(typeof C!="object"||C===null)return C;var O=Array.isArray(C)?[]:{};for(var F in C)O[F]=I(C[F]);return O}function T(C,O){return function(){C.apply(O,arguments)}}function $(C){return typeof C=="function"}return a})});function jH(t,e){let n=t.slice(0,e).split(/\r?\n/);return[n.length,n.pop().length+1]}function qH(t,e,n){let r=t.split(/\r?\n/),s="",i=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=r[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
|
|
863
863
|
`,o===e&&(s+=" ".repeat(i+n+2),s+=`^
|
|
864
864
|
`))}return s}var je,Ea=L(()=>{je=class t extends Error{line;column;codeblock;constructor(e,n){let[r,s]=jH(n.toml,n.ptr),i=qH(n.toml,r,s);super(`Invalid TOML document: ${e}
|
|
865
865
|
|
|
@@ -1261,7 +1261,7 @@ Run 'xan --help' for usage.
|
|
|
1261
1261
|
`,exitCode:1};e.nullValue=t[++o]}else if(a==="-cmd"){if(o+1>=t.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -cmd
|
|
1262
1262
|
`,exitCode:1};e.cmd=t[++o]}else{if(a.startsWith("-"))return{stdout:"",stderr:`sqlite3: Error: unknown option: ${a.startsWith("--")?a.slice(1):a}
|
|
1263
1263
|
Use -help for a list of options.
|
|
1264
|
-
`,exitCode:1};n===null?n=a:r===null&&(r=a)}}return{options:e,database:n,sql:r,showVersion:s}}async function wQ(){let t=await
|
|
1264
|
+
`,exitCode:1};n===null?n=a:r===null&&(r=a)}}return{options:e,database:n,sql:r,showVersion:s}}async function wQ(){let t=await nt.runTrustedAsync(()=>(0,tI.default)()),e=new t.Database;try{let n=e.exec("SELECT sqlite_version()");return n.length>0&&n[0].values.length>0?String(n[0].values[0][0]):"unknown"}finally{e.close()}}function sI(t=(0,wi.dirname)((0,JO.fileURLToPath)(SQ.url))){let e=[(0,wi.join)(t,"sqlite3-worker.js"),(0,wi.join)(t,"../../commands/sqlite3/worker.js")];(t.endsWith(`${wi.sep}commands${wi.sep}sqlite3`)||t.endsWith("/commands/sqlite3"))&&e.push((0,wi.join)(t,"worker.js")),e.push((0,wi.join)(t,"../../../dist/commands/sqlite3/worker.js"));for(let n of e)if((0,QO.existsSync)(n))return n;throw new Error("sqlite3 worker not found. Run 'pnpm build' to compile the worker.")}function bQ(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let n=t;return typeof n.protocolToken!="string"||n.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:n.type==="security-violation"?{success:!1,error:`Security violation: ${typeof n.violation?.type=="string"?n.violation.type:"unknown"}`}:typeof n.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:n.success?Array.isArray(n.results)?typeof n.hasModifications!="boolean"?{success:!1,error:"Malformed worker response: missing hasModifications flag"}:n.dbBuffer!==null&&n.dbBuffer!==void 0&&!(n.dbBuffer instanceof Uint8Array)?{success:!1,error:"Malformed worker response: invalid dbBuffer"}:{success:!0,results:n.results,hasModifications:n.hasModifications,dbBuffer:n.dbBuffer===void 0?null:n.dbBuffer,defenseStats:n.defenseStats}:{success:!1,error:"Malformed worker response: missing results array"}:{success:!1,error:typeof n.error=="string"&&n.error.length>0?n.error:"Worker execution failed"}}async function xQ(t,e,n){try{let r=sI();return await new Promise(s=>{let i,o=!1,a=!1,l=()=>{!a||!i||(a=!1,i.removeListener?.("message",p),i.removeListener?.("error",m),i.removeListener?.("exit",g))},c=async(y,w)=>{if(o)return;o=!0,l();let b=w?await e.terminate(i):!1;e.close(),s(b?y:{success:!1,error:nI})},u=li(n,"sqlite3","worker cancellation callback",y=>{c({success:!1,error:y==="abort"?e.abortMessage():e.timeoutMessage("Query")},!0)});if(e.arm(y=>{try{u(y)}catch(w){c({success:!1,error:Ot(Qe(w))},!0)}}),e.isCanceled)return;try{i=nt.runTrusted(()=>iI.createWorker(r,t))}catch(y){throw e.close(),y}let f=li(n,"sqlite3","worker message callback",y=>{try{let w=y&&typeof y=="object"?{protocolToken:y.protocolToken,type:y.type,violation:y.violation,success:y.success,error:y.error,results:y.results,hasModifications:y.hasModifications,defenseStats:y.defenseStats}:y;e.assertMessageSize(w,"response"),c(bQ(y,t.protocolToken),!0)}catch(w){c({success:!1,error:Ot(Qe(w))},!0)}}),d=li(n,"sqlite3","worker error callback",y=>{c({success:!1,error:Ot(Qe(y))},!0)}),h=li(n,"sqlite3","worker exit callback",y=>{y!==0&&c({success:!1,error:`Worker exited with code ${y}`},!1)}),p=y=>{try{f(y)}catch(w){let b=w instanceof Error?w.message:String(w);c({success:!1,error:Ot(b)},!0)}},m=y=>{try{d(y)}catch(w){let b=w instanceof Error?w.message:String(w);c({success:!1,error:Ot(b)},!0)}},g=y=>{try{h(y)}catch(w){let b=w instanceof Error?w.message:String(w);c({success:!1,error:Ot(b)},!0)}};i.on("message",p),i.on("error",m),i.on("exit",g),a=!0})}catch(r){let s=Ot(r.message);throw new Error(`sqlite3 worker failed to load: ${s}`)}}var QO,wi,JO,eI,tI,SQ,fQ,dQ,hQ,nI,SE,gQ,iI,EQ,AE,vE=L(()=>{"use strict";QO=require("node:fs"),wi=require("node:path"),JO=require("node:url"),eI=require("node:worker_threads"),tI=jt(require("sql.js"),1);pe();Tn();Kr();Un();Zr();cn();xe();Wp();YO();SQ={},fQ=1024,dQ=128,hQ=16,nI="Worker termination was not acknowledged";SE=new WeakMap;gQ={name:"sqlite3",summary:"SQLite database CLI",usage:"sqlite3 [OPTIONS] DATABASE [SQL]",options:["-list output in list mode (default)","-csv output in CSV mode","-json output in JSON mode","-line output in line mode","-column output in column mode","-table output as ASCII table","-markdown output as markdown table","-tabs output in tab-separated mode","-box output in Unicode box mode","-quote output in SQL quote mode","-html output as HTML table","-ascii output in ASCII mode (control chars)","-header show column headers","-noheader hide column headers","-separator SEP field separator for list mode (default: |)","-newline SEP row separator (default: \\n)","-nullvalue TEXT text for NULL values (default: empty)","-readonly open database read-only (no writeback)","-bail stop on first error","-echo print SQL before execution","-cmd COMMAND run SQL command before main SQL","-version show SQLite version","-- end of options","--help show this help"],examples:['sqlite3 :memory: "CREATE TABLE t(x); INSERT INTO t VALUES(1); SELECT * FROM t"','sqlite3 -json data.db "SELECT * FROM users"','sqlite3 -csv -header data.db "SELECT id, name FROM products"','sqlite3 -box data.db "SELECT * FROM users"']};iI={createWorker(t,e){return new eI.Worker(t,{workerData:e,resourceLimits:{maxOldGenerationSizeMb:dQ,maxYoungGenerationSizeMb:hQ}})},findWorkerPath:sI,acquireDatabaseLock:rI};EQ={name:"sqlite3",async execute(t,e){if(Z(t)||t.includes("-help"))return K(gQ);let n=yQ(t);if("exitCode"in n)return n;let{options:r,database:s,sql:i,showVersion:o}=n;if(o)return{stdout:`${await wQ()}
|
|
1265
1265
|
`,stderr:"",exitCode:0};if(!s)return{stdout:"",stderr:`sqlite3: missing database argument
|
|
1266
1266
|
`,exitCode:1};let a=i||fe(e.stdin).trim();if(r.cmd&&(a=r.cmd+(a?`; ${a}`:"")),!a)return{stdout:"",stderr:`sqlite3: no SQL provided
|
|
1267
1267
|
`,exitCode:1};let l=s===":memory:",c="",u=[],f=null,d,h;try{if(!l){c=e.fs.resolvePath(e.cwd,s);let p=await Gr(e.fs,c);if(p.existence==="unknown")throw new Error("database identity cannot be determined safely");if(p.canonicalPath!==void 0&&(c=p.canonicalPath),u=[],p.canonicalPath!==void 0&&u.push(`path:${p.canonicalPath}`),p.existence==="existing"){if(p.stableIdentity===void 0)throw new Error("database identity cannot be determined safely");u.push(`identity:${p.stableIdentity}`)}if(u.length===0)throw new Error("database identity cannot be determined safely");if(d=await pQ(e.fsIdentity??e.fs,u,e.signal),await e.fs.exists(c)){let m=await e.fs.stat(c);jp(m.size,e.limits.maxDatabaseBytes),f=await e.fs.readFileBuffer(c),jp(f.byteLength,e.limits.maxDatabaseBytes),h=e.executionScope?.reserveBytes("sqlite-database",f.byteLength,"sqlite3 database")}}}catch(p){d?.();let m=Be(p.message);return{stdout:"",stderr:`sqlite3: unable to open database "${s}": ${m}
|
|
@@ -1280,10 +1280,10 @@ ${this.commandName}: execution timeout exceeded
|
|
|
1280
1280
|
`,this.output.exitCode=124;break}let r=this.remainingMs();if(!await this.protocol.waitUntilReady(r)){if(!this.running)break;this.output.stderr+=`
|
|
1281
1281
|
${this.commandName}: execution timeout exceeded
|
|
1282
1282
|
`,this.output.exitCode=124;break}if(!this.running)break;this.protocol.setRequest(Oa.IDLE);let i=this.protocol.getOpCode();await this.handleOperation(i),this.protocol.notifyResult()}return this.output}stop(){this.running=!1,this.lastResult=null,this.protocol.setRequest(Oa.CANCELLED),this.protocol.notifyRequest()}async handleOperation(e){try{switch(e){case Ht.READ_FILE:await this.handleReadFile();break;case Ht.WRITE_FILE:await this.handleWriteFile();break;case Ht.STAT:await this.handleStat();break;case Ht.LSTAT:await this.handleLstat();break;case Ht.READDIR:await this.handleReaddir();break;case Ht.MKDIR:await this.handleMkdir();break;case Ht.READ_RESULT_RANGE:this.handleReadResultRange();break;case Ht.WRITE_FILE_RANGE:await this.handleWriteFileRange();break;case Ht.RM:await this.handleRm();break;case Ht.EXISTS:await this.handleExists();break;case Ht.APPEND_FILE:await this.handleAppendFile();break;case Ht.SYMLINK:await this.handleSymlink();break;case Ht.READLINK:await this.handleReadlink();break;case Ht.CHMOD:await this.handleChmod();break;case Ht.REALPATH:await this.handleRealpath();break;case Ht.RENAME:await this.handleRename();break;case Ht.COPY_FILE:await this.handleCopyFile();break;case Ht.WRITE_STDOUT:this.handleWriteStdout();break;case Ht.WRITE_STDERR:this.handleWriteStderr();break;case Ht.EXIT:this.handleExit();break;case Ht.HTTP_REQUEST:await this.handleHttpRequest();break;case Ht.EXEC_COMMAND:await this.handleExecCommand();break;case Ht.INVOKE_TOOL:await this.handleInvokeTool();break;default:this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultState(wt.ERROR)}}catch(n){this.setErrorFromException(n)}}publishResult(e){let n=typeof e=="string"?new TextEncoder().encode(e):e;this.lastResult=n,this.protocol.setResultPrefix(n),this.protocol.setResultState(wt.SUCCESS)}handleReadResultRange(){let e=this.protocol.getFlags(),n=this.protocol.getMode(),r=this.lastResult;if(!r||e>=r.length){this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString(`No retained result for range read (offset=${e}, length=${n}, retained=${r?.length??"none"})`),this.protocol.setResultState(wt.ERROR);return}this.protocol.setResult(r.subarray(e,e+n)),this.protocol.setResultState(wt.SUCCESS)}resolvePath(e){return this.fs.resolvePath(this.cwd,e)}async handleReadFile(){let e=this.resolvePath(this.protocol.getPath());try{let n=await this.fs.readFileBuffer(e);this.publishResult(n)}catch(n){this.setErrorFromException(n)}}async handleWriteFileRange(){let e=this.resolvePath(this.protocol.getPath()),n=this.protocol.getFlags(),r=this.protocol.getData();try{if(n===0)await this.fs.writeFile(e,r);else{let s=await this.fs.stat(e);if(s.size!==n)throw new D("EIO",`non-sequential range write to '${e}': offset ${n} != size ${s.size}`);await this.fs.appendFile(e,r)}this.protocol.setResultState(wt.SUCCESS)}catch(s){this.setErrorFromException(s)}}async handleWriteFile(){let e=this.resolvePath(this.protocol.getPath()),n=this.protocol.getData();try{await this.fs.writeFile(e,n),this.protocol.setResultState(wt.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleStat(){let e=this.resolvePath(this.protocol.getPath());try{let n=await this.fs.stat(e);this.protocol.encodeStat(n),this.protocol.setResultState(wt.SUCCESS)}catch(n){this.setErrorFromException(n)}}async handleLstat(){let e=this.resolvePath(this.protocol.getPath());try{let n=await this.fs.lstat(e);this.protocol.encodeStat(n),this.protocol.setResultState(wt.SUCCESS)}catch(n){this.setErrorFromException(n)}}async handleReaddir(){let e=this.resolvePath(this.protocol.getPath());try{let n=await this.fs.readdir(e);this.publishResult(JSON.stringify(n))}catch(n){this.setErrorFromException(n)}}async handleMkdir(){let e=this.resolvePath(this.protocol.getPath()),r=(this.protocol.getFlags()&rf.MKDIR_RECURSIVE)!==0;try{await this.fs.mkdir(e,{recursive:r}),this.protocol.setResultState(wt.SUCCESS)}catch(s){this.setErrorFromException(s)}}async handleRm(){let e=this.resolvePath(this.protocol.getPath()),n=this.protocol.getFlags(),r=(n&rf.RECURSIVE)!==0,s=(n&rf.FORCE)!==0;try{await this.fs.rm(e,{recursive:r,force:s}),this.protocol.setResultState(wt.SUCCESS)}catch(i){this.setErrorFromException(i)}}async handleExists(){let e=this.resolvePath(this.protocol.getPath());try{let n=await this.fs.exists(e);this.protocol.setResult(new Uint8Array([n?1:0])),this.protocol.setResultState(wt.SUCCESS)}catch(n){this.setErrorFromException(n)}}async handleAppendFile(){let e=this.resolvePath(this.protocol.getPath()),n=this.protocol.getData();try{await this.fs.appendFile(e,n),this.protocol.setResultState(wt.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleSymlink(){let e=this.protocol.getPath(),n=this.protocol.getDataAsString(),r=this.resolvePath(e);try{await this.fs.symlink(n,r),this.protocol.setResultState(wt.SUCCESS)}catch(s){this.setErrorFromException(s)}}async handleReadlink(){let e=this.resolvePath(this.protocol.getPath());try{let n=await this.fs.readlink(e);this.protocol.setResultFromString(n),this.protocol.setResultState(wt.SUCCESS)}catch(n){this.setErrorFromException(n)}}async handleChmod(){let e=this.resolvePath(this.protocol.getPath()),n=this.protocol.getMode();try{await this.fs.chmod(e,n),this.protocol.setResultState(wt.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleRealpath(){let e=this.resolvePath(this.protocol.getPath());try{let n=await this.fs.realpath(e);this.protocol.setResultFromString(n),this.protocol.setResultState(wt.SUCCESS)}catch(n){this.setErrorFromException(n)}}async handleRename(){let e=this.resolvePath(this.protocol.getPath()),n=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.mv(e,n),this.protocol.setResultState(wt.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleCopyFile(){let e=this.resolvePath(this.protocol.getPath()),n=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.cp(e,n),this.protocol.setResultState(wt.SUCCESS)}catch(r){this.setErrorFromException(r)}}handleWriteStdout(){let e=this.protocol.getDataAsString();if(!this.tryAppendOutput("stdout",e)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setResultState(wt.ERROR);return}this.protocol.setResultState(wt.SUCCESS)}handleWriteStderr(){let e=this.protocol.getDataAsString();if(!this.tryAppendOutput("stderr",e)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setResultState(wt.ERROR);return}this.protocol.setResultState(wt.SUCCESS)}handleExit(){let e=this.protocol.getFlags();this.outputLimitExceeded?this.output.exitCode===0&&(this.output.exitCode=1):this.output.exitCode=e,this.protocol.setResultState(wt.SUCCESS),this.running=!1}tryAppendOutput(e,n){return this.outputLimitExceeded?!1:this.maxOutputSize<=0?(e==="stdout"?this.output.stdout+=n:this.output.stderr+=n,!0):this.output.stdout.length+this.output.stderr.length+n.length>this.maxOutputSize?!1:(e==="stdout"?this.output.stdout+=n:this.output.stderr+=n,!0)}appendOutputLimitError(){if(this.maxOutputSize<=0)return;let e=`${this.commandName}: total output size exceeded (>${this.maxOutputSize} bytes), increase executionLimits.maxOutputSize
|
|
1283
|
-
`,n=e.length>this.maxOutputSize?e.slice(0,this.maxOutputSize):e;if(this.output.stderr.includes("total output size exceeded"))return;let s=this.output.stdout.length+this.output.stderr.length+n.length-this.maxOutputSize;if(s>0)if(this.output.stdout.length>=s)this.output.stdout=this.output.stdout.slice(0,this.output.stdout.length-s);else{let i=s-this.output.stdout.length;this.output.stdout="",i>=this.output.stderr.length?this.output.stderr="":this.output.stderr=this.output.stderr.slice(0,this.output.stderr.length-i)}this.output.stderr+=n}async handleHttpRequest(){let e=this.secureFetch;if(!e){this.protocol.setErrorCode(zt.NETWORK_NOT_CONFIGURED),this.protocol.setResultFromString("Network access not configured. Enable network in Bash options."),this.protocol.setResultState(wt.ERROR);return}let n=this.protocol.getPath(),r=this.protocol.getDataAsString();try{let s=r?JSON.parse(r):{},i=this.remainingMs(),o=await this.raceDeadline(()=>e(n,{method:s.method,headers:s.headers,body:s.body,timeoutMs:i})),a=JSON.stringify({status:o.status,statusText:o.statusText,headers:o.headers,bodyBase64:ts(o.body,"base64"),url:o.url});this.publishResult(a)}catch(s){let i=Be(s instanceof Error?s.message:String(s));this.protocol.setErrorCode(zt.NETWORK_ERROR),this.protocol.setResultFromString(i),this.protocol.setResultState(wt.ERROR)}}async handleExecCommand(){let e=this.exec;if(!e){this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString("Command execution not available in this context."),this.protocol.setResultState(wt.ERROR);return}let n=this.protocol.getPath(),r=this.protocol.getDataAsString(),s=new AbortController;try{let i={cwd:this.cwd,signal:s.signal};if(r){let l=JSON.parse(r);l.stdin&&(i.stdin=l.stdin),l.args&&Array.isArray(l.args)&&(i.args=l.args.map(c=>String(c)),n=Fn([n]))}let o=await this.raceDeadline(()=>e(n,i)),a=JSON.stringify({stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode});this.publishResult(a)}catch(i){s.abort();let o=i instanceof Error?i.message:String(i);this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString(o),this.protocol.setResultState(wt.ERROR)}}async handleInvokeTool(){let e=this.invokeTool;if(!e){this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString("Tool invocation not available in this context."),this.protocol.setResultState(wt.ERROR);return}let n=this.protocol.getPath(),r=this.protocol.getDataAsString();try{let s=await this.raceDeadline(()=>
|
|
1283
|
+
`,n=e.length>this.maxOutputSize?e.slice(0,this.maxOutputSize):e;if(this.output.stderr.includes("total output size exceeded"))return;let s=this.output.stdout.length+this.output.stderr.length+n.length-this.maxOutputSize;if(s>0)if(this.output.stdout.length>=s)this.output.stdout=this.output.stdout.slice(0,this.output.stdout.length-s);else{let i=s-this.output.stdout.length;this.output.stdout="",i>=this.output.stderr.length?this.output.stderr="":this.output.stderr=this.output.stderr.slice(0,this.output.stderr.length-i)}this.output.stderr+=n}async handleHttpRequest(){let e=this.secureFetch;if(!e){this.protocol.setErrorCode(zt.NETWORK_NOT_CONFIGURED),this.protocol.setResultFromString("Network access not configured. Enable network in Bash options."),this.protocol.setResultState(wt.ERROR);return}let n=this.protocol.getPath(),r=this.protocol.getDataAsString();try{let s=r?JSON.parse(r):{},i=this.remainingMs(),o=await this.raceDeadline(()=>e(n,{method:s.method,headers:s.headers,body:s.body,timeoutMs:i})),a=JSON.stringify({status:o.status,statusText:o.statusText,headers:o.headers,bodyBase64:ts(o.body,"base64"),url:o.url});this.publishResult(a)}catch(s){let i=Be(s instanceof Error?s.message:String(s));this.protocol.setErrorCode(zt.NETWORK_ERROR),this.protocol.setResultFromString(i),this.protocol.setResultState(wt.ERROR)}}async handleExecCommand(){let e=this.exec;if(!e){this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString("Command execution not available in this context."),this.protocol.setResultState(wt.ERROR);return}let n=this.protocol.getPath(),r=this.protocol.getDataAsString(),s=new AbortController;try{let i={cwd:this.cwd,signal:s.signal};if(r){let l=JSON.parse(r);l.stdin&&(i.stdin=l.stdin),l.args&&Array.isArray(l.args)&&(i.args=l.args.map(c=>String(c)),n=Fn([n]))}let o=await this.raceDeadline(()=>e(n,i)),a=JSON.stringify({stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode});this.publishResult(a)}catch(i){s.abort();let o=i instanceof Error?i.message:String(i);this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString(o),this.protocol.setResultState(wt.ERROR)}}async handleInvokeTool(){let e=this.invokeTool;if(!e){this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString("Tool invocation not available in this context."),this.protocol.setResultState(wt.ERROR);return}let n=this.protocol.getPath(),r=this.protocol.getDataAsString();try{let s=await this.raceDeadline(()=>nt.runTrustedAsync(()=>e(n,r)));this.publishResult(s)}catch(s){let i=Ot(s instanceof Error?s.message:String(s));this.protocol.setErrorCode(zt.IO_ERROR),this.protocol.setResultFromString(i),this.protocol.setResultState(wt.ERROR)}}setErrorFromException(e){let n=e instanceof Error?e.message:String(e),r=Be(n);this.protocol.setErrorCode(kQ(tl(e))),this.protocol.setResultFromString(r),this.protocol.setResultState(wt.ERROR)}}});var NE={};he(NE,{_resetExecutionQueue:()=>IQ,python3Command:()=>cI,pythonCommand:()=>LQ});function TQ(t){let e={code:null,module:null,scriptFile:null,showVersion:!1,scriptArgs:[]};if(t.length===0)return e;let n=t.findIndex(r=>!r.startsWith("-")||r==="-"||r==="--");for(let r=0;r<(n===-1?t.length:n);r++){let s=t[r];if(s==="-c")return r+1>=t.length?{stdout:"",stderr:`python3: option requires an argument -- 'c'
|
|
1284
1284
|
`,exitCode:2}:(e.code=t[r+1],e.scriptArgs=t.slice(r+2),e);if(s==="-m")return r+1>=t.length?{stdout:"",stderr:`python3: option requires an argument -- 'm'
|
|
1285
1285
|
`,exitCode:2}:(e.module=t[r+1],e.scriptArgs=t.slice(r+2),e);if(s==="--version"||s==="-V")return e.showVersion=!0,e;if(s.startsWith("-")&&s!=="-")return{stdout:"",stderr:`python3: unrecognized option '${s}'
|
|
1286
|
-
`,exitCode:2}}if(n!==-1){let r=t[n];r==="--"?n+1<t.length&&(e.scriptFile=t[n+1],e.scriptArgs=t.slice(n+2)):(e.scriptFile=r,e.scriptArgs=t.slice(n+1))}return e}function OQ(t){let e=kE.get(t);return e||(e={executionQueue:[],activeExecution:null,poisonedError:null},kE.set(t,e)),e}function IQ(){kE=new WeakMap}function PQ(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let n=t;return typeof n.protocolToken!="string"||n.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:n.type==="security-violation"?{success:!1,error:`Security violation: ${typeof n.violation?.type=="string"?n.violation.type:"unknown"}`}:typeof n.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:n.success?{success:!0}:{success:!1,error:typeof n.error=="string"&&n.error.length>0?n.error:"Worker execution failed"}}function sf(t){if(t.poisonedError!==null){for(let d of t.executionQueue.splice(0))d.state==="queued"&&(d.state="settled",d.stopBridge(),d.settle({success:!1,error:t.poisonedError}));return}if(t.activeExecution!==null||t.executionQueue.length===0)return;for(;t.executionQueue.length>0&&t.executionQueue[0]?.state!=="queued";)t.executionQueue.shift();if(t.executionQueue.length===0)return;let e=t.executionQueue.shift();if(!e)return;e.state="running",t.activeExecution=e;let n;try{n=
|
|
1286
|
+
`,exitCode:2}}if(n!==-1){let r=t[n];r==="--"?n+1<t.length&&(e.scriptFile=t[n+1],e.scriptArgs=t.slice(n+2)):(e.scriptFile=r,e.scriptArgs=t.slice(n+1))}return e}function OQ(t){let e=kE.get(t);return e||(e={executionQueue:[],activeExecution:null,poisonedError:null},kE.set(t,e)),e}function IQ(){kE=new WeakMap}function PQ(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let n=t;return typeof n.protocolToken!="string"||n.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:n.type==="security-violation"?{success:!1,error:`Security violation: ${typeof n.violation?.type=="string"?n.violation.type:"unknown"}`}:typeof n.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:n.success?{success:!0}:{success:!1,error:typeof n.error=="string"&&n.error.length>0?n.error:"Worker execution failed"}}function sf(t){if(t.poisonedError!==null){for(let d of t.executionQueue.splice(0))d.state==="queued"&&(d.state="settled",d.stopBridge(),d.settle({success:!1,error:t.poisonedError}));return}if(t.activeExecution!==null||t.executionQueue.length===0)return;for(;t.executionQueue.length>0&&t.executionQueue[0]?.state!=="queued";)t.executionQueue.shift();if(t.executionQueue.length===0)return;let e=t.executionQueue.shift();if(!e)return;e.state="running",t.activeExecution=e;let n;try{n=nt.runTrusted(()=>new lI.Worker(RQ,{workerData:e.input}))}catch(d){let h=d instanceof Error?d.message:String(d);e.state="settled",e.settle({success:!1,error:Ot(h)}),t.activeExecution===e&&(t.activeExecution=null,sf(t));return}e.worker=n;let r=!0,s=()=>{r&&(r=!1,n.removeListener("message",c),n.removeListener("error",u),n.removeListener("exit",f))},i=async(d,h)=>{if(!(t.activeExecution?.executionId!==e.executionId||e.state!=="running")){if(e.state="terminating",s(),e.settle(d),h&&!await e.controller.terminate(n)){let m="Worker termination was not acknowledged";e.worker=null,e.state="settled",t.poisonedError=m,t.activeExecution?.executionId===e.executionId&&(t.activeExecution=null),sf(t);return}e.worker=null,e.state="settled",t.activeExecution?.executionId===e.executionId&&(t.activeExecution=null,sf(t))}};e.cancel=d=>{i(d,!0)};let o=li(e.requireDefenseContext,"python3","worker message callback",d=>{try{e.controller.assertMessageSize(d,"response")}catch(h){i({success:!1,error:Ot(Qe(h))},!0);return}i(PQ(d,e.input.protocolToken),!0)}),a=li(e.requireDefenseContext,"python3","worker error callback",d=>{let h=Ot(Qe(d));i({success:!1,error:h},!0)}),l=li(e.requireDefenseContext,"python3","worker exit callback",()=>{i({success:!1,error:"Worker exited unexpectedly"},!1)}),c=d=>{try{o(d)}catch(h){let p=h instanceof Error?h.message:String(h);i({success:!1,error:Ot(p)},!0)}},u=d=>{try{a(d)}catch(h){let p=h instanceof Error?h.message:String(h);i({success:!1,error:Ot(p)},!0)}},f=()=>{try{l()}catch(d){let h=d instanceof Error?d.message:String(d);i({success:!1,error:Ot(h)},!0)}};n.on("message",c),n.on("error",u),n.on("exit",f)}async function $Q(t,e,n,r,s=[]){let i=Hp(),o=new ec(i,n.fs,n.cwd,"python3",n.fetch,n.limits.maxOutputSize),a=n.limits.maxPythonTimeoutMs,l=OQ(n.fs);if(l.poisonedError!==null)return{stdout:"",stderr:`python3: ${l.poisonedError}
|
|
1287
1287
|
`,exitCode:1};let c=new No({commandName:"python3",timeoutMs:a,signal:n.signal,maxMessageBytes:n.limits.maxWorkerMessageBytes}),u={protocolToken:c.protocolToken,sharedBuffer:i,pythonCode:t,stdin:e,cwd:n.cwd,env:dn(n.env),args:s,scriptPath:r,timeoutMs:a,maxFileSize:n.limits.maxStringLength};c.assertMessageSize({...u,sharedBuffer:void 0},"request");let f=new Promise(p=>{let m=!1,g={executionId:Symbol("python3 execution"),input:u,settle:b=>{m||(m=!0,c.close(),p(b))},requireDefenseContext:n.requireDefenseContext,state:"queued",worker:null,controller:c,stopBridge:()=>o.stop?.(),cancel:()=>{}};g.cancel=b=>{if(g.state!=="queued")return;g.state="settled";let x=l.executionQueue.indexOf(g);x!==-1&&l.executionQueue.splice(x,1),g.settle(b),sf(l)};let y=li(n.requireDefenseContext,"python3","worker cancellation callback",b=>{o.stop?.(),g.cancel({success:!1,error:b==="abort"?c.abortMessage():c.timeoutMessage()})}),w=b=>{try{y(b)}catch(x){let S=x instanceof Error?x.message:String(x);g.cancel({success:!1,error:Ot(S)})}};c.arm(w),c.isCanceled||(l.executionQueue.push(g),sf(l))}),[d,h]=await Promise.all([o.run(a).catch(p=>({stdout:"",stderr:`python3: bridge error: ${Ot(Qe(p))}
|
|
1288
1288
|
`,exitCode:1})),f.catch(p=>({success:!1,error:Ot(Qe(p))}))]);if(!h.success&&h.error){let p=Ot(h.error),m=h.error===c.timeoutMessage()||h.error===c.abortMessage();return{stdout:d.stdout,stderr:`${d.stderr}python3: ${p}
|
|
1289
1289
|
`,exitCode:d.exitCode||(m?124:1)}}return{...d}}var aI,lI,FQ,NQ,kE,RQ,cI,LQ,TE=L(()=>{"use strict";aI=require("node:url"),lI=require("node:worker_threads");pe();Tn();hs();Un();Zr();cn();xe();CE();Gp();Wp();FQ={},NQ={name:"python3",summary:"Execute Python code via CPython Emscripten",usage:"python3 [OPTIONS] [-c CODE | -m MODULE | FILE] [ARGS...]",description:["Execute Python code using CPython compiled to WebAssembly via Emscripten.","","This command runs Python in an isolated environment with access to","the virtual filesystem. Standard library modules are available."],options:["-c CODE Execute CODE as Python script","-m MODULE Run library module as a script","--version Show Python version","--help Show this help"],examples:['python3 -c "print(1 + 2)"','python3 -c "import sys; print(sys.version)"',"python3 script.py","python3 script.py arg1 arg2",`echo 'print("hello")' | python3`],notes:["CPython runs in WebAssembly, so execution may be slower than native Python.","Standard library modules are available (no pip install).","Maximum execution time is 30 seconds by default."]};kE=new WeakMap;RQ=(0,aI.fileURLToPath)(new URL("./worker.js",FQ.url));cI={handlesOwnVersion:!0,name:"python3",async execute(t,e){if(Z(t))return K(NQ);let n=TQ(t);if("exitCode"in n)return n;if(n.showVersion)return{stdout:`Python 3.13.2 (Emscripten)
|
|
@@ -1293,7 +1293,7 @@ ${this.commandName}: execution timeout exceeded
|
|
|
1293
1293
|
`,exitCode:2}}}else if(fe(e.stdin).trim())r=fe(e.stdin),i="",s="<stdin>";else return{stdout:"",stderr:`python3: no input provided (use -c CODE, -m MODULE, or provide a script file)
|
|
1294
1294
|
`,exitCode:2};return $Q(r,i,e,s,n.scriptArgs)}},LQ={name:"python",async execute(t,e){return cI.execute(t,e)}}});var OE={};he(OE,{_hasSharedJsExecWorkerForTests:()=>BQ,_resetJsExecWorkerForTests:()=>zQ,_setJsExecWorkerIdleTimeoutMsForTests:()=>MQ,jsExecCommand:()=>ZQ,nodeStubCommand:()=>XQ});function DQ(t){let e={code:null,scriptFile:null,showVersion:!1,scriptArgs:[],isModule:!1,stripTypes:!1};if(t.length===0)return e;for(let n=0;n<t.length;n++){let r=t[n];if(r==="-m"||r==="--module"){e.isModule=!0;continue}if(r==="--strip-types"){e.stripTypes=!0;continue}if(r==="-c")return n+1>=t.length?{stdout:"",stderr:`js-exec: option requires an argument -- 'c'
|
|
1295
1295
|
`,exitCode:2}:(e.code=t[n+1],e.scriptArgs=t.slice(n+2),e);if(r==="--version"||r==="-V")return e.showVersion=!0,e;if(r.startsWith("-")&&r!=="-"&&r!=="--")return{stdout:"",stderr:`js-exec: unrecognized option '${r}'
|
|
1296
|
-
`,exitCode:2};if(r==="--")return n+1<t.length&&(e.scriptFile=t[n+1],e.scriptArgs=t.slice(n+2)),e;if(!r.startsWith("-"))return e.scriptFile=r,e.scriptArgs=t.slice(n+1),e}return e}function MQ(t){mI=t}function BQ(){return vn!==null}function gI(t,e,n){t.controller.close();let r=!1,s=()=>{if(!r&&(r=!0,Hr(o),Ut===t)){Pa="worker termination was not acknowledged";for(let a of Mn)a.bridgeHandler.stop(),a.resolve({success:!1,error:Pa});Mn.length=0,t.resolve(n)}},i=()=>{r||(r=!0,Hr(o),Ut===t&&(t.resolve(n),Ut=null,Ra()))},o=P1(()=>{s()},_Q);t.controller.terminate(e).then(a=>a?i():s(),s)}function zQ(){Ia&&(Hr(Ia),Ia=null),Ut?.bridgeHandler.stop(),Ut=null;for(let e of Mn)e.bridgeHandler.stop();Mn.length=0;let t=vn;vn=null,t&&t.terminate(),Pa=null}function Ra(){if(Ut||Mn.length===0)return;let t=Mn.shift();if(!t)return;Ut=t;let e=null;try{e=jQ(),e.postMessage(t.input)}catch(n){t.bridgeHandler.stop();let r={success:!1,error:Ot(Qe(n))},s=e??vn;vn===s&&(vn=null),s?gI(t,s,r):(t.resolve(r),Ut===t&&(Ut=null),Ra())}}function WQ(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let n=t;return typeof n.protocolToken!="string"||n.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:typeof n.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:n.success?{success:!0}:{success:!1,type:n.type==="initialization-failure"?"initialization-failure":void 0,error:typeof n.error=="string"&&n.error.length>0?n.error:"Worker execution failed"}}function jQ(){if(Ia&&(Hr(Ia),Ia=null),vn)return vn;let t=
|
|
1296
|
+
`,exitCode:2};if(r==="--")return n+1<t.length&&(e.scriptFile=t[n+1],e.scriptArgs=t.slice(n+2)),e;if(!r.startsWith("-"))return e.scriptFile=r,e.scriptArgs=t.slice(n+1),e}return e}function MQ(t){mI=t}function BQ(){return vn!==null}function gI(t,e,n){t.controller.close();let r=!1,s=()=>{if(!r&&(r=!0,Hr(o),Ut===t)){Pa="worker termination was not acknowledged";for(let a of Mn)a.bridgeHandler.stop(),a.resolve({success:!1,error:Pa});Mn.length=0,t.resolve(n)}},i=()=>{r||(r=!0,Hr(o),Ut===t&&(t.resolve(n),Ut=null,Ra()))},o=P1(()=>{s()},_Q);t.controller.terminate(e).then(a=>a?i():s(),s)}function zQ(){Ia&&(Hr(Ia),Ia=null),Ut?.bridgeHandler.stop(),Ut=null;for(let e of Mn)e.bridgeHandler.stop();Mn.length=0;let t=vn;vn=null,t&&t.terminate(),Pa=null}function Ra(){if(Ut||Mn.length===0)return;let t=Mn.shift();if(!t)return;Ut=t;let e=null;try{e=jQ(),e.postMessage(t.input)}catch(n){t.bridgeHandler.stop();let r={success:!1,error:Ot(Qe(n))},s=e??vn;vn===s&&(vn=null),s?gI(t,s,r):(t.resolve(r),Ut===t&&(Ut=null),Ra())}}function WQ(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let n=t;return typeof n.protocolToken!="string"||n.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:typeof n.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:n.success?{success:!0}:{success:!1,type:n.type==="initialization-failure"?"initialization-failure":void 0,error:typeof n.error=="string"&&n.error.length>0?n.error:"Worker execution failed"}}function jQ(){if(Ia&&(Hr(Ia),Ia=null),vn)return vn;let t=nt.runTrusted(()=>new dI.Worker(UQ));return vn=t,t.on("message",e=>{if(vn===t){if(Ut){let n;try{Ut.controller.assertMessageSize(e,"response"),n=WQ(e,Ut.input.protocolToken)}catch(r){n={success:!1,error:Ot(Qe(r))}}if(n.type==="initialization-failure"){Pa=n.error??"Worker initialization failed",Ut.bridgeHandler.stop(),Ut.resolve(n),Ut=null;for(let r of Mn)r.bridgeHandler.stop(),r.resolve({success:!1,type:"initialization-failure",error:Pa});Mn.length=0,vn=null,t.terminate();return}Ut.resolve(n),Ut=null}Mn.length>0?Ra():qQ()}}),t.on("error",e=>{if(vn===t){if(Ut){let n=Ot(Qe(e));Ut.resolve({success:!1,error:n}),Ut=null}for(let n of Mn)n.resolve({success:!1,error:"Worker crashed"});Mn.length=0,vn=null}}),t.on("exit",()=>{vn===t&&(vn=null,Ut&&(Ut.resolve({success:!1,error:"Worker exited unexpectedly"}),Ut=null),Mn.length>0&&Ra())}),t}function qQ(){Ia=P1(()=>{vn&&!Ut&&Mn.length===0&&(vn.terminate(),vn=null)},mI)}async function VQ(t,e,n,r=[],s,i,o){return hI.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
|
|
1297
1297
|
`,exitCode:1}:KQ(t,e,n,r,s,i,o)}async function HQ(t,e,n,r){let s,i=new Promise(u=>{s=u}),o={input:t,bridgeHandler:e,resolve:()=>{},controller:r};r.assertMessageSize({...t,sharedBuffer:void 0},"request");let a=u=>{e.stop();let f={success:!1,error:u==="abort"?o.controller.abortMessage():o.controller.timeoutMessage()};if(Ut===o){let d=vn;vn=null,d?gI(o,d,f):(o.resolve(f),Ut=null,Ra())}else{let d=Mn.indexOf(o);d!==-1&&Mn.splice(d,1),o.resolve(f),Ut||Ra()}};if(o.resolve=u=>{o.controller.close(),s(u)},o.controller.arm(a),!o.controller.isCanceled){Mn.push(o);try{Ra()}catch(u){let f=Mn.indexOf(o);throw f!==-1&&Mn.splice(f,1),o.controller.close(),u}}let[l,c]=await Promise.all([e.run(n),i.catch(u=>({success:!1,error:Ot(Qe(u))}))]);return{bridgeOutput:l,workerResult:c}}function GQ(t){return t.limits.maxJsTimeoutMs}async function KQ(t,e,n,r=[],s,i,o){if(Pa!==null)return{stdout:"",stderr:`js-exec: ${Ot(Pa)}
|
|
1298
1298
|
`,exitCode:1};let a=Hp(),l=e.exec,c=l?(g,y)=>hI.run(!0,()=>l(g,y)):void 0,u=new ec(a,e.fs,e.cwd,"js-exec",e.fetch,e.limits.maxOutputSize,c,e.invokeTool),f=GQ(e),d=new No({commandName:"js-exec",timeoutMs:f,signal:e.signal,maxMessageBytes:e.limits.maxWorkerMessageBytes}),h={protocolToken:d.protocolToken,sharedBuffer:a,jsCode:t,cwd:e.cwd,env:dn(e.env),args:r,scriptPath:n,bootstrapCode:s,isModule:i,stripTypes:o,timeoutMs:f,memoryBytes:e.limits.maxJsMemoryBytes,hasInvokeTool:e.invokeTool!==void 0},{bridgeOutput:p,workerResult:m}=await HQ(h,u,f,d);if(!m.success&&m.error){let g=m.error===d.timeoutMessage()||m.error===d.abortMessage();return{stdout:p.stdout,stderr:`${p.stderr}js-exec: ${Ot(m.error)}
|
|
1299
1299
|
`,exitCode:p.exitCode||(g?124:1)}}return{...p}}var uI,fI,dI,YQ,hI,pI,vn,Ia,Mn,Ut,Pa,_Q,mI,UQ,ZQ,XQ,IE=L(()=>{"use strict";uI=require("node:async_hooks"),fI=require("node:url"),dI=require("node:worker_threads");pe();Tn();hs();Un();cn();Os();xe();CE();Gp();Wp();YQ={},hI=new uI.AsyncLocalStorage,pI=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs
|
|
@@ -1415,12 +1415,12 @@ ${QQ(n)}\r
|
|
|
1415
1415
|
`,exitCode:2};if(!e.fetch)return{stdout:"",stderr:`curl: internal error: fetch not available
|
|
1416
1416
|
`,exitCode:1};let s=r.url;s.match(/^https?:\/\//)||(s=`https://${s}`);try{let i=await tJ(r,e);r.getMode&&(s=rJ(s,i instanceof Uint8Array?eJ.decode(i):i));let{body:o,contentType:a}=await nJ(r,e,i),l=sJ(r,a);if(r.dumpHeader!==void 0&&r.dumpHeader!=="-"){let m=e.fs.resolvePath(e.cwd,r.dumpHeader);await e.fs.writeFile(m,"")}let c=await e.fetch(s,{method:r.method,headers:l,body:o,followRedirects:r.followRedirects,timeoutMs:r.timeoutMs,maxRedirects:r.maxRedirects,signal:e.signal});await iJ(r,c.headers,e);let u=of(c.status,c.statusText,c.headers),f="";if(c.redirectChain)for(let m of c.redirectChain)f+=of(m.status,m.statusText,m.headers);if(f+=u,r.dumpHeader!==void 0&&r.dumpHeader!=="-"){let m=e.fs.resolvePath(e.cwd,r.dumpHeader);await e.fs.writeFile(m,f)}if(r.failSilently&&c.status>=400){let m=r.showError||!r.silent?`curl: (22) The requested URL returned error: ${c.status}
|
|
1417
1417
|
`:"",g=r.dumpHeader==="-"?f:"";return{stdout:g,stderr:m,exitCode:22,stdoutKind:g?"bytes":void 0}}let d=!!(r.outputFile||r.useRemoteName),p=d&&!r.verbose?"":aJ(r,c,s);if(d){let m=r.outputFile||vI(s),g=e.fs.resolvePath(e.cwd,m);if(await e.fs.writeFile(g,r.headOnly?"":c.body),r.verbose?p=(r.dumpHeader==="-"?f:"")+p:r.dumpHeader==="-"?p=f:p="",r.writeOut){let y=$E(r.writeOut,{status:c.status,headers:c.headers,url:c.url,bodyLength:c.body.byteLength});r.verbose?p+=y:r.dumpHeader==="-"?p=f+y:p=y}}else r.dumpHeader==="-"&&(p=f+p);return{stdout:p,stderr:"",exitCode:0,stdoutKind:"bytes"}}catch(i){let o=Qe(i),a=1;return o.includes("Network access denied")?a=7:o.includes("HTTP method")&&o.includes("not allowed")?a=3:o.includes("Redirect target not in allow-list")||o.includes("Too many redirects")?a=47:o.includes("aborted")&&(a=28),{stdout:"",stderr:!r.silent||r.showError?`curl: (${a}) ${o}
|
|
1418
|
-
`:"",exitCode:a}}}}});function TI(){return cJ}var cJ,OI=L(()=>{"use strict";vd();O0();h2();my();kd();z1();yg();By();iy();D0();ug();M0();E2();b2();yy();Sy();M1();Ad();X0();Q0();P2();iw();hy();K0();Dc();ru();vg();cw();Iy();xw();aw();ly();f2();pg();X1();L2();D2();M2();Q1();ng();dg();H0();vw();z0();j1();bg();Eg();q0();i0();lg();sg();m0();I2();v2();P0();ry();vE();Rg();ey();ww();kg();Kw();uy();T2();k2();og();W0();by();Cd();L0();Og();gw();Sw();EE();Py();_y();Tx();cJ=[_1,B1,W1,Z1,Y1,tg,rg,ig,ag,cg,fg,hg,gg,wg,xg,Ag,Cg,Tg,Ig,Qg,Jg,e0,s0,p0,T0,R0,$0,F0,_0,B0,U0,j0,V0,G0,Z0,Y0,J0,ny,sy,ay,cy,dy,py,gy,wy,Ey,Ay,vy,ky,Ny,Oy,Ry,$y,Ly,Dy,My,zy,Uy,u2,d2,w2,x2,A2,C2,N2,O2,R2,$2,F2,_2,sw,ow,lw,mw,yw,bw,Ew,Aw,Tw,Ow,Iw,Gw,Nx,xE,AE]});var RI={};he(RI,{emitFlagCoverage:()=>uJ});function uJ(t,e,n){let r=II.get(e);if(!(!r||r.size===0))for(let s of n)r.has(s)&&t.hit(`cmd:flag:${e}:${s}`)}var II,PI=L(()=>{"use strict";OI();II=new Map;for(let t of TI())II.set(t.name,new Set(t.flags.map(e=>e.flag)))});var Are={};he(Are,{AgentSandbox:()=>Lf,Bash:()=>Xo,BashTransformPipeline:()=>w1,CommandCollectorPlugin:()=>b1,DefenseInDepthBox:()=>tt,EMPTY_BYTES:()=>Ri,FsError:()=>D,InMemoryFs:()=>ir,MountableFs:()=>Wr,NetworkAccessDeniedError:()=>ls,OverlayFs:()=>Ts,ReadWriteFs:()=>Ff,RedirectNotAllowedError:()=>ki,Sandbox:()=>Df,SandboxCommand:()=>Ga,SecurityViolationError:()=>Re,SecurityViolationLogger:()=>_f,TeePlugin:()=>x1,TooManyRedirectsError:()=>Zo,applyDiffToRealFs:()=>Rf,bytesOutput:()=>i4,createAgentSandbox:()=>uF,createCommandContext:()=>GI,createConsoleViolationCallback:()=>H7,createVfsTemplate:()=>dF,decodeBytesToUtf8:()=>fe,defineCommand:()=>ZI,encodeUtf8ToBytes:()=>vr,fsErrorCode:()=>tl,getCommandNames:()=>FI,getJavaScriptCommandNames:()=>UI,getNetworkCommandNames:()=>DI,getPythonCommandNames:()=>BI,isFsErrorCode:()=>st,latin1FromBytes:()=>kt,parse:()=>or,serialize:()=>sc,stdoutAsBytes:()=>ni,stdoutKind:()=>zf,textOutput:()=>s4,toFsError:()=>g4,unsafeBytesFromLatin1:()=>to});module.exports=bF(Are);var Yn=jt(require("node:path"),1);Os();Qa();Qt();Qa();cn();var La=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(M1(),a4))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(z1(),l4))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(j1(),h4))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(X1(),A4))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(Q1(),v4))).mkdirCommand},{name:"mktemp",load:async()=>(await Promise.resolve().then(()=>(ng(),O4))).mktempCommand,handlesOwnVersion:!0},{name:"rmdir",load:async()=>(await Promise.resolve().then(()=>(sg(),P4))).rmdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(og(),$4))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(lg(),L4))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(ug(),F4))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(dg(),D4))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>(pg(),_4))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(yg(),M4))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>(bg(),B4))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(Eg(),z4))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(vg(),j4))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(kg(),q4))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(Og(),H4))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(Rg(),G4))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(Dc(),nd))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(Dc(),nd))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(Dc(),nd))).egrepCommand},{name:"rg",load:async()=>(await Promise.resolve().then(()=>(i0(),j3))).rgCommand,handlesOwnVersion:!0},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(m0(),eA))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(O0(),$A))).awkCommand2},{name:"sort",load:async()=>(await Promise.resolve().then(()=>(P0(),WA))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(L0(),jA))).uniqCommand},{name:"comm",load:async()=>(await Promise.resolve().then(()=>(D0(),qA))).commCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(M0(),VA))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(z0(),GA))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(W0(),ZA))).trCommand},{name:"rev",load:async()=>(await Promise.resolve().then(()=>(q0(),XA))).rev},{name:"nl",load:async()=>(await Promise.resolve().then(()=>(H0(),QA))).nl},{name:"fold",load:async()=>(await Promise.resolve().then(()=>(K0(),e8))).fold},{name:"expand",load:async()=>(await Promise.resolve().then(()=>(X0(),n8))).expand},{name:"unexpand",load:async()=>(await Promise.resolve().then(()=>(Q0(),i8))).unexpand},{name:"strings",load:async()=>(await Promise.resolve().then(()=>(ey(),l8))).strings},{name:"split",load:async()=>(await Promise.resolve().then(()=>(ry(),f8))).split},{name:"column",load:async()=>(await Promise.resolve().then(()=>(iy(),h8))).column},{name:"join",load:async()=>(await Promise.resolve().then(()=>(ly(),p8))).join},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(uy(),m8))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(hy(),S8))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>(my(),A8))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(yy(),v8))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(by(),k8))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(Sy(),N8))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(Ad(),Cy))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(Ad(),Cy))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(vd(),Ty))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(vd(),Ty))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(Iy(),O8))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(Py(),R8))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(Cd(),Fy))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(Cd(),Fy))).falseCommand},{name:"yes",load:async()=>(await Promise.resolve().then(()=>(_y(),P8))).yesCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(By(),$8))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(kd(),Wy))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(kd(),Wy))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(f2(),f9))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(h2(),m9))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(b2(),P9))).diffCommand,handlesOwnVersion:!0},{name:"date",load:async()=>(await Promise.resolve().then(()=>(E2(),$9))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(v2(),F9))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>(k2(),D9))).timeoutCommand},{name:"time",load:async()=>(await Promise.resolve().then(()=>(T2(),z9))).timeCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(I2(),U9))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(P2(),W9))).exprCommand},{name:"md5sum",load:async()=>(await Promise.resolve().then(()=>(L2(),q9))).md5sumCommand},{name:"sha1sum",load:async()=>(await Promise.resolve().then(()=>(D2(),V9))).sha1sumCommand},{name:"sha256sum",load:async()=>(await Promise.resolve().then(()=>(M2(),H9))).sha256sumCommand},{name:"file",load:async()=>(await Promise.resolve().then(()=>(iw(),sC))).fileCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>(aw(),oC))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(cw(),aC))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(gw(),cC))).whichCommand},{name:"tac",load:async()=>(await Promise.resolve().then(()=>(ww(),uC))).tac},{name:"hostname",load:async()=>(await Promise.resolve().then(()=>(xw(),fC))).hostname},{name:"whoami",load:async()=>(await Promise.resolve().then(()=>(Sw(),dC))).whoami},{name:"od",load:async()=>(await Promise.resolve().then(()=>(vw(),hC))).od},{name:"gzip",load:async()=>(await Promise.resolve().then(()=>(ru(),ah))).gzipCommand},{name:"gunzip",load:async()=>(await Promise.resolve().then(()=>(ru(),ah))).gunzipCommand},{name:"zcat",load:async()=>(await Promise.resolve().then(()=>(ru(),ah))).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(La.push({name:"tar",load:async()=>(await Promise.resolve().then(()=>(Kw(),tk))).tarCommand}),La.push({name:"yq",load:async()=>(await Promise.resolve().then(()=>(Tx(),gO))).yqCommand}),La.push({name:"xan",load:async()=>(await Promise.resolve().then(()=>(EE(),qO))).xanCommand}),La.push({name:"sqlite3",load:async()=>(await Promise.resolve().then(()=>(vE(),oI))).sqlite3Command}));var Zp=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Zp.push({name:"python3",load:async()=>(await Promise.resolve().then(()=>(TE(),NE))).python3Command,handlesOwnVersion:!0}),Zp.push({name:"python",load:async()=>(await Promise.resolve().then(()=>(TE(),NE))).pythonCommand,handlesOwnVersion:!0}));var Xp=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Xp.push({name:"js-exec",load:async()=>(await Promise.resolve().then(()=>(IE(),OE))).jsExecCommand,handlesOwnVersion:!0}),Xp.push({name:"node",load:async()=>(await Promise.resolve().then(()=>(IE(),OE))).nodeStubCommand}));var LI=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(NI(),kI))).curlCommand}],$I=new Map;function Yp(t){return{name:t.name,handlesOwnVersion:t.handlesOwnVersion,async execute(e,n){let r=$I.get(t.name);if(r||(r=await tt.runTrustedAsync(()=>Ac(t.load(),n.signal,`bash: ${t.name} was cancelled before it started
|
|
1418
|
+
`:"",exitCode:a}}}}});function TI(){return cJ}var cJ,OI=L(()=>{"use strict";vd();O0();h2();my();kd();z1();yg();By();iy();D0();ug();M0();E2();b2();yy();Sy();M1();Ad();X0();Q0();P2();iw();hy();K0();Dc();ru();vg();cw();Iy();xw();aw();ly();f2();pg();X1();L2();D2();M2();Q1();ng();dg();H0();vw();z0();j1();bg();Eg();q0();i0();lg();sg();m0();I2();v2();P0();ry();vE();Rg();ey();ww();kg();Kw();uy();T2();k2();og();W0();by();Cd();L0();Og();gw();Sw();EE();Py();_y();Tx();cJ=[_1,B1,W1,Z1,Y1,tg,rg,ig,ag,cg,fg,hg,gg,wg,xg,Ag,Cg,Tg,Ig,Qg,Jg,e0,s0,p0,T0,R0,$0,F0,_0,B0,U0,j0,V0,G0,Z0,Y0,J0,ny,sy,ay,cy,dy,py,gy,wy,Ey,Ay,vy,ky,Ny,Oy,Ry,$y,Ly,Dy,My,zy,Uy,u2,d2,w2,x2,A2,C2,N2,O2,R2,$2,F2,_2,sw,ow,lw,mw,yw,bw,Ew,Aw,Tw,Ow,Iw,Gw,Nx,xE,AE]});var RI={};he(RI,{emitFlagCoverage:()=>uJ});function uJ(t,e,n){let r=II.get(e);if(!(!r||r.size===0))for(let s of n)r.has(s)&&t.hit(`cmd:flag:${e}:${s}`)}var II,PI=L(()=>{"use strict";OI();II=new Map;for(let t of TI())II.set(t.name,new Set(t.flags.map(e=>e.flag)))});var Are={};he(Are,{AgentSandbox:()=>Lf,Bash:()=>Xo,BashTransformPipeline:()=>w1,CommandCollectorPlugin:()=>b1,DefenseInDepthBox:()=>nt,EMPTY_BYTES:()=>Ri,FsError:()=>D,InMemoryFs:()=>ir,MountableFs:()=>Wr,NetworkAccessDeniedError:()=>ls,OverlayFs:()=>Ts,ReadWriteFs:()=>Ff,RedirectNotAllowedError:()=>ki,Sandbox:()=>Df,SandboxCommand:()=>Ga,SecurityViolationError:()=>Re,SecurityViolationLogger:()=>_f,TeePlugin:()=>x1,TooManyRedirectsError:()=>Zo,applyDiffToRealFs:()=>Rf,bytesOutput:()=>i4,createAgentSandbox:()=>uF,createCommandContext:()=>GI,createConsoleViolationCallback:()=>H7,createVfsTemplate:()=>dF,decodeBytesToUtf8:()=>fe,defineCommand:()=>ZI,encodeUtf8ToBytes:()=>vr,fsErrorCode:()=>tl,getCommandNames:()=>FI,getJavaScriptCommandNames:()=>UI,getNetworkCommandNames:()=>DI,getPythonCommandNames:()=>BI,isFsErrorCode:()=>st,latin1FromBytes:()=>kt,parse:()=>or,serialize:()=>sc,stdoutAsBytes:()=>ni,stdoutKind:()=>zf,textOutput:()=>s4,toFsError:()=>g4,unsafeBytesFromLatin1:()=>to});module.exports=bF(Are);var Yn=jt(require("node:path"),1);Os();Qa();Qt();Qa();cn();var La=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(M1(),a4))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(z1(),l4))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(j1(),h4))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(X1(),A4))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(Q1(),v4))).mkdirCommand},{name:"mktemp",load:async()=>(await Promise.resolve().then(()=>(ng(),O4))).mktempCommand,handlesOwnVersion:!0},{name:"rmdir",load:async()=>(await Promise.resolve().then(()=>(sg(),P4))).rmdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(og(),$4))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(lg(),L4))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(ug(),F4))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(dg(),D4))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>(pg(),_4))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(yg(),M4))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>(bg(),B4))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(Eg(),z4))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(vg(),j4))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(kg(),q4))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(Og(),H4))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(Rg(),G4))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(Dc(),nd))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(Dc(),nd))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(Dc(),nd))).egrepCommand},{name:"rg",load:async()=>(await Promise.resolve().then(()=>(i0(),j3))).rgCommand,handlesOwnVersion:!0},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(m0(),eA))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(O0(),$A))).awkCommand2},{name:"sort",load:async()=>(await Promise.resolve().then(()=>(P0(),WA))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(L0(),jA))).uniqCommand},{name:"comm",load:async()=>(await Promise.resolve().then(()=>(D0(),qA))).commCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(M0(),VA))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(z0(),GA))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(W0(),ZA))).trCommand},{name:"rev",load:async()=>(await Promise.resolve().then(()=>(q0(),XA))).rev},{name:"nl",load:async()=>(await Promise.resolve().then(()=>(H0(),QA))).nl},{name:"fold",load:async()=>(await Promise.resolve().then(()=>(K0(),e8))).fold},{name:"expand",load:async()=>(await Promise.resolve().then(()=>(X0(),n8))).expand},{name:"unexpand",load:async()=>(await Promise.resolve().then(()=>(Q0(),i8))).unexpand},{name:"strings",load:async()=>(await Promise.resolve().then(()=>(ey(),l8))).strings},{name:"split",load:async()=>(await Promise.resolve().then(()=>(ry(),f8))).split},{name:"column",load:async()=>(await Promise.resolve().then(()=>(iy(),h8))).column},{name:"join",load:async()=>(await Promise.resolve().then(()=>(ly(),p8))).join},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(uy(),m8))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(hy(),S8))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>(my(),A8))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(yy(),v8))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(by(),k8))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(Sy(),N8))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(Ad(),Cy))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(Ad(),Cy))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(vd(),Ty))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(vd(),Ty))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(Iy(),O8))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(Py(),R8))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(Cd(),Fy))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(Cd(),Fy))).falseCommand},{name:"yes",load:async()=>(await Promise.resolve().then(()=>(_y(),P8))).yesCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(By(),$8))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(kd(),Wy))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(kd(),Wy))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(f2(),f9))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(h2(),m9))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(b2(),P9))).diffCommand,handlesOwnVersion:!0},{name:"date",load:async()=>(await Promise.resolve().then(()=>(E2(),$9))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(v2(),F9))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>(k2(),D9))).timeoutCommand},{name:"time",load:async()=>(await Promise.resolve().then(()=>(T2(),z9))).timeCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(I2(),U9))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(P2(),W9))).exprCommand},{name:"md5sum",load:async()=>(await Promise.resolve().then(()=>(L2(),q9))).md5sumCommand},{name:"sha1sum",load:async()=>(await Promise.resolve().then(()=>(D2(),V9))).sha1sumCommand},{name:"sha256sum",load:async()=>(await Promise.resolve().then(()=>(M2(),H9))).sha256sumCommand},{name:"file",load:async()=>(await Promise.resolve().then(()=>(iw(),sC))).fileCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>(aw(),oC))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(cw(),aC))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(gw(),cC))).whichCommand},{name:"tac",load:async()=>(await Promise.resolve().then(()=>(ww(),uC))).tac},{name:"hostname",load:async()=>(await Promise.resolve().then(()=>(xw(),fC))).hostname},{name:"whoami",load:async()=>(await Promise.resolve().then(()=>(Sw(),dC))).whoami},{name:"od",load:async()=>(await Promise.resolve().then(()=>(vw(),hC))).od},{name:"gzip",load:async()=>(await Promise.resolve().then(()=>(ru(),ah))).gzipCommand},{name:"gunzip",load:async()=>(await Promise.resolve().then(()=>(ru(),ah))).gunzipCommand},{name:"zcat",load:async()=>(await Promise.resolve().then(()=>(ru(),ah))).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(La.push({name:"tar",load:async()=>(await Promise.resolve().then(()=>(Kw(),tk))).tarCommand}),La.push({name:"yq",load:async()=>(await Promise.resolve().then(()=>(Tx(),gO))).yqCommand}),La.push({name:"xan",load:async()=>(await Promise.resolve().then(()=>(EE(),qO))).xanCommand}),La.push({name:"sqlite3",load:async()=>(await Promise.resolve().then(()=>(vE(),oI))).sqlite3Command}));var Zp=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Zp.push({name:"python3",load:async()=>(await Promise.resolve().then(()=>(TE(),NE))).python3Command,handlesOwnVersion:!0}),Zp.push({name:"python",load:async()=>(await Promise.resolve().then(()=>(TE(),NE))).pythonCommand,handlesOwnVersion:!0}));var Xp=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Xp.push({name:"js-exec",load:async()=>(await Promise.resolve().then(()=>(IE(),OE))).jsExecCommand,handlesOwnVersion:!0}),Xp.push({name:"node",load:async()=>(await Promise.resolve().then(()=>(IE(),OE))).nodeStubCommand}));var LI=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(NI(),kI))).curlCommand}],$I=new Map;function Yp(t){return{name:t.name,handlesOwnVersion:t.handlesOwnVersion,async execute(e,n){let r=$I.get(t.name);if(r||(r=await nt.runTrustedAsync(()=>Ac(t.load(),n.signal,`bash: ${t.name} was cancelled before it started
|
|
1419
1419
|
`)),$I.set(t.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await Ac(Promise.resolve().then(()=>(PI(),RI)),n.signal,`bash: ${t.name} was cancelled before it started
|
|
1420
1420
|
`);s(n.coverage,t.name,e)}return r.execute(e,n)}}}function FI(){return La.map(t=>t.name)}function DI(){return LI.map(t=>t.name)}function _I(t){return(t?La.filter(n=>t.includes(n.name)):La).map(Yp)}function MI(){return LI.map(Yp)}function BI(){return Zp.map(t=>t.name)}function zI(){return Zp.map(Yp)}function UI(){return Xp.map(t=>t.name)}function WI(){return Xp.map(Yp)}Qa();pe();var jI=new WeakMap,qI=new WeakSet;function Qp(t){let e=jI.get(t);return e===void 0&&(e=Object.freeze(Object.create(null)),jI.set(t,e),qI.add(e)),e}function VI(t){return qI.has(t)}var HI={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxJsMemoryBytes:67108864,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},fJ={...HI,maxSourceBytes:8*1024*1024,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxExtensionCleanupTimeMs:25,maxGlobOperations:1e5,maxStringLength:10*1024*1024,maxArrayElements:1e5,maxHeredocSize:10*1024*1024,maxBraceExpansionResults:1e4,maxOutputSize:10*1024*1024,maxFileDescriptors:1024,maxQueryTokens:25e3,maxQueryDepth:256,maxQueryElements:1e5,maxAwkParserTokens:25e3,maxAwkParserDepth:128,maxAwkParserOperations:1e5,maxCsvRows:1e5,maxCsvCells:1e6,maxWorkUnits:1e5,maxTraversalEntries:1e5,maxTraversalDepth:256,maxTraversalWork:1e5,maxLiveBytes:64*1024*1024,maxInputBytes:32*1024*1024,maxFileSystemBytes:128*1024*1024,maxDatabaseBytes:64*1024*1024,maxDatabaseResultBytes:16*1024*1024,maxArchiveBytes:128*1024*1024,maxArchiveCompressedBytes:64*1024*1024,maxArchiveEntryBytes:64*1024*1024,maxArchiveEntries:1e5,maxWorkerMessageBytes:16*1024*1024,maxExecutionTimeMs:3e4};function dJ(t){return Number.isFinite(t)?Math.min(Math.max(0,Math.floor(t)),4294967295):4294967295}function Jp(t,e="normal"){if(e!=="normal"&&e!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=e==="hardened"?fJ:HI;if(!t)return{...n};let r={maxSourceBytes:t.maxSourceBytes??n.maxSourceBytes,maxExecDepth:t.maxExecDepth??n.maxExecDepth,maxCallDepth:t.maxCallDepth??n.maxCallDepth,maxCommandCount:t.maxCommandCount??n.maxCommandCount,maxLoopIterations:t.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??n.maxAwkIterations,maxSedIterations:t.maxSedIterations??n.maxSedIterations,maxJqIterations:t.maxJqIterations??n.maxJqIterations,maxQueryTokens:t.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:t.maxQueryDepth??n.maxQueryDepth,maxQueryElements:t.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:t.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:t.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:t.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:t.maxCsvRows??n.maxCsvRows,maxCsvCells:t.maxCsvCells??n.maxCsvCells,maxWorkUnits:t.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:t.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:t.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:t.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:t.maxLiveBytes??n.maxLiveBytes,maxInputBytes:t.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:t.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:t.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:t.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:t.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:t.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:t.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:t.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:t.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:t.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:t.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:t.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:t.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:t.maxJsTimeoutMs??n.maxJsTimeoutMs,maxJsMemoryBytes:dJ(t.maxJsMemoryBytes??n.maxJsMemoryBytes),maxGlobOperations:t.maxGlobOperations??n.maxGlobOperations,maxStringLength:t.maxStringLength??n.maxStringLength,maxArrayElements:t.maxArrayElements??n.maxArrayElements,maxHeredocSize:t.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:t.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:t.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:t.maxOutputSize??n.maxOutputSize,maxFileDescriptors:t.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:t.maxSourceDepth??n.maxSourceDepth};for(let s of Object.keys(r)){let i=r[s];if(i!==Number.POSITIVE_INFINITY&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`${s} must be a non-negative safe integer or positive Infinity`)}return r}co();function GI(t){let{executionLimits:e,executionLimitProfile:n,fs:r,stdin:s=Ri,...i}=t;return{fs:r,fsIdentity:i.fsIdentity??Qp(r),cwd:"/",env:new Map,stdin:s,limits:Jp(e,n),...i}}function KI(t){return"load"in t&&typeof t.load=="function"}function ZI(t,e,n={}){return{name:t,trusted:n.trusted!==!1,execute:e}}function XI(t){let e=null,n=!1,r=new Set,s=a=>{e=a;for(let l of r)l.resolve(a);r.clear()},i=a=>{n=!1;for(let l of r)l.reject(a);r.clear()},o=()=>{n=!0;let a;try{a=Promise.resolve(t.load())}catch(l){i(l);return}B9.call(a,s,i)};return{name:t.name,trusted:t.trusted!==!1,handlesOwnVersion:t.handlesOwnVersion,async execute(a,l){if(!e){let u,f=new Promise((d,h)=>{u={resolve:d,reject:h},r.add(u)});n||o();try{e=await Ac(f,l.signal,`bash: ${t.name} was cancelled before it started
|
|
1421
|
-
`)}finally{u&&r.delete(u)}}let c=e;if(!c)throw new Error(`Failed to load command: ${t.name}`);return c.execute(a,l)}}}pe();pe();X();Os();var YI=Object.freeze(Object.create(null)),em=class{limits;signal;abortOnUnresolvedCommands;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();unresolvedCommands=new Set;get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(e,n=void 0,r=!1){this.limits=e,this.signal=n,this.abortOnUnresolvedCommands=r}recordUnresolvedCommand(e){this.unresolvedCommands.add(e)}get unresolvedCommandNames(){return[...this.unresolvedCommands]}fail(e){throw this.poisoned??=e,this.poisoned}poisonAfterAbort(e){this.poisoned??=e}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(e=1,n="execution"){return this.consume("work",e,n)}consumeLimited(e,n,r,s=e){this.assertUsable();let i=this.countersByKind.get(e)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new v(`${s}: ${e} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new v(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(e,i+n),this.workUnits+=n,i+n}consumeInput(e,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(e)||e<0||e>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new v(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=e,this.inputBytes}consume(e,n=1,r=e){this.assertUsable();let s=this.countersByKind.get(e)??0,i=e==="commands"?this.commandCount:this.workUnits,o=e==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>o-i)&&this.fail(new v(e==="commands"?`too many commands executed (>${o}), increase executionLimits.maxCommandCount`:`${r}: ${e} work limit exceeded (${o})`,e==="commands"?"commands":"iterations"));let a=i+n;return e==="commands"?this.commandCount=a:this.workUnits=a,this.countersByKind.set(e,s+n),a}reserveBytes(e,n,r){this.assertUsable();let s=typeof e=="string"?e:"live",i=typeof e=="string"?n:e,o=typeof e=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new v(`${o}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let a=!1;return{release:()=>{if(a)return;a=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(e,n,r="execution",s=0,i="text"){this.assertUsable();let o=i==="bytes"?n.length:j(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new v(`${r}: invalid ${e} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new v(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=a,o}accountResult(e,n="execution",r=Number.POSITIVE_INFINITY){let s=e.internalOutputAccounting,i=Math.min(s?.stdout??0,r),o=Math.min(s?.stderr??0,Math.max(0,r-i)),a=this.appendOutput("stdout",e.stdout,n,i,e.stdoutKind==="bytes"||e.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",e.stderr,n,o);return Object.isExtensible(e)?(e.internalOutputAccounting={stdout:a,stderr:l},e):a===0&&l===0?e:{...e,internalOutputAccounting:{stdout:a,stderr:l}}}relinquishOutput(e,n,r){this.assertUsable(),r!==YI&&this.fail(new v(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(e)||e<0||e>this.outputBytes)&&this.fail(new v(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=e}enterDepth(e,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??e,o=this.depthByKind.get(e)??0;o>=s&&this.fail(new v(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(e,o+1);let a=!1;return{release:()=>{if(a)return;a=!0;let l=(this.depthByKind.get(e)??1)-1;l<=0?this.depthByKind.delete(e):this.depthByKind.set(e,l)}}}throwIfAborted(e="execution"){this.signal?.aborted&&this.fail(new
|
|
1422
|
-
`)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new
|
|
1423
|
-
`))}remainingTimeMs(){return Math.max(0,this.limits.maxExecutionTimeMs-(Date.now()-this.startedAt))}registerCleanup(e){this.assertUsable(),this.cleanupCallbacks.push(e);let n=!0;return()=>{if(!n)return;n=!1;let r=this.cleanupCallbacks.indexOf(e);r>=0&&this.cleanupCallbacks.splice(r,1)}}async close(){if(this.closed)return;this.closed=!0;let e=[],n=Date.now()+this.limits.maxExtensionCleanupTimeMs;for(let r=this.cleanupCallbacks.length-1;r>=0;r--)try{let s=n-Date.now();if(s<=0){e.push(new Error("execution cleanup grace period exceeded"));break}let i,o=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[r]).then(()=>({ok:!0}),a=>({ok:!1,error:a})),new Promise(a=>{i=Oi(()=>a({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(Ii(i),!o.ok&&(e.push(o.error),Date.now()>=n))break}catch(s){e.push(s)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,e.length>0)throw new AggregateError(e,"execution cleanup failed")}assertExecDepth(e){this.assertUsable(),e>this.limits.maxExecDepth&&this.fail(new v(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function QI(t){let e=Object.create(null);return Object.defineProperties(e,{remainingLiveBytes:{enumerable:!0,get:()=>t.remainingLiveBytes},consumeWork:{enumerable:!0,value:t.consumeWork.bind(t)},consumeLimited:{enumerable:!0,value:t.consumeLimited.bind(t)},consumeInput:{enumerable:!0,value:t.consumeInput.bind(t)},reserveBytes:{enumerable:!0,value:t.reserveBytes.bind(t)},enterDepth:{enumerable:!0,value:t.enterDepth.bind(t)},throwIfAborted:{enumerable:!0,value:t.throwIfAborted.bind(t)},remainingTimeMs:{enumerable:!0,value:t.remainingTimeMs.bind(t)},registerCleanup:{enumerable:!0,value:t.registerCleanup.bind(t)}}),Object.freeze(e)}function JI(t,e,n="pipeline"){t.relinquishOutput(e,n,YI)}pe();cn();Jl();bn();us();var Fa=new TextEncoder;function hJ(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var ir=class{data=new Map;entryIdentities=new WeakMap;nextEntryIdentity=1;maxTotalBytes;retainedBytes=0;contentReferences=new WeakMap;materializedContent(e){return e?.type==="file"&&"content"in e?e.content:null}storedByteLength(e){return e===null?0:e instanceof Uint8Array?e.byteLength:j(e)}wouldReleaseBytes(e){let n=this.materializedContent(e);return n===null?0:n instanceof Uint8Array?this.contentReferences.get(n)===1?n.byteLength:0:this.storedByteLength(n)}assertCanAllocate(e,n){let r=this.wouldReleaseBytes(this.data.get(e));if(!Number.isSafeInteger(n)||n<0||n>this.maxTotalBytes-this.retainedBytes+r)throw new D("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(e,n){let r=this.data.get(e),s=this.materializedContent(r),i=this.materializedContent(n);if(s===i){this.data.set(e,n);return}let o=this.wouldReleaseBytes(r),a=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(a>this.maxTotalBytes-this.retainedBytes+o)throw new D("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(s instanceof Uint8Array){let l=this.contentReferences.get(s)??0;l<=1?this.contentReferences.delete(s):this.contentReferences.set(s,l-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=a-o,this.data.set(e,n)}deleteEntry(e){let n=this.data.get(e);if(!n)return!1;let r=this.materializedContent(n),s=this.wouldReleaseBytes(n);if(r instanceof Uint8Array){let i=this.contentReferences.get(r)??0;i<=1?this.contentReferences.delete(r):this.contentReferences.set(r,i-1)}return this.retainedBytes-=s,this.data.delete(e)}contentByteLength(e,n){if(e instanceof Uint8Array)return e.byteLength;if(n==="hex")return Math.floor(e.length/2);if(n==="base64"){let r=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.max(0,Math.floor(e.length*3/4)-r)}return n==="binary"||n==="latin1"?e.length:j(e)}identityFor(e){let n=this.entryIdentities.get(e);return n||(n=`memfs:${this.nextEntryIdentity++}`,this.entryIdentities.set(e,n)),n}constructor(e,n={}){if(this.maxTotalBytes=n.maxTotalBytes??1024*1024*1024,!Number.isSafeInteger(this.maxTotalBytes)||this.maxTotalBytes<0)throw new Error("InMemoryFs: invalid maxTotalBytes");if(this.data.set("/",{type:"directory",mode:Rs,mtime:new Date}),e)for(let[r,s]of Object.entries(e))typeof s=="function"?this.writeFileLazy(r,s):hJ(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(e){let n=kr(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:Rs,mtime:new Date})))}writeFileSync(e,n,r,s){ve(e,"write");let i=ce(e);this.ensureParentDirs(i);let o=As(r);this.assertCanAllocate(i,this.contentByteLength(n,o));let a=Hs(n,o);this.setEntry(i,{type:"file",content:a,mode:s?.mode??so,mtime:s?.mtime??new Date})}writeFileLazy(e,n,r){ve(e,"write");let s=ce(e);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??so,mtime:r?.mtime??new Date})}async materializeLazy(e,n){let r=await tt.runTrustedAsync(async()=>n.lazy()),s=typeof r=="string"?Fa.encode(r):r,i={type:"file",content:s,mode:n.mode,mtime:n.mtime};return this.assertCanAllocate(e,s.byteLength),this.setEntry(e,i),i}async readFile(e,n){let r=await this.readFileBuffer(e),s=As(n);return ts(r,s)}async readFileBytes(e){let n=await this.readFileBuffer(e);return ts(n,"binary")}async readFileBuffer(e){ve(e,"open");let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, open '${e}'`);if(r.type!=="file")throw new D("EISDIR",`illegal operation on a directory, read '${e}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:Fa.encode(s.content)}return r.content instanceof Uint8Array?r.content:Fa.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){ve(e,"append");let s=ce(e),i=this.data.get(s);if(i&&i.type==="directory")throw new D("EISDIR",`illegal operation on a directory, write '${e}'`);let o=As(r),a=this.contentByteLength(n,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:Fa.encode("content"in l?l.content:"");this.assertCanAllocate(s,c.byteLength+a);let u=Hs(n,o),f=new Uint8Array(c.length+u.length);f.set(c),f.set(u,c.length),this.setEntry(s,{type:"file",content:f,mode:l.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){if(e.includes("\0"))return!1;try{let n=this.resolvePathWithSymlinks(e);return this.data.has(n)}catch{return!1}}async stat(e){ve(e,"stat");let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, stat '${e}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Fa.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}async lstat(e){ve(e,"lstat");let n=this.resolveIntermediateSymlinks(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Fa.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}resolveIntermediateSymlinks(e){let n=ce(e);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];s=`${s}/${a}`;let l=this.data.get(s),c=0,u=Nc;for(;l&&l.type==="symlink"&&c<u;){if(i.has(s))throw new D("ELOOP",`too many levels of symbolic links, lstat '${e}'`);i.add(s),s=nl(s,l.target),l=this.data.get(s),c++}if(c>=u)throw new D("ELOOP",`too many levels of symbolic links, lstat '${e}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(e){let n=ce(e);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let o of r){s=`${s}/${o}`;let a=this.data.get(s),l=0,c=Nc;for(;a&&a.type==="symlink"&&l<c;){if(i.has(s))throw new D("ELOOP",`too many levels of symbolic links, open '${e}'`);i.add(s),s=nl(s,a.target),a=this.data.get(s),l++}if(l>=c)throw new D("ELOOP",`too many levels of symbolic links, open '${e}'`)}return s}async mkdir(e,n){this.mkdirSync(e,n)}async createExclusive(e,n){let r=n.directory?"mkdir":"open";ve(e,n.directory?"mkdir":"write");let s=ce(e),i=kr(s),o=i==="/"?"/":this.resolvePathWithSymlinks(i),a=rr(o,s.slice(s.lastIndexOf("/")+1));if(this.data.has(a))throw new D("EEXIST",`file already exists, ${r} '${e}'`);if(o!=="/"){let l=this.data.get(o);if(!l)throw new D("ENOENT",`no such file or directory, ${r} '${e}'`);if(l.type!=="directory")throw new D("ENOTDIR",`not a directory, ${r} '${e}'`)}if(n.directory){this.setEntry(a,{type:"directory",mode:n.mode,mtime:new Date});return}this.assertCanAllocate(a,0),this.setEntry(a,{type:"file",content:new Uint8Array(0),mode:n.mode,mtime:new Date})}mkdirSync(e,n){ve(e,"mkdir");let r=ce(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new D("EEXIST",`file already exists, mkdir '${e}'`);if(!n?.recursive)throw new D("EEXIST",`directory already exists, mkdir '${e}'`);return}let s=kr(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new D("ENOENT",`no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:Rs,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){ve(e,"scandir");let n=ce(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, scandir '${e}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new D("ELOOP",`too many levels of symbolic links, scandir '${e}'`);s.add(n),n=nl(n,r.target),r=this.data.get(n)}if(!r)throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(e,n){ve(e,"rm");let r=ce(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new D("ENOENT",`no such file or directory, rm '${e}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new D("ENOTEMPTY",`directory not empty, rm '${e}'`);for(let o of i){let a=rr(r,o);await this.rm(a,n)}}}this.deleteEntry(r)}async cp(e,n,r){ve(e,"cp"),ve(n,"cp");let s=ce(e),i=ce(n),o=this.data.get(s);if(!o)throw new D("ENOENT",`no such file or directory, cp '${e}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?o.content.byteLength:Fa.encode(o.content).byteLength;this.assertCanAllocate(i,a);let l=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.setEntry(i,{...o,content:l})}else this.setEntry(i,{...o});else if(o.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new D("EISDIR",`is a directory, cp '${e}'`);if(ur(s,i))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=rr(s,l),u=rr(i,l);await this.cp(c,u,r)}}}async mv(e,n){ve(e,"mv"),ve(n,"mv");let r=ce(e),s=ce(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new D("ENOENT",`no such file or directory, mv '${e}'`);if(i.type==="directory"&&ur(r,s))throw new D("EINVAL",`cannot move '${e}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let o=await this.readdir(r);for(let a of o)await this.mv(rr(r,a),rr(s,a));this.deleteEntry(r);return}this.ensureParentDirs(s),this.setEntry(s,i),this.deleteEntry(r)}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){return io(e,n)}async chmod(e,n){ve(e,"chmod");let r=ce(e),s=this.data.get(r);if(!s)throw new D("ENOENT",`no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){ve(n,"symlink");let r=ce(n);if(this.data.has(r))throw new D("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:Vf,mtime:new Date})}async link(e,n){ve(e,"link"),ve(n,"link");let r=ce(e),s=ce(n),i=this.data.get(r);if(!i)throw new D("ENOENT",`no such file or directory, link '${e}'`);if(i.type!=="file")throw new D("EPERM",`operation not permitted, link '${e}'`);if(this.data.has(s))throw new D("EEXIST",`file already exists, link '${n}'`);let o=i;"lazy"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(s);let a={type:"file",content:o.content,mode:o.mode,mtime:o.mtime};this.entryIdentities.set(a,this.identityFor(o)),this.setEntry(s,a)}async readlink(e){ve(e,"readlink");let n=ce(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new D("EINVAL",`invalid argument, readlink '${e}'`);return r.target}async realpath(e){ve(e,"realpath");let n=this.resolvePathWithSymlinks(e);if(!this.data.has(n))throw new D("ENOENT",`no such file or directory, realpath '${e}'`);return n}async utimes(e,n,r){ve(e,"utimes");let s=ce(e),i=this.resolvePathWithSymlinks(s),o=this.data.get(i);if(!o)throw new D("ENOENT",`no such file or directory, utimes '${e}'`);o.mtime=r}};var eR="5.1.0(1)-release",tR="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function LE(t){let{pid:e,ppid:n,uid:r,gid:s}=t;return`Name: bash
|
|
1421
|
+
`)}finally{u&&r.delete(u)}}let c=e;if(!c)throw new Error(`Failed to load command: ${t.name}`);return c.execute(a,l)}}}pe();pe();X();Os();var YI=Object.freeze(Object.create(null)),em=class{limits;signal;abortOnUnresolvedCommands;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();unresolvedCommands=new Set;get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(e,n=void 0,r=!1){this.limits=e,this.signal=n,this.abortOnUnresolvedCommands=r}recordUnresolvedCommand(e){this.unresolvedCommands.add(e)}get unresolvedCommandNames(){return[...this.unresolvedCommands]}fail(e){throw this.poisoned??=e,this.poisoned}poisonAfterAbort(e){this.poisoned??=e}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(e=1,n="execution"){return this.consume("work",e,n)}consumeLimited(e,n,r,s=e){this.assertUsable();let i=this.countersByKind.get(e)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new v(`${s}: ${e} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new v(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(e,i+n),this.workUnits+=n,i+n}consumeInput(e,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(e)||e<0||e>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new v(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=e,this.inputBytes}consume(e,n=1,r=e){this.assertUsable();let s=this.countersByKind.get(e)??0,i=e==="commands"?this.commandCount:this.workUnits,o=e==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>o-i)&&this.fail(new v(e==="commands"?`too many commands executed (>${o}), increase executionLimits.maxCommandCount`:`${r}: ${e} work limit exceeded (${o})`,e==="commands"?"commands":"iterations"));let a=i+n;return e==="commands"?this.commandCount=a:this.workUnits=a,this.countersByKind.set(e,s+n),a}reserveBytes(e,n,r){this.assertUsable();let s=typeof e=="string"?e:"live",i=typeof e=="string"?n:e,o=typeof e=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new v(`${o}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let a=!1;return{release:()=>{if(a)return;a=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(e,n,r="execution",s=0,i="text"){this.assertUsable();let o=i==="bytes"?n.length:j(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new v(`${r}: invalid ${e} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new v(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=a,o}accountResult(e,n="execution",r=Number.POSITIVE_INFINITY){let s=e.internalOutputAccounting,i=Math.min(s?.stdout??0,r),o=Math.min(s?.stderr??0,Math.max(0,r-i)),a=this.appendOutput("stdout",e.stdout,n,i,e.stdoutKind==="bytes"||e.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",e.stderr,n,o);return Object.isExtensible(e)?(e.internalOutputAccounting={stdout:a,stderr:l},e):a===0&&l===0?e:{...e,internalOutputAccounting:{stdout:a,stderr:l}}}relinquishOutput(e,n,r){this.assertUsable(),r!==YI&&this.fail(new v(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(e)||e<0||e>this.outputBytes)&&this.fail(new v(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=e}enterDepth(e,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??e,o=this.depthByKind.get(e)??0;o>=s&&this.fail(new v(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(e,o+1);let a=!1;return{release:()=>{if(a)return;a=!0;let l=(this.depthByKind.get(e)??1)-1;l<=0?this.depthByKind.delete(e):this.depthByKind.set(e,l)}}}throwIfAborted(e="execution"){this.signal?.aborted&&this.fail(new et("",`bash: ${e} aborted
|
|
1422
|
+
`)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new et("",`bash: ${e} exceeded execution deadline (${this.limits.maxExecutionTimeMs}ms)
|
|
1423
|
+
`))}remainingTimeMs(){return Math.max(0,this.limits.maxExecutionTimeMs-(Date.now()-this.startedAt))}registerCleanup(e){this.assertUsable(),this.cleanupCallbacks.push(e);let n=!0;return()=>{if(!n)return;n=!1;let r=this.cleanupCallbacks.indexOf(e);r>=0&&this.cleanupCallbacks.splice(r,1)}}async close(){if(this.closed)return;this.closed=!0;let e=[],n=Date.now()+this.limits.maxExtensionCleanupTimeMs;for(let r=this.cleanupCallbacks.length-1;r>=0;r--)try{let s=n-Date.now();if(s<=0){e.push(new Error("execution cleanup grace period exceeded"));break}let i,o=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[r]).then(()=>({ok:!0}),a=>({ok:!1,error:a})),new Promise(a=>{i=Oi(()=>a({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(Ii(i),!o.ok&&(e.push(o.error),Date.now()>=n))break}catch(s){e.push(s)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,e.length>0)throw new AggregateError(e,"execution cleanup failed")}assertExecDepth(e){this.assertUsable(),e>this.limits.maxExecDepth&&this.fail(new v(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function QI(t){let e=Object.create(null);return Object.defineProperties(e,{remainingLiveBytes:{enumerable:!0,get:()=>t.remainingLiveBytes},consumeWork:{enumerable:!0,value:t.consumeWork.bind(t)},consumeLimited:{enumerable:!0,value:t.consumeLimited.bind(t)},consumeInput:{enumerable:!0,value:t.consumeInput.bind(t)},reserveBytes:{enumerable:!0,value:t.reserveBytes.bind(t)},enterDepth:{enumerable:!0,value:t.enterDepth.bind(t)},throwIfAborted:{enumerable:!0,value:t.throwIfAborted.bind(t)},remainingTimeMs:{enumerable:!0,value:t.remainingTimeMs.bind(t)},registerCleanup:{enumerable:!0,value:t.registerCleanup.bind(t)}}),Object.freeze(e)}function JI(t,e,n="pipeline"){t.relinquishOutput(e,n,YI)}pe();cn();Jl();bn();us();var Fa=new TextEncoder;function hJ(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var ir=class{data=new Map;entryIdentities=new WeakMap;nextEntryIdentity=1;maxTotalBytes;retainedBytes=0;contentReferences=new WeakMap;materializedContent(e){return e?.type==="file"&&"content"in e?e.content:null}storedByteLength(e){return e===null?0:e instanceof Uint8Array?e.byteLength:j(e)}wouldReleaseBytes(e){let n=this.materializedContent(e);return n===null?0:n instanceof Uint8Array?this.contentReferences.get(n)===1?n.byteLength:0:this.storedByteLength(n)}assertCanAllocate(e,n){let r=this.wouldReleaseBytes(this.data.get(e));if(!Number.isSafeInteger(n)||n<0||n>this.maxTotalBytes-this.retainedBytes+r)throw new D("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(e,n){let r=this.data.get(e),s=this.materializedContent(r),i=this.materializedContent(n);if(s===i){this.data.set(e,n);return}let o=this.wouldReleaseBytes(r),a=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(a>this.maxTotalBytes-this.retainedBytes+o)throw new D("ENOSPC",`in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(s instanceof Uint8Array){let l=this.contentReferences.get(s)??0;l<=1?this.contentReferences.delete(s):this.contentReferences.set(s,l-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=a-o,this.data.set(e,n)}deleteEntry(e){let n=this.data.get(e);if(!n)return!1;let r=this.materializedContent(n),s=this.wouldReleaseBytes(n);if(r instanceof Uint8Array){let i=this.contentReferences.get(r)??0;i<=1?this.contentReferences.delete(r):this.contentReferences.set(r,i-1)}return this.retainedBytes-=s,this.data.delete(e)}contentByteLength(e,n){if(e instanceof Uint8Array)return e.byteLength;if(n==="hex")return Math.floor(e.length/2);if(n==="base64"){let r=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.max(0,Math.floor(e.length*3/4)-r)}return n==="binary"||n==="latin1"?e.length:j(e)}identityFor(e){let n=this.entryIdentities.get(e);return n||(n=`memfs:${this.nextEntryIdentity++}`,this.entryIdentities.set(e,n)),n}constructor(e,n={}){if(this.maxTotalBytes=n.maxTotalBytes??1024*1024*1024,!Number.isSafeInteger(this.maxTotalBytes)||this.maxTotalBytes<0)throw new Error("InMemoryFs: invalid maxTotalBytes");if(this.data.set("/",{type:"directory",mode:Rs,mtime:new Date}),e)for(let[r,s]of Object.entries(e))typeof s=="function"?this.writeFileLazy(r,s):hJ(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(e){let n=kr(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:Rs,mtime:new Date})))}writeFileSync(e,n,r,s){Ce(e,"write");let i=ce(e);this.ensureParentDirs(i);let o=As(r);this.assertCanAllocate(i,this.contentByteLength(n,o));let a=Hs(n,o);this.setEntry(i,{type:"file",content:a,mode:s?.mode??so,mtime:s?.mtime??new Date})}writeFileLazy(e,n,r){Ce(e,"write");let s=ce(e);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??so,mtime:r?.mtime??new Date})}async materializeLazy(e,n){let r=await nt.runTrustedAsync(async()=>n.lazy()),s=typeof r=="string"?Fa.encode(r):r,i={type:"file",content:s,mode:n.mode,mtime:n.mtime};return this.assertCanAllocate(e,s.byteLength),this.setEntry(e,i),i}async readFile(e,n){let r=await this.readFileBuffer(e),s=As(n);return ts(r,s)}async readFileBytes(e){let n=await this.readFileBuffer(e);return ts(n,"binary")}async readFileBuffer(e){Ce(e,"open");let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, open '${e}'`);if(r.type!=="file")throw new D("EISDIR",`illegal operation on a directory, read '${e}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:Fa.encode(s.content)}return r.content instanceof Uint8Array?r.content:Fa.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){Ce(e,"append");let s=ce(e),i=this.data.get(s);if(i&&i.type==="directory")throw new D("EISDIR",`illegal operation on a directory, write '${e}'`);let o=As(r),a=this.contentByteLength(n,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:Fa.encode("content"in l?l.content:"");this.assertCanAllocate(s,c.byteLength+a);let u=Hs(n,o),f=new Uint8Array(c.length+u.length);f.set(c),f.set(u,c.length),this.setEntry(s,{type:"file",content:f,mode:l.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){if(e.includes("\0"))return!1;try{let n=this.resolvePathWithSymlinks(e);return this.data.has(n)}catch{return!1}}async stat(e){Ce(e,"stat");let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, stat '${e}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Fa.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}async lstat(e){Ce(e,"lstat");let n=this.resolveIntermediateSymlinks(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Fa.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}resolveIntermediateSymlinks(e){let n=ce(e);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];s=`${s}/${a}`;let l=this.data.get(s),c=0,u=Nc;for(;l&&l.type==="symlink"&&c<u;){if(i.has(s))throw new D("ELOOP",`too many levels of symbolic links, lstat '${e}'`);i.add(s),s=nl(s,l.target),l=this.data.get(s),c++}if(c>=u)throw new D("ELOOP",`too many levels of symbolic links, lstat '${e}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(e){let n=ce(e);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let o of r){s=`${s}/${o}`;let a=this.data.get(s),l=0,c=Nc;for(;a&&a.type==="symlink"&&l<c;){if(i.has(s))throw new D("ELOOP",`too many levels of symbolic links, open '${e}'`);i.add(s),s=nl(s,a.target),a=this.data.get(s),l++}if(l>=c)throw new D("ELOOP",`too many levels of symbolic links, open '${e}'`)}return s}async mkdir(e,n){this.mkdirSync(e,n)}async createExclusive(e,n){let r=n.directory?"mkdir":"open";Ce(e,n.directory?"mkdir":"write");let s=ce(e),i=kr(s),o=i==="/"?"/":this.resolvePathWithSymlinks(i),a=rr(o,s.slice(s.lastIndexOf("/")+1));if(this.data.has(a))throw new D("EEXIST",`file already exists, ${r} '${e}'`);if(o!=="/"){let l=this.data.get(o);if(!l)throw new D("ENOENT",`no such file or directory, ${r} '${e}'`);if(l.type!=="directory")throw new D("ENOTDIR",`not a directory, ${r} '${e}'`)}if(n.directory){this.setEntry(a,{type:"directory",mode:n.mode,mtime:new Date});return}this.assertCanAllocate(a,0),this.setEntry(a,{type:"file",content:new Uint8Array(0),mode:n.mode,mtime:new Date})}mkdirSync(e,n){Ce(e,"mkdir");let r=ce(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new D("EEXIST",`file already exists, mkdir '${e}'`);if(!n?.recursive)throw new D("EEXIST",`directory already exists, mkdir '${e}'`);return}let s=kr(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new D("ENOENT",`no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:Rs,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){Ce(e,"scandir");let n=ce(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, scandir '${e}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new D("ELOOP",`too many levels of symbolic links, scandir '${e}'`);s.add(n),n=nl(n,r.target),r=this.data.get(n)}if(!r)throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(e,n){Ce(e,"rm");let r=ce(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new D("ENOENT",`no such file or directory, rm '${e}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new D("ENOTEMPTY",`directory not empty, rm '${e}'`);for(let o of i){let a=rr(r,o);await this.rm(a,n)}}}this.deleteEntry(r)}async cp(e,n,r){Ce(e,"cp"),Ce(n,"cp");let s=ce(e),i=ce(n),o=this.data.get(s);if(!o)throw new D("ENOENT",`no such file or directory, cp '${e}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?o.content.byteLength:Fa.encode(o.content).byteLength;this.assertCanAllocate(i,a);let l=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.setEntry(i,{...o,content:l})}else this.setEntry(i,{...o});else if(o.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new D("EISDIR",`is a directory, cp '${e}'`);if(ur(s,i))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=rr(s,l),u=rr(i,l);await this.cp(c,u,r)}}}async mv(e,n){Ce(e,"mv"),Ce(n,"mv");let r=ce(e),s=ce(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new D("ENOENT",`no such file or directory, mv '${e}'`);if(i.type==="directory"&&ur(r,s))throw new D("EINVAL",`cannot move '${e}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let o=await this.readdir(r);for(let a of o)await this.mv(rr(r,a),rr(s,a));this.deleteEntry(r);return}this.ensureParentDirs(s),this.setEntry(s,i),this.deleteEntry(r)}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){return io(e,n)}async chmod(e,n){Ce(e,"chmod");let r=ce(e),s=this.data.get(r);if(!s)throw new D("ENOENT",`no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){Ce(n,"symlink");let r=ce(n);if(this.data.has(r))throw new D("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:Vf,mtime:new Date})}async link(e,n){Ce(e,"link"),Ce(n,"link");let r=ce(e),s=ce(n),i=this.data.get(r);if(!i)throw new D("ENOENT",`no such file or directory, link '${e}'`);if(i.type!=="file")throw new D("EPERM",`operation not permitted, link '${e}'`);if(this.data.has(s))throw new D("EEXIST",`file already exists, link '${n}'`);let o=i;"lazy"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(s);let a={type:"file",content:o.content,mode:o.mode,mtime:o.mtime};this.entryIdentities.set(a,this.identityFor(o)),this.setEntry(s,a)}async readlink(e){Ce(e,"readlink");let n=ce(e),r=this.data.get(n);if(!r)throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new D("EINVAL",`invalid argument, readlink '${e}'`);return r.target}async realpath(e){Ce(e,"realpath");let n=this.resolvePathWithSymlinks(e);if(!this.data.has(n))throw new D("ENOENT",`no such file or directory, realpath '${e}'`);return n}async utimes(e,n,r){Ce(e,"utimes");let s=ce(e),i=this.resolvePathWithSymlinks(s),o=this.data.get(i);if(!o)throw new D("ENOENT",`no such file or directory, utimes '${e}'`);o.mtime=r}};var eR="5.1.0(1)-release",tR="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function LE(t){let{pid:e,ppid:n,uid:r,gid:s}=t;return`Name: bash
|
|
1424
1424
|
State: R (running)
|
|
1425
1425
|
Pid: ${e}
|
|
1426
1426
|
PPid: ${n}
|
|
@@ -1428,7 +1428,7 @@ Uid: ${r} ${r} ${r} ${r}
|
|
|
1428
1428
|
Gid: ${s} ${s} ${s} ${s}
|
|
1429
1429
|
`}function pJ(t){let e=t;return typeof e.mkdirSync=="function"&&typeof e.writeFileSync=="function"}function mJ(t,e){t.mkdirSync("/bin",{recursive:!0}),t.mkdirSync("/usr/bin",{recursive:!0}),e&&(t.mkdirSync("/home/user",{recursive:!0}),t.mkdirSync("/tmp",{recursive:!0}))}function gJ(t){t.mkdirSync("/dev",{recursive:!0}),t.mkdirSync("/dev/fd",{recursive:!0}),t.writeFileSync("/dev/null",""),t.writeFileSync("/dev/zero",new Uint8Array(0)),t.writeFileSync("/dev/stdin",""),t.writeFileSync("/dev/stdout",""),t.writeFileSync("/dev/stderr","")}function yJ(t,e){t.mkdirSync("/proc/self/fd",{recursive:!0}),t.writeFileSync("/proc/version",`${tR}
|
|
1430
1430
|
`),t.writeFileSync("/proc/self/exe","/bin/bash"),t.writeFileSync("/proc/self/cmdline","bash\0"),t.writeFileSync("/proc/self/comm",`bash
|
|
1431
|
-
`),t.writeFileLazy?t.writeFileLazy("/proc/self/status",()=>LE(e)):t.writeFileSync("/proc/self/status",LE(e)),t.writeFileSync("/proc/self/fd/0","/dev/stdin"),t.writeFileSync("/proc/self/fd/1","/dev/stdout"),t.writeFileSync("/proc/self/fd/2","/dev/stderr")}function nR(t,e,n={pid:1,ppid:0,uid:1e3,gid:1e3}){if(pJ(t)){let r=wJ(t);mJ(r,e),gJ(r),yJ(r,n)}}function wJ(t){let e=r=>{try{r()}catch(s){if(s?.code!=="ENOSYS")throw s}},n={mkdirSync:(r,s)=>e(()=>t.mkdirSync(r,s)),writeFileSync:(r,s)=>e(()=>t.writeFileSync(r,s))};return t.writeFileLazy&&(n.writeFileLazy=(r,s)=>e(()=>t.writeFileLazy?.(r,s))),n}pe();J1();bn();us();var Wr=class{baseFs;mounts=new Map;constructor(e){if(this.baseFs=e?.base??new ir,e?.mounts)for(let{mountPoint:n,filesystem:r}of e.mounts)this.mount(n,r)}mount(e,n){this.validateMountPath(e);let r=ce(e);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(e){let n=ce(e);if(!this.mounts.has(n))throw new Error(`No filesystem mounted at '${e}'`);this.mounts.delete(n)}getMounts(){return Array.from(this.mounts.values()).map(e=>({mountPoint:e.mountPoint,filesystem:e.filesystem}))}diff(e){let n=e?.space??"vfs",r=[],s=[],i=[];for(let o of this.mounts.values()){let a=o.filesystem;if(typeof a.diff!="function")throw new D("EINVAL",`mounted filesystem at '${o.mountPoint}' does not support diff()`);let l=a.diff(),c=u=>{if(n==="vfs")return o.mountPoint==="/"?u:`${o.mountPoint}${u}`;if(typeof a.rootDir!="string")throw new D("EINVAL",`cannot produce a host-space diff: mount at '${o.mountPoint}' has no real root`);return`${a.rootDir}${u}`};for(let u of l.writes)r.push({...u,path:c(u.path)});for(let u=0;u<l.deletions.length;u++)s.push(c(l.deletions[u])),i.push(l.deletionChangedAt?.[u]??0)}return{writes:r,deletions:s,...i.length>0&&{deletionChangedAt:i}}}restamp(e,n,r="full"){let{fs:s,relativePath:i}=this.routePath(e),o=s.restamp;typeof o=="function"&&o.call(s,i,n,r)}isMountPoint(e){let n=ce(e);return this.mounts.has(n)}validateMountPath(e){let n=e.split("/");for(let r of n)if(r==="."||r==="..")throw new Error(`Invalid mount point '${e}': contains '.' or '..' segments`)}validateMount(e){if(e==="/")throw new Error("Cannot mount at root '/'");for(let n of this.mounts.keys())if(n!==e){if(e.startsWith(`${n}/`))throw new Error(`Cannot mount at '${e}': inside existing mount '${n}'`);if(n.startsWith(`${e}/`))throw new Error(`Cannot mount at '${e}': would contain existing mount '${n}'`)}}routePath(e){ve(e,"access");let n=ce(e),r=null,s=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(n===o)return{fs:i.filesystem,relativePath:"/"};n.startsWith(`${o}/`)&&o.length>s&&(r=i,s=o.length)}if(r){let i=n.slice(s);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:n}}getChildMountPoints(e){let n=ce(e),r=n==="/"?"/":`${n}/`,s=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!s.includes(a)&&s.push(a)}return s}async readFile(e,n){let{fs:r,relativePath:s}=this.routePath(e);return r.readFile(s,n)}async readFileBytes(e){let{fs:n,relativePath:r}=this.routePath(e);return zn(n,r)}async readFileBuffer(e){let{fs:n,relativePath:r}=this.routePath(e);return n.readFileBuffer(r)}async writeFile(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.writeFile(i,n,r)}async appendFile(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.appendFile(i,n,r)}async exists(e){let n=ce(e);if(this.mounts.has(n)||this.getChildMountPoints(n).length>0)return!0;let{fs:s,relativePath:i}=this.routePath(e);return s.exists(i)}async stat(e){let n=ce(e),r=this.mounts.get(n);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.stat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(e);return i.stat(o)}async lstat(e){let n=ce(e),r=this.mounts.get(n);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.lstat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(e);return i.lstat(o)}async mkdir(e,n){let r=ce(e);if(this.mounts.has(r)){if(n?.recursive)return;throw new D("EEXIST",`directory already exists, mkdir '${e}'`)}if(this.getChildMountPoints(r).length>0&&n?.recursive)return;let{fs:i,relativePath:o}=this.routePath(e);return i.mkdir(o,n)}async createExclusive(e,n){let r=ce(e),s=n.directory?"mkdir":"open";if(this.mounts.has(r))throw new D("EEXIST",`file already exists, ${s} '${e}'`);let{fs:i,relativePath:o}=this.routePath(e);if(!i.createExclusive)throw new Oc(e,s);let a=kr(o);return a!=="/"&&this.getChildMountPoints(kr(r)).length>0&&!await i.exists(a)&&await i.mkdir(a,{recursive:!0}),i.createExclusive(o,n)}async readdir(e){let n=ce(e),r=new Set,s=null,{fs:i,relativePath:o}=this.routePath(e);try{let l=await i.readdir(o);for(let c of l)r.add(c)}catch(l){if(!st(l,"ENOENT"))throw l;s=l}let a=this.getChildMountPoints(n);for(let l of a)r.add(l);if(r.size===0&&s&&!this.mounts.has(n))throw s;return Array.from(r).sort()}async rm(e,n){let r=ce(e);if(this.mounts.has(r))throw new D("EBUSY",`mount point, cannot remove '${e}'`);if(this.getChildMountPoints(r).length>0)throw new D("EBUSY",`contains mount points, cannot remove '${e}'`);let{fs:i,relativePath:o}=this.routePath(e);return i.rm(o,n)}async cp(e,n,r){if((await this.stat(e)).isDirectory&&ur(e,n))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);let i=this.routePath(e),o=this.routePath(n);return i.fs===o.fs?i.fs.cp(i.relativePath,o.relativePath,r):this.crossMountCopy(e,n,r)}async mv(e,n){let r=ce(e);if((await this.stat(e)).isDirectory&&ur(e,n))throw new D("EINVAL",`cannot move '${e}' into itself, '${n}'`);if(this.mounts.has(r))throw new D("EBUSY",`mount point, cannot move '${e}'`);let i=this.routePath(e),o=this.routePath(n);if(i.fs===o.fs)return i.fs.mv(i.relativePath,o.relativePath);await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){return io(e,n)}getAllPaths(){let e=new Set;for(let n of this.baseFs.getAllPaths())e.add(n);for(let n of this.mounts.keys()){let r=n.split("/").filter(Boolean),s="";for(let o of r)s=`${s}/${o}`,e.add(s);let i=this.mounts.get(n);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?e.add(n):e.add(`${n}${o}`)}return Array.from(e).sort()}async chmod(e,n){let r=ce(e),s=this.mounts.get(r);if(s)return s.filesystem.chmod("/",n);let{fs:i,relativePath:o}=this.routePath(e);return i.chmod(o,n)}async symlink(e,n){let{fs:r,relativePath:s}=this.routePath(n);return r.symlink(e,s)}async link(e,n){let r=this.routePath(e),s=this.routePath(n);if(r.fs!==s.fs)throw new D("EXDEV",`cross-device link not permitted, link '${e}' -> '${n}'`);return r.fs.link(r.relativePath,s.relativePath)}async readlink(e){let{fs:n,relativePath:r}=this.routePath(e);return n.readlink(r)}async realpath(e){let n=ce(e);if(this.mounts.get(n))return n;let{fs:s,relativePath:i}=this.routePath(e),o=await s.realpath(i);for(let[a,l]of this.mounts)if(n===a||n.startsWith(`${a}/`))return o==="/"?a:`${a}${o}`;return o}async crossMountCopy(e,n,r){let s=await this.lstat(e);if(s.isFile){let i=await this.readFileBuffer(e);await this.writeFile(n,i),await this.chmod(n,s.mode)}else if(s.isDirectory){if(!r?.recursive)throw new Error(`cp: ${e} is a directory (not copied)`);await this.mkdir(n,{recursive:!0});let i=await this.readdir(e);for(let o of i){let a=rr(e,o),l=rr(n,o);await this.crossMountCopy(a,l,r)}}else if(s.isSymbolicLink){let i=await this.readlink(e);await this.symlink(i,n)}}mkdirSync(e,n){let{fs:r,relativePath:s}=this.routePath(e),i=r;if(!i.mkdirSync)throw new D("ENOSYS",`function not implemented, mkdir '${e}'`);i.mkdirSync(s,n)}writeFileSync(e,n){let{fs:r,relativePath:s}=this.routePath(e),i=r;if(!i.writeFileSync)throw new D("ENOSYS",`function not implemented, write '${e}'`);i.writeFileSync(s,n)}async utimes(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.utimes(i,n,r)}};Tn();hs();Rl();function tm(t){let e={commands:new Set,definedFunctions:new Set,definedAliases:new Set};return FE(t,e),{commands:[...e.commands],definedFunctions:e.definedFunctions,definedAliases:e.definedAliases}}function bJ(t){return t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}function xJ(t,e){for(let n of t){let r=n.parts[0];if(r?.type!=="Literal")continue;let s=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.value);s&&e.definedAliases.add(s[1])}}function FE(t,e){for(let n of t.statements)bi(n,e)}function bi(t,e){for(let n of t.pipelines)EJ(n,e)}function EJ(t,e){for(let n of t.commands)rR(n,e)}function rR(t,e){switch(t.type){case"SimpleCommand":if(t.name){let n=bJ(t.name);n&&(e.commands.add(n),n==="alias"&&xJ(t.args,e)),wr(t.name.parts,e)}for(let n of t.args)wr(n.parts,e);for(let n of t.assignments)if(n.value&&wr(n.value.parts,e),n.array)for(let r of n.array)wr(r.parts,e);for(let n of t.redirections)n.target.type==="Word"?wr(n.target.parts,e):n.target.type==="HereDoc"&&!n.target.quoted&&wr(n.target.content.parts,e);break;case"If":for(let n of t.clauses){for(let r of n.condition)bi(r,e);for(let r of n.body)bi(r,e)}if(t.elseBody)for(let n of t.elseBody)bi(n,e);break;case"For":if(t.words)for(let n of t.words)wr(n.parts,e);for(let n of t.body)bi(n,e);break;case"CStyleFor":for(let n of t.body)bi(n,e);break;case"While":case"Until":for(let n of t.condition)bi(n,e);for(let n of t.body)bi(n,e);break;case"Case":wr(t.word.parts,e);for(let n of t.items)for(let r of n.body)bi(r,e);break;case"Subshell":case"Group":for(let n of t.body)bi(n,e);break;case"ArithmeticCommand":case"ConditionalCommand":break;case"FunctionDef":e.definedFunctions.add(t.name),rR(t.body,e);break}}function wr(t,e){for(let n of t)switch(n.type){case"CommandSubstitution":FE(n.body,e);break;case"ProcessSubstitution":FE(n.body,e);break;case"DoubleQuoted":wr(n.parts,e);break;case"ParameterExpansion":n.operation&&sR(n.operation,e);break}}function sR(t,e){switch(t.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":wr(t.word.parts,e);break;case"ErrorIfUnset":t.word&&wr(t.word.parts,e);break;case"PatternRemoval":wr(t.pattern.parts,e);break;case"PatternReplacement":wr(t.pattern.parts,e),t.replacement&&wr(t.replacement.parts,e);break;case"CaseModification":t.pattern&&wr(t.pattern.parts,e);break;case"Indirection":t.innerOp&&sR(t.innerOp,e);break}}function nm(t,e){return t===`/bin/${e}`||t===`/usr/bin/${e}`}async function rm(t,e,n){if(e.includes("/")){let o=t.fs.resolvePath(t.state.cwd,e);if(!await t.fs.exists(o))return{error:"not_found",path:o};try{let a=await t.fs.stat(o);if(a.isDirectory)return{error:"permission_denied",path:o};let l=o.split("/").pop()||e,c=t.commands.get(l);return c&&nm(o,l)?{cmd:c,path:o}:(a.mode&73)!==0?{script:!0,path:o}:{error:"permission_denied",path:o}}catch{return{error:"not_found",path:o}}}if(!n&&t.state.hashTable){let o=t.state.hashTable.get(e);if(o){try{let a=await t.fs.stat(o);if(!a.isDirectory){let l=t.commands.get(e);if(l&&nm(o,e))return{cmd:l,path:o};if((a.mode&73)!==0)return{script:!0,path:o}}}catch{}t.state.hashTable.delete(e)}}let s=(n??t.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let o of s){if(!o)continue;let l=`${o.startsWith("/")?o:t.fs.resolvePath(t.state.cwd,o)}/${e}`;if(await t.fs.exists(l))try{let c=await t.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=t.commands.get(e),d=nm(l,e);if(f&&d)return{cmd:f,path:l};if(u){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await t.fs.exists("/usr/bin")){let o=t.commands.get(e);if(o)return{cmd:o,path:`/usr/bin/${e}`}}return null}async function sm(t,e){let n=[];if(e.includes("/")){let i=t.fs.resolvePath(t.state.cwd,e);if(await t.fs.exists(i))try{let o=await t.fs.stat(i);o.isDirectory||(o.mode&73)!==0&&n.push(e)}catch{}return n}let s=(t.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let i of s){if(!i)continue;let a=`${i.startsWith("/")?i:t.fs.resolvePath(t.state.cwd,i)}/${e}`;if(nm(a,e)&&t.commands.has(e)){n.push(a);continue}if(await t.fs.exists(a)){try{let l=await t.fs.stat(a);if(l.isDirectory||(l.mode&73)===0)continue}catch{continue}n.push(i.startsWith("/")?a:`${i}/${e}`)}}return n}X();pe();X();function br(t){return{kind:t.kind,elements:new Map(t.elements)}}function vs(t){return new Map(Array.from(t??[],([e,n])=>[e,br(n)]))}function Rn(t,e){return t.state.arrays?.get(e)}function af(t,e,n="indexed"){t.state.arrays??=new Map;let r=t.state.arrays.get(e);return r||(r={kind:n,elements:new Map},t.state.arrays.set(e,r)),r}function Oo(t,e,n){let r=af(t,e,n);return r.kind=n,r}function Vn(t,e){return t.state.arrays?.has(e)??!1}function bt(t,e,n){return Rn(t,e)?.elements.get(String(n))}function Io(t,e,n){return Rn(t,e)?.elements.has(String(n))??!1}function Fe(t,e,n,r,s){let i=af(t,e,s),o=String(n);if(!i.elements.has(o)&&i.elements.size>=t.limits.maxArrayElements)throw new v(`array element limit exceeded (${t.limits.maxArrayElements})`,"array_elements");if(j(r)>t.limits.maxStringLength)throw new v(`array value string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");i.elements.set(o,r)}function Da(t,e,n,r=!1){let s=new Set(r?[]:Rn(t,e)?.elements.keys()??[]);for(let i of n)if(s.add(String(i)),s.size>t.limits.maxArrayElements)throw new v(`array element limit exceeded (${t.limits.maxArrayElements})`,"array_elements")}function _a(t,e,n){return Rn(t,e)?.elements.delete(String(n))??!1}function lf(t,e){t.state.arrays?.delete(e),t.state.associativeArrays?.delete(e)}function Cn(t,e){return Array.from(Rn(t,e)?.elements.keys()??[]).filter(r=>/^(0|[1-9]\d*)$/.test(r)).map(Number).sort((r,s)=>r-s)}function an(t,e){af(t,e,t.state.associativeArrays?.has(e)?"associative":"indexed").elements.clear()}function xi(t,e){return Array.from(Rn(t,e)?.elements.keys()??[]).sort()}function im(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function DE(t){if(t.parts.length<2)return null;let e=t.parts[0],n=t.parts[1];if(e.type!=="Glob"||!e.pattern.startsWith("["))return null;let r,s=n,i=1;if(n.type==="Literal"&&n.value.startsWith("]")){let f=n.value.slice(1);if(f.startsWith("+=")||f.startsWith("="))r=e.pattern.slice(1);else if(f===""){if(t.parts.length<3)return null;let d=t.parts[2];if(d.type!=="Literal"||!d.value.startsWith("=")&&!d.value.startsWith("+="))return null;r=e.pattern.slice(1),s=d,i=2}else return null}else if(e.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(t.parts.length<3)return null;let f=t.parts[2];if(f.type!=="Literal"||!f.value.startsWith("]=")&&!f.value.startsWith("]+="))return null;if(n.type==="SingleQuoted")r=n.value;else{r="";for(let d of n.parts)(d.type==="Literal"||d.type==="Escaped")&&(r+=d.value)}s=f,i=2}else if(e.pattern.endsWith("]")){if(n.type!=="Literal"||!n.value.startsWith("=")&&!n.value.startsWith("+="))return null;r=e.pattern.slice(1,-1)}else return null;r=im(r);let o;if(s.type!=="Literal")return null;s.value.startsWith("]=")||s.value.startsWith("]+=")?o=s.value.slice(1):o=s.value;let a=o.startsWith("+=");if(!a&&!o.startsWith("="))return null;let l=[],c=a?2:1,u=o.slice(c);u&&l.push({type:"Literal",value:u});for(let f=i+1;f<t.parts.length;f++){let d=t.parts[f];d.type==="BraceExpansion"?l.push({type:"Literal",value:SJ(d)}):l.push(d)}return{key:r,valueParts:l,append:a}}function SJ(t){return`{${t.items.map(n=>{if(n.type==="Range"){let r=n.startStr??String(n.start),s=n.endStr??String(n.end),i=`${r}..${s}`;return n.step&&(i+=`..${n.step}`),i}return tc(n.word)}).join(",")}}`}function tc(t){let e="";for(let n of t.parts)switch(n.type){case"Literal":e+=n.value;break;case"Glob":e+=n.pattern;break;case"SingleQuoted":e+=n.value;break;case"DoubleQuoted":for(let r of n.parts)(r.type==="Literal"||r.type==="Escaped")&&(e+=r.value);break;case"Escaped":e+=n.value;break;case"BraceExpansion":e+="{",e+=n.items.map(r=>r.type==="Range"?`${r.startStr}..${r.endStr}${r.step?`..${r.step}`:""}`:tc(r.word)).join(","),e+="}";break;case"TildeExpansion":e+="~",n.user&&(e+=n.user);break}return e}var cf=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function iR(t){return cf.has(t)}var uf=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]);var AJ=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],vJ=["braceexpand","hashall","interactive-comments"];function _E(t){let e=[],n=[...vJ.map(r=>({name:r,enabled:!0})),...AJ.map(r=>({name:r,enabled:t[r]}))].sort((r,s)=>r.name.localeCompare(s.name));for(let r of n)r.enabled&&e.push(r.name);return e.join(":")}function nc(t){t.state.env.set("SHELLOPTS",_E(t.state.options))}var CJ=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function ME(t){let e=[];for(let n of CJ)t[n]&&e.push(n);return e.join(":")}function BE(t){t.state.env.set("BASHOPTS",ME(t.state.shoptOptions))}pe();hl();Kt();hs();var ue={script(t){return{type:"Script",statements:t}},statement(t,e=[],n=!1,r,s){let i={type:"Statement",pipelines:t,operators:e,background:n};return r&&(i.deferredError=r),s!==void 0&&(i.sourceText=s),i},pipeline(t,e=!1,n=!1,r=!1,s){return{type:"Pipeline",commands:t,negated:e,timed:n,timePosix:r,pipeStderr:s}},simpleCommand(t,e=[],n=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:n,redirections:r}},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}},processSubstitution(t,e){return{type:"ProcessSubstitution",body:t,direction:e}},assignment(t,e,n=!1,r=null){return{type:"Assignment",name:t,value:e,append:n,array:r}},redirection(t,e,n=null,r){let s={type:"Redirection",fd:n,operator:t,target:e};return r&&(s.fdVariable=r),s},hereDoc(t,e,n=!1,r=!1,s){let i={type:"HereDoc",delimiter:t,content:e,stripTabs:n,quoted:r};return s!==void 0&&(i.terminated=s),i},ifNode(t,e=null,n=[]){return{type:"If",clauses:t,elseBody:e,redirections:n}},forNode(t,e,n,r=[]){return{type:"For",variable:t,words:e,body:n,redirections:r}},whileNode(t,e,n=[]){return{type:"While",condition:t,body:e,redirections:n}},untilNode(t,e,n=[]){return{type:"Until",condition:t,body:e,redirections:n}},caseNode(t,e,n=[]){return{type:"Case",word:t,items:e,redirections:n}},caseItem(t,e,n=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:n}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,n=[],r){return{type:"FunctionDef",name:t,body:e,redirections:n,sourceFile:r}},conditionalCommand(t,e=[],n){return{type:"ConditionalCommand",expression:t,redirections:e,line:n}},arithmeticCommand(t,e=[],n){return{type:"ArithmeticCommand",expression:t,redirections:e,line:n}}};function oR(t,e){let n=t.length,r=e+3,s=2,i=!1,o=!1;for(;r<n&&s>0;){let a=t[r];if(i){a==="'"&&(i=!1),r++;continue}if(o){if(a==="\\"){r+=2;continue}a==='"'&&(o=!1),r++;continue}if(a==="'"){i=!0,r++;continue}if(a==='"'){o=!0,r++;continue}if(a==="\\"){r+=2;continue}if(a==="("){s++,r++;continue}if(a===")"){if(s--,s===1){let l=r+1;return!(l<n&&t[l]===")")}if(s===0)return!1;r++;continue}if(s===1&&(a==="|"&&r+1<n&&t[r+1]==="|"||a==="&"&&r+1<n&&t[r+1]==="&"||a==="|"&&r+1<n&&t[r+1]!=="|"))return!0;r++}return!1}function om(t,e){let n="",r=e,s=0,i=!1,o,a=l=>l===" "||l===" "||l===`
|
|
1431
|
+
`),t.writeFileLazy?t.writeFileLazy("/proc/self/status",()=>LE(e)):t.writeFileSync("/proc/self/status",LE(e)),t.writeFileSync("/proc/self/fd/0","/dev/stdin"),t.writeFileSync("/proc/self/fd/1","/dev/stdout"),t.writeFileSync("/proc/self/fd/2","/dev/stderr")}function nR(t,e,n={pid:1,ppid:0,uid:1e3,gid:1e3}){if(pJ(t)){let r=wJ(t);mJ(r,e),gJ(r),yJ(r,n)}}function wJ(t){let e=r=>{try{r()}catch(s){if(s?.code!=="ENOSYS")throw s}},n={mkdirSync:(r,s)=>e(()=>t.mkdirSync(r,s)),writeFileSync:(r,s)=>e(()=>t.writeFileSync(r,s))};return t.writeFileLazy&&(n.writeFileLazy=(r,s)=>e(()=>t.writeFileLazy?.(r,s))),n}pe();J1();bn();us();var Wr=class{baseFs;mounts=new Map;constructor(e){if(this.baseFs=e?.base??new ir,e?.mounts)for(let{mountPoint:n,filesystem:r}of e.mounts)this.mount(n,r)}mount(e,n){this.validateMountPath(e);let r=ce(e);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(e){let n=ce(e);if(!this.mounts.has(n))throw new Error(`No filesystem mounted at '${e}'`);this.mounts.delete(n)}getMounts(){return Array.from(this.mounts.values()).map(e=>({mountPoint:e.mountPoint,filesystem:e.filesystem}))}diff(e){let n=e?.space??"vfs",r=[],s=[],i=[];for(let o of this.mounts.values()){let a=o.filesystem;if(typeof a.diff!="function")throw new D("EINVAL",`mounted filesystem at '${o.mountPoint}' does not support diff()`);let l=a.diff(),c=u=>{if(n==="vfs")return o.mountPoint==="/"?u:`${o.mountPoint}${u}`;if(typeof a.rootDir!="string")throw new D("EINVAL",`cannot produce a host-space diff: mount at '${o.mountPoint}' has no real root`);return`${a.rootDir}${u}`};for(let u of l.writes)r.push({...u,path:c(u.path)});for(let u=0;u<l.deletions.length;u++)s.push(c(l.deletions[u])),i.push(l.deletionChangedAt?.[u]??0)}return{writes:r,deletions:s,...i.length>0&&{deletionChangedAt:i}}}restamp(e,n,r="full"){let{fs:s,relativePath:i}=this.routePath(e),o=s.restamp;typeof o=="function"&&o.call(s,i,n,r)}isMountPoint(e){let n=ce(e);return this.mounts.has(n)}validateMountPath(e){let n=e.split("/");for(let r of n)if(r==="."||r==="..")throw new Error(`Invalid mount point '${e}': contains '.' or '..' segments`)}validateMount(e){if(e==="/")throw new Error("Cannot mount at root '/'");for(let n of this.mounts.keys())if(n!==e){if(e.startsWith(`${n}/`))throw new Error(`Cannot mount at '${e}': inside existing mount '${n}'`);if(n.startsWith(`${e}/`))throw new Error(`Cannot mount at '${e}': would contain existing mount '${n}'`)}}routePath(e){Ce(e,"access");let n=ce(e),r=null,s=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(n===o)return{fs:i.filesystem,relativePath:"/"};n.startsWith(`${o}/`)&&o.length>s&&(r=i,s=o.length)}if(r){let i=n.slice(s);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:n}}getChildMountPoints(e){let n=ce(e),r=n==="/"?"/":`${n}/`,s=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!s.includes(a)&&s.push(a)}return s}async readFile(e,n){let{fs:r,relativePath:s}=this.routePath(e);return r.readFile(s,n)}async readFileBytes(e){let{fs:n,relativePath:r}=this.routePath(e);return zn(n,r)}async readFileBuffer(e){let{fs:n,relativePath:r}=this.routePath(e);return n.readFileBuffer(r)}async writeFile(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.writeFile(i,n,r)}async appendFile(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.appendFile(i,n,r)}async exists(e){let n=ce(e);if(this.mounts.has(n)||this.getChildMountPoints(n).length>0)return!0;let{fs:s,relativePath:i}=this.routePath(e);return s.exists(i)}async stat(e){let n=ce(e),r=this.mounts.get(n);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.stat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(e);return i.stat(o)}async lstat(e){let n=ce(e),r=this.mounts.get(n);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.lstat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:Rs,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(e);return i.lstat(o)}async mkdir(e,n){let r=ce(e);if(this.mounts.has(r)){if(n?.recursive)return;throw new D("EEXIST",`directory already exists, mkdir '${e}'`)}if(this.getChildMountPoints(r).length>0&&n?.recursive)return;let{fs:i,relativePath:o}=this.routePath(e);return i.mkdir(o,n)}async createExclusive(e,n){let r=ce(e),s=n.directory?"mkdir":"open";if(this.mounts.has(r))throw new D("EEXIST",`file already exists, ${s} '${e}'`);let{fs:i,relativePath:o}=this.routePath(e);if(!i.createExclusive)throw new Oc(e,s);let a=kr(o);return a!=="/"&&this.getChildMountPoints(kr(r)).length>0&&!await i.exists(a)&&await i.mkdir(a,{recursive:!0}),i.createExclusive(o,n)}async readdir(e){let n=ce(e),r=new Set,s=null,{fs:i,relativePath:o}=this.routePath(e);try{let l=await i.readdir(o);for(let c of l)r.add(c)}catch(l){if(!st(l,"ENOENT"))throw l;s=l}let a=this.getChildMountPoints(n);for(let l of a)r.add(l);if(r.size===0&&s&&!this.mounts.has(n))throw s;return Array.from(r).sort()}async rm(e,n){let r=ce(e);if(this.mounts.has(r))throw new D("EBUSY",`mount point, cannot remove '${e}'`);if(this.getChildMountPoints(r).length>0)throw new D("EBUSY",`contains mount points, cannot remove '${e}'`);let{fs:i,relativePath:o}=this.routePath(e);return i.rm(o,n)}async cp(e,n,r){if((await this.stat(e)).isDirectory&&ur(e,n))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);let i=this.routePath(e),o=this.routePath(n);return i.fs===o.fs?i.fs.cp(i.relativePath,o.relativePath,r):this.crossMountCopy(e,n,r)}async mv(e,n){let r=ce(e);if((await this.stat(e)).isDirectory&&ur(e,n))throw new D("EINVAL",`cannot move '${e}' into itself, '${n}'`);if(this.mounts.has(r))throw new D("EBUSY",`mount point, cannot move '${e}'`);let i=this.routePath(e),o=this.routePath(n);if(i.fs===o.fs)return i.fs.mv(i.relativePath,o.relativePath);await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){return io(e,n)}getAllPaths(){let e=new Set;for(let n of this.baseFs.getAllPaths())e.add(n);for(let n of this.mounts.keys()){let r=n.split("/").filter(Boolean),s="";for(let o of r)s=`${s}/${o}`,e.add(s);let i=this.mounts.get(n);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?e.add(n):e.add(`${n}${o}`)}return Array.from(e).sort()}async chmod(e,n){let r=ce(e),s=this.mounts.get(r);if(s)return s.filesystem.chmod("/",n);let{fs:i,relativePath:o}=this.routePath(e);return i.chmod(o,n)}async symlink(e,n){let{fs:r,relativePath:s}=this.routePath(n);return r.symlink(e,s)}async link(e,n){let r=this.routePath(e),s=this.routePath(n);if(r.fs!==s.fs)throw new D("EXDEV",`cross-device link not permitted, link '${e}' -> '${n}'`);return r.fs.link(r.relativePath,s.relativePath)}async readlink(e){let{fs:n,relativePath:r}=this.routePath(e);return n.readlink(r)}async realpath(e){let n=ce(e);if(this.mounts.get(n))return n;let{fs:s,relativePath:i}=this.routePath(e),o=await s.realpath(i);for(let[a,l]of this.mounts)if(n===a||n.startsWith(`${a}/`))return o==="/"?a:`${a}${o}`;return o}async crossMountCopy(e,n,r){let s=await this.lstat(e);if(s.isFile){let i=await this.readFileBuffer(e);await this.writeFile(n,i),await this.chmod(n,s.mode)}else if(s.isDirectory){if(!r?.recursive)throw new Error(`cp: ${e} is a directory (not copied)`);await this.mkdir(n,{recursive:!0});let i=await this.readdir(e);for(let o of i){let a=rr(e,o),l=rr(n,o);await this.crossMountCopy(a,l,r)}}else if(s.isSymbolicLink){let i=await this.readlink(e);await this.symlink(i,n)}}mkdirSync(e,n){let{fs:r,relativePath:s}=this.routePath(e),i=r;if(!i.mkdirSync)throw new D("ENOSYS",`function not implemented, mkdir '${e}'`);i.mkdirSync(s,n)}writeFileSync(e,n){let{fs:r,relativePath:s}=this.routePath(e),i=r;if(!i.writeFileSync)throw new D("ENOSYS",`function not implemented, write '${e}'`);i.writeFileSync(s,n)}async utimes(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.utimes(i,n,r)}};Tn();hs();Rl();function tm(t){let e={commands:new Set,definedFunctions:new Set,definedAliases:new Set};return FE(t,e),{commands:[...e.commands],definedFunctions:e.definedFunctions,definedAliases:e.definedAliases}}function bJ(t){return t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}function xJ(t,e){for(let n of t){let r=n.parts[0];if(r?.type!=="Literal")continue;let s=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.value);s&&e.definedAliases.add(s[1])}}function FE(t,e){for(let n of t.statements)bi(n,e)}function bi(t,e){for(let n of t.pipelines)EJ(n,e)}function EJ(t,e){for(let n of t.commands)rR(n,e)}function rR(t,e){switch(t.type){case"SimpleCommand":if(t.name){let n=bJ(t.name);n&&(e.commands.add(n),n==="alias"&&xJ(t.args,e)),wr(t.name.parts,e)}for(let n of t.args)wr(n.parts,e);for(let n of t.assignments)if(n.value&&wr(n.value.parts,e),n.array)for(let r of n.array)wr(r.parts,e);for(let n of t.redirections)n.target.type==="Word"?wr(n.target.parts,e):n.target.type==="HereDoc"&&!n.target.quoted&&wr(n.target.content.parts,e);break;case"If":for(let n of t.clauses){for(let r of n.condition)bi(r,e);for(let r of n.body)bi(r,e)}if(t.elseBody)for(let n of t.elseBody)bi(n,e);break;case"For":if(t.words)for(let n of t.words)wr(n.parts,e);for(let n of t.body)bi(n,e);break;case"CStyleFor":for(let n of t.body)bi(n,e);break;case"While":case"Until":for(let n of t.condition)bi(n,e);for(let n of t.body)bi(n,e);break;case"Case":wr(t.word.parts,e);for(let n of t.items)for(let r of n.body)bi(r,e);break;case"Subshell":case"Group":for(let n of t.body)bi(n,e);break;case"ArithmeticCommand":case"ConditionalCommand":break;case"FunctionDef":e.definedFunctions.add(t.name),rR(t.body,e);break}}function wr(t,e){for(let n of t)switch(n.type){case"CommandSubstitution":FE(n.body,e);break;case"ProcessSubstitution":FE(n.body,e);break;case"DoubleQuoted":wr(n.parts,e);break;case"ParameterExpansion":n.operation&&sR(n.operation,e);break}}function sR(t,e){switch(t.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":wr(t.word.parts,e);break;case"ErrorIfUnset":t.word&&wr(t.word.parts,e);break;case"PatternRemoval":wr(t.pattern.parts,e);break;case"PatternReplacement":wr(t.pattern.parts,e),t.replacement&&wr(t.replacement.parts,e);break;case"CaseModification":t.pattern&&wr(t.pattern.parts,e);break;case"Indirection":t.innerOp&&sR(t.innerOp,e);break}}function nm(t,e){return t===`/bin/${e}`||t===`/usr/bin/${e}`}async function rm(t,e,n){if(e.includes("/")){let o=t.fs.resolvePath(t.state.cwd,e);if(!await t.fs.exists(o))return{error:"not_found",path:o};try{let a=await t.fs.stat(o);if(a.isDirectory)return{error:"permission_denied",path:o};let l=o.split("/").pop()||e,c=t.commands.get(l);return c&&nm(o,l)?{cmd:c,path:o}:(a.mode&73)!==0?{script:!0,path:o}:{error:"permission_denied",path:o}}catch{return{error:"not_found",path:o}}}if(!n&&t.state.hashTable){let o=t.state.hashTable.get(e);if(o){try{let a=await t.fs.stat(o);if(!a.isDirectory){let l=t.commands.get(e);if(l&&nm(o,e))return{cmd:l,path:o};if((a.mode&73)!==0)return{script:!0,path:o}}}catch{}t.state.hashTable.delete(e)}}let s=(n??t.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let o of s){if(!o)continue;let l=`${o.startsWith("/")?o:t.fs.resolvePath(t.state.cwd,o)}/${e}`;if(await t.fs.exists(l))try{let c=await t.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=t.commands.get(e),d=nm(l,e);if(f&&d)return{cmd:f,path:l};if(u){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await t.fs.exists("/usr/bin")){let o=t.commands.get(e);if(o)return{cmd:o,path:`/usr/bin/${e}`}}return null}async function sm(t,e){let n=[];if(e.includes("/")){let i=t.fs.resolvePath(t.state.cwd,e);if(await t.fs.exists(i))try{let o=await t.fs.stat(i);o.isDirectory||(o.mode&73)!==0&&n.push(e)}catch{}return n}let s=(t.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let i of s){if(!i)continue;let a=`${i.startsWith("/")?i:t.fs.resolvePath(t.state.cwd,i)}/${e}`;if(nm(a,e)&&t.commands.has(e)){n.push(a);continue}if(await t.fs.exists(a)){try{let l=await t.fs.stat(a);if(l.isDirectory||(l.mode&73)===0)continue}catch{continue}n.push(i.startsWith("/")?a:`${i}/${e}`)}}return n}X();pe();X();function br(t){return{kind:t.kind,elements:new Map(t.elements)}}function vs(t){return new Map(Array.from(t??[],([e,n])=>[e,br(n)]))}function Rn(t,e){return t.state.arrays?.get(e)}function af(t,e,n="indexed"){t.state.arrays??=new Map;let r=t.state.arrays.get(e);return r||(r={kind:n,elements:new Map},t.state.arrays.set(e,r)),r}function Oo(t,e,n){let r=af(t,e,n);return r.kind=n,r}function Vn(t,e){return t.state.arrays?.has(e)??!1}function bt(t,e,n){return Rn(t,e)?.elements.get(String(n))}function Io(t,e,n){return Rn(t,e)?.elements.has(String(n))??!1}function Fe(t,e,n,r,s){let i=af(t,e,s),o=String(n);if(!i.elements.has(o)&&i.elements.size>=t.limits.maxArrayElements)throw new v(`array element limit exceeded (${t.limits.maxArrayElements})`,"array_elements");if(j(r)>t.limits.maxStringLength)throw new v(`array value string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");i.elements.set(o,r)}function Da(t,e,n,r=!1){let s=new Set(r?[]:Rn(t,e)?.elements.keys()??[]);for(let i of n)if(s.add(String(i)),s.size>t.limits.maxArrayElements)throw new v(`array element limit exceeded (${t.limits.maxArrayElements})`,"array_elements")}function _a(t,e,n){return Rn(t,e)?.elements.delete(String(n))??!1}function lf(t,e){t.state.arrays?.delete(e),t.state.associativeArrays?.delete(e)}function Cn(t,e){return Array.from(Rn(t,e)?.elements.keys()??[]).filter(r=>/^(0|[1-9]\d*)$/.test(r)).map(Number).sort((r,s)=>r-s)}function an(t,e){af(t,e,t.state.associativeArrays?.has(e)?"associative":"indexed").elements.clear()}function xi(t,e){return Array.from(Rn(t,e)?.elements.keys()??[]).sort()}function im(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function DE(t){if(t.parts.length<2)return null;let e=t.parts[0],n=t.parts[1];if(e.type!=="Glob"||!e.pattern.startsWith("["))return null;let r,s=n,i=1;if(n.type==="Literal"&&n.value.startsWith("]")){let f=n.value.slice(1);if(f.startsWith("+=")||f.startsWith("="))r=e.pattern.slice(1);else if(f===""){if(t.parts.length<3)return null;let d=t.parts[2];if(d.type!=="Literal"||!d.value.startsWith("=")&&!d.value.startsWith("+="))return null;r=e.pattern.slice(1),s=d,i=2}else return null}else if(e.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(t.parts.length<3)return null;let f=t.parts[2];if(f.type!=="Literal"||!f.value.startsWith("]=")&&!f.value.startsWith("]+="))return null;if(n.type==="SingleQuoted")r=n.value;else{r="";for(let d of n.parts)(d.type==="Literal"||d.type==="Escaped")&&(r+=d.value)}s=f,i=2}else if(e.pattern.endsWith("]")){if(n.type!=="Literal"||!n.value.startsWith("=")&&!n.value.startsWith("+="))return null;r=e.pattern.slice(1,-1)}else return null;r=im(r);let o;if(s.type!=="Literal")return null;s.value.startsWith("]=")||s.value.startsWith("]+=")?o=s.value.slice(1):o=s.value;let a=o.startsWith("+=");if(!a&&!o.startsWith("="))return null;let l=[],c=a?2:1,u=o.slice(c);u&&l.push({type:"Literal",value:u});for(let f=i+1;f<t.parts.length;f++){let d=t.parts[f];d.type==="BraceExpansion"?l.push({type:"Literal",value:SJ(d)}):l.push(d)}return{key:r,valueParts:l,append:a}}function SJ(t){return`{${t.items.map(n=>{if(n.type==="Range"){let r=n.startStr??String(n.start),s=n.endStr??String(n.end),i=`${r}..${s}`;return n.step&&(i+=`..${n.step}`),i}return tc(n.word)}).join(",")}}`}function tc(t){let e="";for(let n of t.parts)switch(n.type){case"Literal":e+=n.value;break;case"Glob":e+=n.pattern;break;case"SingleQuoted":e+=n.value;break;case"DoubleQuoted":for(let r of n.parts)(r.type==="Literal"||r.type==="Escaped")&&(e+=r.value);break;case"Escaped":e+=n.value;break;case"BraceExpansion":e+="{",e+=n.items.map(r=>r.type==="Range"?`${r.startStr}..${r.endStr}${r.step?`..${r.step}`:""}`:tc(r.word)).join(","),e+="}";break;case"TildeExpansion":e+="~",n.user&&(e+=n.user);break}return e}var cf=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function iR(t){return cf.has(t)}var uf=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]);var AJ=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],vJ=["braceexpand","hashall","interactive-comments"];function _E(t){let e=[],n=[...vJ.map(r=>({name:r,enabled:!0})),...AJ.map(r=>({name:r,enabled:t[r]}))].sort((r,s)=>r.name.localeCompare(s.name));for(let r of n)r.enabled&&e.push(r.name);return e.join(":")}function nc(t){t.state.env.set("SHELLOPTS",_E(t.state.options))}var CJ=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function ME(t){let e=[];for(let n of CJ)t[n]&&e.push(n);return e.join(":")}function BE(t){t.state.env.set("BASHOPTS",ME(t.state.shoptOptions))}pe();hl();Kt();hs();var ue={script(t){return{type:"Script",statements:t}},statement(t,e=[],n=!1,r,s){let i={type:"Statement",pipelines:t,operators:e,background:n};return r&&(i.deferredError=r),s!==void 0&&(i.sourceText=s),i},pipeline(t,e=!1,n=!1,r=!1,s){return{type:"Pipeline",commands:t,negated:e,timed:n,timePosix:r,pipeStderr:s}},simpleCommand(t,e=[],n=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:n,redirections:r}},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}},processSubstitution(t,e){return{type:"ProcessSubstitution",body:t,direction:e}},assignment(t,e,n=!1,r=null){return{type:"Assignment",name:t,value:e,append:n,array:r}},redirection(t,e,n=null,r){let s={type:"Redirection",fd:n,operator:t,target:e};return r&&(s.fdVariable=r),s},hereDoc(t,e,n=!1,r=!1,s){let i={type:"HereDoc",delimiter:t,content:e,stripTabs:n,quoted:r};return s!==void 0&&(i.terminated=s),i},ifNode(t,e=null,n=[]){return{type:"If",clauses:t,elseBody:e,redirections:n}},forNode(t,e,n,r=[]){return{type:"For",variable:t,words:e,body:n,redirections:r}},whileNode(t,e,n=[]){return{type:"While",condition:t,body:e,redirections:n}},untilNode(t,e,n=[]){return{type:"Until",condition:t,body:e,redirections:n}},caseNode(t,e,n=[]){return{type:"Case",word:t,items:e,redirections:n}},caseItem(t,e,n=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:n}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,n=[],r){return{type:"FunctionDef",name:t,body:e,redirections:n,sourceFile:r}},conditionalCommand(t,e=[],n){return{type:"ConditionalCommand",expression:t,redirections:e,line:n}},arithmeticCommand(t,e=[],n){return{type:"ArithmeticCommand",expression:t,redirections:e,line:n}}};function oR(t,e){let n=t.length,r=e+3,s=2,i=!1,o=!1;for(;r<n&&s>0;){let a=t[r];if(i){a==="'"&&(i=!1),r++;continue}if(o){if(a==="\\"){r+=2;continue}a==='"'&&(o=!1),r++;continue}if(a==="'"){i=!0,r++;continue}if(a==='"'){o=!0,r++;continue}if(a==="\\"){r+=2;continue}if(a==="("){s++,r++;continue}if(a===")"){if(s--,s===1){let l=r+1;return!(l<n&&t[l]===")")}if(s===0)return!1;r++;continue}if(s===1&&(a==="|"&&r+1<n&&t[r+1]==="|"||a==="&"&&r+1<n&&t[r+1]==="&"||a==="|"&&r+1<n&&t[r+1]!=="|"))return!0;r++}return!1}function om(t,e){let n="",r=e,s=0,i=!1,o,a=l=>l===" "||l===" "||l===`
|
|
1432
1432
|
`||l===";"||l==="&"||l==="|"||l==="<"||l===">"||l==="("||l===")";for(;r<t.length;){let l=t[r];if(l==="'"){let c=s>0;for(c||(i=!0),c&&(n+=l),r++;r<t.length&&t[r]!=="'";)n+=t[r],r++;r<t.length?(c&&(n+=t[r]),r++):o=l;continue}if(l==='"'){let c=s>0;for(c||(i=!0),c&&(n+=l),r++;r<t.length&&t[r]!=='"';){if(t[r]==="\\"&&r+1<t.length){if(c){n+=t.slice(r,r+2),r+=2;continue}let u=t[r+1];if(u==="$"||u==="`"||u==='"'||u==="\\"||u===`
|
|
1433
1433
|
`){r+=2,u!==`
|
|
1434
1434
|
`&&(n+=u);continue}}n+=t[r],r++}r<t.length?(c&&(n+=t[r]),r++):o=l;continue}if(l==="\\"&&r+1<t.length){if(s>0){n+=t.slice(r,r+2),r+=2;continue}i=!0;let c=t[r+1];c!==`
|
|
@@ -1531,7 +1531,7 @@ ${t.terminator}`}function Aee(t){return`(${Cs(t.body)})${Gs(t.redirections)}`}fu
|
|
|
1531
1531
|
`}:{target:s}:u.length===1?{target:u[0]}:{error:`bash: ${s}: ambiguous redirect
|
|
1532
1532
|
`}}async function TS(t,e){let n=e.parts,r=n.length;if(r===1){let o=await is(t,n[0]);return Bo(o,t.limits.maxStringLength,"word expansion"),o}let s=[];for(let o=0;o<r;o++)s.push(await is(t,n[o]));let i=s.join("");return Bo(i,t.limits.maxStringLength,"word expansion"),i}async function is(t,e,n=!1){if(e.type==="ParameterExpansion")return Tm(t,e,n);let r=mte(t,e,n);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let s=[];for(let i of e.parts)s.push(await is(t,i,!0));return s.join("")}case"CommandSubstitution":{let s=fP(e.body);if(s)try{let h=await ot(t,s.target),p=h.startsWith("/")?h:`${t.state.cwd}/${h}`,m=await t.fs.readFile(p);_o(t.state,0);let g=m.replace(/\n+$/,"");return Bo(g,t.limits.maxStringLength,"command substitution"),g}catch(h){if(h instanceof v)throw h;return _o(t.state,1),""}let i=t.substitutionDepth??0,o=t.limits.maxSubstitutionDepth;if(i>=o)throw new v(`Command substitution nesting limit exceeded (${o})`,"substitution_depth");let a=t.substitutionDepth;t.substitutionDepth=i+1;let l=t.state.bashPid;t.state.bashPid=t.state.nextVirtualPid++;let c=new Map(t.state.env),u=vs(t.state.arrays),f=t.state.cwd,d=t.state.suppressVerbose;t.state.suppressVerbose=!0;try{let h=await t.executeScript(e.body),p=h.exitCode;t.state.env=c,t.state.arrays=u,t.state.cwd=f,t.state.suppressVerbose=d,_o(t.state,p),h.stderr&&(t.state.expansionStderr=(t.state.expansionStderr||"")+h.stderr),t.state.bashPid=l,t.substitutionDepth=a;let m=h.stdout.replace(/\n+$/,"");return Bo(m,t.limits.maxStringLength,"command substitution"),m}catch(h){if(t.state.env=c,t.state.arrays=u,t.state.cwd=f,t.state.bashPid=l,t.substitutionDepth=a,t.state.suppressVerbose=d,h instanceof v)throw h;if(h instanceof Pe){_o(t.state,h.exitCode),h.stderr&&(t.state.expansionStderr=(t.state.expansionStderr||"")+h.stderr);let p=h.stdout.replace(/\n+$/,"");return Bo(p,t.limits.maxStringLength,"command substitution"),p}throw h}}case"ProcessSubstitution":return h$(t,e);case"ArithmeticExpansion":{let s=e.expression.originalText;if(s&&/\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(s)){let o=await uP(t,s),a=new _e,l=it(a,o);return String(await Xe(t,l.expression,!0))}return String(await Xe(t,e.expression.expression,!0))}case"BraceExpansion":{let s=[];for(let i of e.items)if(i.type==="Range"){let o=yS(i.start,i.end,i.step,i.startStr,i.endStr,{maxResults:t.limits.maxBraceExpansionResults,maxStringBytes:t.limits.maxStringLength});if(o.expanded)s.push(...o.expanded);else return o.literal}else s.push(await ot(t,i.word));return s.join(" ")}default:return""}}async function Tm(t,e,n=!1){let{parameter:r}=e,{operation:s}=e,i=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let[,d,h]=i;if(t.state.associativeArrays?.has(d)||h.includes("$(")||h.includes("`")||h.includes("${")){let m=await mS(t,h);r=`${d}[${m}]`}}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&Tt(t,r)){let d=xr(t,r);if(d&&d!==r){let h=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,p,m]=h;if(t.state.associativeArrays?.has(p)||m.includes("$(")||m.includes("`")||m.includes("${")){let y=await mS(t,m);r=`${p}[${y}]`}}}}if(s?.type==="Length"&&/^[a-zA-Z_][a-zA-Z0-9_]*\[[@*]\]$/.test(r))return xS(t,r,"");let o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=await ct(t,r,!o);if(!s)return a;let l=!await Ei(t,r),{isEmpty:c,effectiveValue:u}=CP(t,r,a,n),f={value:a,isUnset:l,isEmpty:c,effectiveValue:u,inDoubleQuotes:n};switch(s.type){case"DefaultValue":return hP(t,s,f,Ys);case"AssignDefault":return pP(t,r,s,f,Ys);case"ErrorIfUnset":return mP(t,r,s,f,Ys);case"UseAlternative":return gP(t,s,f,Ys);case"PatternRemoval":{let d=await yP(t,a,s,Ys,is);return Bo(d,t.limits.maxStringLength,"pattern removal"),d}case"PatternReplacement":{let d=await wP(t,a,s,Ys,is);return Bo(d,t.limits.maxStringLength,"pattern replacement"),d}case"Length":return xS(t,r,a);case"LengthSliceError":throw new lr(r);case"BadSubstitution":throw new lr(s.text);case"Substring":return bP(t,r,a,s);case"CaseModification":{let d=await xP(t,a,s,Ys,Tm);return Bo(d,t.limits.maxStringLength,"case modification"),d}case"Transform":return EP(t,r,a,l,s);case"Indirection":return SP(t,r,a,l,s,Tm,n);case"ArrayKeys":return AP(t,s);case"VarNamePrefix":return vP(t,s);default:return a}}function v$(){return{visited:new Set,depth:0}}function wte(t,e,n){switch(n){case"+":return t+e;case"-":return t-e;case"*":return t*e;case"/":if(e===0)throw new dt("division by 0");return Math.trunc(t/e);case"%":if(e===0)throw new dt("division by 0");return t%e;case"**":if(e<0)throw new dt("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 A$(t,e,n){switch(n){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 bte(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}async function xte(t,e){let n=t.state.env.get(e);if(n!==void 0)return n;let r=bt(t,e,0);return r!==void 0?r:await ct(t,e)}async function Ete(t,e,n){if(!e)return 0;let r=Number.parseInt(e,10);if(!Number.isNaN(r)&&/^-?\d+$/.test(e.trim()))return r;let s=e.trim();if(!s)return 0;let i=new _e,{expr:o,pos:a}=rc(i,s,0);if(a<s.length){let l=s.slice(a).trim(),c=l.split(/\s+/)[0]||l;throw new dt(`syntax error in expression (error token is "${c}")`,"","")}return await lc(t,o,!1,n)}async function Im(t,e,n,r){if(r.depth>100)throw new dt("maximum variable indirection depth exceeded");if(r.visited.has(e))throw new dt(`arithmetic variable cycle detected at ${e}`);r.visited.add(e),r.depth++;try{return await Ete(t,n,r)}finally{r.depth--,r.visited.delete(e)}}async function OS(t,e,n){if(n.depth>100)throw new dt("maximum variable indirection depth exceeded");if(n.visited.has(e))throw new dt(`arithmetic variable cycle detected at ${e}`);n.visited.add(e),n.depth++;try{let r=await xte(t,e);if(!r)return 0;let s=Number.parseInt(r,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(r.trim()))return s;let i=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return await OS(t,i,n);let o=new _e,{expr:a,pos:l}=rc(o,i,0);if(l<i.length){let c=i.slice(l).trim(),u=c.split(/\s+/)[0]||c;throw new dt(`${i}: syntax error in expression (error token is "${u}")`)}return await lc(t,a,!1,n)}finally{n.depth--,n.visited.delete(e)}}async function Rm(t,e){if(e.startsWith("#")){let f=e.slice(1),d=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let p=d[1],m=Me(t,p);return String(m.length)}let h=t.state.env.get(f)||"";return String(h.length)}if(e.startsWith("!")){let f=e.slice(1),d=t.state.env.get(f)||"";return t.state.env.get(d)||""}let n=[":-",":=",":?",":+","-","=","?","+"],r=-1,s="";for(let f of n){let d=e.indexOf(f);d>0&&(r===-1||d<r)&&(r=d,s=f)}if(r===-1)return await ct(t,e);let i=e.slice(0,r),o=e.slice(r+s.length),a=t.state.env.get(i),l=a===void 0,c=a==="",u=s.startsWith(":");switch(s){case":-":case"-":return l||u&&c?o:a||"";case":=":case"=":return l||u&&c?(t.state.env.set(i,o),o):a||"";case":+":case"+":return!(l||u&&c)?o:"";case":?":case"?":{if(l||u&&c)throw new Error(o||`${i}: parameter null or not set`);return a||""}default:return a||""}}async function Xe(t,e,n=!1){return lc(t,e,n,v$())}async function lc(t,e,n,r){let s=(i,o=n)=>lc(t,i,o,r);switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new dt("value too great for base");return e.value;case"ArithVariable":return await OS(t,e.name,r);case"ArithSpecialVar":{let o=(await ct(t,e.name)).trim();if(!o)return 0;let a=Number.parseInt(o,10);if(!Number.isNaN(a)&&/^-?\d+$/.test(o))return a;let l=new _e,{expr:c}=rc(l,o,0);return await s(c)}case"ArithNested":return await s(e.expression);case"ArithCommandSubst":{if(t.execFn){let i=await t.execFn(e.command,{signal:t.state.signal});i.stderr&&(t.state.expansionStderr=(t.state.expansionStderr||"")+i.stderr);let o=i.stdout.trim();return Number.parseInt(o,10)||0}return 0}case"ArithBracedExpansion":{let i=await Rm(t,e.content);return Number.parseInt(i,10)||0}case"ArithDynamicBase":{let i=await Rm(t,e.baseExpr),o=Number.parseInt(i,10);if(o<2||o>64)return 0;let a=`${o}#${e.value}`;return df(a)}case"ArithDynamicNumber":{let o=await Rm(t,e.prefix)+e.suffix;return df(o)}case"ArithArrayElement":{let i=t.state.associativeArrays?.has(e.array),o=async a=>{let l=bt(t,e.array,a);return l!==void 0?await Im(t,`${e.array}[${a}]`,l,r):0};if(e.stringKey!==void 0)return await o(e.stringKey);if(i&&e.index?.type==="ArithVariable"&&!e.index.hasDollarPrefix)return await o(e.index.name);if(i&&e.index?.type==="ArithVariable"&&e.index.hasDollarPrefix){let a=await ct(t,e.index.name);return await o(a)}if(e.index){let a=await s(e.index);if(a<0){let u=Me(t,e.array),f=t.state.currentLine;if(u.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: line ${f}: ${e.array}: bad array subscript
|
|
1533
1533
|
`,0;let h=Math.max(...u.map(([p])=>typeof p=="number"?p:0))+1+a;if(h<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: line ${f}: ${e.array}: bad array subscript
|
|
1534
|
-
`,0;a=h}let l=`${e.array}[${a}]`,c=bt(t,e.array,a);if(c!==void 0)return Im(t,l,c,r);if(a===0){let u=t.state.env.get(e.array);if(u!==void 0)return Im(t,e.array,u,r)}if(t.state.options.nounset&&!(t.state.env.has(e.array)||Vn(t,e.array)))throw new nr(`${e.array}[${a}]`);return 0}return 0}case"ArithDoubleSubscript":throw new dt("double subscript","","");case"ArithNumberSubscript":throw new dt(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithSyntaxError":throw new dt(e.message,"","",!0);case"ArithSingleQuote":{if(n)throw new dt(`syntax error: operand expected (error token is "'${e.content}'")`);return e.value}case"ArithBinary":{if(e.operator==="||")return await s(e.left)||await s(e.right)?1:0;if(e.operator==="&&")return await s(e.left)&&await s(e.right)?1:0;let i=await s(e.left),o=await s(e.right);return wte(i,o,e.operator)}case"ArithUnary":{let i=await s(e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let o=e.operand.name,a=Number.parseInt(await ct(t,o),10)||0,l=e.operator==="++"?a+1:a-1;return t.state.env.set(o,String(l)),e.prefix?l:a}if(e.operand.type==="ArithArrayElement"){let o=e.operand.array,a=t.state.associativeArrays?.has(o),l;if(e.operand.stringKey!==void 0)l=e.operand.stringKey;else if(a&&e.operand.index?.type==="ArithVariable"&&!e.operand.index.hasDollarPrefix)l=e.operand.index.name;else if(a&&e.operand.index?.type==="ArithVariable"&&e.operand.index.hasDollarPrefix)l=await ct(t,e.operand.index.name);else if(e.operand.index){let f=await s(e.operand.index);l=String(f)}else return i;let c=Number.parseInt(bt(t,o,l)||"0",10)||0,u=e.operator==="++"?c+1:c-1;return Fe(t,o,l,String(u),a?"associative":"indexed"),e.prefix?u:c}if(e.operand.type==="ArithConcat"){let o="";for(let a of e.operand.parts)o+=await ac(t,a,n,r);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=Number.parseInt(t.state.env.get(o)||"0",10)||0,l=e.operator==="++"?a+1:a-1;return t.state.env.set(o,String(l)),e.prefix?l:a}}if(e.operand.type==="ArithDynamicElement"){let o="";if(e.operand.nameExpr.type==="ArithConcat")for(let a of e.operand.nameExpr.parts)o+=await ac(t,a,n,r);else e.operand.nameExpr.type==="ArithVariable"&&(o=e.operand.nameExpr.hasDollarPrefix?await ct(t,e.operand.nameExpr.name):e.operand.nameExpr.name);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=await s(e.operand.subscript),l=Number.parseInt(bt(t,o,a)||"0",10)||0,c=e.operator==="++"?l+1:l-1;return Fe(t,o,a,String(c)),e.prefix?c:l}}return i}return bte(i,e.operator)}case"ArithTernary":return await s(e.condition)?await s(e.consequent):await s(e.alternate);case"ArithAssignment":{let i=e.variable,o=i,a;if(e.stringKey!==void 0)a=e.stringKey;else if(e.subscript){let d=t.state.associativeArrays?.has(i);if(d&&e.subscript.type==="ArithVariable"&&!e.subscript.hasDollarPrefix)a=e.subscript.name;else if(d&&e.subscript.type==="ArithVariable"&&e.subscript.hasDollarPrefix)a=await ct(t,e.subscript.name)||"\\";else if(d){let h=await s(e.subscript);a=String(h)}else{let h=await s(e.subscript);if(h<0){let p=Me(t,i);p.length>0&&(h=Math.max(...p.map(([g])=>typeof g=="number"?g:0))+1+h)}a=String(h)}}let l=a===void 0?t.state.env.get(o):bt(t,i,a),c=Number.parseInt(l||"0",10)||0,u=await s(e.value),f=A$(c,u,e.operator);return a===void 0?t.state.env.set(o,String(f)):Fe(t,i,a,String(f),t.state.associativeArrays?.has(i)?"associative":"indexed"),f}case"ArithGroup":return await s(e.expression);case"ArithConcat":{let i="";for(let o of e.parts)i+=await ac(t,o,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?await OS(t,i,r):Number.parseInt(i,10)||0}case"ArithDynamicAssignment":{let i="";if(e.target.type==="ArithConcat")for(let u of e.target.parts)i+=await ac(t,u,n,r);else e.target.type==="ArithVariable"&&(i=e.target.hasDollarPrefix?await ct(t,e.target.name):e.target.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=i;if(e.subscript){let u=await s(e.subscript);o=`${i}_${u}`}let a=Number.parseInt(t.state.env.get(o)||"0",10)||0,l=await s(e.value),c=A$(a,l,e.operator);return t.state.env.set(o,String(c)),c}case"ArithDynamicElement":{let i="";if(e.nameExpr.type==="ArithConcat")for(let c of e.nameExpr.parts)i+=await ac(t,c,n,r);else e.nameExpr.type==="ArithVariable"&&(i=e.nameExpr.hasDollarPrefix?await ct(t,e.nameExpr.name):e.nameExpr.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=await s(e.subscript),a=`${i}_${o}`,l=t.state.env.get(a);return l!==void 0?Im(t,a,l,r):0}default:return 0}}async function ac(t,e,n=!1,r=v$()){switch(e.type){case"ArithNumber":return String(e.value);case"ArithSingleQuote":return String(await lc(t,e,n,r));case"ArithVariable":return e.hasDollarPrefix?await ct(t,e.name):e.name;case"ArithSpecialVar":return await ct(t,e.name);case"ArithBracedExpansion":return await Rm(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command,{signal:t.state.signal})).stdout.trim():"0";case"ArithConcat":{let s="";for(let i of e.parts)s+=await ac(t,i,n,r);return s}default:return String(await lc(t,e,n,r))}}Qt();X();async function C$(t,e){let n="",r=0;for(let E of e.parts){let A=E.type==="Literal"?E.value:"\0",N=j(A);if(N>t.limits.maxStringLength-r)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");n+=A,r+=N}let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\+?=)\(/);if(!s||!n.endsWith(")"))return null;let i=s[1],o=s[2],a=[],l=[],c=!1,u="",f=0,d=0,h=!1,p=!0,m=E=>{let A=j(E);if(A>t.limits.maxStringLength-d-f)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");u+=E,f+=A},g=(E,A=!1)=>{if(a.length>=t.limits.maxArrayElements)throw new v(`array assignment element limit exceeded (${t.limits.maxArrayElements})`,"array_elements");let N=j(E);if(N>t.limits.maxStringLength-d)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");a.push(E),l.push(A),d+=N},y=()=>{g(u,p),u="",f=0,h=!1,p=!0};for(let E of e.parts)if(E.type==="Literal"){let A=E.value;if(!c){let N=A.indexOf("=(");N!==-1&&(c=!0,A=A.slice(N+2))}if(c){A.endsWith(")")&&(A=A.slice(0,-1));for(let N of A)/\s/.test(N)?(u||h)&&y():m(N)}}else if(c)if(E.type==="BraceExpansion")if(/^\[.+\]=/.test(u))m(tc({type:"Word",parts:[E]}));else{(u||h)&&y();let N=await Qs(t,{type:"Word",parts:[E]});for(let I of N.values)g(I)}else{(E.type==="SingleQuoted"||E.type==="DoubleQuoted"||E.type==="Escaped")&&(h=!0),p=!1;let A=await ot(t,{type:"Word",parts:[E]});m(A)}(u||h)&&y();let w=a.splice(0),b=l.splice(0);d=0;for(let E=0;E<w.length;E++){let A=w[E];if(!b[E]){g(A);continue}let N=A.match(/^(\[[^\]]+\]=)(.*)$/s);if(N){let I=Mo(t,N[2]);A=N[1]+I}if(A.includes("{")&&A.includes("}")){let I=new _e().parseWordFromString(A,!1,!1);if(I.parts.some(T=>T.type==="BraceExpansion")){let T=await Qs(t,I);for(let $ of T.values)g($);continue}}g(A)}let x=[`${i}${o}(`],S=j(x[0]);for(let E=0;E<a.length;E++){let A=a[E],N,I=A.match(/^(\[[^\]]+\]=)(.*)$/s);if(I){let C=I[2].replace(/\\/g,"\\\\").replace(/"/g,'\\"');N=`${I[1]}"${C}"`}else A===""?N="''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(A)&&!A.startsWith("'")&&!A.startsWith('"')?N=`'${A.replace(/'/g,"'\\''")}'`:N=A;let T=`${E>0?" ":""}${N}`,$=j(T);if($+1>t.limits.maxStringLength-S)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");x.push(T),S+=$}return x.push(")"),x.join("")}async function k$(t,e){let n=-1,r=-1,s=!1;for(let m=0;m<e.parts.length;m++){let g=e.parts[m];if(g.type==="Literal"){let y=g.value.indexOf("+=");if(y!==-1){let b=g.value.slice(0,y);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){n=m,r=y,s=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){n=m,r=y,s=!0;break}}let w=g.value.indexOf("=");if(w!==-1&&(w===0||g.value[w-1]!=="+")){let b=g.value.slice(0,w);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){n=m,r=w;break}}}}if(n===-1)return null;let i=e.parts.slice(0,n),o=e.parts[n];if(o.type!=="Literal")return null;let a=s?2:1,l=o.value.slice(0,r),c=o.value.slice(r+a),u=e.parts.slice(n+1),f="";for(let m of i)f+=await ot(t,{type:"Word",parts:[m]});f+=l;let d={type:"Word",parts:c!==""?[{type:"Literal",value:c},...u]:u},h=d.parts.length>0?await ot(t,d):"";return`${f}${s?"+=":"="}${h}`}var Ste=["tar","yq","xan","sqlite3","python3","python"];function N$(t){return Ste.includes(t)}pe();Kt();Tn();Zr();cn();co();Os();Rl();X();X();var
|
|
1534
|
+
`,0;a=h}let l=`${e.array}[${a}]`,c=bt(t,e.array,a);if(c!==void 0)return Im(t,l,c,r);if(a===0){let u=t.state.env.get(e.array);if(u!==void 0)return Im(t,e.array,u,r)}if(t.state.options.nounset&&!(t.state.env.has(e.array)||Vn(t,e.array)))throw new nr(`${e.array}[${a}]`);return 0}return 0}case"ArithDoubleSubscript":throw new dt("double subscript","","");case"ArithNumberSubscript":throw new dt(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithSyntaxError":throw new dt(e.message,"","",!0);case"ArithSingleQuote":{if(n)throw new dt(`syntax error: operand expected (error token is "'${e.content}'")`);return e.value}case"ArithBinary":{if(e.operator==="||")return await s(e.left)||await s(e.right)?1:0;if(e.operator==="&&")return await s(e.left)&&await s(e.right)?1:0;let i=await s(e.left),o=await s(e.right);return wte(i,o,e.operator)}case"ArithUnary":{let i=await s(e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let o=e.operand.name,a=Number.parseInt(await ct(t,o),10)||0,l=e.operator==="++"?a+1:a-1;return t.state.env.set(o,String(l)),e.prefix?l:a}if(e.operand.type==="ArithArrayElement"){let o=e.operand.array,a=t.state.associativeArrays?.has(o),l;if(e.operand.stringKey!==void 0)l=e.operand.stringKey;else if(a&&e.operand.index?.type==="ArithVariable"&&!e.operand.index.hasDollarPrefix)l=e.operand.index.name;else if(a&&e.operand.index?.type==="ArithVariable"&&e.operand.index.hasDollarPrefix)l=await ct(t,e.operand.index.name);else if(e.operand.index){let f=await s(e.operand.index);l=String(f)}else return i;let c=Number.parseInt(bt(t,o,l)||"0",10)||0,u=e.operator==="++"?c+1:c-1;return Fe(t,o,l,String(u),a?"associative":"indexed"),e.prefix?u:c}if(e.operand.type==="ArithConcat"){let o="";for(let a of e.operand.parts)o+=await ac(t,a,n,r);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=Number.parseInt(t.state.env.get(o)||"0",10)||0,l=e.operator==="++"?a+1:a-1;return t.state.env.set(o,String(l)),e.prefix?l:a}}if(e.operand.type==="ArithDynamicElement"){let o="";if(e.operand.nameExpr.type==="ArithConcat")for(let a of e.operand.nameExpr.parts)o+=await ac(t,a,n,r);else e.operand.nameExpr.type==="ArithVariable"&&(o=e.operand.nameExpr.hasDollarPrefix?await ct(t,e.operand.nameExpr.name):e.operand.nameExpr.name);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=await s(e.operand.subscript),l=Number.parseInt(bt(t,o,a)||"0",10)||0,c=e.operator==="++"?l+1:l-1;return Fe(t,o,a,String(c)),e.prefix?c:l}}return i}return bte(i,e.operator)}case"ArithTernary":return await s(e.condition)?await s(e.consequent):await s(e.alternate);case"ArithAssignment":{let i=e.variable,o=i,a;if(e.stringKey!==void 0)a=e.stringKey;else if(e.subscript){let d=t.state.associativeArrays?.has(i);if(d&&e.subscript.type==="ArithVariable"&&!e.subscript.hasDollarPrefix)a=e.subscript.name;else if(d&&e.subscript.type==="ArithVariable"&&e.subscript.hasDollarPrefix)a=await ct(t,e.subscript.name)||"\\";else if(d){let h=await s(e.subscript);a=String(h)}else{let h=await s(e.subscript);if(h<0){let p=Me(t,i);p.length>0&&(h=Math.max(...p.map(([g])=>typeof g=="number"?g:0))+1+h)}a=String(h)}}let l=a===void 0?t.state.env.get(o):bt(t,i,a),c=Number.parseInt(l||"0",10)||0,u=await s(e.value),f=A$(c,u,e.operator);return a===void 0?t.state.env.set(o,String(f)):Fe(t,i,a,String(f),t.state.associativeArrays?.has(i)?"associative":"indexed"),f}case"ArithGroup":return await s(e.expression);case"ArithConcat":{let i="";for(let o of e.parts)i+=await ac(t,o,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?await OS(t,i,r):Number.parseInt(i,10)||0}case"ArithDynamicAssignment":{let i="";if(e.target.type==="ArithConcat")for(let u of e.target.parts)i+=await ac(t,u,n,r);else e.target.type==="ArithVariable"&&(i=e.target.hasDollarPrefix?await ct(t,e.target.name):e.target.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=i;if(e.subscript){let u=await s(e.subscript);o=`${i}_${u}`}let a=Number.parseInt(t.state.env.get(o)||"0",10)||0,l=await s(e.value),c=A$(a,l,e.operator);return t.state.env.set(o,String(c)),c}case"ArithDynamicElement":{let i="";if(e.nameExpr.type==="ArithConcat")for(let c of e.nameExpr.parts)i+=await ac(t,c,n,r);else e.nameExpr.type==="ArithVariable"&&(i=e.nameExpr.hasDollarPrefix?await ct(t,e.nameExpr.name):e.nameExpr.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=await s(e.subscript),a=`${i}_${o}`,l=t.state.env.get(a);return l!==void 0?Im(t,a,l,r):0}default:return 0}}async function ac(t,e,n=!1,r=v$()){switch(e.type){case"ArithNumber":return String(e.value);case"ArithSingleQuote":return String(await lc(t,e,n,r));case"ArithVariable":return e.hasDollarPrefix?await ct(t,e.name):e.name;case"ArithSpecialVar":return await ct(t,e.name);case"ArithBracedExpansion":return await Rm(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command,{signal:t.state.signal})).stdout.trim():"0";case"ArithConcat":{let s="";for(let i of e.parts)s+=await ac(t,i,n,r);return s}default:return String(await lc(t,e,n,r))}}Qt();X();async function C$(t,e){let n="",r=0;for(let E of e.parts){let A=E.type==="Literal"?E.value:"\0",N=j(A);if(N>t.limits.maxStringLength-r)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");n+=A,r+=N}let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\+?=)\(/);if(!s||!n.endsWith(")"))return null;let i=s[1],o=s[2],a=[],l=[],c=!1,u="",f=0,d=0,h=!1,p=!0,m=E=>{let A=j(E);if(A>t.limits.maxStringLength-d-f)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");u+=E,f+=A},g=(E,A=!1)=>{if(a.length>=t.limits.maxArrayElements)throw new v(`array assignment element limit exceeded (${t.limits.maxArrayElements})`,"array_elements");let N=j(E);if(N>t.limits.maxStringLength-d)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");a.push(E),l.push(A),d+=N},y=()=>{g(u,p),u="",f=0,h=!1,p=!0};for(let E of e.parts)if(E.type==="Literal"){let A=E.value;if(!c){let N=A.indexOf("=(");N!==-1&&(c=!0,A=A.slice(N+2))}if(c){A.endsWith(")")&&(A=A.slice(0,-1));for(let N of A)/\s/.test(N)?(u||h)&&y():m(N)}}else if(c)if(E.type==="BraceExpansion")if(/^\[.+\]=/.test(u))m(tc({type:"Word",parts:[E]}));else{(u||h)&&y();let N=await Qs(t,{type:"Word",parts:[E]});for(let I of N.values)g(I)}else{(E.type==="SingleQuoted"||E.type==="DoubleQuoted"||E.type==="Escaped")&&(h=!0),p=!1;let A=await ot(t,{type:"Word",parts:[E]});m(A)}(u||h)&&y();let w=a.splice(0),b=l.splice(0);d=0;for(let E=0;E<w.length;E++){let A=w[E];if(!b[E]){g(A);continue}let N=A.match(/^(\[[^\]]+\]=)(.*)$/s);if(N){let I=Mo(t,N[2]);A=N[1]+I}if(A.includes("{")&&A.includes("}")){let I=new _e().parseWordFromString(A,!1,!1);if(I.parts.some(T=>T.type==="BraceExpansion")){let T=await Qs(t,I);for(let $ of T.values)g($);continue}}g(A)}let x=[`${i}${o}(`],S=j(x[0]);for(let E=0;E<a.length;E++){let A=a[E],N,I=A.match(/^(\[[^\]]+\]=)(.*)$/s);if(I){let C=I[2].replace(/\\/g,"\\\\").replace(/"/g,'\\"');N=`${I[1]}"${C}"`}else A===""?N="''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(A)&&!A.startsWith("'")&&!A.startsWith('"')?N=`'${A.replace(/'/g,"'\\''")}'`:N=A;let T=`${E>0?" ":""}${N}`,$=j(T);if($+1>t.limits.maxStringLength-S)throw new v(`array assignment string limit exceeded (${t.limits.maxStringLength} bytes)`,"string_length");x.push(T),S+=$}return x.push(")"),x.join("")}async function k$(t,e){let n=-1,r=-1,s=!1;for(let m=0;m<e.parts.length;m++){let g=e.parts[m];if(g.type==="Literal"){let y=g.value.indexOf("+=");if(y!==-1){let b=g.value.slice(0,y);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){n=m,r=y,s=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){n=m,r=y,s=!0;break}}let w=g.value.indexOf("=");if(w!==-1&&(w===0||g.value[w-1]!=="+")){let b=g.value.slice(0,w);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){n=m,r=w;break}}}}if(n===-1)return null;let i=e.parts.slice(0,n),o=e.parts[n];if(o.type!=="Literal")return null;let a=s?2:1,l=o.value.slice(0,r),c=o.value.slice(r+a),u=e.parts.slice(n+1),f="";for(let m of i)f+=await ot(t,{type:"Word",parts:[m]});f+=l;let d={type:"Word",parts:c!==""?[{type:"Literal",value:c},...u]:u},h=d.parts.length>0?await ot(t,d):"";return`${f}${s?"+=":"="}${h}`}var Ste=["tar","yq","xan","sqlite3","python3","python"];function N$(t){return Ste.includes(t)}pe();Kt();Tn();Zr();cn();co();Os();Rl();X();X();var tt=Object.freeze({stdout:"",stderr:"",exitCode:0,internalStdinConsumed:0});function Je(t=""){return{stdout:t,stderr:"",exitCode:0}}function J(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function ee(t,e,n){return{stdout:t,stderr:e,exitCode:n}}function pn(t){return{stdout:"",stderr:"",exitCode:t?0:1,internalStdinConsumed:0}}function zo(t,e,n="",r=""){throw new v(t,e,n,r)}function T$(t){let e=t.state.fileDescriptors;if(e&&e.size>=t.limits.maxFileDescriptors)throw new v(`too many open file descriptors (max ${t.limits.maxFileDescriptors})`,"file_descriptors")}function IS(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new si;return tt}if(e.length>1)throw new Pe(1,"",`bash: break: too many arguments
|
|
1535
1535
|
`);let n=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)throw new Pe(128,"",`bash: break: ${e[0]}: numeric argument required
|
|
1536
1536
|
`);n=r}throw new Jn(n)}async function RS(t,e){let n,r=!1,s=!1,i=0;for(;i<e.length;)if(e[i]==="--"){i++;break}else if(e[i]==="-L")s=!1,i++;else if(e[i]==="-P")s=!0,i++;else if(e[i].startsWith("-")&&e[i]!=="-")i++;else break;let o=e.slice(i);if(o.length===0||o[0]==="~"?n=t.state.env.get("HOME")||"/":o[0]==="-"?(n=t.state.previousDir,r=!0):n=o[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let f=t.state.env.get("CDPATH");if(f){let d=f.split(":").filter(h=>h);for(let h of d){let p=h.startsWith("/")?`${h}/${n}`:`${t.state.cwd}/${h}/${n}`;try{if((await t.fs.stat(p)).isDirectory){n=p,r=!0;break}}catch{}}}}let l=(n.startsWith("/")?n:`${t.state.cwd}/${n}`).split("/").filter(f=>f&&f!=="."),c="";for(let f of l)if(f==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await t.fs.stat(c)).isDirectory)return J(`bash: cd: ${n}: Not a directory
|
|
1537
1537
|
`)}catch{return J(`bash: cd: ${n}: No such file or directory
|
|
@@ -1572,7 +1572,7 @@ ${t.terminator}`}function Aee(t){return`(${Cs(t.body)})${Gs(t.redirections)}`}fu
|
|
|
1572
1572
|
`,1),w)}}else if(b.operator==="<>"){let A=await KS(t,S,!0);if(A.error)return h(A.error,w);let N=A.entry;m(x,N),x===0&&N.kind==="readwrite"&&(c=N.content,u=-1)}}return d()}function hc(t,e,n){let r={numericSnapshot:new Map,fdVariableSnapshot:new Map,standardSnapshot:new Map,standardClosedSnapshot:new Map,fdVariableEnv:new Map,nextFd:t.state.nextFd,policy:n},s=!1;return{prepare:(i="")=>qte(t,e,i,r),finish:()=>{if(!s){if(s=!0,n!=="persistent"&&Xm(t,r.numericSnapshot),n!=="persistent"){Xm(t,r.standardSnapshot);for(let[i,o]of r.standardClosedSnapshot)o?(t.state.closedStandardFds??=new Set,t.state.closedStandardFds.add(i)):t.state.closedStandardFds?.delete(i)}if(n==="bare"){Xm(t,r.fdVariableSnapshot);for(let[i,o]of r.fdVariableEnv)o===void 0?t.state.env.delete(i):t.state.env.set(i,o);t.state.nextFd=r.nextFd}}}}}function pc(t){if(!t.error)throw new Error("Expected a redirection error");if(t.errorCause)throw t.errorCause.stdout=t.error.stdout,t.errorCause.stderr=t.error.stderr,t.errorCause;return t.error}async function ZS(t,e,n,r){let s=e instanceof Pe||e instanceof Nn||e instanceof tr?e.exitCode:e instanceof v?v.EXIT_CODE:0,i=await Ho(t,ee(e.stdout,e.stderr,s),n,r.targets,r.dupSources,r.standardRoutes);e.stdout=i.stdout,e.stderr=i.stderr,e.internalOutputAccounting=i.internalOutputAccounting??{stdout:j(i.stdout),stderr:j(i.stderr)}}async function as(t,e,n,r){let s=hc(t,e,xf),i;try{if(i=await s.prepare(n),i.error)return pc(i);let o=t.state.groupStdin,a=t.state.groupStdinSourceFd;i.stdin!==void 0&&(t.state.groupStdin=i.stdin,t.state.groupStdinSourceFd=i.stdinSourceFd);try{let l=await r(i);return await Ho(t,l,e,i.targets,i.dupSources,i.standardRoutes)}finally{i.stdin!==void 0&&(t.state.groupStdin=o,t.state.groupStdinSourceFd=a)}}catch(o){throw!(o instanceof Bt)||!i||await ZS(t,o,e,i),o}finally{s.finish()}}async function Ho(t,e,n,r,s=new Map,i=new Map,o="bash",a=!1){n.length>0&&(e=t.executionScope.accountResult(e,"redirection"));let{stdout:l,stderr:c,exitCode:u}=e,d=e.stdoutKind==="bytes"||e.stdoutKind===void 0&&e.stdoutEncoding==="binary"?"binary":"utf8",h=x=>d,p={kind:"live-stdout"},m={kind:"live-stderr"},g=x=>{if(!x)return null;if(x.kind==="entry"){if(x.entry.kind==="dup-out"){if(x.entry.sourceFd===1)return{kind:"live-stdout"};if(x.entry.sourceFd===2)return{kind:"live-stderr"}}return x.entry.kind==="output"||x.entry.kind==="readwrite"?{kind:"descriptor",source:x}:null}return x.fd===1?p:x.fd===2?m:null},y=x=>{let S=i.get(x)??os(t,x);return S?S.kind==="closed"?{kind:"invalid-output",fd:x}:S.kind==="input"||S.kind==="dup-in"?{kind:"invalid-output",fd:x}:S.kind==="dup-out"?S.sourceFd===1?{kind:"live-stdout"}:S.sourceFd===2?{kind:"live-stderr"}:null:S.kind==="output"||S.kind==="readwrite"?{kind:"descriptor",source:{kind:"entry",entry:S,descriptors:jo(t,x)}}:null:null};p=y(1)??p,m=y(2)??m;for(let x=0;x<n.length;x++){let S=n[x];if(S.target.type==="HereDoc"||S.fdVariable)continue;let E=r.get(x);if(E!==void 0)switch(S.operator){case">":case">|":case">>":{let A=S.fd??1;if(A!==1&&A!==2)break;let N=S.operator===">>";if(E==="/dev/stdout"){A===2&&(m=p);break}if(E==="/dev/stderr"){A===1&&(p=m);break}if(E==="/dev/full"){c+=`bash: echo: write error: No space left on device
|
|
1573
1573
|
`,u=1,A===1&&(l="");break}if(E==="/dev/null"&&A===2){m={kind:"discard"};break}let I=t.fs.resolvePath(t.state.cwd,E);A===1?p={kind:"file",path:I,append:N}:m={kind:"file",path:I,append:N};break}case">&":case"<&":{let A=S.fd??(S.operator==="<&"?0:1);if(A>=mn||A===0)break;if(E==="-"){A===1?p={kind:"discard"}:m={kind:"discard"};break}let N=g(s.get(x));if(!N)break;S.fd==null&&Ym(E)===null?(p=N,m=N):A===1?p=N:A===2&&(m=N);break}case"&>":{p={kind:"file",path:t.fs.resolvePath(t.state.cwd,E),append:!1},m=p;break}case"&>>":{p={kind:"file",path:t.fs.resolvePath(t.state.cwd,E),append:!0},m=p;break}}}if(l!==""||c!==""){let x=l,S=c;l="",c="",p.kind==="invalid-output"&&x!==""&&(x="",S+=`${a?"":"bash: "}${o}: write error: Bad file descriptor
|
|
1574
1574
|
`,u=1),m.kind==="invalid-output"&&(S="");let E=async(A,N,I)=>{A.append?await t.fs.appendFile(A.path,N,I):await t.fs.writeFile(A.path,N,I)};if(p===m&&(p.kind==="file"||p.kind==="descriptor")){let A=x+S;A!==""&&(p.kind==="file"?await E(p,A,h(A)):await HS(t,p.source.entry,p.source.descriptors,A,h(A)))}else for(let[A,N,I]of[[x,p,!0],[S,m,!1]])if(A!=="")switch(N.kind){case"live-stdout":l+=A;break;case"live-stderr":c+=A;break;case"file":await E(N,A,I?h(A):q$(A));break;case"descriptor":await HS(t,N.source.entry,N.source.descriptors,A,I?h(A):q$(A));break;case"invalid-output":break;case"discard":break}}let w=ee(l,c,u);if(e.stdoutKind&&(w.stdoutKind=e.stdoutKind),e.stdoutEncoding==="binary"&&(w.stdoutEncoding="binary"),e.internalPipeStatusOverride&&(w.internalPipeStatusOverride=e.internalPipeStatusOverride),n.length>0||t.state.fileDescriptors?.has(1)===!0||t.state.fileDescriptors?.has(2)===!0){let x=(e.internalOutputAccounting?.stdout??0)+(e.internalOutputAccounting?.stderr??0),S=j(w.stdout),E=j(w.stderr),A=Math.min(S,x);w.internalOutputAccounting={stdout:A,stderr:Math.min(E,x-A)},t.executionScope.accountResult(w,"redirection")}else e.internalOutputAccounting&&(w.internalOutputAccounting=e.internalOutputAccounting);return w}function K$(t,e){if(t.state.options.posix&&cf.has(e.name)){let r=`bash: line ${t.state.currentLine}: \`${e.name}': is a special builtin
|
|
1575
|
-
`;throw new Pe(2,"",r)}let n={...e,sourceFile:e.sourceFile??t.state.currentSource??"main"};return t.state.functions.set(e.name,n),
|
|
1575
|
+
`;throw new Pe(2,"",r)}let n={...e,sourceFile:e.sourceFile??t.state.currentSource??"main"};return t.state.functions.set(e.name,n),tt}async function Qm(t,e,n,r="",s,i=!1){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,zo(`${e.name}: maximum recursion depth (${t.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),t.state.funcNameStack||(t.state.funcNameStack=[]),t.state.callLineStack||(t.state.callLineStack=[]),t.state.sourceStack||(t.state.sourceStack=[]),t.state.funcNameStack.unshift(e.name),t.state.callLineStack.unshift(s??t.state.currentLine),t.state.sourceStack.unshift(e.sourceFile??"main"),t.state.localScopes.push(new Map),t.state.localArrayScopes??=[],t.state.localArrayScopes.push(new Map),t.state.localExportedVars||(t.state.localExportedVars=[]),t.state.localExportedVars.push(new Set);let o=new Map,a=Number.parseInt(t.state.env.get("#")??"0",10),l=Math.max(n.length,a);for(let h=0;h<l;h++){let p=String(h+1);o.set(p,t.state.env.get(p)),h<n.length?t.state.env.set(p,n[h]):t.state.env.delete(p)}o.set("@",t.state.env.get("@")),o.set("#",t.state.env.get("#")),t.state.env.set("@",n.join(" ")),t.state.env.set("#",String(n.length));let c=!1,u=()=>{if(c)return;c=!0;let h=t.state.localScopes.length-1,p=t.state.localScopes.pop(),m=t.state.localArrayScopes?.pop();if(p)for(let[g,y]of p)y===void 0?t.state.env.delete(g):t.state.env.set(g,y);if(m){t.state.arrays??=new Map;for(let[g,y]of m)y===void 0?(t.state.arrays.delete(g),t.state.associativeArrays?.delete(g)):(t.state.arrays.set(g,br(y)),t.state.associativeArrays??=new Set,y.kind==="associative"?t.state.associativeArrays.add(g):t.state.associativeArrays.delete(g))}if(z$(t,h),t.state.fullyUnsetLocals)for(let[g,y]of t.state.fullyUnsetLocals.entries())y===h&&t.state.fullyUnsetLocals.delete(g);if(t.state.localExportedVars&&t.state.localExportedVars.length>0){let g=t.state.localExportedVars.pop();if(g)for(let y of g)t.state.exportedVars?.delete(y)}for(let[g,y]of o)y===void 0?t.state.env.delete(g):t.state.env.set(g,y);t.state.funcNameStack?.shift(),t.state.callLineStack?.shift(),t.state.sourceStack?.shift(),t.state.callDepth--},f=null,d=hc(t,e.redirections,xf);try{if(f=await d.prepare(r),f.error)return pc(f);let h=f.stdin??r,p=i||f.stdin!==void 0||r!=="",m=await t.executeCommand(e.body,h,p);return Ho(t,m,e.redirections,f.targets,f.dupSources,f.standardRoutes)}catch(h){if(h instanceof Bt&&f&&(await ZS(t,h,e.redirections,f),h instanceof Nn))return ee(h.stdout,h.stderr,h.exitCode);throw h}finally{d.finish(),u()}}Qt();X();function Ci(t,e,n,r){let s=n+j(e)+1;if(s>r)throw new v(`shopt: output size limit exceeded (${r} bytes)`,"output_size");return t.push(e),s}var e1=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],Z$=["autocd","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","execfail","extdebug","extquote","force_fignore","globasciiranges","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath"],X$=[...e1,...Z$];function Jm(t){return e1.includes(t)}function Vte(t){return Z$.includes(t)}function Y$(t,e){let n=t.limits.maxArrayElements;if(e.length>n)throw new v(`shopt: argument limit exceeded (${n})`,"array_elements");let r=Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),s=!1,i=!1,o=!1,a=!1,l=!1,c=[],u=0;for(;u<e.length;){let g=e[u];if(g==="--"){u++;break}if(g.startsWith("-")&&g.length>1){for(let y=1;y<g.length;y++){let w=g[y];switch(w){case"s":s=!0;break;case"u":i=!0;break;case"p":o=!0;break;case"q":a=!0;break;case"o":l=!0;break;default:return{exitCode:2,stdout:"",stderr:`shopt: -${w}: invalid option
|
|
1576
1576
|
`}}}u++}else break}for(;u<e.length;)c.push(e[u]),u++;if(l)return Hte(t,c,s,i,o,a);if(s&&i)return{exitCode:1,stdout:"",stderr:`shopt: cannot set and unset shell options simultaneously
|
|
1577
1577
|
`};if(c.length===0){if(s||i){let y=[];for(let w of e1){let b=t.state.shoptOptions[w];s&&b?y.push(o?`shopt -s ${w}`:`${w} on`):i&&!b&&y.push(o?`shopt -u ${w}`:`${w} off`)}return{exitCode:0,stdout:y.length>0?`${y.join(`
|
|
1578
1578
|
`)}
|
|
@@ -1625,7 +1625,7 @@ ${t.terminator}`}function Aee(t){return`(${Cs(t.body)})${Gs(t.redirections)}`}fu
|
|
|
1625
1625
|
`,2);s.push(c)}else if(l==="+o"){if(a++,a>=e.length)return J(`compopt: +o: option requires an argument
|
|
1626
1626
|
`,2);let c=e[a];if(!rL.includes(c))return J(`compopt: ${c}: invalid option name
|
|
1627
1627
|
`,2);i.push(c)}else if(l==="--"){o.push(...e.slice(a+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&o.push(l)}if(n){let a=t.state.defaultCompletionSpec??{isDefault:!0},l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,t.state.defaultCompletionSpec=a,Je("")}if(r){let a=t.state.emptyCompletionSpec??Object.create(null),l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,t.state.emptyCompletionSpec=a,Je("")}if(o.length>0){for(let a of o){let l=t.state.completionSpecs.get(a)??{},c=new Set(l.options??[]);for(let u of s)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,t.state.completionSpecs.set(a,l)}return Je("")}return J(`compopt: not currently executing completion function
|
|
1628
|
-
`,1)}X();function s7(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new si;return
|
|
1628
|
+
`,1)}X();function s7(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new si;return tt}if(e.length>1)throw new Pe(1,"",`bash: continue: too many arguments
|
|
1629
1629
|
`);let n=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)throw new Pe(1,"",`bash: continue: ${e[0]}: numeric argument required
|
|
1630
1630
|
`);n=r}throw new er(n)}Nt();function sL(t,e){let n="";return t.state.integerVars?.has(e)&&(n+="i"),t.state.lowercaseVars?.has(e)&&(n+="l"),Tt(t,e)&&(n+="n"),t.state.readonlyVars?.has(e)&&(n+="r"),t.state.uppercaseVars?.has(e)&&(n+="u"),t.state.exportedVars?.has(e)&&(n+="x"),n===""?"--":`-${n}`}function i7(t){return gn(t)}function o7(t){return`'${t.replace(/'/g,"'\\''")}'`}function iL(t,e){let n="",r="",s=!1;for(let i of e){let o=sL(t,i);if(t.state.associativeArrays?.has(i)){let u=xi(t,i);if(u.length===0)n+=`declare -A ${i}=()
|
|
1631
1631
|
`;else{let f=u.map(d=>{let h=bt(t,i,d)??"",p=i7(h);return`[${o7(d)}]=${p}`});n+=`declare -A ${i}=(${f.join(" ")})
|
|
@@ -1654,12 +1654,12 @@ ${t.terminator}`}function Aee(t){return`(${Cs(t.body)})${Gs(t.redirections)}`}fu
|
|
|
1654
1654
|
}
|
|
1655
1655
|
`;return Je($)}let T=!0;for(let $ of w)t.state.functions.has($)||(T=!1);return ee("","",T?0:1)}if(a&&w.length>0)return iL(t,w);if(a&&w.length===0)return oL(t,{filterExport:o,filterReadonly:i,filterNameref:l,filterIndexedArray:r,filterAssocArray:s});if(w.length===0&&s&&!a)return aL(t);if(w.length===0&&r&&!a)return lL(t);if(w.length===0&&!a)return cL(t);let N="",I=0;for(let T of w){let $=T.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if($&&!u){let R=$[1],_=$[2],U=Rt(t,R);if(U)return U;if(s&&Cn(t,R).length>0){N+=`bash: declare: ${R}: cannot convert indexed to associative array
|
|
1656
1656
|
`,I=1;continue}if((r||!s&&!r)&&t.state.associativeArrays?.has(R)){N+=`bash: declare: ${R}: cannot convert associative to indexed array
|
|
1657
|
-
`,I=1;continue}let B=s&&_.includes("[")?jm(_,n):void 0,W=B===void 0?Zi(_,{...n,maxElements:s?n.maxElements*2:n.maxElements}):void 0;if(t.executionScope.consumeWork(B?.length??W?.length??0,"declare array assignment"),E(R),s?(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(R),Oo(t,R,"associative")):Oo(t,R,"indexed"),an(t,R),t.state.env.delete(R),s&&_.includes("["))for(let[M,Y]of B??[])Fe(t,R,M,Mo(t,Y),"associative");else if(s){let M=W??[];for(let Y=0;Y<M.length;Y+=2){let q=M[Y],H=Y+1<M.length?M[Y+1]:"";Fe(t,R,q,H,"associative")}}else{let M=W??[];if(M.some(q=>/^\[[^\]]+\]=/.test(q))){let q=0;for(let H of M){let re=H.match(/^\[([^\]]+)\]=(.*)$/);if(re){let se=re[1],de=re[2],
|
|
1657
|
+
`,I=1;continue}let B=s&&_.includes("[")?jm(_,n):void 0,W=B===void 0?Zi(_,{...n,maxElements:s?n.maxElements*2:n.maxElements}):void 0;if(t.executionScope.consumeWork(B?.length??W?.length??0,"declare array assignment"),E(R),s?(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(R),Oo(t,R,"associative")):Oo(t,R,"indexed"),an(t,R),t.state.env.delete(R),s&&_.includes("["))for(let[M,Y]of B??[])Fe(t,R,M,Mo(t,Y),"associative");else if(s){let M=W??[];for(let Y=0;Y<M.length;Y+=2){let q=M[Y],H=Y+1<M.length?M[Y+1]:"";Fe(t,R,q,H,"associative")}}else{let M=W??[];if(M.some(q=>/^\[[^\]]+\]=/.test(q))){let q=0;for(let H of M){let re=H.match(/^\[([^\]]+)\]=(.*)$/);if(re){let se=re[1],de=re[2],Ie;if(/^-?\d+$/.test(se))Ie=Number.parseInt(se,10);else try{let oe=new _e,Se=it(oe,se);Ie=await Xe(t,Se.expression)}catch{Ie=0}Fe(t,R,Ie,Mo(t,de)),q=Ie+1}else Fe(t,R,q,H),q++}}else for(let q=0;q<M.length;q++)Fe(t,R,q,M[q])}A(R),i&&Vr(t,R),o&&Xs(t,R);continue}if(c){let R=T.includes("=")?T.slice(0,T.indexOf("=")):T;if(oP(t,R),!T.includes("="))continue}if(f){let R=T.includes("=")?T.slice(0,T.indexOf("=")):T;if(Em(t,R),!T.includes("="))continue}let C=dne(T);if(C){let{name:R,indexExpr:_,value:U}=C,B=Rt(t,R);if(B)return B;E(R);let W;try{let M=new _e,Y=it(M,_);W=await Xe(t,Y.expression)}catch{let M=parseInt(_,10);W=Number.isNaN(M)?0:M}Fe(t,R,W,U),A(R),i&&Vr(t,R),o&&Xs(t,R);continue}let O=T.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(O&&!u){let R=O[1],_=O[2],U=Rt(t,R);if(U)return U;E(R);let B=Zi(_,n);if(t.state.associativeArrays?.has(R)){let W=jm(_,n);t.executionScope.consumeWork(W.length,"declare array append"),Da(t,R,W.map(([M])=>M));for(let[M,Y]of W)Fe(t,R,M,Y,"associative")}else{t.executionScope.consumeWork(B.length,"declare array append");let W=Cn(t,R),M=0,Y=t.state.env.get(R);W.length===0&&Y!==void 0?(Fe(t,R,0,Y),t.state.env.delete(R),M=1):W.length>0&&(M=Math.max(...W)+1),Da(t,R,Array.from({length:B.length},(q,H)=>M+H));for(let q=0;q<B.length;q++)Fe(t,R,M+q,B[q])}A(R),i&&Vr(t,R),o&&Xs(t,R);continue}let F=T.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(F){let R=F[1],_=F[2],U=Rt(t,R);if(U)return U;S(R),d&&a7(t,R),h&&l7(t,R),p&&c7(t,R);let W=Cn(t,R).length>0||t.state.associativeArrays?.has(R);if(Af(t,R)){let M=t.state.env.get(R)??"0",Y=parseInt(M,10)||0,q=parseInt(await uL(t,_),10)||0;_=String(Y+q),t.state.env.set(R,_)}else if(W){_=gc(t,R,_);let M=bt(t,R,0)??"";Fe(t,R,0,cr([M,_],"",t.limits.maxStringLength,"declare append"))}else{_=gc(t,R,_);let M=t.state.env.get(R)??"";t.state.env.set(R,cr([M,_],"",t.limits.maxStringLength,"declare append"))}A(R),i&&Vr(t,R),o&&Xs(t,R),t.state.options.allexport&&!f&&(t.state.exportedVars=t.state.exportedVars||new Set,t.state.exportedVars.add(R));continue}if(T.includes("=")){let R=T.indexOf("="),_=T.slice(0,R),U=T.slice(R+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(_)){N+=`bash: typeset: \`${_}': not a valid identifier
|
|
1658
1658
|
`,I=1;continue}let B=Rt(t,_);if(B)return B;if(S(_),l){if(U!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(U)){N+=`bash: declare: \`${U}': invalid variable name for name reference
|
|
1659
1659
|
`,I=1;continue}t.state.env.set(_,U),Ki(t,_),U!==""&&ym(t,U)&&pS(t,_),A(_),i&&Vr(t,_),o&&Xs(t,_);continue}if(d&&a7(t,_),h&&l7(t,_),p&&c7(t,_),Af(t,_)&&(U=await uL(t,U)),U=gc(t,_,U),Tt(t,_)){let W=xr(t,_);W&&W!==_?t.state.env.set(W,U):t.state.env.set(_,U)}else t.state.env.set(_,U);A(_),i&&Vr(t,_),o&&Xs(t,_),t.state.options.allexport&&!f&&(t.state.exportedVars=t.state.exportedVars||new Set,t.state.exportedVars.add(_))}else{let R=T;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(R)){N+=`bash: typeset: \`${R}': not a valid identifier
|
|
1660
1660
|
`,I=1;continue}if(r||s?E(R):S(R),l){Ki(t,R);let U=t.state.env.get(R);U!==void 0&&U!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(U)?aP(t,R):U&&ym(t,U)&&pS(t,R),A(R),i&&Vr(t,R),o&&Xs(t,R);continue}if(d&&a7(t,R),h&&l7(t,R),p&&c7(t,R),s){if(Cn(t,R).length>0){N+=`bash: declare: ${R}: cannot convert indexed to associative array
|
|
1661
1661
|
`,I=1;continue}t.state.associativeArrays??=new Set,t.state.associativeArrays.add(R),Oo(t,R,"associative")}let _=Vn(t,R);!t.state.env.has(R)&&!_&&(r||s?Oo(t,R,s?"associative":"indexed"):(t.state.declaredVars??=new Set,t.state.declaredVars.add(R))),A(R),i&&Vr(t,R),o&&Xs(t,R)}}return ee("",N,I)}async function u7(t,e){let n={maxElements:t.limits.maxArrayElements,maxStringBytes:t.limits.maxStringLength},r=!1,s=!1,i=!1,o=[];for(let a=0;a<e.length;a++){let l=e[a];if(l==="-a")r=!0;else if(l==="-A")s=!0;else if(l==="-p")i=!0;else if(l==="--"){o.push(...e.slice(a+1));break}else l.startsWith("-")||o.push(l)}if(o.length===0){let a="",l=Array.from(t.state.readonlyVars||[]).sort();for(let c of l){let u=t.state.env.get(c);if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${c}="${f}"
|
|
1662
|
-
`}}return Je(a)}for(let a of o){let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(l){let d=l[1],h=l[2],p=Rt(t,d);if(p)return p;let m=Zi(h,n);if(t.state.associativeArrays?.has(d)){let g=jm(h,n);t.executionScope.consumeWork(g.length,"readonly array append"),Da(t,d,g.map(([y])=>y));for(let[y,w]of g)Fe(t,d,y,w,"associative")}else{t.executionScope.consumeWork(m.length,"readonly array append");let g=Cn(t,d),y=0,w=t.state.env.get(d);g.length===0&&w!==void 0?(Fe(t,d,0,w),t.state.env.delete(d),y=1):g.length>0&&(y=Math.max(...g)+1),Da(t,d,Array.from({length:m.length},(b,x)=>y+x));for(let b=0;b<m.length;b++)Fe(t,d,y+b,m[b])}Vr(t,d);continue}let c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c){let d=c[1],h=c[2],p=Rt(t,d);if(p)return p;let m=t.state.env.get(d)??"";t.state.env.set(d,cr([m,h],"",t.limits.maxStringLength,"readonly append")),Vr(t,d);continue}let u=_$(a,n);if(u.value===void 0&&!u.isArray){Vr(t,u.name);continue}let f=await M$(t,u,{makeReadonly:!0});if(f)return f}return
|
|
1662
|
+
`}}return Je(a)}for(let a of o){let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(l){let d=l[1],h=l[2],p=Rt(t,d);if(p)return p;let m=Zi(h,n);if(t.state.associativeArrays?.has(d)){let g=jm(h,n);t.executionScope.consumeWork(g.length,"readonly array append"),Da(t,d,g.map(([y])=>y));for(let[y,w]of g)Fe(t,d,y,w,"associative")}else{t.executionScope.consumeWork(m.length,"readonly array append");let g=Cn(t,d),y=0,w=t.state.env.get(d);g.length===0&&w!==void 0?(Fe(t,d,0,w),t.state.env.delete(d),y=1):g.length>0&&(y=Math.max(...g)+1),Da(t,d,Array.from({length:m.length},(b,x)=>y+x));for(let b=0;b<m.length;b++)Fe(t,d,y+b,m[b])}Vr(t,d);continue}let c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c){let d=c[1],h=c[2],p=Rt(t,d);if(p)return p;let m=t.state.env.get(d)??"";t.state.env.set(d,cr([m,h],"",t.limits.maxStringLength,"readonly append")),Vr(t,d);continue}let u=_$(a,n);if(u.value===void 0&&!u.isArray){Vr(t,u.name);continue}let f=await M$(t,u,{makeReadonly:!0});if(f)return f}return tt}function f7(t){return t.state.directoryStack??=[],t.state.directoryStack}function vf(t,e){return e&&t===e?"~":e&&t.startsWith(`${e}/`)?`~${t.slice(e.length)}`:t}function hne(t){let e=t.split("/").filter(r=>r&&r!=="."),n=[];for(let r of e)r===".."?n.pop():n.push(r);return`/${n.join("/")}`}async function d7(t,e){let n=f7(t),r;for(let a=0;a<e.length;a++){let l=e[a];if(l==="--"){if(a+1<e.length){if(r!==void 0)return J(`bash: pushd: too many arguments
|
|
1663
1663
|
`,2);r=e[a+1],a++}}else{if(l.startsWith("-")&&l!=="-")return J(`bash: pushd: ${l}: invalid option
|
|
1664
1664
|
`,2);if(r!==void 0)return J(`bash: pushd: too many arguments
|
|
1665
1665
|
`,2);r=l}}if(r===void 0){if(n.length<2)return J(`bash: pushd: no other directory
|
|
@@ -1673,38 +1673,38 @@ ${t.terminator}`}function Aee(t){return`(${Cs(t.body)})${Gs(t.redirections)}`}fu
|
|
|
1673
1673
|
`,1);t.state.previousDir=t.state.cwd,t.state.cwd=r,t.state.env.set("PWD",r),t.state.env.set("OLDPWD",t.state.previousDir);let s=t.state.env.get("HOME")||"",i=`${[r,...n].map(o=>vf(o,s)).join(" ")}
|
|
1674
1674
|
`;return Je(i)}function p7(t,e){let n=f7(t),r=!1,s=!1,i=!1,o=!1;for(let u of e)if(u!=="--")if(u.startsWith("-"))for(let f of u.slice(1))if(f==="c")r=!0;else if(f==="l")s=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,o=!0;else return J(`bash: dirs: -${f}: invalid option
|
|
1675
1675
|
`,2);else return J(`bash: dirs: too many arguments
|
|
1676
|
-
`,1);if(r)return t.state.directoryStack=[],
|
|
1676
|
+
`,1);if(r)return t.state.directoryStack=[],tt;let a=[t.state.cwd,...n],l=t.state.env.get("HOME")||"",c;return o?(c=a.map((u,f)=>{let d=s?u:vf(u,l);return` ${f} ${d}`}).join(`
|
|
1677
1677
|
`),c+=`
|
|
1678
1678
|
`):i?c=a.map(u=>s?u:vf(u,l)).join(`
|
|
1679
1679
|
`)+`
|
|
1680
1680
|
`:c=a.map(u=>s?u:vf(u,l)).join(" ")+`
|
|
1681
1681
|
`,Je(c)}X();async function m7(t,e,n,r=!1){let s=e;if(s.length>0){let l=s[0];if(l==="--")s=s.slice(1);else if(l.startsWith("-")&&l!=="-"&&l.length>1)return J(`bash: eval: ${l}: invalid option
|
|
1682
1682
|
eval: usage: eval [arg ...]
|
|
1683
|
-
`,2)}if(s.length===0)return
|
|
1683
|
+
`,2)}if(s.length===0)return tt;let i=s.join(" ");if(i.trim()==="")return tt;let o=t.state.groupStdin,a=r||n!==void 0&&n!=="";a&&(t.state.groupStdin=n??"");try{let l=or(i);return await t.executeScript(l)}catch(l){if(l instanceof Jn||l instanceof er||l instanceof Nn||l instanceof Pe||l instanceof un)throw l;if(l.name==="ParseException")return J(`bash: eval: ${l.message}
|
|
1684
1684
|
`);throw l}finally{(a||o!==void 0&&t.state.groupStdin===void 0)&&(t.state.groupStdin=o)}}X();function g7(t,e){let n,r="";if(e.length===0)n=t.state.lastExitCode;else{let s=e[0];if(s===""||!/^-?\d+$/.test(s))r=`bash: exit: ${s}: numeric argument required
|
|
1685
1685
|
`,n=2;else{let i=BigInt(s);n=Number((i%256n+256n)%256n)}}throw new Pe(n,"",r)}function y7(t,e){let n=!1,r=[];for(let o of e)o==="-n"?n=!0:o==="-p"||o==="--"||r.push(o);if(r.length===0&&!n){let o="",a=t.state.exportedVars??new Set,l=Array.from(a).sort();for(let c of l){let u=t.state.env.get(c);u!==void 0&&(o+=`declare -x ${c}=${Sf(u)}
|
|
1686
1686
|
`)}return Je(o)}if(n){for(let o of r){let a,l;if(o.includes("=")){let c=o.indexOf("=");a=o.slice(0,c),l=o.slice(c+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return ee("",`bash: export: \`${o}': not a valid identifier
|
|
1687
|
-
`,1);l!==void 0&&(Rt(t,a),t.state.env.set(a,l)),Em(t,a)}return
|
|
1687
|
+
`,1);l!==void 0&&(Rt(t,a),t.state.env.set(a,l)),Em(t,a)}return tt}let s="",i=0;for(let o of r){let a,l,c=!1,u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)a=u[1],l=u[2],c=!0;else if(o.includes("=")){let f=o.indexOf("=");a=o.slice(0,f),l=o.slice(f+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${o}': not a valid identifier
|
|
1688
1688
|
`,i=1;continue}if(l!==void 0)if(Rt(t,a),c){let f=t.state.env.get(a)??"";t.state.env.set(a,f+l)}else t.state.env.set(a,l);else t.state.env.has(a)||t.state.env.set(a,"");Xs(t,a)}return ee("",s,i)}function r1(t,e){if(e.length<2)return J(`bash: getopts: usage: getopts optstring name [arg ...]
|
|
1689
1689
|
`);let n=e[0],r=e[1],s=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=n.startsWith(":"),o=i?n.slice(1):n,a;if(e.length>2)a=e.slice(2);else{let m=Number.parseInt(t.state.env.get("#")||"0",10);a=[];for(let g=1;g<=m;g++)a.push(t.state.env.get(String(g))||"")}let l=Number.parseInt(t.state.env.get("OPTIND")||"1",10);l<1&&(l=1);let c=Number.parseInt(t.state.env.get("__GETOPTS_CHARINDEX")||"0",10);if(t.state.env.set("OPTARG",""),l>a.length)return s||t.state.env.set(r,"?"),t.state.env.set("OPTIND",String(a.length+1)),t.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:1,stdout:"",stderr:""};let u=a[l-1];if(!u||u==="-"||!u.startsWith("-"))return s||t.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};if(u==="--")return t.state.env.set("OPTIND",String(l+1)),t.state.env.set("__GETOPTS_CHARINDEX","0"),s||t.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};let f=c===0?1:c,d=u[f];if(!d)return t.state.env.set("OPTIND",String(l+1)),t.state.env.set("__GETOPTS_CHARINDEX","0"),r1(t,e);let h=o.indexOf(d);if(h===-1){let m="";return i?t.state.env.set("OPTARG",d):m=`bash: illegal option -- ${d}
|
|
1690
1690
|
`,s||t.state.env.set(r,"?"),f+1<u.length?(t.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),t.state.env.set("OPTIND",String(l))):(t.state.env.set("OPTIND",String(l+1)),t.state.env.set("__GETOPTS_CHARINDEX","0")),{exitCode:s?2:0,stdout:"",stderr:m}}if(h+1<o.length&&o[h+1]===":")if(f+1<u.length)t.state.env.set("OPTARG",u.slice(f+1)),t.state.env.set("OPTIND",String(l+1)),t.state.env.set("__GETOPTS_CHARINDEX","0");else{if(l>=a.length){let m="";return i?(t.state.env.set("OPTARG",d),s||t.state.env.set(r,":")):(m=`bash: option requires an argument -- ${d}
|
|
1691
1691
|
`,s||t.state.env.set(r,"?")),t.state.env.set("OPTIND",String(l+1)),t.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:0,stdout:"",stderr:m}}t.state.env.set("OPTARG",a[l]),t.state.env.set("OPTIND",String(l+2)),t.state.env.set("__GETOPTS_CHARINDEX","0")}else f+1<u.length?(t.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),t.state.env.set("OPTIND",String(l))):(t.state.env.set("OPTIND",String(l+1)),t.state.env.set("__GETOPTS_CHARINDEX","0"));return s||t.state.env.set(r,d),{exitCode:s?2:0,stdout:"",stderr:""}}async function w7(t,e){t.state.hashTable||(t.state.hashTable=new Map);let n=!1,r=!1,s=!1,i=!1,o=!1,a="",l=[],c=0;for(;c<e.length;){let p=e[c];if(p==="--"){c++,l.push(...e.slice(c));break}if(p==="-r")n=!0,c++;else if(p==="-d")r=!0,c++;else if(p==="-l")s=!0,c++;else if(p==="-t")o=!0,c++;else if(p==="-p"){if(i=!0,c++,c>=e.length)return J(`bash: hash: -p: option requires an argument
|
|
1692
1692
|
`,1);a=e[c],c++}else if(p.startsWith("-")&&p.length>1){for(let m of p.slice(1))if(m==="r")n=!0;else if(m==="d")r=!0;else if(m==="l")s=!0;else if(m==="t")o=!0;else return m==="p"?J(`bash: hash: -p: option requires an argument
|
|
1693
1693
|
`,1):J(`bash: hash: -${m}: invalid option
|
|
1694
|
-
`,1);c++}else l.push(p),c++}if(n)return t.state.hashTable.clear(),
|
|
1694
|
+
`,1);c++}else l.push(p),c++}if(n)return t.state.hashTable.clear(),tt;if(r){if(l.length===0)return J(`bash: hash: -d: option requires an argument
|
|
1695
1695
|
`,1);let p=!1,m="";for(let g of l)t.state.hashTable.has(g)?t.state.hashTable.delete(g):(m+=`bash: hash: ${g}: not found
|
|
1696
|
-
`,p=!0);return p?J(m,1):
|
|
1696
|
+
`,p=!0);return p?J(m,1):tt}if(o){if(l.length===0)return J(`bash: hash: -t: option requires an argument
|
|
1697
1697
|
`,1);let p="",m=!1,g="";for(let y of l){let w=t.state.hashTable.get(y);w?l.length>1?p+=`${y} ${w}
|
|
1698
1698
|
`:p+=`${w}
|
|
1699
1699
|
`:(g+=`bash: hash: ${y}: not found
|
|
1700
1700
|
`,m=!0)}return m?{exitCode:1,stdout:p,stderr:g}:Je(p)}if(i){if(l.length===0)return J(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
|
|
1701
|
-
`,1);let p=l[0];return t.state.hashTable.set(p,a),
|
|
1701
|
+
`,1);let p=l[0];return t.state.hashTable.set(p,a),tt}if(l.length===0){if(t.state.hashTable.size===0)return Je(`hash: hash table empty
|
|
1702
1702
|
`);let p="";if(s)for(let[m,g]of t.state.hashTable){let y=m.startsWith("-")?" --":"";p+=`builtin hash -p ${gn(g)}${y} ${gn(m)}
|
|
1703
1703
|
`}else{p=`hits command
|
|
1704
1704
|
`;for(let[,m]of t.state.hashTable)p+=` 1 ${m}
|
|
1705
1705
|
`}return Je(p)}let u=!1,f="",h=(t.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let p of l){if(p.includes("/")){f+=`bash: hash: ${p}: cannot use / in name
|
|
1706
1706
|
`,u=!0;continue}let m=!1;for(let g of h){if(!g)continue;let y=`${g}/${p}`;if(await t.fs.exists(y)){t.state.hashTable.set(p,y),m=!0;break}}m||(f+=`bash: hash: ${p}: not found
|
|
1707
|
-
`,u=!0)}return u?J(f,1):
|
|
1707
|
+
`,u=!0)}return u?J(f,1):tt}$t();var fL=new Map([[":",[": [arguments]",`Null command.
|
|
1708
1708
|
No effect; the command does nothing.
|
|
1709
1709
|
Exit Status:
|
|
1710
1710
|
Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
|
|
@@ -2105,13 +2105,13 @@ Options:
|
|
|
2105
2105
|
`}function mL(t){let e=gL.map(r=>`set ${t.state.options[r]?"-o":"+o"} ${r}`),n=yL.map(r=>`set +o ${r}`);return`${[...e,...n].sort().join(`
|
|
2106
2106
|
`)}
|
|
2107
2107
|
`}function k7(t,e){if(e.includes("--help"))return Je(Cf);if(e.length===0){let i=Ene(t),o=Sne(t),a=[];for(let[u,f]of t.state.env)/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)&&(i.has(u)||o.has(u)||a.push([u,f]));let l=[...a.map(([u,f])=>({kind:"scalar",name:u,value:f})),...Array.from(i,u=>({kind:"indexed",name:u})),...Array.from(o,u=>({kind:"associative",name:u}))];l.sort((u,f)=>u.name<f.name?-1:u.name>f.name?1:0);let c=new $e(t.limits.maxOutputSize,"set");for(let u of l)t.executionScope.consumeWork(1,"set variable listing"),u.kind==="scalar"?(c.append(u.name).append("="),c.reserve(tL(u.value)),c.append(gn(u.value))):u.kind==="indexed"?wne(t,c,u.name):xne(t,c,u.name),c.append(`
|
|
2108
|
-
`);return Je(c.build())}let n=[],r=()=>n.length>0?Je(n.join("")):
|
|
2108
|
+
`);return Je(c.build())}let n=[],r=()=>n.length>0?Je(n.join("")):tt,s=0;for(;s<e.length;){let i=e[s];if((i==="-o"||i==="+o")&&yne(e,s)){let o=e[s+1];if(!i1.has(o)){let a=`bash: set: ${o}: invalid option name
|
|
2109
2109
|
${Cf}`;if(t.state.options.posix)throw new Cr(1,"",a);return J(a)}v7(t,i1.get(o)??null,i==="-o"),s+=2;continue}if(i==="-o"){n.push(pL(t)),s++;continue}if(i==="+o"){n.push(mL(t)),s++;continue}if(i.length>1&&(i[0]==="-"||i[0]==="+")&&i[1]!=="-"){let o=i[0]==="-",a=0;for(let l=1;l<i.length;l++){let c=i[l];if(c==="o"){let u=s+1+a;if(u<e.length&&!e[u].startsWith("-")&&!e[u].startsWith("+")){let d=e[u];if(!i1.has(d)){let h=`bash: set: ${d}: invalid option name
|
|
2110
2110
|
${Cf}`;if(t.state.options.posix)throw new Cr(1,"",h);return J(h)}v7(t,i1.get(d)??null,o),a++;continue}n.push(o?pL(t):mL(t));continue}if(!hL.has(c)){let u=`bash: set: ${i[0]}${c}: invalid option
|
|
2111
2111
|
${Cf}`;if(t.state.options.posix)throw new Cr(1,"",u);return J(u)}v7(t,hL.get(c)??null,o)}s+=1+a;continue}if(i==="--")return C7(t,e.slice(s+1)),r();if(i==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,nc(t),s+1<e.length)return C7(t,e.slice(s+1)),r();s++;continue}if(i==="+"){s++;continue}if(i.startsWith("-")||i.startsWith("+")){let o=`bash: set: ${i}: invalid option
|
|
2112
2112
|
${Cf}`;if(t.state.options.posix)throw new Cr(1,"",o);return J(o)}return C7(t,e.slice(s)),r()}return r()}function C7(t,e){let n=1;for(;t.state.env.has(String(n));)t.state.env.delete(String(n)),n++;for(let r=0;r<e.length;r++)t.state.env.set(String(r+1),e[r]);t.state.env.set("#",String(e.length)),t.state.env.set("@",e.join(" ")),t.state.env.set("*",e.join(" "))}X();function N7(t,e){let n=1;if(e.length>0){let o=Number.parseInt(e[0],10);if(Number.isNaN(o)||o<0){let a=`bash: shift: ${e[0]}: numeric argument required
|
|
2113
2113
|
`;if(t.state.options.posix)throw new Cr(1,"",a);return J(a)}n=o}let r=Number.parseInt(t.state.env.get("#")||"0",10);if(n>r){let o=`bash: shift: shift count out of range
|
|
2114
|
-
`;if(t.state.options.posix)throw new Cr(1,"",o);return J(o)}if(n===0)return
|
|
2114
|
+
`;if(t.state.options.posix)throw new Cr(1,"",o);return J(o)}if(n===0)return tt;let s=[];for(let o=1;o<=r;o++)s.push(t.state.env.get(String(o))||"");let i=s.slice(n);for(let o=1;o<=r;o++)t.state.env.delete(String(o));for(let o=0;o<i.length;o++)t.state.env.set(String(o+1),i[o]);return t.state.env.set("#",String(i.length)),t.state.env.set("@",i.join(" ")),tt}X();async function o1(t,e){let n=e;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return ee("",`bash: source: filename argument required
|
|
2115
2115
|
`,2);let r=n[0],s=null,i=null;if(r.includes("/")){let c=t.fs.resolvePath(t.state.cwd,r);try{i=await t.fs.readFile(c),s=c}catch{}}else{let u=(t.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of u){let d=t.fs.resolvePath(t.state.cwd,`${f}/${r}`);try{if((await t.fs.stat(d)).isDirectory)continue;i=await t.fs.readFile(d),s=d;break}catch{}}if(i===null){let f=t.fs.resolvePath(t.state.cwd,r);try{i=await t.fs.readFile(f),s=f}catch{}}}if(i===null)return J(`bash: ${r}: No such file or directory
|
|
2116
2116
|
`);let o=new Map;if(n.length>1){for(let u=1;u<=9;u++)o.set(String(u),t.state.env.get(String(u)));o.set("#",t.state.env.get("#")),o.set("@",t.state.env.get("@"));let c=n.slice(1);t.state.env.set("#",String(c.length)),t.state.env.set("@",c.join(" "));for(let u=0;u<c.length&&u<9;u++)t.state.env.set(String(u+1),c[u]);for(let u=c.length+1;u<=9;u++)t.state.env.delete(String(u))}let a=t.state.currentSource,l=()=>{if(t.state.sourceDepth--,t.state.currentSource=a,n.length>1)for(let[c,u]of o)u===void 0?t.state.env.delete(c):t.state.env.set(c,u)};if(t.state.sourceDepth++,t.state.sourceDepth>t.limits.maxSourceDepth)throw t.state.sourceDepth--,new v(`source: maximum nesting depth (${t.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,"recursion");t.state.currentSource=r;try{let c=or(i),u=await t.executeScript(c);return l(),u}catch(c){if(l(),c instanceof Pe)throw c;if(c instanceof Nn)return ee(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return J(`bash: ${r}: ${c.message}
|
|
2117
2117
|
`);throw c}}function wL(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}function Ane(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')}async function bL(t,e){if(Ane(e))return null;try{let n=new _e,r=it(n,e);return await Xe(t,r.expression)}catch{let n=parseInt(e,10);return Number.isNaN(n)?0:n}}function xL(t,e){if(t.state.localVarStack?.has(e)){let r=Vm(t,e);if(r){r.value===void 0?t.state.env.delete(e):t.state.env.set(e,r.value);let s=t.state.localVarStack?.get(e);if(!s||s.length===0)qm(t,e),t.state.localVarStack?.delete(e),t.state.fullyUnsetLocals=t.state.fullyUnsetLocals||new Map,t.state.fullyUnsetLocals.set(e,r.scopeIndex),T7(t,e);else{let i=s[s.length-1];t.state.localVarDepth=t.state.localVarDepth||new Map,t.state.localVarDepth.set(e,i.scopeIndex+1)}return!0}return t.state.env.delete(e),qm(t,e),t.state.localVarStack?.delete(e),t.state.fullyUnsetLocals=t.state.fullyUnsetLocals||new Map,t.state.fullyUnsetLocals.set(e,0),!0}for(let r=t.state.localScopes.length-1;r>=0;r--){let s=t.state.localScopes[r];if(s.has(e)){let i=s.get(e);i===void 0?t.state.env.delete(e):t.state.env.set(e,i),s.delete(e);let o=!1;for(let a=r-1;a>=0;a--)if(t.state.localScopes[a].has(e)){t.state.localVarDepth&&t.state.localVarDepth.set(e,a+1),o=!0;break}return o||qm(t,e),!0}}return!1}function T7(t,e){if(!t.state.tempEnvBindings||t.state.tempEnvBindings.length===0)return!1;for(let n=t.state.tempEnvBindings.length-1;n>=0;n--){let r=t.state.tempEnvBindings[n];if(r.has(e)){let s=r.get(e);return s===void 0?t.state.env.delete(e):t.state.env.set(e,s),r.delete(e),!0}}return!1}async function EL(t,e){if(e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.startsWith('"')&&e.endsWith('"')){let n=e.slice(1,-1),s=new _e().parseWordFromString(n,!0,!1);return ot(t,s)}if(e.includes("$")){let r=new _e().parseWordFromString(e,!1,!1);return ot(t,r)}return e}async function O7(t,e){let n="both",r="",s=0;for(let i of e){if(i==="-v"){n="variable";continue}if(i==="-f"){n="function";continue}if(n==="function"){t.state.functions.delete(i);continue}if(n==="variable"){let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let d=c[1],h=c[2];if(Er(t,d)){r+=`bash: unset: ${d}: cannot unset: readonly variable
|
|
@@ -2183,25 +2183,25 @@ ${t} ()
|
|
|
2183
2183
|
`),o=1)}else if(t.commands.has(a)){let u=(t.state.env.get("PATH")??"/usr/bin:/bin").split(":"),f=null;for(let d of u){if(!d)continue;let h=`${d}/${a}`;try{let p=await t.fs.stat(h);if(!p.isDirectory&&(p.mode&73)!==0){f=h;break}}catch{}}f||(f=`/usr/bin/${a}`),r?s+=`${a} is ${f}
|
|
2184
2184
|
`:s+=`${f}
|
|
2185
2185
|
`}else r&&(i+=`${a}: not found
|
|
2186
|
-
`),o=1}return ee(s,i,o)}async function $L(t,e){if(e.includes("/")){let s=t.fs.resolvePath(t.state.cwd,e);if(await t.fs.exists(s)){try{let i=await t.fs.stat(s);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return e}return null}let r=(t.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let s of r){if(!s)continue;let o=`${s.startsWith("/")?s:t.fs.resolvePath(t.state.cwd,s)}/${e}`;if(await t.fs.exists(o)){try{let a=await t.fs.stat(o);if(a.isDirectory||(a.mode&73)===0)continue}catch{continue}return`${s}/${e}`}}if(t.commands.has(e)){for(let s of r)if(s==="/usr/bin"||s==="/bin")return`${s}/${e}`;return`/usr/bin/${e}`}return null}function LL(t,e){let n=!0,r=t.signal?new AbortController:void 0,s=new WeakMap,i=()=>{if(!n)throw new
|
|
2187
|
-
`)},o=f=>{if(f===null||typeof f!="object"&&typeof f!="function")return f;let d=s.get(f);if(d!==void 0)return d;if(typeof f=="object"&&VI(f))return f;if(f instanceof Uint8Array){let g=new Uint8Array(f);return s.set(f,g),g}if(f instanceof ArrayBuffer){let g=f.slice(0);return s.set(f,g),g}if(f instanceof Promise){let g=f.then(y=>(i(),o(y)));return s.set(f,g),g}if(typeof f=="function"){let g=function(...y){return i(),o(Reflect.apply(f,this,y))};return s.set(f,g),g}let h=Object.getPrototypeOf(f);if(Array.isArray(f)||h===Object.prototype||h===null){let g=Array.isArray(f)?[]:Object.create(h);s.set(f,g);let y=Object.getOwnPropertyDescriptors(f);for(let w of Object.values(y)){if("value"in w){let b=w.value;w.value=typeof b=="function"?(...x)=>(i(),o(Reflect.apply(b,f,x))):o(b)}if(w.get){let b=w.get;w.get=()=>(i(),o(Reflect.apply(b,f,[])))}if(w.set){let b=w.set;w.set=x=>{i(),Reflect.apply(b,f,[x])}}}return Object.defineProperties(g,y),g}let p=new Map,m=new M9(f,{get(g,y){if(i(),y==="constructor"||y==="prototype"||y==="__proto__")throw new Error(`${e}: unsafe context property access`);let w=Reflect.get(g,y,g);if(typeof w!="function")return o(w);if(p.has(y))return p.get(y);let b=(...x)=>(i(),o(Reflect.apply(w,g,x)));return p.set(y,b),b},set(g,y,w){if(i(),y==="constructor"||y==="prototype"||y==="__proto__")throw new Error(`${e}: unsafe context property access`);return Reflect.set(g,y,w,g)}});return s.set(f,m),m},a=f=>o(f),l=f=>f&&((...d)=>(i(),o(f(...d)))),c=f=>({value:f,enumerable:!0,configurable:!0,writable:!0}),u=Object.getOwnPropertyDescriptors(t);return Object.assign(u,{fs:c(a(t.fs)),env:c(a(t.env)),limits:c(Object.freeze({...t.limits})),exportedEnv:c(t.exportedEnv?Object.freeze({...t.exportedEnv}):void 0),executionScope:c(t.executionScope?a(t.executionScope):void 0),fileDescriptors:c(t.fileDescriptors?a(t.fileDescriptors):void 0),coverage:c(t.coverage?a(t.coverage):void 0),assignShellVariable:c(l(t.assignShellVariable)),exec:c(l(t.exec)),origCommand:c(l(t.origCommand)),execWithInheritedStdin:c(l(t.execWithInheritedStdin)),fetch:c(l(t.fetch)),getRegisteredCommands:c(l(t.getRegisteredCommands)),sleep:c(l(t.sleep)),trace:c(l(t.trace)),invokeTool:c(l(t.invokeTool)),signal:c(r?.signal)}),{context:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),u),revoke(){n=!1,r?.signal.aborted||r?.abort(new
|
|
2188
|
-
`))}}}async function _ne(t,e,n,r,s,i){let o=s.remainingTimeMs()??e.limits.maxExecutionTimeMs,a=e.limits.maxExtensionCleanupTimeMs,l,c,u,d=Promise.resolve().then(t).then(p=>({kind:"result",result:p}),p=>({kind:"error",error:p})),h=new Promise(p=>{let m=()=>{n(),p({kind:"abort"})};c=m,i?.addEventListener("abort",m,{once:!0}),i?.aborted&&m(),l=Oi(()=>{n(),p({kind:"deadline"})},o)});try{let p=await Promise.race([d,h]);if(p.kind==="result")return p.result;if(p.kind==="error")throw p.error;n();let m=await Promise.race([d.then(()=>!0),new Promise(y=>{u=Oi(()=>y(!1),a)})]),g=p.kind==="deadline"?new
|
|
2189
|
-
`):new
|
|
2190
|
-
`);throw m||s.poisonAfterAbort(g),g}finally{n(),Ii(l),Ii(u),c&&i?.removeEventListener("abort",c)}}var FL={export:(t,e)=>y7(t.ctx,e),unset:(t,e)=>O7(t.ctx,e),exit:(t,e)=>g7(t.ctx,e),local:(t,e)=>E7(t.ctx,e),set:(t,e)=>k7(t.ctx,e),break:(t,e)=>IS(t.ctx,e),continue:(t,e)=>s7(t.ctx,e),return:(t,e)=>A7(t.ctx,e),shift:(t,e)=>N7(t.ctx,e),getopts:(t,e)=>r1(t.ctx,e),compgen:(t,e)=>JS(t.ctx,e),complete:(t,e)=>n7(t.ctx,e),compopt:(t,e)=>r7(t.ctx,e),pushd:(t,e)=>d7(t.ctx,e),popd:(t,e)=>h7(t.ctx,e),dirs:(t,e)=>p7(t.ctx,e),source:(t,e)=>o1(t.ctx,e),".":(t,e)=>o1(t.ctx,e),read:(t,e,n)=>S7(t.ctx,e,n.stdin,n.stdinSourceFd),mapfile:(t,e,n)=>s1(t.ctx,e,n.stdin),readarray:(t,e,n)=>s1(t.ctx,e,n.stdin),declare:(t,e)=>n1(t.ctx,e),typeset:(t,e)=>n1(t.ctx,e),readonly:(t,e)=>u7(t.ctx,e),eval:(t,e,n)=>m7(t.ctx,e,n.stdin,n.stdinRedirected),cd:(t,e)=>RS(t.ctx,e),":":()=>
|
|
2186
|
+
`),o=1}return ee(s,i,o)}async function $L(t,e){if(e.includes("/")){let s=t.fs.resolvePath(t.state.cwd,e);if(await t.fs.exists(s)){try{let i=await t.fs.stat(s);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return e}return null}let r=(t.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let s of r){if(!s)continue;let o=`${s.startsWith("/")?s:t.fs.resolvePath(t.state.cwd,s)}/${e}`;if(await t.fs.exists(o)){try{let a=await t.fs.stat(o);if(a.isDirectory||(a.mode&73)===0)continue}catch{continue}return`${s}/${e}`}}if(t.commands.has(e)){for(let s of r)if(s==="/usr/bin"||s==="/bin")return`${s}/${e}`;return`/usr/bin/${e}`}return null}function LL(t,e){let n=!0,r=t.signal?new AbortController:void 0,s=new WeakMap,i=()=>{if(!n)throw new et("",`bash: ${e} used its context after cancellation
|
|
2187
|
+
`)},o=f=>{if(f===null||typeof f!="object"&&typeof f!="function")return f;let d=s.get(f);if(d!==void 0)return d;if(typeof f=="object"&&VI(f))return f;if(f instanceof Uint8Array){let g=new Uint8Array(f);return s.set(f,g),g}if(f instanceof ArrayBuffer){let g=f.slice(0);return s.set(f,g),g}if(f instanceof Promise){let g=f.then(y=>(i(),o(y)));return s.set(f,g),g}if(typeof f=="function"){let g=function(...y){return i(),o(Reflect.apply(f,this,y))};return s.set(f,g),g}let h=Object.getPrototypeOf(f);if(Array.isArray(f)||h===Object.prototype||h===null){let g=Array.isArray(f)?[]:Object.create(h);s.set(f,g);let y=Object.getOwnPropertyDescriptors(f);for(let w of Object.values(y)){if("value"in w){let b=w.value;w.value=typeof b=="function"?(...x)=>(i(),o(Reflect.apply(b,f,x))):o(b)}if(w.get){let b=w.get;w.get=()=>(i(),o(Reflect.apply(b,f,[])))}if(w.set){let b=w.set;w.set=x=>{i(),Reflect.apply(b,f,[x])}}}return Object.defineProperties(g,y),g}let p=new Map,m=new M9(f,{get(g,y){if(i(),y==="constructor"||y==="prototype"||y==="__proto__")throw new Error(`${e}: unsafe context property access`);let w=Reflect.get(g,y,g);if(typeof w!="function")return o(w);if(p.has(y))return p.get(y);let b=(...x)=>(i(),o(Reflect.apply(w,g,x)));return p.set(y,b),b},set(g,y,w){if(i(),y==="constructor"||y==="prototype"||y==="__proto__")throw new Error(`${e}: unsafe context property access`);return Reflect.set(g,y,w,g)}});return s.set(f,m),m},a=f=>o(f),l=f=>f&&((...d)=>(i(),o(f(...d)))),c=f=>({value:f,enumerable:!0,configurable:!0,writable:!0}),u=Object.getOwnPropertyDescriptors(t);return Object.assign(u,{fs:c(a(t.fs)),env:c(a(t.env)),limits:c(Object.freeze({...t.limits})),exportedEnv:c(t.exportedEnv?Object.freeze({...t.exportedEnv}):void 0),executionScope:c(t.executionScope?a(t.executionScope):void 0),fileDescriptors:c(t.fileDescriptors?a(t.fileDescriptors):void 0),coverage:c(t.coverage?a(t.coverage):void 0),assignShellVariable:c(l(t.assignShellVariable)),exec:c(l(t.exec)),origCommand:c(l(t.origCommand)),execWithInheritedStdin:c(l(t.execWithInheritedStdin)),fetch:c(l(t.fetch)),getRegisteredCommands:c(l(t.getRegisteredCommands)),sleep:c(l(t.sleep)),trace:c(l(t.trace)),invokeTool:c(l(t.invokeTool)),signal:c(r?.signal)}),{context:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),u),revoke(){n=!1,r?.signal.aborted||r?.abort(new et("",`bash: ${e} context revoked
|
|
2188
|
+
`))}}}async function _ne(t,e,n,r,s,i){let o=s.remainingTimeMs()??e.limits.maxExecutionTimeMs,a=e.limits.maxExtensionCleanupTimeMs,l,c,u,d=Promise.resolve().then(t).then(p=>({kind:"result",result:p}),p=>({kind:"error",error:p})),h=new Promise(p=>{let m=()=>{n(),p({kind:"abort"})};c=m,i?.addEventListener("abort",m,{once:!0}),i?.aborted&&m(),l=Oi(()=>{n(),p({kind:"deadline"})},o)});try{let p=await Promise.race([d,h]);if(p.kind==="result")return p.result;if(p.kind==="error")throw p.error;n();let m=await Promise.race([d.then(()=>!0),new Promise(y=>{u=Oi(()=>y(!1),a)})]),g=p.kind==="deadline"?new et("",`bash: ${r} exceeded its execution deadline
|
|
2189
|
+
`):new et("",`bash: execution aborted
|
|
2190
|
+
`);throw m||s.poisonAfterAbort(g),g}finally{n(),Ii(l),Ii(u),c&&i?.removeEventListener("abort",c)}}var FL={export:(t,e)=>y7(t.ctx,e),unset:(t,e)=>O7(t.ctx,e),exit:(t,e)=>g7(t.ctx,e),local:(t,e)=>E7(t.ctx,e),set:(t,e)=>k7(t.ctx,e),break:(t,e)=>IS(t.ctx,e),continue:(t,e)=>s7(t.ctx,e),return:(t,e)=>A7(t.ctx,e),shift:(t,e)=>N7(t.ctx,e),getopts:(t,e)=>r1(t.ctx,e),compgen:(t,e)=>JS(t.ctx,e),complete:(t,e)=>n7(t.ctx,e),compopt:(t,e)=>r7(t.ctx,e),pushd:(t,e)=>d7(t.ctx,e),popd:(t,e)=>h7(t.ctx,e),dirs:(t,e)=>p7(t.ctx,e),source:(t,e)=>o1(t.ctx,e),".":(t,e)=>o1(t.ctx,e),read:(t,e,n)=>S7(t.ctx,e,n.stdin,n.stdinSourceFd),mapfile:(t,e,n)=>s1(t.ctx,e,n.stdin),readarray:(t,e,n)=>s1(t.ctx,e,n.stdin),declare:(t,e)=>n1(t.ctx,e),typeset:(t,e)=>n1(t.ctx,e),readonly:(t,e)=>u7(t.ctx,e),eval:(t,e,n)=>m7(t.ctx,e,n.stdin,n.stdinRedirected),cd:(t,e)=>RS(t.ctx,e),":":()=>tt,true:()=>tt,false:()=>pn(!1),let:(t,e)=>x7(t.ctx,e),command:(t,e,n)=>Mne(t,e,n.stdin,n.stdinRedirected),builtin:(t,e,n)=>Bne(t,e,n.stdin,n.stdinRedirected),shopt:(t,e)=>Y$(t.ctx,e),exec:async(t,e,n)=>{if(e.length===0)return tt;let[r,...s]=e;return{...await t.runCommand(r,s,[],n.stdin,!1,!1,-1,n.stdinRedirected),internalProducerOmitsShellPrefix:!0}},wait:()=>tt,type:(t,e)=>IL(t.ctx,e,n=>$L(t.ctx,n),n=>sm(t.ctx,n)),hash:(t,e)=>w7(t.ctx,e),help:(t,e)=>b7(t.ctx,e),"[":(t,e)=>e[e.length-1]!=="]"?J("[: missing `]'\n",2):uc(t.ctx,e.slice(0,-1)),test:(t,e)=>uc(t.ctx,e)};async function DL(t,e,n,r,s,i,o,a,l=!1){let{ctx:c}=t;c.coverage&&Bs.has(e)&&c.coverage.hit(`bash:builtin:${e}`);let u={stdin:s,stdinRedirected:l,stdinSourceFd:a},f=dw(e),d=(f==="early"||f==="late")&&Object.hasOwn(FL,e)?FL[e]:void 0;if(d&&(f==="early"||c.state.options.posix&&hw(e)))return d(t,n,u);if(!i){let h=c.state.functions.get(e);if(h)return Qm(c,h,n,s,void 0,l)}if(e==="__just_bash_tee_restore"){if(n.length===0||n.length>c.limits.maxArrayElements)return J(`bash: invalid internal pipeline status restore
|
|
2191
2191
|
`,2);let h=[];for(let g of n){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(g))return J(`bash: invalid internal pipeline status restore
|
|
2192
2192
|
`,2);let y=Number(g);if(!Number.isSafeInteger(y)||y>255)return J(`bash: invalid internal pipeline status restore
|
|
2193
|
-
`,2);h.push(y)}let p=h[h.length-1]??0,m=[...h].reverse().find(g=>g!==0);return{stdout:"",stderr:"",exitCode:c.state.options.pipefail&&m!==void 0?m:p,internalPipeStatusOverride:h}}return d&&f==="late"?d(t,n,u):null}async function Mne(t,e,n,r=!1){let{ctx:s,runCommand:i}=t;if(e.length===0)return
|
|
2193
|
+
`,2);h.push(y)}let p=h[h.length-1]??0,m=[...h].reverse().find(g=>g!==0);return{stdout:"",stderr:"",exitCode:c.state.options.pipefail&&m!==void 0?m:p,internalPipeStatusOverride:h}}return d&&f==="late"?d(t,n,u):null}async function Mne(t,e,n,r=!1){let{ctx:s,runCommand:i}=t;if(e.length===0)return tt;let o=!1,a=!1,l=!1,c=e;for(;c.length>0&&c[0].startsWith("-");){let d=c[0];if(d==="--"){c=c.slice(1);break}for(let h of d.slice(1))h==="p"?o=!0:h==="V"?a=!0:h==="v"&&(l=!0);c=c.slice(1)}if(c.length===0)return tt;if(l||a)return await PL(s,c,l,a);let[u,...f]=c;return i(u,f,[],n,!0,o,-1,r)}async function Bne(t,e,n,r=!1){let{runCommand:s}=t;if(e.length===0)return tt;let i=e;if(i[0]==="--"&&(i=i.slice(1),i.length===0))return tt;let o=i[0];if(o!=="__just_bash_tee_restore"&&!Bs.has(o))return J(`bash: builtin: ${o}: not a shell builtin
|
|
2194
2194
|
`);let[,...a]=i;return s(o,a,[],n,!0,!1,-1,r)}async function _L(t,e,n,r,s){let{ctx:i,buildExportedEnv:o,executeUserScript:a}=t,c=await rm(i,e,s?"/usr/bin:/bin":void 0);if(!c){i.executionScope.recordUnresolvedCommand(e);let S=i.executionScope.abortOnUnresolvedCommands;if(N$(e)){let E=`bash: ${e}: command not available in browser environments. Exclude '${e}' from your commands or use the Node.js bundle.
|
|
2195
2195
|
`;if(S)throw new un(e,"",E);return J(E,127)}if(S)throw new un(e,"",`bash: ${e}: command not found
|
|
2196
2196
|
`);return J(`bash: ${e}: command not found
|
|
2197
2197
|
`,127)}if("error"in c)return c.error==="permission_denied"?J(`bash: ${e}: Permission denied
|
|
2198
2198
|
`,126):J(`bash: ${e}: No such file or directory
|
|
2199
|
-
`,127);if("script"in c)return e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,f));let d=r||i.state.groupStdin||"",h=!1,p=o();i.state.fileDescriptors??=new Map;let m={fs:i.fs,fsIdentity:Qp(i.fs),cwd:i.state.cwd,env:i.state.env,assignShellVariable:async(S,E,A)=>{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(S))throw new Error(`${S}: not a valid identifier`);let N=A===void 0?S:`${S}[${A}]`,I=wm(i,S,E);if(I===void 0)throw new Error(`${S}: circular name reference`);if(I===null)return;let T=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(?:\[(.*)\])?$/);if(!T)throw new Error(`${N}: not a valid identifier`);let $=T[1],C=T[2]??A;if(Er(i,S)||Er(i,$))throw new Error(`${$}: readonly variable`);if(C===void 0)i.state.env.set($,E);else{let O=i.state.associativeArrays?.has($)?"associative":"indexed";if(O==="associative"){Fe(i,$,C,E,O);return}let F=await R7(i,$,C);if(F.error)throw new Pe(F.error.exitCode,F.error.stdout,F.error.stderr);Fe(i,$,F.index,E,O)}},exportedEnv:p,get stdin(){return h=!0,d},limits:i.limits,executionScope:u.internalIsExtension?QI(i.executionScope):i.executionScope,exec:(S,E)=>i.execFn(S,E,!1),execWithInheritedStdin:(S,E)=>i.execFn(S,{...E,stdin:d,stdinKind:"bytes"},!0),fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,invokeTool:i.invokeTool},g=u.internalOriginalCommand,y=()=>{};if(g){let S=Object.getOwnPropertyDescriptors(m);S.executionScope={value:i.executionScope,enumerable:!0,configurable:!0,writable:!0};let E=Object.defineProperties(Object.create(Object.getPrototypeOf(m)),S),A=LL(E,g.name),N=I7(A.context,g.name);y=A.revoke,m.origCommand=I=>{let T=()=>g.execute(I,N);return g.trusted?
|
|
2200
|
-
`,stderr:"",exitCode:0};let S=()=>Wn(i.requireDefenseContext,"command",`${e} execution`,()=>u.execute(n,b)),E=()=>_ne(S,b,x,e,i.executionScope,i.state.signal),A=u.trusted?await
|
|
2199
|
+
`,127);if("script"in c)return e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,f));let d=r||i.state.groupStdin||"",h=!1,p=o();i.state.fileDescriptors??=new Map;let m={fs:i.fs,fsIdentity:Qp(i.fs),cwd:i.state.cwd,env:i.state.env,assignShellVariable:async(S,E,A)=>{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(S))throw new Error(`${S}: not a valid identifier`);let N=A===void 0?S:`${S}[${A}]`,I=wm(i,S,E);if(I===void 0)throw new Error(`${S}: circular name reference`);if(I===null)return;let T=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(?:\[(.*)\])?$/);if(!T)throw new Error(`${N}: not a valid identifier`);let $=T[1],C=T[2]??A;if(Er(i,S)||Er(i,$))throw new Error(`${$}: readonly variable`);if(C===void 0)i.state.env.set($,E);else{let O=i.state.associativeArrays?.has($)?"associative":"indexed";if(O==="associative"){Fe(i,$,C,E,O);return}let F=await R7(i,$,C);if(F.error)throw new Pe(F.error.exitCode,F.error.stdout,F.error.stderr);Fe(i,$,F.index,E,O)}},exportedEnv:p,get stdin(){return h=!0,d},limits:i.limits,executionScope:u.internalIsExtension?QI(i.executionScope):i.executionScope,exec:(S,E)=>i.execFn(S,E,!1),execWithInheritedStdin:(S,E)=>i.execFn(S,{...E,stdin:d,stdinKind:"bytes"},!0),fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,invokeTool:i.invokeTool},g=u.internalOriginalCommand,y=()=>{};if(g){let S=Object.getOwnPropertyDescriptors(m);S.executionScope={value:i.executionScope,enumerable:!0,configurable:!0,writable:!0};let E=Object.defineProperties(Object.create(Object.getPrototypeOf(m)),S),A=LL(E,g.name),N=I7(A.context,g.name);y=A.revoke,m.origCommand=I=>{let T=()=>g.execute(I,N);return g.trusted?nt.runTrustedAsync(T):nt.runUntrustedAsync(T)}}let w=LL(m,e),b=I7(w.context,e),x=()=>{w.revoke(),y()};try{if(!u.handlesOwnVersion&&n.slice(0,n.indexOf("--")===-1?void 0:n.indexOf("--")).includes("--version"))return{stdout:`${e} (just-bash)
|
|
2200
|
+
`,stderr:"",exitCode:0};let S=()=>Wn(i.requireDefenseContext,"command",`${e} execution`,()=>u.execute(n,b)),E=()=>_ne(S,b,x,e,i.executionScope,i.state.signal),A=u.trusted?await nt.runTrustedAsync(E):await E();return{...A,internalStdinConsumed:A.internalStdinConsumed??(h?r.length:0)}}catch(S){return ke(S),J(`${e}: ${Be(Qe(S))}
|
|
2201
2201
|
`)}}pe();X();hl();async function P7(t,e){let n=t.state.inCondition;t.state.inCondition=!0;let r=new Ir(t.executionScope,"condition"),s=0;try{for(let i of e){let o=await t.executeStatement(i);r.appendResult(o),s=o.exitCode}}catch(i){throw r.prependTo(i),i}finally{t.state.inCondition=n}return r.build(s)}Un();Kt();X();Un();var l1=0;function yc(t,e){return t.state.lastExitCode=e,t.state.env.set("?",String(e)),e}function Nf(t,e,n,r){if(t instanceof Jn)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"break",stdout:e,stderr:n,exitCode:l1};if(t instanceof er)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"continue",stdout:e,stderr:n,exitCode:l1};if(vc(t)||t instanceof Nn||t instanceof tr||t instanceof Pe)return t instanceof Bt&&t.prependOutput(e,n),{action:"rethrow",stdout:e,stderr:n,error:t};let s=Qe(t);return{action:"error",stdout:e,stderr:`${n}${s}
|
|
2202
2202
|
`,exitCode:1}}function ML(t,e){return t!==void 0?{owns:!0,stdin:t}:e!==""?{owns:!0,stdin:e}:{owns:!1}}var Ko=class{ctx;stdoutChunks=[];stderrChunks=[];totalBytes=0;constructor(e){this.ctx=e}append(e,n){let r=j(e)+j(n);r>this.ctx.limits.maxOutputSize-this.totalBytes&&zo(`total output size exceeded (>${this.ctx.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size"),e&&this.stdoutChunks.push(e),n&&this.stderrChunks.push(n),this.totalBytes+=r}appendUnaccounted(e,n){this.ctx.executionScope.appendOutput("stdout",e,"control-flow"),this.ctx.executionScope.appendOutput("stderr",n,"control-flow"),this.append(e,n)}replace(e,n){this.stdoutChunks=[],this.stderrChunks=[],this.totalBytes=0,this.append(e,n)}get stdout(){return this.stdoutChunks.join("")}get stderr(){return this.stderrChunks.join("")}build(e){let n=this.stdout,r=this.stderr;return{stdout:n,stderr:r,exitCode:e,internalOutputAccounting:{stdout:j(n),stderr:j(r)}}}};async function $7(t,e,n){let r=0;try{for(let s of e){let i=await t.executeStatement(s);n.append(i.stdout,i.stderr),r=i.exitCode}}catch(s){if(Uf(s)||s instanceof tr||s instanceof Pe||s instanceof un||s instanceof v||s instanceof si)throw s.prependOutput(n.stdout,n.stderr),s;return n.appendUnaccounted("",`${Qe(s)}
|
|
2203
2203
|
`),n.build(1)}return n.build(r)}async function BL(t,e){return as(t,e.redirections,"",()=>zne(t,e))}async function zne(t,e){let n=new Ko(t);for(let r of e.clauses){let s=await P7(t,r.condition);if(n.append(s.stdout,s.stderr),s.exitCode===0)return $7(t,r.body,n)}return e.elseBody?$7(t,e.elseBody,n):n.build(0)}async function zL(t,e){return as(t,e.redirections,"",()=>Une(t,e))}async function Une(t,e){let n=new Ko(t),r=0,s=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return J(`bash: \`${e.variable}': not a valid identifier
|
|
2204
|
-
`);let i=[];if(e.words===null)i=(t.state.env.get("@")||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else try{for(let o of e.words){let a=await Qs(t,o);Kn(i,a.values,t.limits.maxArrayElements,"for-loop expansion")}}catch(o){if(o instanceof ri)return{stdout:"",stderr:o.stderr,exitCode:1};throw o}t.state.loopDepth++;try{for(let o of i){s++,s>t.limits.maxLoopIterations&&zo(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n.stdout,n.stderr),t.state.env.set(e.variable,o);try{for(let a of e.body){let l=await t.executeStatement(a);n.append(l.stdout,l.stderr),r=l.exitCode}}catch(a){let l=Nf(a,n.stdout,n.stderr,t.state.loopDepth);if(n.replace(l.stdout,l.stderr),l.exitCode!==void 0&&(r=yc(t,l.exitCode)),l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return n.build(l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return n.build(r)}async function UL(t,e){return as(t,e.redirections,"",()=>Wne(t,e))}async function Wne(t,e){let n=e.line;n!==void 0&&(t.state.currentLine=n);let r=new Ko(t),s=0,i=0;e.init&&await Xe(t,e.init.expression),t.state.loopDepth++;try{for(;i++,i>t.limits.maxLoopIterations&&zo(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r.stdout,r.stderr),!(e.condition&&(n!==void 0&&(t.state.currentLine=n),await Xe(t,e.condition.expression)===0));){try{for(let o of e.body){let a=await t.executeStatement(o);r.append(a.stdout,a.stderr),s=a.exitCode}}catch(o){let a=Nf(o,r.stdout,r.stderr,t.state.loopDepth);if(r.replace(a.stdout,a.stderr),a.exitCode!==void 0&&(s=yc(t,a.exitCode)),a.action==="break")break;if(a.action==="continue"){e.update&&await Xe(t,e.update.expression);continue}if(a.action==="error")return r.build(a.exitCode??1);throw a.error}e.update&&await Xe(t,e.update.expression)}}finally{t.state.loopDepth--}return r.build(s)}async function WL(t,e,n=""){return as(t,e.redirections,n,r=>jne(t,e,n,r))}async function jne(t,e,n,r){let s=new Ko(t),i=0,o=0,a=ML(r.stdin,n),l=t.state.groupStdin;a.owns&&(t.state.groupStdin=a.stdin),t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&zo(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=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);s.append(p.stdout,p.stderr),c=p.exitCode}}catch(h){if(h instanceof Jn){if(s.append(h.stdout,h.stderr),h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,t.state.inCondition=d,h;u=!0}else if(h instanceof er){if(s.append(h.stdout,h.stderr),h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,t.state.inCondition=d,h;f=!0}else throw t.state.inCondition=d,h}finally{t.state.inCondition=d}if((u||f)&&(i=yc(t,l1)),u)break;if(!f){if(c!==0)break;try{for(let h of e.body){let p=await t.executeStatement(h);s.append(p.stdout,p.stderr),i=p.exitCode}}catch(h){let p=Nf(h,s.stdout,s.stderr,t.state.loopDepth);if(s.replace(p.stdout,p.stderr),p.exitCode!==void 0&&(i=yc(t,p.exitCode)),p.action==="break")break;if(p.action==="continue")continue;if(p.action==="error")return s.build(p.exitCode??1);throw p.error}}}}finally{t.state.loopDepth--,a.owns&&(t.state.groupStdin=l)}return s.build(i)}async function jL(t,e,n=""){return as(t,e.redirections,n,r=>qne(t,e,n,r))}async function qne(t,e,n,r){let s=new Ko(t),i=0,o=0,a=ML(r.stdin,n),l=t.state.groupStdin;a.owns&&(t.state.groupStdin=a.stdin),t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&zo(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=await P7(t,e.condition);if(s.append(c.stdout,c.stderr),c.exitCode===0)break;try{for(let u of e.body){let f=await t.executeStatement(u);s.append(f.stdout,f.stderr),i=f.exitCode}}catch(u){let f=Nf(u,s.stdout,s.stderr,t.state.loopDepth);if(s.replace(f.stdout,f.stderr),f.exitCode!==void 0&&(i=yc(t,f.exitCode)),f.action==="break")break;if(f.action==="continue")continue;if(f.action==="error")return s.build(f.exitCode??1);throw f.error}}}finally{t.state.loopDepth--,a.owns&&(t.state.groupStdin=l)}return s.build(i)}async function qL(t,e){return as(t,e.redirections,"",()=>Vne(t,e))}async function Vne(t,e){let n=new Ko(t),r=0,s=await ot(t,e.word),i=!1;for(let o=0;o<e.items.length;o++){let a=e.items[o],l=i;if(!i)for(let c of a.patterns){let u=await ot(t,c);g$(c)&&(u=ss(u));let f=t.state.shoptOptions.nocasematch,d=t.state.shoptOptions.extglob;if(cc(s,u,f,d,t.limits.maxCallDepth)){l=!0;break}}if(l){let c=await $7(t,a.body,n);if(n.replace(c.stdout,c.stderr),r=c.exitCode,a.terminator===";;")break;a.terminator===";&"?i=!0:i=!1}else i=!1}return n.build(r)}X();function L7(t,e){if(t.parts.length!==1)return!1;let n=t.parts[0];return n.type!=="Literal"?!1:e.includes(n.value)}pe();co();X();async function VL(t,e,n){let r=e.timed?Sl():0,s="",i=
|
|
2204
|
+
`);let i=[];if(e.words===null)i=(t.state.env.get("@")||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else try{for(let o of e.words){let a=await Qs(t,o);Kn(i,a.values,t.limits.maxArrayElements,"for-loop expansion")}}catch(o){if(o instanceof ri)return{stdout:"",stderr:o.stderr,exitCode:1};throw o}t.state.loopDepth++;try{for(let o of i){s++,s>t.limits.maxLoopIterations&&zo(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n.stdout,n.stderr),t.state.env.set(e.variable,o);try{for(let a of e.body){let l=await t.executeStatement(a);n.append(l.stdout,l.stderr),r=l.exitCode}}catch(a){let l=Nf(a,n.stdout,n.stderr,t.state.loopDepth);if(n.replace(l.stdout,l.stderr),l.exitCode!==void 0&&(r=yc(t,l.exitCode)),l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return n.build(l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return n.build(r)}async function UL(t,e){return as(t,e.redirections,"",()=>Wne(t,e))}async function Wne(t,e){let n=e.line;n!==void 0&&(t.state.currentLine=n);let r=new Ko(t),s=0,i=0;e.init&&await Xe(t,e.init.expression),t.state.loopDepth++;try{for(;i++,i>t.limits.maxLoopIterations&&zo(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r.stdout,r.stderr),!(e.condition&&(n!==void 0&&(t.state.currentLine=n),await Xe(t,e.condition.expression)===0));){try{for(let o of e.body){let a=await t.executeStatement(o);r.append(a.stdout,a.stderr),s=a.exitCode}}catch(o){let a=Nf(o,r.stdout,r.stderr,t.state.loopDepth);if(r.replace(a.stdout,a.stderr),a.exitCode!==void 0&&(s=yc(t,a.exitCode)),a.action==="break")break;if(a.action==="continue"){e.update&&await Xe(t,e.update.expression);continue}if(a.action==="error")return r.build(a.exitCode??1);throw a.error}e.update&&await Xe(t,e.update.expression)}}finally{t.state.loopDepth--}return r.build(s)}async function WL(t,e,n=""){return as(t,e.redirections,n,r=>jne(t,e,n,r))}async function jne(t,e,n,r){let s=new Ko(t),i=0,o=0,a=ML(r.stdin,n),l=t.state.groupStdin;a.owns&&(t.state.groupStdin=a.stdin),t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&zo(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=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);s.append(p.stdout,p.stderr),c=p.exitCode}}catch(h){if(h instanceof Jn){if(s.append(h.stdout,h.stderr),h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,t.state.inCondition=d,h;u=!0}else if(h instanceof er){if(s.append(h.stdout,h.stderr),h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=s.stdout,h.stderr=s.stderr,t.state.inCondition=d,h;f=!0}else throw t.state.inCondition=d,h}finally{t.state.inCondition=d}if((u||f)&&(i=yc(t,l1)),u)break;if(!f){if(c!==0)break;try{for(let h of e.body){let p=await t.executeStatement(h);s.append(p.stdout,p.stderr),i=p.exitCode}}catch(h){let p=Nf(h,s.stdout,s.stderr,t.state.loopDepth);if(s.replace(p.stdout,p.stderr),p.exitCode!==void 0&&(i=yc(t,p.exitCode)),p.action==="break")break;if(p.action==="continue")continue;if(p.action==="error")return s.build(p.exitCode??1);throw p.error}}}}finally{t.state.loopDepth--,a.owns&&(t.state.groupStdin=l)}return s.build(i)}async function jL(t,e,n=""){return as(t,e.redirections,n,r=>qne(t,e,n,r))}async function qne(t,e,n,r){let s=new Ko(t),i=0,o=0,a=ML(r.stdin,n),l=t.state.groupStdin;a.owns&&(t.state.groupStdin=a.stdin),t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&zo(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=await P7(t,e.condition);if(s.append(c.stdout,c.stderr),c.exitCode===0)break;try{for(let u of e.body){let f=await t.executeStatement(u);s.append(f.stdout,f.stderr),i=f.exitCode}}catch(u){let f=Nf(u,s.stdout,s.stderr,t.state.loopDepth);if(s.replace(f.stdout,f.stderr),f.exitCode!==void 0&&(i=yc(t,f.exitCode)),f.action==="break")break;if(f.action==="continue")continue;if(f.action==="error")return s.build(f.exitCode??1);throw f.error}}}finally{t.state.loopDepth--,a.owns&&(t.state.groupStdin=l)}return s.build(i)}async function qL(t,e){return as(t,e.redirections,"",()=>Vne(t,e))}async function Vne(t,e){let n=new Ko(t),r=0,s=await ot(t,e.word),i=!1;for(let o=0;o<e.items.length;o++){let a=e.items[o],l=i;if(!i)for(let c of a.patterns){let u=await ot(t,c);g$(c)&&(u=ss(u));let f=t.state.shoptOptions.nocasematch,d=t.state.shoptOptions.extglob;if(cc(s,u,f,d,t.limits.maxCallDepth)){l=!0;break}}if(l){let c=await $7(t,a.body,n);if(n.replace(c.stdout,c.stderr),r=c.exitCode,a.terminator===";;")break;a.terminator===";&"?i=!0:i=!1}else i=!1}return n.build(r)}X();function L7(t,e){if(t.parts.length!==1)return!1;let n=t.parts[0];return n.type!=="Literal"?!1:e.includes(n.value)}pe();co();X();async function VL(t,e,n){let r=e.timed?Sl():0,s="",i=tt,o=0,a=[],l="",c=0,u=e.commands.length>1,f=t.state.lastArg,d=t.state.groupStdin,h=t.state.groupStdinSourceFd;for(let w=0;w<e.commands.length;w++){let b=e.commands[w],x=w===e.commands.length-1,S=w===0;u&&(t.state.lastArg="",t.state.groupStdin=S?d:void 0,t.state.groupStdinSourceFd=S?h:void 0);let E=u&&(!x||!t.state.shoptOptions.lastpipe),A=E?new Map(t.state.env):null,N=E?vs(t.state.arrays):null,I,T=t.executionScope.outputBytesUsed;try{t.state.commandCount=t.executionScope.chargeCommand(),I=await n(b,s)}catch($){if($ instanceof lr)I={stdout:$.stdout,stderr:$.stderr,exitCode:1};else if($ instanceof Pe&&e.commands.length>1)I={stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode};else if($ instanceof tr&&e.commands.length>1)I={stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode};else throw A&&(t.state.env=A,t.state.arrays=N??new Map),$}finally{u&&(S&&(d=t.state.groupStdin,h=t.state.groupStdinSourceFd),t.state.groupStdin=d,t.state.groupStdinSourceFd=h)}if(A&&(t.state.env=A,t.state.arrays=N??new Map),I=t.executionScope.accountResult(I,"pipeline",t.executionScope.outputBytesUsed-T),!x){let $=e.pipeStderr?.[w]??!1,C=I.internalOutputAccounting?.stdout??0,O=$?I.internalOutputAccounting?.stderr??0:0;JI(t.executionScope,C+O,"pipeline"),I={...I,internalOutputAccounting:{stdout:0,stderr:$?0:I.internalOutputAccounting?.stderr??0}}}a.push(I.exitCode),I.exitCode!==0&&(o=I.exitCode),x?i=I:(e.pipeStderr?.[w]??!1?s=vr(I.stderr)+ni(I):(s=ni(I),l+=I.stderr,c+=I.internalOutputAccounting?.stderr??0),i={stdout:"",stderr:"",exitCode:I.exitCode})}l&&(i={...i,stderr:l+i.stderr,internalOutputAccounting:{stdout:i.internalOutputAccounting?.stdout??0,stderr:c+(i.internalOutputAccounting?.stderr??0)}});let p=e.commands.length>1||e.commands.length===1&&e.commands[0].type==="SimpleCommand",m=i.internalPipeStatusOverride??a;if(p){an(t,"PIPESTATUS");for(let w=0;w<m.length;w++)Fe(t,"PIPESTATUS",w,String(m[w]))}if(t.state.options.pipefail&&o!==0&&(i={...i,exitCode:o}),e.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),e.timed){let b=(Sl()-r)/1e3,x=Math.floor(b/60),S=b%60,E;e.timePosix?E=`real ${b.toFixed(2)}
|
|
2205
2205
|
user 0.00
|
|
2206
2206
|
sys 0.00
|
|
2207
2207
|
`:E=`
|
|
@@ -2213,27 +2213,27 @@ sys 0m0.000s
|
|
|
2213
2213
|
`),o.build(1)}return f(),o.build(a)}async function KL(t,e,n,r,s){let i;try{i=await t.fs.readFile(e)}catch{return J(`bash: ${e}: No such file or directory
|
|
2214
2214
|
`,127)}if(i.startsWith("#!")){let l=i.indexOf(`
|
|
2215
2215
|
`);l!==-1&&(i=i.slice(l+1))}let o=t.state.loopDepth,a=D7(t.state);t.state.parentHasLoopContext=o>0,t.state.loopDepth=0,t.state.bashPid=t.state.nextVirtualPid++,r&&(t.state.groupStdin=r),t.state.currentSource=e,t.state.env.set("0",e),t.state.env.set("#",String(n.length)),t.state.env.set("@",n.join(" ")),t.state.env.set("*",n.join(" "));for(let l=0;l<n.length&&l<9;l++)t.state.env.set(String(l+1),n[l]);for(let l=n.length+1;l<=9;l++)t.state.env.delete(String(l));try{let c=new _e().parse(i),u=await s(c);return a(),u}catch(l){if(a(),l instanceof Pe)return ee(l.stdout,l.stderr,l.exitCode);if(l instanceof un||l instanceof v)throw l;if(l.name==="ParseException")return J(`bash: ${e}: ${l.message}
|
|
2216
|
-
`);throw l}}function Qne(t){throw new TypeError(`Unsupported command node: ${JSON.stringify(t)}`)}var Tf=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,executionScope:e.executionScope,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode,invokeTool:e.invokeTool}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||
|
|
2216
|
+
`);throw l}}function Qne(t){throw new TypeError(`Unsupported command node: ${JSON.stringify(t)}`)}var Tf=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,executionScope:e.executionScope,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode,invokeTool:e.invokeTool}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||nt.isInSandboxedContext())return;let n=`interpreter ${e} attempted outside defense context`;throw new Re(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:nt.getCurrentExecutionId()})}buildExportedEnv(){let e=this.ctx.state.exportedVars,n=this.ctx.state.tempExportedVars,r=new Set;if(e)for(let i of e)r.add(i);if(n)for(let i of n)r.add(i);if(r.size===0)return Object.create(null);let s=Object.create(null);for(let i of r){let o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(e){this.assertDefenseContext("execution");let n=0,r=new Ir(this.ctx.executionScope,"script");for(let s of e.statements)try{let i=await this.executeStatement(s);r.appendResult(i,F1(i)),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(i){if(i instanceof Pe||i instanceof un)throw i.prependOutput(r.stdout,r.stderr),i;if(i instanceof Cr)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:dn(this.ctx.state.env)};if(vc(i))throw r.prependTo(i),i;if(i instanceof tr)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:dn(this.ctx.state.env)};if(i instanceof nr)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:dn(this.ctx.state.env)};if(i instanceof lr)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:dn(this.ctx.state.env)};if(i instanceof dt){r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(i instanceof Xa){r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(i instanceof Jn||i instanceof er){if(this.ctx.state.loopDepth>0)throw i.prependOutput(r.stdout,r.stderr),i;r.append("stdout",i.stdout),r.append("stderr",i.stderr);continue}throw i instanceof Nn&&i.prependOutput(r.stdout,r.stderr),i}return{...r.build(n),env:dn(this.ctx.state.env)}}async executeUserScript(e,n,r=""){return KL(this.ctx,e,n,r,s=>this.executeScript(s))}async executeStatement(e){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new et;if(e.deferredError)throw new Pn(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return tt;this.ctx.state.errexitSafe=!1;let n=new Ir(this.ctx.executionScope,"statement");this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&n.append("stderr",`${e.sourceText}
|
|
2217
2217
|
`);let r=0,s=-1,i=!1;try{for(let l=0;l<e.pipelines.length;l++){let c=e.pipelines[l],u=l>0?e.operators[l-1]:null;if(u==="&&"&&r!==0||u==="||"&&r===0)continue;let f=await this.executePipeline(c);n.appendResult(f,F1(f)),r=f.exitCode,s=l,i=c.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set("?",String(r))}}catch(l){throw n.prependTo(l),l}let o=s<e.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||i||a,this.ctx.state.options.errexit&&r!==0&&s===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition&&!a){let l=new tr(r);throw l.prependOutput(n.stdout,n.stderr),l}return n.build(r)}async executePipeline(e){return VL(this.ctx,e,(n,r)=>this.executeCommand(n,r))}async executeCommand(e,n,r=!1){let s=p$(this.ctx),i;try{i=await this.executeCommandInner(e,n,r)}catch(a){throw await kS(this.ctx,s).catch(()=>{}),a}let o=await kS(this.ctx,s);return!o.stdout&&!o.stderr?i:{...i,stdout:o.stdout?ni(i)+o.stdout:i.stdout,stdoutKind:o.stdout?"bytes":i.stdoutKind,stderr:i.stderr+o.stderr}}async executeCommandInner(e,n,r){switch(this.assertDefenseContext("command"),this.ctx.coverage?.hit(`bash:cmd:${e.type}`),e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return BL(this.ctx,e);case"For":return zL(this.ctx,e);case"CStyleFor":return UL(this.ctx,e);case"While":return WL(this.ctx,e,n);case"Until":return jL(this.ctx,e,n);case"Case":return qL(this.ctx,e);case"Subshell":return this.executeSubshell(e,n,r);case"Group":return this.executeGroup(e,n,r);case"FunctionDef":return K$(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return Qne(e)}}async executeSimpleCommand(e,n){let r;try{return await this.executeSimpleCommandInner(e,n,s=>{r=s})}catch(s){if(r?.finish(),s instanceof ri)return J(s.stderr);throw s}}async executeSimpleCommandInner(e,n,r){if(e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.shoptOptions.expand_aliases&&e.name){let T=e,$=0;for(;;){let C=this.expandAlias(T);if(C===T)break;if($>=this.ctx.limits.maxCallDepth)throw new v(`alias expansion depth limit exceeded (${this.ctx.limits.maxCallDepth})`,"recursion");$++,T=C}this.aliasExpansionStack.clear(),T!==e&&(e=T)}this.ctx.state.expansionStderr="",this.ctx.state.lastSubstitutionExitCode=null;let s=await kL(this.ctx,e);if(s.error)return s.error;let i=s.tempAssignments,o=s.xtraceOutput,a=()=>{for(let[T,$]of i)$===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,$)};if(!e.name){if(e.redirections.length>0){let $=hc(this.ctx,e.redirections,H$);r($);let C=await $.prepare(n);if(C.error){if(a(),!C.errorCause)return $.finish(),C.error;try{return pc(C)}finally{$.finish()}}let O=ee("",o,Sm(this.ctx.state,e.redirections)),F=await Ho(this.ctx,O,e.redirections,C.targets,C.dupSources,C.standardRoutes);return $.finish(),F}this.ctx.state.lastArg="";let T=(this.ctx.state.expansionStderr||"")+o;return this.ctx.state.expansionStderr="",ee("",T,Sm(this.ctx.state,[]))}let l=e.name&&L7(e.name,["local","declare","typeset","export","readonly"]),c=Array.from(i.keys());if(c.length>0&&!l){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let T of c)this.ctx.state.tempExportedVars.add(T)}let u=await ot(this.ctx,e.name),f=[],d=[],h=(T,$)=>{if(f.length>=this.ctx.limits.maxArrayElements)throw new v(`expanded argument element limit exceeded (${this.ctx.limits.maxArrayElements})`,"array_elements");f.push(T),d.push($)};if(L7(e.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let T of e.args){let $=await C$(this.ctx,T);if($)h($,!0);else{let C=await k$(this.ctx,T);if(C!==null)h(C,!0);else{let O=await Qs(this.ctx,T);for(let F of O.values)h(F,O.quoted)}}}else for(let T of e.args){let $=await Qs(this.ctx,T);for(let C of $.values)h(C,$.quoted)}let m=e.name.parts.every(T=>T.type==="CommandSubstitution"||T.type==="ParameterExpansion"||T.type==="ArithmeticExpansion");!u&&m&&f.length>0&&(u=f.shift(),d.shift());let g=hc(this.ctx,e.redirections,u==="exec"?G$:xf);r(g);let y=await g.prepare(n);if(y.error)return a(),y.errorCause?pc(y):(g.finish(),y.error);let w=y.stdinSourceFd,b=y.stdin!==void 0;if(y.stdin!==void 0&&(n=y.stdin),!u)return m?(g.finish(),ee("","",Sm(this.ctx.state,e.redirections))):(g.finish(),J(`bash: : command not found
|
|
2218
|
-
`,127));if(u==="exec"&&(f.length===0||f[0]==="--")){for(let[T,$]of i)$===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,$);if(this.ctx.state.tempExportedVars)for(let T of i.keys())this.ctx.state.tempExportedVars.delete(T);return g.finish(),
|
|
2218
|
+
`,127));if(u==="exec"&&(f.length===0||f[0]==="--")){for(let[T,$]of i)$===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,$);if(this.ctx.state.tempExportedVars)for(let T of i.keys())this.ctx.state.tempExportedVars.delete(T);return g.finish(),tt}if(this.ctx.state.extraArgs){let T=this.ctx.state.extraArgs;this.ctx.state.extraArgs=void 0;for(let $ of T)h($,!0)}let x=await vL(this.ctx,u,f);i.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(i)));let S,E=null;try{S=await this.runCommand(u,f,d,n,!1,!1,w,b)}catch(T){if(T instanceof Jn||T instanceof er)E=T,S=tt;else throw T}w>=0&&u!=="read"&&qo(this.ctx,w,S.internalStdinConsumed??0);let A=o+x;if(A&&(S={...S,stderr:A+S.stderr}),S=await Ho(this.ctx,S,e.redirections,y.targets,y.dupSources,y.standardRoutes,S.internalProducerCommand??u,S.internalProducerOmitsShellPrefix),g.finish(),E)throw E;if(f.length>0){let T=f[f.length-1];if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(T)){let $=T.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);$&&(T=$[1])}this.ctx.state.lastArg=T}else this.ctx.state.lastArg=u;let N=iR(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!N)for(let[T,$]of i)this.ctx.state.fullyUnsetLocals?.has(T)||($===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,$));if(this.ctx.state.tempExportedVars)for(let T of i.keys())this.ctx.state.tempExportedVars.delete(T);return i.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(S={...S,stderr:this.ctx.state.expansionStderr+S.stderr},this.ctx.state.expansionStderr=""),S}async runCommand(e,n,r,s,i=!1,o=!1,a=-1,l=!1){let c={ctx:this.ctx,runCommand:(d,h,p,m,g,y,w,b)=>this.runCommand(d,h,p,m,g,y,w,b),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(d,h,p)=>this.executeUserScript(d,h,p)},u=await DL(c,e,n,r,s,i,o,a,l);return u!==null?u.internalProducerCommand===void 0?{...u,internalProducerCommand:e}:u:{...await _L(c,e,n,s,o),internalProducerCommand:e}}aliasExpansionStack=new Set;expandAlias(e){return QR({env:this.ctx.state.env,limits:this.ctx.limits},e,this.aliasExpansionStack)}async findCommandInPath(e){return sm(this.ctx,e)}async executeSubshell(e,n="",r=!1){return HL(this.ctx,e,n,s=>this.executeStatement(s),r)}async executeGroup(e,n="",r=!1){return GL(this.ctx,e,n,s=>this.executeStatement(s),r)}async executeArithmeticCommand(e){return e.line!==void 0&&(this.ctx.state.currentLine=e.line),as(this.ctx,e.redirections,"",async()=>{try{let n=await Xe(this.ctx,e.expression.expression),r=pn(n!==0);return this.ctx.state.expansionStderr&&(r={...r,stderr:this.ctx.state.expansionStderr+r.stderr},this.ctx.state.expansionStderr=""),r}catch(n){return J(`bash: arithmetic expression: ${n.message}
|
|
2219
2219
|
`)}})}async executeConditionalCommand(e){return e.line!==void 0&&(this.ctx.state.currentLine=e.line),as(this.ctx,e.redirections,"",async()=>{try{let n=await Uo(this.ctx,e.expression),r=pn(n);return this.ctx.state.expansionStderr&&(r={...r,stderr:this.ctx.state.expansionStderr+r.stderr},this.ctx.state.expansionStderr=""),r}catch(n){let r=n instanceof dt?1:2;return J(`bash: conditional expression: ${n.message}
|
|
2220
2220
|
`,r)}})}};Qa();cn();Os();function _7(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function Jne(t){let e=_7(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}var ere=3;function ZL(t){let e=t;for(let n=0;n<ere;n++){if(e.includes("\\")||e.includes(";")||/%(?![0-9a-f]{2})/i.test(e))return!0;let r=e.toLowerCase();if(r.includes("%2f")||r.includes("%2e")||r.includes("%5c")||r.includes("%3b"))return!0;let s;try{s=decodeURIComponent(e)}catch{return!0}if(s===e)return!1;e=s}return e.includes("%")}function tre(t,e){return e==="/"||e===""?!0:e.endsWith("/")?t.startsWith(e):t===e||t.startsWith(`${e}/`)}function M7(t,e){let n=_7(t);if(!n)return!1;let r=Jne(e);return!r||n.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&ZL(n.pathname)?!1:tre(n.pathname,r.pathPrefix)}function XL(t){return typeof t=="string"?t:t.url}function YL(t,e){return!e||e.length===0?!1:e.some(n=>M7(t,XL(n)))}function B7(t){let e=nre(t);if(e==="localhost"||e.endsWith(".localhost"))return!0;let n=QL(e);if(n)return c1(n);let r=sre(e);return r?ire(r):!1}function nre(t){let e=t.trim().toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function rre(t){if(!t)return null;let e=10,n=t;if(n.startsWith("0x")||n.startsWith("0X")?(e=16,n=n.slice(2)):n.length>1&&n.startsWith("0")&&(e=8),!n||e===16&&!/^[0-9a-fA-F]+$/.test(n)||e===10&&!/^\d+$/.test(n)||e===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,e);return!Number.isFinite(r)||r<0?null:r}function QL(t){let e=t.split(".");if(e.length===0||e.length>4)return null;let n=e.map(l=>rre(l));if(n.some(l=>l===null))return null;let r=n;if(e.length===1){let l=r[0];return l>4294967295?null:[l>>>24&255,l>>>16&255,l>>>8&255,l&255]}if(e.length===2){let[l,c]=r;return l>255||c>16777215?null:[l,c>>>16&255,c>>>8&255,c&255]}if(e.length===3){let[l,c,u]=r;return l>255||c>255||u>65535?null:[l,c,u>>>8&255,u&255]}let[s,i,o,a]=r;return s>255||i>255||o>255||a>255?null:[s,i,o,a]}function sre(t){let e=t,n=null;if(e.includes(".")){let m=e.lastIndexOf(":");if(m<0)return null;let g=e.slice(m+1),y=QL(g);if(!y)return null;n=y,e=e.slice(0,m)}let r=e.includes("::")?e.split("::").length-1:0;if(r>1)return null;let[s,i]=e.split("::"),o=s?s.split(":").filter(Boolean):[],a=i?i.split(":").filter(Boolean):[],l=m=>/^[0-9a-f]{1,4}$/i.test(m)?Number.parseInt(m,16):null,c=o.map(l),u=a.map(l);if(c.some(m=>m===null)||u.some(m=>m===null))return null;let f=n?2:0,d=c.length+u.length+f,h=0;if(r===1){if(h=8-d,h<0)return null}else if(d!==8)return null;let p=[...c,...new Array(h).fill(0),...u];return n&&(p.push(n[0]<<8|n[1]),p.push(n[2]<<8|n[3])),p.length===8?p:null}function c1(t){let[e,n]=t;return e===127||e===10||e===172&&n>=16&&n<=31||e===192&&n===168||e===169&&n===254||e===0||e===100&&n>=64&&n<=127||e===198&&(n===18||n===19)||e===192&&n===0&&t[2]===0||e===192&&n===0&&t[2]===2||e===198&&n===51&&t[2]===100||e===203&&n===0&&t[2]===113||e>=240}function ire(t){if(t.every(s=>s===0)||t.slice(0,7).every(s=>s===0)&&t[7]===1||(t[0]&65472)===65152||(t[0]&65024)===64512)return!0;if(t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===65535){let s=[t[6]>>>8&255,t[6]&255,t[7]>>>8&255,t[7]&255];return c1(s)}if(t[0]===8193&&t[1]===3512)return!0;if(t[0]===100&&t[1]===65435&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0){let s=[t[6]>>>8&255,t[6]&255,t[7]>>>8&255,t[7]&255];return c1(s)}if(t[0]===100&&t[1]===65435&&t[2]===1)return!0;if(t[0]===8194){let s=[t[1]>>>8&255,t[1]&255,t[2]>>>8&255,t[2]&255];return c1(s)}return!1}function JL(t){let e=[];for(let n of t){if(typeof n!="string"&&(n===null||typeof n!="object"||!("url"in n)||typeof n.url!="string")){e.push('Invalid allow-list entry: must be a string URL or an object with a "url" string property');continue}let r=XL(n);if(!_7(r)){e.push(`Invalid URL in allow-list: "${r}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let i=new URL(r);if(i.protocol!=="http:"&&i.protocol!=="https:"){e.push(`Only http and https URLs are allowed in allow-list: "${r}"`);continue}if(!i.hostname){e.push(`Allow-list entry must include a hostname: "${r}"`);continue}if(i.pathname!=="/"&&i.pathname!==""&&ZL(i.pathname)){e.push(`Allow-list entry contains ambiguous path separators: "${r}"`);continue}(i.search||i.hash)&&e.push(`Query strings and fragments are ignored in allow-list entries: "${r}"`)}return e}var ls=class extends Error{constructor(e,n){let r=n??"URL not in allow-list";super(`Network access denied: ${r}: ${e}`),this.name="NetworkAccessDeniedError"}},Zo=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},ki=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},u1=class extends Error{constructor(e,n){super(`HTTP method '${e}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}},Va=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name="ResponseTooLargeError"}};var ore=20,are=3e4,lre=10485760,cre=["GET","HEAD"],Of;typeof __BROWSER__<"u"&&__BROWSER__?Of=null:(Of=import("guarded-fetch"),Of.catch(()=>{}));var ure=new Set(["GET","HEAD","OPTIONS"]),fre=new Set([301,302,303,307,308]);function If(t){return t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError")}function dre(t){if(t?.aborted)throw If(t)}function U7(t){let e=t.allowedUrlPrefixes??[];if(t._dnsResolve)throw new Error("NetworkConfig._dnsResolve is no longer supported: DNS resolution is performed by guarded-fetch and cannot be overridden");if(t._createConnectionOwner)throw new Error("NetworkConfig._createConnectionOwner is no longer supported: connect-time IP pinning is performed by guarded-fetch and cannot be overridden");let n=t._fetch;if(!t.dangerouslyAllowFullInternetAccess){let x=JL(e);if(x.length>0)throw new Error(`Invalid network allow-list:
|
|
2221
2221
|
${x.join(`
|
|
2222
|
-
`)}`)}let r=[];for(let x of e)typeof x=="object"&&x.transform&&x.transform.length>0&&r.push(x);function s(x){if(r.length===0)return null;let S=null;for(let E of r)if(M7(x,E.url)&&E.transform){S||(S=new Headers);for(let A of E.transform)for(let[N,I]of Object.entries(A.headers))S.set(N,I)}return S}if(t.maxRedirects!==void 0&&(!Number.isSafeInteger(t.maxRedirects)||t.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let i=t.maxRedirects??ore,o=t.timeoutMs??are,a=t.maxResponseSize??lre,l=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??cre,c=t.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),u=[];for(let x of e){let S=typeof x=="string"?x:x.url;try{u.push(new URL(S).hostname)}catch{}}function f(x){try{return new URL(x).hostname||"localhost.invalid"}catch{return"localhost.invalid"}}function d(x){return t.dangerouslyAllowFullInternetAccess?c?{allowedHosts:void 0,skipSsrfCheckForAllowedHosts:void 0}:{allowedHosts:[f(x)],skipSsrfCheckForAllowedHosts:!0}:{allowedHosts:u,skipSsrfCheckForAllowedHosts:!c}}function h(x){try{return B7(new URL(x).hostname)}catch{return!1}}async function p(x,S){let E={method:S.method,headers:S.headers,signal:S.signal,redirect:"manual"};return S.body!==void 0&&(E.body=S.body),await(n??globalThis.fetch)(x,E)}function m(x){if(!t.dangerouslyAllowFullInternetAccess&&!YL(x,e))throw new ls(x)}function g(x){if(!c)return;let S;try{S=new URL(x)}catch{throw new ls(x,"invalid URL")}if(B7(S.hostname))throw new ls(x,"private/loopback IP address blocked")}function y(x){if(t.dangerouslyAllowFullInternetAccess)return;let S=x.toUpperCase();if(!l.includes(S))throw new u1(S,l)}function w(x,S,E,A){if(!E.isGuardedFetchError(x))return x;let N=x,{onRedirectHop:I,subReason:T}=A;switch(N.code){case"host_not_allowed":case"protocol_not_allowed":return I?new ki(S):new ls(S);case"hostname_unsafe":return I?new ki(S):new ls(S,T==="dns_resolution_failed"?"DNS resolution failed for private IP check":"hostname resolves to private/loopback IP address");case"redirect_to_unsafe_host":return new ki(S);case"too_many_redirects":return new Zo(i);case"response_too_large":return new Va(a);default:return x}}async function b(x,S={}){let E=S.method?.toUpperCase()??"GET",A=S.followRedirects??!0;if(S.maxRedirects!==void 0&&(!Number.isSafeInteger(S.maxRedirects)||S.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let N=S.maxRedirects??i,I=Math.min(i,N),T=S.timeoutMs!==void 0?Math.min(S.timeoutMs,o):o,$=new AbortController,C=Ti(()=>$.abort(new DOMException("The operation was aborted","AbortError")),T),O=Ya(S.signal,$.signal);try{m(x),g(x),y(E);let F=Of?await Of:null,R=x,_=0,U=[],B=E,W=S.body,M=S.headers,Y=!1;for(;;){dre(O.signal);let q=await
|
|
2222
|
+
`)}`)}let r=[];for(let x of e)typeof x=="object"&&x.transform&&x.transform.length>0&&r.push(x);function s(x){if(r.length===0)return null;let S=null;for(let E of r)if(M7(x,E.url)&&E.transform){S||(S=new Headers);for(let A of E.transform)for(let[N,I]of Object.entries(A.headers))S.set(N,I)}return S}if(t.maxRedirects!==void 0&&(!Number.isSafeInteger(t.maxRedirects)||t.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let i=t.maxRedirects??ore,o=t.timeoutMs??are,a=t.maxResponseSize??lre,l=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??cre,c=t.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),u=[];for(let x of e){let S=typeof x=="string"?x:x.url;try{u.push(new URL(S).hostname)}catch{}}function f(x){try{return new URL(x).hostname||"localhost.invalid"}catch{return"localhost.invalid"}}function d(x){return t.dangerouslyAllowFullInternetAccess?c?{allowedHosts:void 0,skipSsrfCheckForAllowedHosts:void 0}:{allowedHosts:[f(x)],skipSsrfCheckForAllowedHosts:!0}:{allowedHosts:u,skipSsrfCheckForAllowedHosts:!c}}function h(x){try{return B7(new URL(x).hostname)}catch{return!1}}async function p(x,S){let E={method:S.method,headers:S.headers,signal:S.signal,redirect:"manual"};return S.body!==void 0&&(E.body=S.body),await(n??globalThis.fetch)(x,E)}function m(x){if(!t.dangerouslyAllowFullInternetAccess&&!YL(x,e))throw new ls(x)}function g(x){if(!c)return;let S;try{S=new URL(x)}catch{throw new ls(x,"invalid URL")}if(B7(S.hostname))throw new ls(x,"private/loopback IP address blocked")}function y(x){if(t.dangerouslyAllowFullInternetAccess)return;let S=x.toUpperCase();if(!l.includes(S))throw new u1(S,l)}function w(x,S,E,A){if(!E.isGuardedFetchError(x))return x;let N=x,{onRedirectHop:I,subReason:T}=A;switch(N.code){case"host_not_allowed":case"protocol_not_allowed":return I?new ki(S):new ls(S);case"hostname_unsafe":return I?new ki(S):new ls(S,T==="dns_resolution_failed"?"DNS resolution failed for private IP check":"hostname resolves to private/loopback IP address");case"redirect_to_unsafe_host":return new ki(S);case"too_many_redirects":return new Zo(i);case"response_too_large":return new Va(a);default:return x}}async function b(x,S={}){let E=S.method?.toUpperCase()??"GET",A=S.followRedirects??!0;if(S.maxRedirects!==void 0&&(!Number.isSafeInteger(S.maxRedirects)||S.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let N=S.maxRedirects??i,I=Math.min(i,N),T=S.timeoutMs!==void 0?Math.min(S.timeoutMs,o):o,$=new AbortController,C=Ti(()=>$.abort(new DOMException("The operation was aborted","AbortError")),T),O=Ya(S.signal,$.signal);try{m(x),g(x),y(E);let F=Of?await Of:null,R=x,_=0,U=[],B=E,W=S.body,M=S.headers,Y=!1;for(;;){dre(O.signal);let q=await nt.runTrustedAsync(async()=>{let H=M;if(Y&&H){let oe=H instanceof Headers?new Headers(H):new Headers(H);oe.delete("authorization"),oe.delete("cookie"),H=oe}let re=s(R),se=pre(H,re),de={method:B,headers:se,signal:O.signal,followRedirects:!1,timeoutMs:T,sanitizeHeaders:!1};if(W&&!ure.has(B)&&(de.body=W),Object.assign(de,d(R)),!F||h(R)){if(c)throw new ls(R,"DNS pinning unavailable for private IP enforcement");return await p(R,de)}c?n&&(de.fetch=n):(de.fetch=n??globalThis.fetch,de.dispatcher=null);let Ie;de.onUrlBlocked=oe=>{Ie=oe.subReason};try{return await F.guardedFetch(R,de)}catch(oe){throw w(oe,R,F,{onRedirectHop:_>0,subReason:Ie})}});if(fre.has(q.status)&&A){let H=q.headers.get("location");if(!H)return await eF(q,R,a,O.signal,U);U.push({status:q.status,statusText:q.statusText,headers:tF(q.headers)});let re=new URL(H,R).href;await z7(hre(q),O.signal);try{m(re),g(re)}catch(Ie){throw O.signal?.aborted?If(O.signal):Ie instanceof ls?new ki(re):Ie}let se=q.status;if(((se===301||se===302)&&B==="POST"||se===303&&B!=="GET"&&B!=="HEAD")&&(B="GET",W=void 0,y(B)),new URL(re).origin!==new URL(R).origin&&(Y=!0),_++,_>I)throw new Zo(I);R=re;continue}return await eF(q,R,a,O.signal,U)}}finally{Hr(C),O.cleanup()}}return b}async function z7(t,e){if(!e)return t;if(e.aborted)throw t.catch(()=>{}),If(e);let n,r=new Promise((s,i)=>{n=()=>i(If(e)),e.addEventListener("abort",n,{once:!0})});try{return await Promise.race([t,r])}finally{n&&e.removeEventListener("abort",n)}}async function hre(t){t.body&&!t.body.locked&&await t.body.cancel()}function pre(t,e){if(!t&&!e)return;if(!e)return t;let n=t instanceof Headers?new Headers(t):new Headers(t);for(let[r,s]of e)n.set(r,s);return n}function tF(t){let e=Object.create(null);return t.forEach((n,r)=>{e[r.toLowerCase()]=n}),e}async function eF(t,e,n,r,s){let i=tF(t.headers);if(n>0){let l=t.headers.get("content-length");if(l){let c=parseInt(l,10);if(!Number.isNaN(c)&&c>n)throw new Va(n)}}let o;if(n>0&&t.body){let l=t.body.getReader(),c=[],u=0;try{for(;;){let{done:d,value:h}=await z7(l.read(),r);if(d)break;if(h){if(u+=h.byteLength,u>n)throw await l.cancel(),new Va(n);c.push(h)}}}catch(d){throw r?.aborted&&await l.cancel(If(r)).catch(()=>{}),d}o=new Uint8Array(u);let f=0;for(let d of c)o.set(d,f),f+=d.byteLength}else{let l=await z7(t.arrayBuffer(),r);if(n>0&&l.byteLength>n)throw new Va(n);o=new Uint8Array(l)}let a={status:t.status,statusText:t.statusText,headers:i,body:o,url:e};return s&&s.length>0&&(a.redirectChain=s),a}cn();Qt();X();function wc(t,e){if(t.length>e||j(t)>e)throw new v(`script input size limit exceeded (${e} bytes)`,"string_length")}var Xo=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;abortOnUnresolvedCommands=!1;invokeToolFn;transformPlugins=[];state;constructor(e={}){if(this.limits=Jp({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}},e.executionLimitProfile),e.fs&&e.files)throw new Error("Bash: options.files is ignored when options.fs is provided; write the files into your filesystem directly or drop options.fs");let n=e.fs??new ir(e.files,{maxTotalBytes:this.limits.maxFileSystemBytes});this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
2223
2223
|
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(e.env??{})]);if(e.fetch?this.secureFetch=e.fetch:e.network&&(this.secureFetch=U7(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.defenseInDepthConfig=e.defenseInDepth??!0,this.abortOnUnresolvedCommands=e.abortOnUnresolvedCommands??!1,this.coverageWriter=e.coverage,this.state={env:s,arrays:new Map,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastSubstitutionExitCode:null,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:e.processInfo?.pid??1,virtualPpid:e.processInfo?.ppid??0,virtualUid:e.processInfo?.uid??1e3,virtualGid:e.processInfo?.gid??1e3,bashPid:e.processInfo?.pid??1,nextVirtualPid:(e.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(e.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",_E(this.state.options)),this.state.env.set("BASHOPTS",ME(this.state.shoptOptions)),nR(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&(n instanceof ir||n instanceof Wr))try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of _I(e.commands))this.registerBundledCommand(o);if(e.fetch||e.network)for(let o of MI())this.registerBundledCommand(o);if(e.python)for(let o of zI())this.registerBundledCommand(o);let i=typeof e.javascript=="object"?e.javascript:Object.create(null);if(e.javascript||i.invokeTool){for(let o of WI())this.registerBundledCommand(o);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(e.customCommands)for(let o of e.customCommands)if(KI(o)){let a=XI(o);this.registerCommandInternal(a,!0)}else this.registerCommandInternal(o,!0)}registerCommand(e){this.registerCommandInternal(e,!0)}registerBundledCommand(e){this.registerCommandInternal(e,!1)}registerCommandInternal(e,n,r=n?e.trusted??!0:e.trusted){let s=this.commands.get(e.name),i=n?s?.internalOriginalCommand??(s&&!s.internalIsExtension?s:void 0):void 0,o={name:e.name,trusted:r,internalIsExtension:n,internalOriginalCommand:i,handlesOwnVersion:e.handlesOwnVersion,execute:(l,c)=>e.execute(l,c)};this.commands.set(e.name,o);let a=this.fs;if(typeof a.writeFileSync=="function"){let l=`#!/bin/bash
|
|
2224
2224
|
# Built-in command: ${e.name}
|
|
2225
2225
|
`;try{a.writeFileSync(`/bin/${e.name}`,l)}catch{}try{a.writeFileSync(`/usr/bin/${e.name}`,l)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e.stdout=nF(e.stdout),e.stderr=nF(e.stderr),e}async exec(e,n){let r=new em(this.limits,n?.signal,this.abortOnUnresolvedCommands),s;try{s=await this.execInScope(e,n,r,0,n?.signal,!1,!1)}catch(o){try{await r.close()}catch{}throw o}let i=s;try{await r.close()}catch{i={...s,stderr:`${s.stderr}bash: execution cleanup failed
|
|
2226
|
-
`,exitCode:126}}return i.unresolvedCommands=r.unresolvedCommandNames,e.trim()?this.logResult(i):i}async execInScope(e,n,r,s,i,o=!1,a=!0){let l=f=>a?this.logResult(f):f,c=Ya(i,n?.signal),u=n?{...n,signal:c.signal}:{signal:c.signal};try{if(r.assertExecDepth(s),wc(e,this.limits.maxSourceBytes),!e.trim())return{stdout:"",stderr:"",exitCode:0,env:Tr(this.state.env,u.env)};this.logger?.info("exec",{command:e});let f=u.cwd??this.state.cwd,d,h=f;if(u.cwd)if(u.env&&"PWD"in u.env)d=u.env.PWD;else if(u.env&&!("PWD"in u.env))try{d=await this.fs.realpath(f),h=d}catch{d=f}else d=f;let p=u.replaceEnv?new Map:new Map(this.state.env);if(u.env)for(let[b,x]of Object.entries(u.env))p.set(b,x);d!==void 0&&p.set("PWD",d);let m={...this.state,env:p,arrays:u.replaceEnv?new Map:vs(this.state.arrays),cwd:h,previousDir:u.env?.OLDPWD??this.state.previousDir,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:yre(u.stdin,u.stdinKind,this.limits.maxInputBytes,this.limits.maxStringLength,r,o),signal:u.signal,extraArgs:u.args},g=e;u.rawScript||(g=W7(e));let y=this.defenseInDepthConfig?
|
|
2226
|
+
`,exitCode:126}}return i.unresolvedCommands=r.unresolvedCommandNames,e.trim()?this.logResult(i):i}async execInScope(e,n,r,s,i,o=!1,a=!0){let l=f=>a?this.logResult(f):f,c=Ya(i,n?.signal),u=n?{...n,signal:c.signal}:{signal:c.signal};try{if(r.assertExecDepth(s),wc(e,this.limits.maxSourceBytes),!e.trim())return{stdout:"",stderr:"",exitCode:0,env:Tr(this.state.env,u.env)};this.logger?.info("exec",{command:e});let f=u.cwd??this.state.cwd,d,h=f;if(u.cwd)if(u.env&&"PWD"in u.env)d=u.env.PWD;else if(u.env&&!("PWD"in u.env))try{d=await this.fs.realpath(f),h=d}catch{d=f}else d=f;let p=u.replaceEnv?new Map:new Map(this.state.env);if(u.env)for(let[b,x]of Object.entries(u.env))p.set(b,x);d!==void 0&&p.set("PWD",d);let m={...this.state,env:p,arrays:u.replaceEnv?new Map:vs(this.state.arrays),cwd:h,previousDir:u.env?.OLDPWD??this.state.previousDir,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:yre(u.stdin,u.stdinKind,this.limits.maxInputBytes,this.limits.maxStringLength,r,o),signal:u.signal,extraArgs:u.args},g=e;u.rawScript||(g=W7(e));let y=this.defenseInDepthConfig?nt.getInstance(this.defenseInDepthConfig):null,w=y?.activate();try{let b=async()=>{let x=or(g,{maxHeredocSize:this.limits.maxHeredocSize}),S;if(this.transformPlugins.length>0){let T=Object.create(null);for(let $ of this.transformPlugins){let C=$.transform({ast:x,metadata:T});x=C.ast,C.metadata&&(T=Di(T,C.metadata))}S=T}let E={fs:this.fs,commands:this.commands,limits:this.limits,executionScope:r,exec:(T,$,C=!1)=>this.execInScope(T,$,r,s+1,u.signal,C),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:y?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},I=await new Tf(E,m).executeScript(x);return S&&(I.metadata=S),l(I)};return w?await w.run(b):await b()}catch(b){if(b instanceof Pe)return l({stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,internalOutputAccounting:b.internalOutputAccounting,env:Tr(this.state.env,u.env)});if(b instanceof un){if(s>0)throw b;return l({stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,internalOutputAccounting:b.internalOutputAccounting,env:Tr(this.state.env,u.env)})}if(b instanceof Cr)return l({stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,env:Tr(this.state.env,u.env)});if(b instanceof dt)return l({stdout:b.stdout,stderr:b.stderr,exitCode:1,env:Tr(this.state.env,u.env)});if(b instanceof et)return l({stdout:b.stdout,stderr:b.stderr,exitCode:124,env:Tr(this.state.env,u.env)});if(b instanceof v)return l({stdout:b.stdout,stderr:Be(b.stderr),exitCode:v.EXIT_CODE,internalOutputAccounting:b.internalOutputAccounting,env:Tr(this.state.env,u.env)});if(b instanceof Re)return l({stdout:"",stderr:`bash: security violation: ${Be(b.message)}
|
|
2227
2227
|
`,exitCode:1,env:Tr(this.state.env,u.env)});if(b.name==="ParseException")return l({stdout:"",stderr:`bash: syntax error: ${Be(b.message)}
|
|
2228
2228
|
`,exitCode:2,env:Tr(this.state.env,u.env)});if(b instanceof rs)return l({stdout:"",stderr:`bash: ${Be(b.message)}
|
|
2229
2229
|
`,exitCode:2,env:Tr(this.state.env,u.env)});if(b instanceof RangeError)return l({stdout:"",stderr:`bash: ${Be(b.message)}
|
|
2230
|
-
`,exitCode:1,env:Tr(this.state.env,u.env)});throw b}finally{w?.deactivate()}}catch(f){if(f instanceof
|
|
2230
|
+
`,exitCode:1,env:Tr(this.state.env,u.env)});throw b}finally{w?.deactivate()}}catch(f){if(f instanceof et)return l({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:Tr(this.state.env,u.env)});if(f instanceof v)return l({stdout:f.stdout,stderr:Be(f.stderr),exitCode:v.EXIT_CODE,internalOutputAccounting:f.internalOutputAccounting,env:Tr(this.state.env,u.env)});throw f}finally{c.cleanup()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),n)}getCwd(){return this.state.cwd}getEnv(){return dn(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){wc(e,this.limits.maxSourceBytes);let n=W7(e),r=or(n,{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let i of this.transformPlugins){let o=i.transform({ast:r,metadata:s});r=o.ast,o.metadata&&(s=Di(s,o.metadata))}return{script:sc(r),ast:r,metadata:s}}async analyzeCommands(e){wc(e,this.limits.maxSourceBytes);let n=or(W7(e),{maxHeredocSize:this.limits.maxHeredocSize}),{commands:r,definedFunctions:s,definedAliases:i}=tm(n),o=[];for(let a of r)s.has(a)||i.has(a)||await this.resolvesCommandForAnalysis(a)||o.push(a);return{commands:r,unresolved:o}}async resolvesCommandForAnalysis(e){if((cf.has(e)||Bs.has(e))&&!fw.has(e)||this.state.functions.has(e))return!0;let n=await rm({fs:this.fs,state:{...this.state,hashTable:new Map},commands:this.commands},e);return n!==null&&!("error"in n)}};function mre(t,e){let n=e;for(let r=0;r<t.length;r++){let s=t[r];if(n==="single")s==="'"&&(n="none");else if(n==="double")s==="\\"?r++:s==='"'&&(n="none");else if(s==="'")n="single";else if(s==='"')n="double";else if(s==="\\")r++;else if(s==="#"&&(r===0||/\s/.test(t[r-1])))break}return n}function W7(t){let e=t.split(`
|
|
2231
2231
|
`),n=[],r=[],s="none";for(let i=0;i<e.length;i++){let o=e[i];if(r.length>0){let u=r[r.length-1];if((u.stripTabs?o.replace(/^\t+/,""):o)===u.delimiter){n.push(o.trimStart()),r.pop();continue}n.push(o);continue}let a=s,l=a==="none"?o.trimStart():o;if(n.push(l),s=mre(o,a),a!=="none")continue;let c=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let u of l.matchAll(c)){let f=u[1]==="-",d=u[3];r.push({delimiter:d,stripTabs:f})}}return n.join(`
|
|
2232
|
-
`)}var gre=new TextDecoder("utf-8",{fatal:!0});function nF(t){if(!t)return t;let e=!1;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s>255)return t;s>127&&(e=!0)}if(!e)return t;let n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);try{return gre.decode(n)}catch{return t}}function yre(t,e,n,r,s,i){if(t===void 0)return;let o=e==="bytes"?t.length:j(t);if(o>n||o>r)throw new v(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),e==="bytes"?t:vr(t)}var yn=jt(require("node:fs"),1),f1=jt(require("node:path"),1);bn();function bc(t){return yn.realpathSync(t)}function j7(t){yn.rmSync(t,{recursive:!0,force:!0})}function sF(t,e){let n;try{n=yn.lstatSync(t)}catch{return!1}return e?!n.isDirectory():n.isDirectory()}function rF(t,e){sF(t,e)&&yn.rmSync(t,{recursive:!0,force:!0})}function q7(t,e){if(e.nodeType==="directory"){rF(t,!0),yn.mkdirSync(t,{recursive:!0}),process.platform!=="win32"&&yn.chmodSync(t,e.mode),yn.utimesSync(t,e.mtime,e.mtime);return}if(yn.mkdirSync(f1.dirname(t),{recursive:!0}),e.nodeType==="symlink"){yn.rmSync(t,{force:!0,recursive:!0}),yn.symlinkSync(new TextDecoder().decode(e.content),t);return}if(e.metadataOnly&&sF(t,!1))throw new D("EINVAL",`metadata-only entry over a different on-disk type: '${t}'`);e.metadataOnly||(rF(t,!1),yn.writeFileSync(t,e.content)),process.platform!=="win32"&&yn.chmodSync(t,e.mode),yn.utimesSync(t,e.mtime,e.mtime)}function Rf(t){for(let r of[...t.deletions,...t.writes.map(s=>s.path)])if(f1.resolve(r)!==r)throw new D("EINVAL",`change-set path is not normalized: '${r}'`);let e=[...t.deletions].sort((r,s)=>s.length-r.length||(r<s?-1:r>s?1:0));for(let r of e)j7(r);let n=[...t.writes].sort((r,s)=>r.path.length-s.path.length||(r.path<s.path?-1:r.path>s.path?1:0));for(let{path:r,...s}of n)q7(r,s)}var sn=jt(require("node:fs"),1),Xn=jt(require("node:path"),1);pe();Jl();bn();us();var Sr=jt(require("node:fs"),1),$n=jt(require("node:path"),1);us();bn();us();Tn();function Zn(t,e){let n=/^[A-Za-z]:[\\/]/.test(e)?$n.win32:$n.posix,r=n.relative(e,t);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function Ha(t,e){try{let n=Sr.realpathSync(t);return Zn(n,e)?n:null}catch(n){if(n.code==="ENOENT"){let r=$n.dirname(t);if(r===t)return null;let s=Ha(r,e);if(s===null)return null;try{if(Sr.lstatSync(t).isSymbolicLink()){let o=Sr.readlinkSync(t),a=$n.isAbsolute(o)?o:$n.resolve($n.dirname(t),o),l=Ha(a,e);return l===null?null:l}}catch{}return $n.join(s,$n.basename(t))}return null}}function d1(t,e,n){let r=Ha(t,n);if(r===null)return null;let s=$n.resolve(t),i=s.slice(e.length),o=r.slice(n.length);if(i!==o)return null;try{if(Sr.lstatSync(s).isSymbolicLink())return null}catch{}return r}function h1(t,e){if(!Sr.existsSync(t))throw new Error(`${e} root does not exist`);if(!Sr.statSync(t).isDirectory())throw new Error(`${e} root is not a directory`)}function iF(t,e){if(!$n.isAbsolute(t))return{withinRoot:!0,relativePath:t};let n;try{n=Sr.realpathSync(t)}catch{n=$n.resolve(t)}return Zn(n,e)?{withinRoot:!0,relativePath:Jo(n.slice(e.length))||"/"}:{withinRoot:!1,safeName:$n.basename(t)}}function p1(t,e,n,r){let s=t;if(s.path===void 0){for(let o of r)if(s.message?.includes(o))throw t}let i=s.code||"EIO";throw new D(i,`${n} '${e}'`)}async function Js(t){return oF(await Sr.promises.lstat(t))}function V7(t){return oF(Sr.lstatSync(t))}function oF(t){return process.platform==="win32"&&t.isDirectory()&&(t.mode=t.mode&-512|493),t}bn();us();function m1(t){let e=t.content.byteLength;for(let n of t.appendChunks??[])e+=n.byteLength;return e}function cF(t){return m1(t)}function y1(t,e){if(!t.appendChunks||t.appendChunks.length===0)return t.content;let n=t.appendChunks.reduce((i,o)=>i+o.byteLength,t.content.byteLength);if(!Number.isSafeInteger(n))throw new D("EFBIG",`file too large, read '${e}'`);let r=new Uint8Array(n);r.set(t.content);let s=t.content.byteLength;for(let i of t.appendChunks)r.set(i,s),s+=i.byteLength;return t.content=r,t.appendChunks=void 0,r}function aF(t){return!t||t.type!=="file"?0:m1(t)}function Pf(){return{type:"directory",children:new Map,changedAt:Date.now(),mode:Rs,mtime:new Date}}function $f(t){return t.split("/").filter(Boolean)}var g1=class t{maxMemoryBytes;rootNode=Pf();bytes=0;mutationSeq_=0;constructor(e){this.maxMemoryBytes=e}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(e){let n=$f(e),r=[this.rootNode],s=this.rootNode;for(let i=0;i<n.length;i++){let o=s.children.get(n[i]);if(o===void 0)return{kind:"missing",stack:r,missingAt:i};if(i===n.length-1)return{kind:"found",stack:r,node:o};if(o.type==="whiteout")return{kind:"blocked",stack:r,blockedAt:i};if(o.type!=="directory")return{kind:"notdir",stack:r,notdirAt:i};r.push(o),s=o}return{kind:"found",stack:[],node:this.rootNode}}ensureDirs(e,n){let r=this.rootNode,s="";for(let i of $f(e)){s=`${s}/${i}`;let o=r.children.get(i);if(o===void 0)o=Pf(),r.children.set(i,o);else if(o.type==="whiteout")o=this.resurrectDir(r,i,s,o.changedAt??0,n);else if(o.type!=="directory")throw new D("ENOTDIR",`not a directory, mkdir '${e}'`);r=o}return r}resurrectDir(e,n,r,s,i){let o=Pf();e.children.set(n,o);let a=i?.(r);if(a)for(let l of a)o.children.has(l)||o.children.set(l,{type:"whiteout",changedAt:s});return o}attach(e,n){n.changedAt=Date.now();let r=$f(e);if(r.length===0)throw new D("EINVAL",`cannot attach at root, attach '${e}'`);let s=this.parentDirOf(r,e),i=s.children.get(r[r.length-1]);if(i?.type==="directory"&&n.type!=="directory")throw new D("EISDIR",`cannot replace directory with ${n.type}, attach '${e}'`);if(i!==void 0&&n.type==="directory")throw new D("EEXIST",`cannot replace ${i.type} with directory, attach '${e}'`);let o=aF(i),a=aF(n);this.assertCapacity(a,o),s.children.set(r[r.length-1],n),this.bytes+=a-o}detach(e){let n=$f(e);if(n.length===0)return;let r=this.descend(e);return r.kind!=="found"?void 0:(r.stack[r.stack.length-1].children.delete(n[n.length-1]),this.bytes-=t.subtreeBytes(r.node),r.node)}putWhiteout(e){let n=$f(e);if(n.length===0)throw new D("EINVAL",`cannot whiteout the root, rm '${e}'`);let r=this.rootNode;for(let o=0;o<n.length-1;o++)r=this.ensureChildDir(r,n[o],e);let s=n[n.length-1],i=r.children.get(s);i?.type!=="whiteout"&&(this.bytes-=t.subtreeBytes(i),r.children.set(s,{type:"whiteout",changedAt:Date.now()}))}appendChunk(e,n){this.assertCapacity(n.byteLength),e.appendChunks||(e.appendChunks=[]),e.appendChunks.push(n),this.bytes+=n.byteLength,this.touch(e)}touch(e){e.seq=++this.mutationSeq_,e.changedAt=Date.now()}detachIfUnchanged(e,n,r){let s=this.descend(e);return s.kind!=="found"||s.node!==n||n.seq!==r||n.type==="directory"&&n.children.size>0?!1:(this.detach(e),!0)}*preOrder(){let e=[{path:"/",node:this.rootNode}];for(;e.length>0;){let n=e.pop();if(yield n,n.node.type==="directory"){let r=[...n.node.children.entries()];for(let s=r.length-1;s>=0;s--){let[i,o]=r[s];e.push({path:lF(n.path,i),node:o})}}}}*postOrder(){let e=[],n=[{path:"/",node:this.rootNode}];for(;n.length>0;){let r=n.pop();if(e.push(r),r.node.type==="directory")for(let[s,i]of r.node.children)n.push({path:lF(r.path,s),node:i})}for(let r=e.length-1;r>=0;r--)yield e[r]}clear(){this.rootNode=Pf(),this.bytes=0}static subtreeBytes(e){if(e===void 0)return 0;if(e.type==="file")return m1(e);if(e.type!=="directory")return 0;let n=0,r=[e];for(;r.length>0;){let s=r.pop();for(let i of s.children.values())i.type==="file"?n+=m1(i):i.type==="directory"&&r.push(i)}return n}parentDirOf(e,n){let r=this.rootNode;for(let s=0;s<e.length-1;s++){let i=r.children.get(e[s]);if(i?.type!=="directory")throw new D("ENOTDIR",`not a directory, attach '${n}'`);r=i}return r}ensureChildDir(e,n,r){let s=e.children.get(n);if(s===void 0||s.type==="whiteout")s=Pf(),e.children.set(n,s);else if(s.type!=="directory")throw new D("ENOTDIR",`not a directory, rm '${r}'`);return s}assertCapacity(e,n=0){if(!Number.isSafeInteger(e)||e<0||e>this.maxMemoryBytes-this.bytes+n)throw new D("ENOSPC",`overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function lF(t,e){return t==="/"?`/${e}`:`${t}/${e}`}var wre=["ELOOP","EFBIG","EPERM"],bre="/home/user/project",Ts=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;get rootDir(){return this.root}restamp(e,n,r="full"){let s=ce(e),i=c=>{let u=this.tree.descend(c);u.kind==="found"&&(u.node.changedAt=n)},o=c=>{let u=this.tree.descend(c);if(u.kind==="found"){let f=u.node;(f.changedAt??0)>n&&(f.changedAt=n,f.mtime=new Date(n))}};r==="full"&&i(s);let a=s;for(;;){let c=a.lastIndexOf("/");if(c<=0)break;a=a.slice(0,c),o(a)}if(r==="ancestors")return;let l=[s];for(;l.length>0;){let c=l.pop(),u=this.tree.descend(c);if(!(u.kind!=="found"||u.node.type!=="directory"))for(let f of u.node.children.keys()){let d=`${c==="/"?"":c}/${f}`;o(d),l.push(d)}}}identityFor(e){return e.type==="symlink"?"":(e.identity||(e.identity=`overlay:${this.nextMemoryIdentity++}`),e.identity)}constructor(e){this.root=Xn.resolve(e.root);let n=e.mountPoint??bre;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=e.readOnly??!1,this.maxFileReadSize=e.maxFileReadSize??10485760,this.maxMemoryBytes=e.maxMemoryBytes??1024*1024*1024,!Number.isSafeInteger(this.maxMemoryBytes)||this.maxMemoryBytes<0)throw new Error("OverlayFs: invalid maxMemoryBytes");this.allowSymlinks=e.allowSymlinks??!1,h1(this.root,"OverlayFs"),this.canonicalRoot=sn.realpathSync(this.root),this.tree=new g1(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new D("EROFS",`read-only file system, ${e}`)}createMountPointDirs(){this.tree.ensureDirs(this.mountPoint)}getMountPoint(){return this.mountPoint}diff(){let e=[],n=[],r=[];for(let{path:i,node:o}of this.tree.preOrder()){let a=this.getRelativeToMount(i);if(!(a===null||a==="/")){if(o.type==="whiteout"){this.existsOnRealFs(i)&&(n.push(a),r.push(o.changedAt??0));continue}if(o.type==="file")if(o.metacopy){if(!this.existsOnRealFs(i))continue;e.push({path:a,nodeType:"file",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0,metadataOnly:!0})}else e.push({path:a,nodeType:"file",content:y1(o,i),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0});else o.type==="directory"?e.push({path:a,nodeType:"directory",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0}):e.push({path:a,nodeType:"symlink",content:new TextEncoder().encode(o.target),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0})}}e.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0);let s=n.map((i,o)=>({path:i,changedAt:r[o]}));return s.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),{writes:e,deletions:s.map(i=>i.path),...s.length>0&&{deletionChangedAt:s.map(i=>i.changedAt)}}}async sync(){for(let{path:e,node:n}of this.tree.postOrder()){let r=this.getRelativeToMount(e);if(r===null||r==="/")continue;if(n.type==="whiteout"){this.existsOnRealFs(e)||this.tree.detach(e);continue}if(n.type==="directory"&&n.children.size>0)continue;let s=n.seq;await this.nodeMatchesDisk(e,n)&&this.tree.detachIfUnchanged(e,n,s)}}reset(){this.tree.clear(),this.createMountPointDirs()}drop(e){let n=e.map(r=>{let s=ce(r);if(s==="/")throw new D("EINVAL",`invalid argument, drop '${r}'`);return this.mountPoint==="/"?s:`${this.mountPoint}${s}`});n.sort((r,s)=>s.length-r.length);for(let r of n){let s=this.tree.descend(r);if(s.kind!=="found")continue;let i=s.node;i.type==="directory"&&i.children.size>0||this.tree.detach(r)}}async lstatLower(e){let n=this.resolveRealPathParent_(this.toRealPath(e));if(!n)return null;try{return{canonical:n,stat:await Js(n)}}catch{return null}}async nodeMatchesDisk(e,n){if(n.type==="directory")return(await this.lstatLower(e))?.stat.isDirectory()??!1;if(n.type==="symlink"){if(!this.allowSymlinks)return!1;let s=await this.lstatLower(e);if(!s?.stat.isSymbolicLink())return!1;try{let i=await sn.promises.readlink(s.canonical);return this.realTargetToVirtual(i)===n.target}catch{return!1}}if(n.metacopy){let s=await this.lstatLower(e);if(!s?.stat.isFile())return!1;let{stat:i}=s;return!(i.mtime.getTime()!==n.mtime.getTime()||process.platform!=="win32"&&(i.mode&4095)!==(n.mode&4095))}let r=this.resolveRealPath_(this.toRealPath(e));if(!r)return!1;try{let s=await Js(r);if(!s.isFile())return!1;let i=y1(n,e);if(s.size!==i.byteLength)return!1;let o=this.allowSymlinks?sn.constants.O_RDONLY:sn.constants.O_RDONLY|sn.constants.O_NOFOLLOW,a=await sn.promises.open(r,o),l;try{l=new Uint8Array(await a.readFile())}finally{await a.close()}for(let c=0;c<l.byteLength;c++)if(l[c]!==i[c])return!1;return!0}catch{return!1}}mkdirSync(e,n){this.tree.ensureDirs(ce(e),r=>this.lowerChildren(r))}writeFileSync(e,n){let r=ce(e);this.ensureParentDirs(r);let s=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.tree.attach(r,{type:"file",content:s,mode:so,mtime:new Date})}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let n=ce(e),r=this.getRelativeToMount(n);if(r===null)return null;let s=Xn.join(this.root,r),i=Xn.resolve(s);return Zn(i,this.root)?i:null}resolveRealPath_(e){return e?this.allowSymlinks?Ha(e,this.canonicalRoot):d1(e,this.root,this.canonicalRoot):null}resolveRealPathParent_(e){if(!e)return null;let n=Xn.dirname(e),r=this.resolveRealPath_(n);return r===null?null:Xn.join(r,Xn.basename(e))}sanitizeError(e,n,r){p1(e,n,r,wre)}ensureParentDirs(e){let n=kr(e);n!=="/"&&this.tree.ensureDirs(n,r=>this.lowerChildren(r))}lowerChildren(e){let n=this.resolveRealPath_(this.toRealPath(e));if(!n)return null;try{return sn.readdirSync(n)}catch{return null}}async existsInOverlay(e){let n=ce(e),r=this.tree.descend(n);if(r.kind==="found")return r.node.type!=="whiteout";if(r.kind==="blocked"||r.kind==="notdir")return!1;let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)return!1;try{return await Js(s),!0}catch{return!1}}async readFile(e,n){let r=await this.readFileBuffer(e),s=As(n);return ts(r,s)}async readFileBytes(e){let n=await this.readFileBuffer(e);return ts(n,"binary")}async readFileBuffer(e,n=new Set){ve(e,"open");let r=ce(e);if(n.has(r))throw new D("ELOOP",`too many levels of symbolic links, open '${e}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new D("ENOENT",`no such file or directory, open '${e}'`);if(s.kind==="notdir")throw new D("ENOTDIR",`not a directory, open '${e}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new D("ENOENT",`no such file or directory, open '${e}'`);if(i.type==="symlink"){let a=this.resolveSymlink(r,i.target);return this.readFileBuffer(a,n)}if(i.type!=="file")throw new D("EISDIR",`illegal operation on a directory, read '${e}'`);if(!i.metacopy)return y1(i,e);let o=await this.readLowerFileBytes(r,e,n);if(process.platform==="win32")try{this.tree.attach(r,{type:"file",content:o,mode:i.mode,mtime:i.mtime})}catch(a){if(!st(a,"ENOSPC"))throw a}return o}return this.readLowerFileBytes(r,e,n)}async readLowerFileBytes(e,n,r){let s=this.resolveRealPath_(this.toRealPath(e));if(!s)throw new D("ENOENT",`no such file or directory, open '${n}'`);try{let i=await Js(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new D("ENOENT",`no such file or directory, open '${n}'`);let l=await sn.promises.readlink(s),c=this.realTargetToVirtual(l),u=this.resolveSymlink(e,c);return this.readFileBuffer(u,r)}if(i.isDirectory())throw new D("EISDIR",`illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new D("EFBIG",`file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?sn.constants.O_RDONLY:sn.constants.O_RDONLY|sn.constants.O_NOFOLLOW,a=await sn.promises.open(s,o);try{let l=await a.readFile();return new Uint8Array(l)}finally{await a.close()}}catch(i){let o=i.code;if(o==="ENOENT")throw new D("ENOENT",`no such file or directory, open '${n}'`);if(o==="ELOOP")throw new D("ENOENT",`no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(e,n,r){ve(e,"write"),this.assertWritable(`write '${e}'`);let s=ce(e);this.ensureParentDirs(s);let i=As(r),o=Hs(n,i);this.tree.attach(s,{type:"file",content:o,mode:await this.inheritedMode(s),mtime:new Date})}async inheritedMode(e){let n=this.entryAt(e);if(n?.type==="file")return n.mode;if(n?.type==="directory")return so;if(process.platform==="win32")return so;try{let r=await this.stat(e);if(r.isFile)return r.mode}catch{}return so}async appendFile(e,n,r){ve(e,"append"),this.assertWritable(`append '${e}'`);let s=ce(e),i=As(r),o=Hs(n,i),a=this.tree.descend(s);if(a.kind==="found"&&a.node.type==="file"){await this.appendToExisting_(s,a.node,o,e);return}if(a.kind==="blocked")throw new D("ENOENT",`no such file or directory, append '${e}'`);if(a.kind==="notdir")throw new D("ENOTDIR",`not a directory, append '${e}'`);let l;try{l=await this.readFileBuffer(s)}catch(f){if(!st(f,"ENOENT"))throw f;l=new Uint8Array(0)}let c=await this.inheritedMode(s),u=this.tree.descend(s);if(u.kind==="found"&&u.node.type==="file"){await this.appendToExisting_(s,u.node,o,e);return}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[o],mode:c,mtime:new Date})}async appendToExisting_(e,n,r,s){if(n.metacopy){let i=await this.readLowerFileBytes(e,s,new Set),o=this.tree.descend(e);if(o.kind==="found"&&o.node.type==="file"&&!o.node.metacopy){this.tree.appendChunk(o.node,r),o.node.mtime=new Date;return}this.tree.attach(e,{type:"file",content:i,appendChunks:[r],mode:n.mode,mtime:new Date});return}this.tree.appendChunk(n,r),n.mtime=new Date}async exists(e){return e.includes("\0")?!1:this.existsInOverlay(e)}async stat(e,n=new Set){ve(e,"stat");let r=ce(e);if(n.has(r))throw new D("ELOOP",`too many levels of symbolic links, stat '${e}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new D("ENOENT",`no such file or directory, stat '${e}'`);if(s.kind==="notdir")throw new D("ENOTDIR",`not a directory, stat '${e}'`);if(s.kind==="found"){let o=s.node;if(o.type==="whiteout")throw new D("ENOENT",`no such file or directory, stat '${e}'`);if(o.type==="symlink"){let a=this.resolveSymlink(r,o.target);return this.stat(a,n)}return this.memoryEntryStat(o)}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new D("ENOENT",`no such file or directory, stat '${e}'`);try{let o=await Js(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new D("ENOENT",`no such file or directory, stat '${e}'`);let a=await sn.promises.readlink(i),l=this.realTargetToVirtual(a),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime,dev:o.dev,ino:o.ino}}catch(o){if(o.code==="ENOENT")throw new D("ENOENT",`no such file or directory, stat '${e}'`);this.sanitizeError(o,e,"stat")}}async lstat(e){ve(e,"lstat");let n=ce(e),r=this.tree.descend(n);if(r.kind==="blocked")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);if(r.kind==="notdir")throw new D("ENOTDIR",`not a directory, lstat '${e}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new D("ENOENT",`no such file or directory, lstat '${e}'`);try{let i=await Js(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);this.sanitizeError(i,e,"lstat")}}memoryEntryStat(e){if(e.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:e.mode,size:e.target.length,mtime:e.mtime};let n=0;return e.type==="file"&&(n=e.metacopy?e.lowerSize??0:cF(e)),{isFile:e.type==="file",isDirectory:e.type==="directory",isSymbolicLink:!1,mode:e.mode,size:n,mtime:e.mtime,identity:this.identityFor(e)}}resolveSymlink(e,n){return nl(e,n)}realTargetToVirtual(e){let n=iF(e,this.canonicalRoot);if(n.withinRoot){if(!Xn.isAbsolute(e))return e;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(e,n){ve(e,"mkdir"),this.assertWritable(`mkdir '${e}'`);let r=ce(e);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new D("EEXIST",`file already exists, mkdir '${e}'`);return}let i=kr(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new D("ENOENT",`no such file or directory, mkdir '${e}'`);this.tree.ensureDirs(r,o=>this.lowerChildren(o))}async createExclusive(e,n){let r=n.directory?"mkdir":"open";ve(e,r),this.assertWritable(`${r} '${e}'`);let s=ce(e);if(await this.existsInOverlay(s))throw new D("EEXIST",`file already exists, ${r} '${e}'`);let i=kr(s),o=s;if(i!=="/"){let l;try{l=await this.realpath(i)}catch{throw new D("ENOENT",`no such file or directory, ${r} '${e}'`)}let c=await this.stat(l).catch(()=>null);if(!c)throw new D("ENOENT",`no such file or directory, ${r} '${e}'`);if(!c.isDirectory)throw new D("ENOTDIR",`not a directory, ${r} '${e}'`);if(o=rr(l,s.slice(s.lastIndexOf("/")+1)),o!==s&&await this.existsInOverlay(o))throw new D("EEXIST",`file already exists, ${r} '${e}'`)}if(n.directory){let l=this.tree.descend(o);if(l.kind==="found"&&l.node.type!=="whiteout")throw new D("EEXIST",`file already exists, ${r} '${e}'`);let c=this.tree.ensureDirs(o,u=>this.lowerChildren(u));c.mode=n.mode;return}this.ensureParentDirs(o);let a=this.tree.descend(o);if(a.kind==="found"&&a.node.type!=="whiteout")throw new D("EEXIST",`file already exists, ${r} '${e}'`);this.tree.attach(o,{type:"file",content:new Uint8Array(0),mode:n.mode,mtime:new Date})}async readdirCore(e,n){let r=new Map,s=new Set,i=this.tree.descend(n);if(i.kind==="blocked")throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(i.kind==="notdir")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);let o;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(l.type!=="directory")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);o=l;for(let[c,u]of l.children){if(u.type==="whiteout"){s.add(c);continue}r.set(c,{name:c,isFile:u.type==="file",isDirectory:u.type==="directory",isSymbolicLink:u.type==="symlink"})}}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await Js(a)).isSymbolicLink()){if(!o)throw new D("ENOENT",`no such file or directory, scandir '${e}'`);return r}let l=await sn.promises.readdir(a,{withFileTypes:!0});for(let c of l)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!o)throw new D("ENOENT",`no such file or directory, scandir '${e}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,e,"scandir")}return r}async resolveForReaddir(e,n=!1){let r=ce(e),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let c=l.node;if(c.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new D("ELOOP",`too many levels of symbolic links, scandir '${e}'`);s.add(r),i=!0,r=this.resolveSymlink(r,c.target)}if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let a=this.resolveRealPath_(this.toRealPath(r));if(!a)return{normalized:r,outsideOverlay:!0};try{if((await Js(a)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let c=await sn.promises.readlink(a),u=this.realTargetToVirtual(c),f=this.resolveSymlink(r,u);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(e){ve(e,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(e){ve(e,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(e,n){ve(e,"rm"),this.assertWritable(`rm '${e}'`);let r=ce(e);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new D("ENOENT",`no such file or directory, rm '${e}'`)}let i=!1;try{(await this.stat(r)).isDirectory&&(i=(await this.readdir(r)).length>0)}catch{}if(i&&!n?.recursive)throw new D("ENOTEMPTY",`directory not empty, rm '${e}'`);this.existsOnRealFs(r)?this.tree.putWhiteout(r):this.tree.detach(r)}existsOnRealFs(e){let n=this.toRealPath(e),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return V7(r),!0}catch{return!1}}async cp(e,n,r){ve(e,"cp"),ve(n,"cp"),this.assertWritable(`cp '${n}'`);let s=ce(e),i=ce(n);if(!await this.existsInOverlay(s))throw new D("ENOENT",`no such file or directory, cp '${e}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new D("EISDIR",`is a directory, cp '${e}'`);if(ur(s,i))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(e,n){this.assertWritable(`mv '${n}'`),await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){return io(e,n)}getAllPaths(){let e=new Set;for(let{path:n,node:r}of this.tree.preOrder())r.type!=="whiteout"&&e.add(n);return this.scanRealFs(this.mountPoint,e),Array.from(e)}scanRealFs(e,n){if(this.lowerHidden(e))return;let r=this.resolveRealPath_(this.toRealPath(e));if(r)try{let s=sn.readdirSync(r);for(let i of s){let o=e==="/"?`/${i}`:`${e}/${i}`;if(this.lowerHidden(o))continue;n.add(o);let a=Xn.join(r,i);V7(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}lowerHidden(e){let n=this.tree.descend(e);switch(n.kind){case"blocked":case"notdir":return!0;case"found":return n.node.type!=="directory";default:return!1}}entryAt(e){let n=this.tree.descend(e);if(n.kind==="found"&&n.node.type!=="whiteout")return n.node}async chmod(e,n){ve(e,"chmod"),this.assertWritable(`chmod '${e}'`);let r=ce(e);if(!await this.existsInOverlay(r))throw new D("ENOENT",`no such file or directory, chmod '${e}'`);let i=this.entryAt(r);if(i){i.mode=n,this.tree.touch(i);return}let o=await this.stat(r);this.attachMetacopyShadow(r,o,n,o.isFile?o.mtime:new Date)}attachMetacopyShadow(e,n,r,s){this.ensureParentDirs(e),n.isFile?this.tree.attach(e,{type:"file",content:new Uint8Array(0),metacopy:!0,lowerSize:n.size,mode:r,mtime:s}):n.isDirectory&&this.tree.attach(e,{type:"directory",children:new Map,mode:r,mtime:s})}async symlink(e,n){if(!this.allowSymlinks)throw new D("EPERM",`operation not permitted, symlink '${n}'`);ve(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=ce(n);if(await this.existsInOverlay(r))throw new D("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:e,mode:Vf,mtime:new Date})}async link(e,n){ve(e,"link"),ve(n,"link"),this.assertWritable(`link '${n}'`);let r=ce(e),s=ce(n);if(!await this.existsInOverlay(r))throw new D("ENOENT",`no such file or directory, link '${e}'`);let o=await this.stat(r);if(!o.isFile)throw new D("EPERM",`operation not permitted, link '${e}'`);if(await this.existsInOverlay(s))throw new D("EEXIST",`file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,mode:o.mode,mtime:new Date,identity:o.identity??`overlay:${this.nextMemoryIdentity++}`})}async readlink(e){ve(e,"readlink");let n=ce(e),r=this.tree.descend(n);if(r.kind==="blocked")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(r.kind==="notdir")throw new D("ENOTDIR",`not a directory, readlink '${e}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(i.type!=="symlink")throw new D("EINVAL",`invalid argument, readlink '${e}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new D("ENOENT",`no such file or directory, readlink '${e}'`);try{let i=await sn.promises.readlink(s);if(!Xn.isAbsolute(i)){let o=Xn.resolve(Xn.dirname(s),i),a;try{a=sn.realpathSync(o)}catch{a=o}if(!Zn(a,this.canonicalRoot))return Xn.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(i.code==="EINVAL")throw new D("EINVAL",`invalid argument, readlink '${e}'`);this.sanitizeError(i,e,"readlink")}}async realpath(e){ve(e,"realpath");let n=ce(e),r=new Set,s=l=>{let c=this.tree.descend(l);if(c.kind==="blocked"||c.kind==="found"&&c.node.type==="whiteout")throw new D("ENOENT",`no such file or directory, realpath '${e}'`);return c.kind==="found"?c.node:void 0},i=async l=>{let c=l==="/"?[]:l.slice(1).split("/"),u="";for(let f of c){if(u=`${u}/${f}`,r.has(u))throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);let d=s(u),h=0,p=Nc;for(;d&&d.type==="symlink"&&h<p;){if(r.add(u),u=this.resolveSymlink(u,d.target),h++,r.has(u))throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);d=s(u)}if(h>=p)throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);if(!d){let m=this.toRealPath(u),g=this.resolveRealPath_(m);if(g)try{if((await Js(g)).isSymbolicLink()){if(!this.allowSymlinks)throw new D("ENOENT",`no such file or directory, realpath '${e}'`);let w=await sn.promises.readlink(g),b=this.realTargetToVirtual(w);return r.add(u),u=this.resolveSymlink(u,b),i(u)}}catch(y){if(y.code==="ENOENT")throw new D("ENOENT",`no such file or directory, realpath '${e}'`);this.sanitizeError(y,e,"realpath")}else if(!this.allowSymlinks){let y=this.resolveRealPathParent_(m);if(y)try{if((await Js(y)).isSymbolicLink())throw new D("ENOENT",`no such file or directory, realpath '${e}'`)}catch(w){if(st(w,"ENOENT")||st(w,"ELOOP"))throw new D("ENOENT",`no such file or directory, realpath '${e}'`);this.sanitizeError(w,e,"realpath")}}}}return u||"/"},o=await i(n);if(!await this.existsInOverlay(o))throw new D("ENOENT",`no such file or directory, realpath '${e}'`);return o}async utimes(e,n,r){ve(e,"utimes"),this.assertWritable(`utimes '${e}'`);let s=ce(e);if(!await this.existsInOverlay(s))throw new D("ENOENT",`no such file or directory, utimes '${e}'`);let o=this.entryAt(s);if(o){o.mtime=r,this.tree.touch(o);return}let a=await this.stat(s);this.attachMetacopyShadow(s,a,a.mode,r)}};var Lf=class{bash;overlays;constructor(e={}){let{home:n,project:r,cwd:s,env:i,...o}=e,a=new Map,l=[],c=n?bc(n):null,u=r?bc(r):null,f=c&&u&&(()=>{let p=Yn.relative(c,u);return p!==".."&&!p.startsWith(`..${Yn.sep}`)&&!Yn.isAbsolute(p)})();if(c){let p=new Ts({root:c,mountPoint:"/"});a.set("/home/user",{root:c,fs:p}),l.push({mountPoint:"/home/user",filesystem:p})}let d="/home/user";if(u)if(f&&c){let p=Yn.relative(c,u);d=p?`/home/user/${p.split(Yn.sep).join("/")}`:"/home/user"}else{let p=new Ts({root:u,mountPoint:"/"});a.set("/project",{root:u,fs:p}),l.push({mountPoint:"/project",filesystem:p}),d="/project"}let h=new Wr({base:new ir,mounts:l});this.overlays=a,this.bash=new Xo({...o,env:{HOME:"/home/user",...i},cwd:s??d,fs:h})}analyzeCommands(e){return this.bash.analyzeCommands(e)}exec(e){return this.bash.exec(e)}diff(){let e=[],n=[];for(let{root:r,fs:s}of this.overlays.values()){let i=s.diff();for(let{path:o,...a}of i.writes)e.push({...a,path:Yn.join(r,o)});for(let o=0;o<i.deletions.length;o++)n.push({path:Yn.join(r,i.deletions[o]),changedAt:i.deletionChangedAt?.[o]})}return e.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),n.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),{writes:e,deletions:n.map(r=>r.path),...n.length>0&&{deletionChangedAt:n.map(r=>r.changedAt??0)}}}async applyChanges(e=this.diff()){let n=new Map,r=s=>{let i=this.findOverlay(s);if(!i)return;let o=`/${Yn.relative(i.root,s).split(Yn.sep).join("/")}`;if(o==="/")return;let a=n.get(i.fs);a?a.push(o):n.set(i.fs,[o])};try{for(let s of e.deletions)j7(s),r(s);for(let s of e.writes)q7(s.path,s),r(s.path)}finally{for(let[s,i]of n)s.drop(i)}}findOverlayEntry(e){let n=null;for(let[r,s]of this.overlays)(e===s.root||e.startsWith(s.root+Yn.sep))&&(!n||s.root.length>n.root.length)&&(n={mountPoint:r,root:s.root,fs:s.fs});return n}findOverlay(e){return this.findOverlayEntry(e)}resolveRealPath(e){let n=this.findOverlayEntry(e);if(!n)return null;let r=`/${Yn.relative(n.root,e).split(Yn.sep).join("/")}`;return{mountPoint:n.mountPoint,overlay:n.fs,path:r}}toRealPath(e){let n=e.startsWith("/")?e:`/${e}`,r=null;for(let[s,i]of this.overlays)(n===s||n.startsWith(`${s}/`))&&(!r||s.length>r.mountPoint.length)&&(r={mountPoint:s,root:i.root});return r?Yn.join(r.root,n.slice(r.mountPoint.length)):null}async sync(){for(let{fs:e}of this.overlays.values())await e.sync()}reset(){for(let{fs:e}of this.overlays.values())e.reset()}};function uF(t={}){return new Lf(t)}pe();bn();var fF=require("node:crypto"),Q=jt(require("node:fs"),1),De=jt(require("node:path"),1);pe();Jl();bn();us();var xre=["EACCES","escaping sandbox","EFBIG","ENOTSUP"],Ff=class t{static activeMutationRoots=new Set;static pendingMutations=[];root;canonicalRoot;maxFileReadSize;maxCopyOnWriteSize;maxCopySize;allowSymlinks;constructor(e){this.root=De.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.maxCopyOnWriteSize=e.maxCopyOnWriteSize??104857600,this.maxCopySize=e.maxCopySize??0,this.allowSymlinks=e.allowSymlinks??!1,h1(this.root,"ReadWriteFs"),this.canonicalRoot=Q.realpathSync(this.root)}resolveAndValidate(e,n){let r=this.allowSymlinks?Ha(e,this.canonicalRoot):d1(e,this.root,this.canonicalRoot);if(r===null)throw new D("EACCES",`permission denied, '${n}' resolves outside sandbox`);return r}validateParent(e,n){let r=De.dirname(e),s=this.resolveAndValidate(r,n);return De.join(s,De.basename(e))}toRealPath(e){let n=ce(e),r=De.join(this.root,n);return De.resolve(r)}async readFile(e,n){let r=await this.readFileBuffer(e),s=As(n);return ts(r,s)}async readFileBytes(e){let n=await this.readFileBuffer(e);return ts(n,"binary")}async readFileBuffer(e){ve(e,"open");let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let s=this.allowSymlinks?Q.constants.O_RDONLY:Q.constants.O_RDONLY|Q.constants.O_NOFOLLOW,i=await Q.promises.open(r,s);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new D("EFBIG",`file too large, read '${e}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, open '${e}'`);if(i.code==="EISDIR")throw new D("EISDIR",`illegal operation on a directory, read '${e}'`);if(i.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(s,e,"open")}}async writeFile(e,n,r){await this.withFilesystemMutation(()=>this.writeFileUnlocked(e,n,r))}async writeFileUnlocked(e,n,r){ve(e,"write");let s=this.toRealPath(e),i=this.resolveAndValidate(s,e),o=As(r),a=Hs(n,o),l=De.dirname(i);try{await Q.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,e);let c=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,u=null;try{let f=await Q.promises.lstat(i);if(!f.isFile()&&!f.isDirectory())throw new D("EACCES",`cannot write special file '${e}'`);let d=await Q.promises.open(i,Q.constants.O_WRONLY|Q.constants.O_NONBLOCK|c);try{if(u=await d.stat(),!u.isFile())throw new D("EACCES",`cannot write special file '${e}'`);if(u.nlink<=1){await d.truncate(0),await d.writeFile(a);return}}finally{await d.close()}}catch(f){if(f.code!=="ENOENT")throw f}await this.replaceFile(i,a,u)}catch(c){if(c.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(c,e,"write")}}async appendFile(e,n,r){await this.withFilesystemMutation(()=>this.appendFileUnlocked(e,n,r))}async appendFileUnlocked(e,n,r){ve(e,"append");let s=this.toRealPath(e),i=As(r),o=Hs(n,i),a=this.resolveAndValidate(s,e),l=De.dirname(a);try{await Q.promises.mkdir(l,{recursive:!0}),a=this.resolveAndValidate(s,e);let c=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,u=null;try{let d=await Q.promises.lstat(a);if(!d.isFile()&&!d.isDirectory())throw new D("EACCES",`cannot append special file '${e}'`);let h=await Q.promises.open(a,Q.constants.O_WRONLY|Q.constants.O_APPEND|Q.constants.O_NONBLOCK|c);try{if(u=await h.stat(),!u.isFile())throw new D("EACCES",`cannot append special file '${e}'`);if(u.nlink<=1){await h.writeFile(o);return}}finally{await h.close()}}catch(d){if(d.code!=="ENOENT")throw d}if(!u){await this.replaceFile(a,o,null);return}this.assertCopyOnWriteSize(u.size,"append",e);let f=await this.openCopySource(a);try{let d=await f.stat();if(!d.isFile()||d.dev!==u.dev||d.ino!==u.ino)throw new D("EACCES",`file identity changed, append '${e}'`);await this.replaceFile(a,o,d,{handle:f,size:u.size})}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(c,e,"append")}}async withFilesystemMutation(e){return new Promise((n,r)=>{t.pendingMutations.push({root:this.canonicalRoot,start:()=>{t.activeMutationRoots.add(this.canonicalRoot),e().then(n,r).finally(()=>{t.activeMutationRoots.delete(this.canonicalRoot),t.drainMutationQueue()})}}),t.drainMutationQueue()})}static drainMutationQueue(){for(let e=0;e<t.pendingMutations.length;){let n=t.pendingMutations[e];if([...t.activeMutationRoots].some(s=>Zn(n.root,s)||Zn(s,n.root))){e++;continue}t.pendingMutations.splice(e,1),n.start()}}assertCopyOnWriteSize(e,n,r){if(this.maxCopyOnWriteSize>0&&e>this.maxCopyOnWriteSize)throw new D("EFBIG",`file too large for copy-on-write ${n} '${r}' (${e} bytes, max ${this.maxCopyOnWriteSize})`)}assertCopySize(e,n){if(this.maxCopySize>0&&e.size>this.maxCopySize)throw new D("EFBIG",`file too large to copy '${n}' (${e.size} bytes, max ${this.maxCopySize})`)}randomTransactionToken(){return(0,fF.randomBytes)(16).toString("hex")}async openCopySource(e){let n=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,r=Q.constants.O_RDONLY|Q.constants.O_NONBLOCK|n,s=Q.constants.O_NOATIME;if(process.platform!=="linux"||s===void 0)return Q.promises.open(e,r);try{return await Q.promises.open(e,r|s)}catch(i){if(i.code!=="EPERM")throw i;return Q.promises.open(e,r)}}async replaceFile(e,n,r,s,i,o=!1){let a=De.dirname(e),l="",c=null,u=r===null?438:384;for(let p=0;p<16;p++){l=De.join(a,`.just-bash-write-${this.randomTransactionToken()}`);try{c=await Q.promises.open(l,Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL,u);break}catch(m){if(m.code!=="EEXIST")throw m}}if(!c)throw new D("EEXIST",`replacement write '${e}'`);let f=c,d=await f.stat(),h=!1;try{try{let m=0,g=async y=>{let w=0;for(;w<y.byteLength;){let{bytesWritten:b}=await f.write(y,w,y.byteLength-w,m+w);if(b===0)throw new D("EIO","replacement write made no progress");w+=b}m+=w};if(s){let y=Buffer.allocUnsafe(65536),w=0,b=s.size;for(;b>0;){let x=Math.min(y.length,b),{bytesRead:S}=await s.handle.read(y,0,x,w);if(S===0)break;await g(y.subarray(0,S)),w+=S,b-=S}}if(await g(n),r!==null&&await f.chmod(r.mode&(o?4095:511)),i)await f.utimes(i.atime,i.mtime);else if(r!==null){let y=await f.stat();await f.utimes(r.atime,y.mtime)}}finally{await f.close(),c=null}let p=await Q.promises.lstat(l);if(!p.isFile()||p.dev!==d.dev||p.ino!==d.ino)throw new D("EACCES","replacement staging entry changed");await Q.promises.rename(l,e),h=!0}finally{c&&await c.close().catch(()=>{}),h||await Q.promises.rm(l,{force:!0}).catch(()=>{})}}async exists(e){if(e.includes("\0"))return!1;let n=this.toRealPath(e);try{let r=this.resolveAndValidate(n,e);return await Q.promises.access(r),!0}catch{return!1}}async stat(e){ve(e,"stat");let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let s=await Q.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new D("EACCES",`permission denied, '${e}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new D("ENOENT",`no such file or directory, stat '${e}'`);this.sanitizeError(s,e,"stat")}}async lstat(e){ve(e,"lstat");let n=this.toRealPath(e),r=n===this.root?this.resolveAndValidate(n,e):this.validateParent(n,e);try{let s=await Q.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);this.sanitizeError(s,e,"lstat")}}async mkdir(e,n){await this.withFilesystemMutation(()=>this.mkdirUnlocked(e,n))}async createExclusive(e,n){await this.withFilesystemMutation(()=>this.createExclusiveUnlocked(e,n))}async createExclusiveUnlocked(e,n){let r=n.directory?"mkdir":"open";ve(e,r);let s=this.toRealPath(e),i=s===this.root?this.resolveAndValidate(s,e):this.validateParent(s,e);try{if(n.directory){await Q.promises.mkdir(i,{mode:n.mode});let l=await Q.promises.open(i,Q.constants.O_RDONLY|(Q.constants.O_DIRECTORY??0)|(this.allowSymlinks?0:Q.constants.O_NOFOLLOW));try{await this.assertCreatedInsideRoot(i,s,e,r,await l.stat())}finally{await l.close()}return}let o=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,a=await Q.promises.open(i,Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|o,n.mode);try{await this.assertCreatedInsideRoot(i,s,e,r,await a.stat())}finally{await a.close()}}catch(o){let a=o;if(a.code==="EEXIST")throw new D("EEXIST",`file already exists, ${r} '${e}'`);if(a.code==="ENOENT")throw new D("ENOENT",`no such file or directory, ${r} '${e}'`);this.sanitizeError(o,e,r)}}async assertCreatedInsideRoot(e,n,r,s,i){let o=!1;try{let a=this.resolveAndValidate(n,r),l=await Q.promises.lstat(a);o=a===e&&l.dev===i.dev&&l.ino===i.ino}catch{o=!1}if(!o)throw new D("EACCES",`permission denied, '${r}' resolves outside sandbox during ${s}`)}async mkdirUnlocked(e,n){ve(e,"mkdir");let r=this.toRealPath(e),s=r===this.root?this.resolveAndValidate(r,e):this.validateParent(r,e);try{await Q.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new D("EEXIST",`file already exists, mkdir '${e}'`);if(o.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mkdir '${e}'`);this.sanitizeError(i,e,"mkdir")}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){ve(e,"scandir");let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{if(!this.allowSymlinks&&(await Q.promises.lstat(r)).isSymbolicLink())throw new D("EACCES",`permission denied, '${e}' is a symlink`);return(await Q.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(i.code==="ENOTDIR")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);this.sanitizeError(s,e,"scandir")}}async rm(e,n){await this.withFilesystemMutation(()=>this.rmUnlocked(e,n))}async rmUnlocked(e,n){ve(e,"rm");let r=this.toRealPath(e),s=this.validateParent(r,e);try{let i=await Q.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new D("EACCES",`permission denied, '${e}' is a symlink`);await Q.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"){if(n?.force)return;throw new D("ENOENT",`no such file or directory, rm '${e}'`)}if(o.code==="ENOTEMPTY")throw new D("ENOTEMPTY",`directory not empty, rm '${e}'`);this.sanitizeError(i,e,"rm")}}async cp(e,n,r){await this.withFilesystemMutation(()=>this.cpUnlocked(e,n,r))}async cpUnlocked(e,n,r){ve(e,"cp"),ve(n,"cp");let s=this.toRealPath(e),i=this.toRealPath(n),o=this.validateParent(s,e),a=this.resolveAndValidate(i,n),l;try{l=await Q.promises.lstat(o)}catch(c){if(c.code==="ENOENT")throw new D("ENOENT",`no such file or directory, cp '${e}'`);this.sanitizeError(c,e,"cp")}if(l.isDirectory()&&Zn(a,o))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);if(!l.isDirectory())try{let c=this.validateParent(i,n),u=await Q.promises.lstat(c);if(l.dev===u.dev&&l.ino===u.ino)throw new D("EINVAL",`cannot copy '${e}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}if(l.isFile())try{let c=await Q.promises.stat(a);if(l.dev===c.dev&&l.ino===c.ino)throw new D("EINVAL",`cannot copy '${e}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}try{await this.preflightCopyTree(o,e)}catch(c){this.sanitizeError(c,e,"cp")}if(l.isFile()||l.isSymbolicLink())try{await Q.promises.mkdir(De.dirname(a),{recursive:!0}),this.resolveAndValidate(i,n)}catch(c){this.sanitizeError(c,n,"cp")}try{await this.copyTreeEntry(o,i,e,n,r?.recursive??!1)}catch(c){let u=c;if(u.code==="ENOENT")throw new D("ENOENT",`no such file or directory, cp '${e}'`);if(u.code==="EISDIR")throw new D("EISDIR",`is a directory, cp '${e}'`);this.sanitizeError(c,e,"cp")}}async copyTreeEntry(e,n,r,s,i){let o=await Q.promises.lstat(e);if(o.isFile()){this.assertCopySize(o,r);let a=this.resolveAndValidate(n,s),l=await this.assertCopyDestinationWritable(a,s),c=await this.openCopySource(e);try{let u=await c.stat();if(!u.isFile()||u.dev!==o.dev||u.ino!==o.ino)throw new D("EACCES",`file identity changed, cp '${r}'`);await this.replaceFile(a,new Uint8Array(0),l??o,{handle:c,size:o.size})}finally{await c.close()}return}if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new D("EACCES",`permission denied, cp '${r}' contains a symlink`);let a=await Q.promises.readlink(e),l=De.isAbsolute(a)?await this.toVirtualAbsoluteSymlinkTarget(a,r):a;await this.replaceSymlink(n,s,l);return}if(o.isDirectory()){if(!i)throw new D("EISDIR",`is a directory, cp '${r}'`);let a=this.resolveAndValidate(n,s);await Q.promises.mkdir(a,{recursive:!0}),a=this.resolveAndValidate(n,s);for(let l of await Q.promises.readdir(e))await this.copyTreeEntry(De.join(e,l),De.join(n,l),De.join(r,l),De.join(s,l),!0);await Q.promises.chmod(a,o.mode&4095);return}throw new D("EINVAL",`unsupported file type, cp '${r}'`)}async assertCopyDestinationWritable(e,n){let r;try{r=await Q.promises.lstat(e)}catch(o){if(o.code==="ENOENT")return null;throw o}if(!r.isFile()){if(r.isDirectory())return r;throw new D("EACCES",`cannot copy over special file '${n}'`)}let s=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,i=await Q.promises.open(e,Q.constants.O_WRONLY|Q.constants.O_NONBLOCK|s);try{let o=await i.stat();if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)throw new D("EACCES",`destination changed, cp '${n}'`)}finally{await i.close()}return r}async replaceSymlink(e,n,r){let s=this.validateParent(e,n),i=De.dirname(ce(n)),o="",a="",l="",c=null;for(let f=0;f<16;f++){let d=`.just-bash-copy-link-${this.randomTransactionToken()}`;o=i==="/"?`/${d}`:`${i}/${d}`,a=this.toRealPath(o);try{await this.symlinkUnlocked(r,o),l=this.validateParent(a,o),c=await Q.promises.lstat(l);break}catch(h){if(!st(h,"EEXIST"))throw h}}if(!c)throw new D("EEXIST",`replacement symlink '${n}'`);let u=!1;try{let f=await Q.promises.lstat(l);if(!f.isSymbolicLink()||f.dev!==c.dev||f.ino!==c.ino)throw new D("EACCES","replacement symlink entry changed");await Q.promises.rename(l,s),u=!0}finally{!u&&l&&await Q.promises.rm(l,{force:!0}).catch(()=>{})}}async toVirtualAbsoluteSymlinkTarget(e,n){let r=De.resolve(e),s=await Q.promises.realpath(r),i=await Q.promises.realpath(De.dirname(r)),o=De.join(i,De.basename(r));if(!Zn(s,this.canonicalRoot)||!Zn(o,this.canonicalRoot))throw new D("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return Jo(o.slice(this.canonicalRoot.length))||"/"}async preflightCopyTree(e,n,r=new Set){let s=await Q.promises.lstat(e),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new D("ELOOP",`cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new D("EACCES",`permission denied, cp '${n}' contains a symlink`);let o=await Q.promises.realpath(e);if(!Zn(o,this.canonicalRoot))throw new D("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let o=await Q.promises.readdir(e);for(let a of o)await this.preflightCopyTree(De.join(e,a),De.join(n,a),r)}finally{r.delete(i)}}}async mv(e,n){await this.withFilesystemMutation(()=>this.mvUnlocked(e,n))}async mvUnlocked(e,n){ve(e,"mv"),ve(n,"mv");let r=this.toRealPath(e),s=this.toRealPath(n),i=this.validateParent(r,e),o=this.validateParent(s,n),a;try{a=await Q.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mv '${e}'`);this.sanitizeError(c,e,"mv")}if(a.isDirectory()&&this.isSameOrDescendantIdentity(i,o))throw new D("EINVAL",`cannot move '${e}' into itself, '${n}'`);try{if(a.isSymbolicLink()){let c=await Q.promises.readlink(i),u=De.resolve(De.dirname(o),c),f=await Q.promises.realpath(u).catch(()=>u);if(!Zn(f,this.canonicalRoot))throw new D("EACCES",`permission denied, mv '${e}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mv '${e}'`);if(st(u,"EACCES"))throw c}let l=De.dirname(o);try{await Q.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await Q.promises.rename(i,o)}catch(c){let u=c;if(u.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mv '${e}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(e,n);return}this.sanitizeError(c,e,"mv")}try{if(Q.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await Q.promises.rename(o,i),new D("EACCES",`permission denied, mv '${e}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(st(c,"EACCES"))throw c;await Q.promises.rename(o,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(e,n){let r=e,s=n;try{r=Q.realpathSync(e)}catch{}try{s=Q.realpathSync(n)}catch{try{let i=Q.realpathSync(De.dirname(n));s=De.join(i,De.basename(n))}catch{}}return Zn(s,r)}async uniqueTransactionPath(e,n){let r=De.posix.dirname(e);for(let s=0;s<16;s++){let i=De.posix.join(r,`.just-bash-mv-${n}-${this.randomTransactionToken()}`);if(!await this.exists(i))return i}throw new D("EEXIST",`mv '${e}'`)}async moveAcrossDevices(e,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(e,"source"),o=this.validateParent(this.toRealPath(r),r),a=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(e),e),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,h=!1,p=async()=>{h&&await Q.promises.rename(c,l).catch(()=>{}),d&&await Q.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await Q.promises.rename(a,u).catch(()=>{}),await Q.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cpUnlocked(e,r,{recursive:!0}),(await Q.promises.lstat(o)).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw new D("EACCES",`permission denied, mv '${e}' -> '${n}' would create symlinks escaping sandbox`);try{await Q.promises.rename(u,a),f=!0}catch(g){if(g.code!=="ENOENT")throw g}await Q.promises.rename(o,u),d=!0,await Q.promises.rename(l,c),h=!0,await Q.promises.rm(c,{recursive:!0,force:!1}),h=!1,f&&await Q.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await p(),this.sanitizeError(m,e,"mv")}}resolvePath(e,n){return io(e,n)}getAllPaths(){let e=[];return this.scanDir("/",e),e}sanitizeError(e,n,r){p1(e,n,r,xre)}findEscapingSymlinks(e){let n=[],r=Q.readdirSync(e);for(let s of r){let i=De.join(e,s),o=Q.lstatSync(i);if(o.isSymbolicLink()){let a=Q.readlinkSync(i),l=De.resolve(e,a),c;try{c=Q.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}Zn(c,this.canonicalRoot)||n.push(i)}else o.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(e,n){let r=this.toRealPath(e),s;try{s=this.resolveAndValidate(r,e)}catch{return}try{let i=Q.readdirSync(s);for(let o of i){let a=e==="/"?`/${o}`:`${e}/${o}`;n.push(a);let l=De.join(s,o);Q.lstatSync(l).isDirectory()&&this.scanDir(a,n)}}catch{}}async chmod(e,n){await this.withFilesystemMutation(()=>this.chmodUnlocked(e,n))}async chmodUnlocked(e,n){ve(e,"chmod");let r=this.toRealPath(e),s=this.resolveAndValidate(r,e);try{let i=await Q.promises.lstat(s);if(!i.isFile()){if(!i.isDirectory()&&i.nlink>1)throw new D("EACCES",`cannot chmod multiply-linked special file '${e}'`);await Q.promises.chmod(s,n);return}if(i.nlink<=1){await Q.promises.chmod(s,n);return}this.assertCopyOnWriteSize(i.size,"chmod",e);let o=await this.openCopySource(s);try{let a=await o.stat();if(!a.isFile())throw new D("EACCES",`file type changed, chmod '${e}'`);await this.replaceFile(s,new Uint8Array(0),{mode:n,atime:a.atime,mtime:a.mtime},{handle:o,size:a.size},{atime:a.atime,mtime:a.mtime},!0)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new D("ENOENT",`no such file or directory, chmod '${e}'`);if(o.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(i,e,"chmod")}}async symlink(e,n){await this.withFilesystemMutation(()=>this.symlinkUnlocked(e,n))}async symlinkUnlocked(e,n){if(!this.allowSymlinks)throw new D("EPERM",`operation not permitted, symlink '${n}'`);ve(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=ce(n),o=ce(De.dirname(i)),a=e.startsWith("/")?ce(e):ce(o==="/"?`/${e}`:`${o}/${e}`),l=De.join(this.canonicalRoot,a),c=De.dirname(s),u=e.startsWith("/")?l:De.relative(c,l)||".";try{await Q.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new D("EEXIST",`file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(e,n){await this.withFilesystemMutation(()=>this.linkUnlocked(e,n))}async linkUnlocked(e,n){ve(e,"link"),ve(n,"link");let r=this.toRealPath(e),s=this.toRealPath(n),i=this.resolveAndValidate(r,e),o=s===this.root?this.resolveAndValidate(s,n):this.validateParent(s,n);try{await Q.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new D("ENOENT",`no such file or directory, link '${e}'`);if(l.code==="EEXIST")throw new D("EEXIST",`file already exists, link '${n}'`);if(l.code==="EPERM")throw new D("EPERM",`operation not permitted, link '${e}'`);this.sanitizeError(a,e,"link")}}async readlink(e){ve(e,"readlink");let n=this.toRealPath(e),r=n===this.root?this.resolveAndValidate(n,e):this.validateParent(n,e);try{let s=await Q.promises.readlink(r),i=ce(e),o=De.dirname(i),a=De.isAbsolute(s)?s:De.resolve(De.dirname(r),s),l=await Q.promises.realpath(a).catch(()=>a);if(Zn(l,this.canonicalRoot)){let c=Jo(l.slice(this.canonicalRoot.length))||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:Jo(De.relative(o,c))}return De.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(i.code==="EINVAL")throw new D("EINVAL",`invalid argument, readlink '${e}'`);this.sanitizeError(s,e,"readlink")}}async realpath(e){ve(e,"realpath");let n=this.toRealPath(e);try{this.resolveAndValidate(n,e)}catch{throw new D("ENOENT",`no such file or directory, realpath '${e}'`)}let r;try{r=await Q.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, realpath '${e}'`);if(i.code==="ELOOP")throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(s,e,"realpath")}if(Zn(r,this.canonicalRoot))return Jo(r.slice(this.canonicalRoot.length))||"/";throw new D("ENOENT",`no such file or directory, realpath '${e}'`)}async utimes(e,n,r){await this.withFilesystemMutation(()=>this.utimesUnlocked(e,n,r))}async utimesUnlocked(e,n,r){ve(e,"utimes");let s=this.toRealPath(e),i=this.resolveAndValidate(s,e);try{let o=await Q.promises.lstat(i);if(!o.isFile()){if(!o.isDirectory()&&o.nlink>1)throw new D("EACCES",`cannot change times on multiply-linked special file '${e}'`);await Q.promises.utimes(i,n,r);return}if(o.nlink<=1){await Q.promises.utimes(i,n,r);return}this.assertCopyOnWriteSize(o.size,"utimes",e);let a=await this.openCopySource(i);try{let l=await a.stat();if(!l.isFile())throw new D("EACCES",`file type changed, utimes '${e}'`);await this.replaceFile(i,new Uint8Array(0),l,{handle:a,size:l.size},{atime:n,mtime:r},!0)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new D("ENOENT",`no such file or directory, utimes '${e}'`);if(a.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(o,e,"utimes")}}};var Xi=jt(require("node:path"),1);bn();function dF(t){if(t.mounts.length===0)throw new D("EINVAL","createVfsTemplate needs at least one mount");let e=t.mounts.map(({at:c,root:u})=>{let f=bc(u);return{at:(c.startsWith("/")?c:`/${c}`).replace(/\/+$/,"")||"/",root:f}}),n=new Set;for(let{at:c}of e){if(n.has(c))throw new D("EINVAL",`duplicate mount point '${c}' in createVfsTemplate`);if(n.add(c),c==="/")throw new D("EINVAL","mount point '/' would swallow the shared scratch space");for(let u of n)if(u!==c&&c.startsWith(`${u}/`))throw new D("EINVAL",`mount point '${c}' is nested inside '${u}'`)}let r=[];for(let{root:c}of e){for(let u of r){let f=Xi.default.sep;if(c!==u&&(c.startsWith(u+f)||u.startsWith(c+f)))throw new D("EINVAL",`nested template roots share one real subtree: '${c}' and '${u}'`)}r.push(c)}let s=new ir,i=()=>{let c=new Wr({base:s});for(let{at:u,root:f}of e)c.mount(u,new Ts({root:f,mountPoint:"/",...t.readOnly!==void 0&&{readOnly:t.readOnly},...t.maxMemoryBytes!==void 0&&{maxMemoryBytes:t.maxMemoryBytes}}));return c};return{fork:()=>i(),merge:async c=>{let u=[],f=0;for(let h of c){let p=h instanceof Wr?h.diff({space:"vfs"}):h;for(let m of p.writes){let g=m.changedAt??0;u.push({kind:"write",changedAt:g,order:f++,write:m})}for(let m=0;m<p.deletions.length;m++){let g=p.deletionChangedAt?.[m]??0;u.push({kind:"delete",changedAt:g,order:f++,path:p.deletions[m]})}}u.sort((h,p)=>h.changedAt!==p.changedAt?h.changedAt-p.changedAt:h.order-p.order);let d=i();for(let h of u){if(h.kind==="write"&&h.write.metadataOnly&&h.write.mode===void 0&&h.write.mtime===void 0)continue;let p=!1;try{if(h.kind==="delete")await d.rm(h.path,{recursive:!0});else{let m=h.write;m.metadataOnly?(m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="directory"?(await d.mkdir(m.path,{recursive:!0}),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="symlink"?await d.symlink(new TextDecoder().decode(m.content),m.path):(await d.writeFile(m.path,m.content),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime))}p=!0}catch{}p?d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt):d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt,"ancestors")}return d},apply:c=>{let u={writes:c.writes.map(f=>({...f,path:Xi.default.normalize(f.path)})),deletions:c.deletions.map(f=>Xi.default.normalize(f)),...c.deletionChangedAt&&{deletionChangedAt:c.deletionChangedAt}};for(let f of u.writes)if(f.nodeType==="symlink")throw new D("EINVAL",`change-set contains a symlink write: '${f.path}'`);for(let f of[...u.deletions,...u.writes.map(d=>d.path)]){if(!e.some(({root:m})=>f===m||f.startsWith(m+Xi.default.sep)))throw new D("EINVAL",`change-set entry outside every template root: '${f}'`);if(u.deletions.includes(f)&&e.some(({root:g})=>f===g))throw new D("EINVAL",`change-set deletes a registered root: '${f}'`);let h=Ere(f);if(!e.some(({root:m})=>h===m||h.startsWith(m+Xi.default.sep)))throw new D("EINVAL",`change-set entry escapes its root through a symlink: '${f}'`)}Rf(u)}}}function Ere(t){let e=t,n=[];for(;;)try{let r=bc(e);return n.length===0?r:Xi.default.join(r,...n.reverse())}catch{let r=Xi.default.dirname(e);if(r===e)return t;n.push(Xi.default.basename(e)),e=r}}Fi();Os();var Ga=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(e,n,r,s,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=e,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let e=Math.max(0,this.timeoutMs);this.timeoutId=Ti(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${e}ms`))},e)}}cleanupCancellation(){this.timeoutId!==void 0&&(Hr(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener("abort",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let e={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let n=await this.bashEnv.exec(this.cmdLine,e);return this.exitCode=n.exitCode,n}finally{this.cleanupCancellation()}}async*logs(){let e=await this.resultPromise;e.stdout&&(yield{type:"stdout",data:e.stdout,timestamp:new Date}),e.stderr&&(yield{type:"stderr",data:e.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let e=await this.resultPromise;return e.stdout+e.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error("command killed"))}};var Df=class t{bashEnv;timeoutMs;constructor(e,n){this.bashEnv=e,this.timeoutMs=n}static async create(e){let n=e?.fs;if(e?.overlayRoot){if(e?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Ts({root:e.overlayRoot})}let r=new Xo({env:e?.env,cwd:e?.cwd,fs:n,maxCallDepth:e?.maxCallDepth,maxCommandCount:e?.maxCommandCount,maxLoopIterations:e?.maxLoopIterations,network:e?.network,defenseInDepth:e?.defenseInDepth,python:e?.python,javascript:e?.javascript,commands:e?.commands,customCommands:e?.customCommands,fetch:e?.fetch});return new t(r,e?.timeoutMs)}async runCommand(e,n,r){let s,i,o,a,l=!1,c,u;if(typeof e=="object"){let m=e,g=[m.cmd,...m.args??[]];s=Fn(g),i=m.cwd,o=m.env,a=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=Fn([e,...n]),a=m?.signal}else{s=e;let m=n;i=m?.cwd,o=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new Ga(this.bashEnv,s,f,o,d,a,this.timeoutMs);if(l)return h;let p=await h.wait();if(c){let m=await h.stdout();m&&c.write(m)}if(u){let m=await h.stderr();m&&u.write(m)}return p}async writeFiles(e){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(e)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let o=this.bashEnv.fs.resolvePath(n,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(e,n){let r=await this.bashEnv.readFile(e);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(e,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),e);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(e){}get domain(){}get bashEnvInstance(){return this.bashEnv}};cn();var _f=class{violations=[];violationsByType=new Map;options;constructor(e={}){this.options={maxViolationsPerType:e.maxViolationsPerType??100,maxViolationsTotal:e.maxViolationsTotal??1e3,includeStackTraces:e.includeStackTraces??!0,onViolation:e.onViolation??(()=>{}),logToConsole:e.logToConsole??!1}}record(e){let n=this.options.includeStackTraces?e:{...e,stack:void 0};this.violations.unshift(n),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(e.type);r||(r=[],this.violationsByType.set(e.type,r)),r.length<this.options.maxViolationsPerType&&r.push(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${e.type}: ${e.message}`,e.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(e){return[...this.violationsByType.get(e)??[]]}getSummary(){let e=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)s.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);e.push({type:n,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(s)})}return e.sort((n,r)=>r.count-n.count),e}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return e=>this.record(e)}};function H7(){return t=>{console.warn("[DefenseInDepth] Security violation detected:",`
|
|
2232
|
+
`)}var gre=new TextDecoder("utf-8",{fatal:!0});function nF(t){if(!t)return t;let e=!1;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s>255)return t;s>127&&(e=!0)}if(!e)return t;let n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);try{return gre.decode(n)}catch{return t}}function yre(t,e,n,r,s,i){if(t===void 0)return;let o=e==="bytes"?t.length:j(t);if(o>n||o>r)throw new v(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),e==="bytes"?t:vr(t)}var yn=jt(require("node:fs"),1),f1=jt(require("node:path"),1);bn();function bc(t){return yn.realpathSync(t)}function j7(t){yn.rmSync(t,{recursive:!0,force:!0})}function sF(t,e){let n;try{n=yn.lstatSync(t)}catch{return!1}return e?!n.isDirectory():n.isDirectory()}function rF(t,e){sF(t,e)&&yn.rmSync(t,{recursive:!0,force:!0})}function q7(t,e){if(e.nodeType==="directory"){rF(t,!0),yn.mkdirSync(t,{recursive:!0}),process.platform!=="win32"&&yn.chmodSync(t,e.mode),yn.utimesSync(t,e.mtime,e.mtime);return}if(yn.mkdirSync(f1.dirname(t),{recursive:!0}),e.nodeType==="symlink"){yn.rmSync(t,{force:!0,recursive:!0}),yn.symlinkSync(new TextDecoder().decode(e.content),t);return}if(e.metadataOnly&&sF(t,!1))throw new D("EINVAL",`metadata-only entry over a different on-disk type: '${t}'`);e.metadataOnly||(rF(t,!1),yn.writeFileSync(t,e.content)),process.platform!=="win32"&&yn.chmodSync(t,e.mode),yn.utimesSync(t,e.mtime,e.mtime)}function Rf(t){for(let r of[...t.deletions,...t.writes.map(s=>s.path)])if(f1.resolve(r)!==r)throw new D("EINVAL",`change-set path is not normalized: '${r}'`);let e=[...t.deletions].sort((r,s)=>s.length-r.length||(r<s?-1:r>s?1:0));for(let r of e)j7(r);let n=[...t.writes].sort((r,s)=>r.path.length-s.path.length||(r.path<s.path?-1:r.path>s.path?1:0));for(let{path:r,...s}of n)q7(r,s)}var sn=jt(require("node:fs"),1),Xn=jt(require("node:path"),1);pe();Jl();bn();us();var Sr=jt(require("node:fs"),1),$n=jt(require("node:path"),1);us();bn();us();Tn();function Zn(t,e){let n=/^[A-Za-z]:[\\/]/.test(e)?$n.win32:$n.posix,r=n.relative(e,t);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function Ha(t,e){try{let n=Sr.realpathSync(t);return Zn(n,e)?n:null}catch(n){if(n.code==="ENOENT"){let r=$n.dirname(t);if(r===t)return null;let s=Ha(r,e);if(s===null)return null;try{if(Sr.lstatSync(t).isSymbolicLink()){let o=Sr.readlinkSync(t),a=$n.isAbsolute(o)?o:$n.resolve($n.dirname(t),o),l=Ha(a,e);return l===null?null:l}}catch{}return $n.join(s,$n.basename(t))}return null}}function d1(t,e,n){let r=Ha(t,n);if(r===null)return null;let s=$n.resolve(t),i=s.slice(e.length),o=r.slice(n.length);if(i!==o)return null;try{if(Sr.lstatSync(s).isSymbolicLink())return null}catch{}return r}function h1(t,e){if(!Sr.existsSync(t))throw new Error(`${e} root does not exist`);if(!Sr.statSync(t).isDirectory())throw new Error(`${e} root is not a directory`)}function iF(t,e){if(!$n.isAbsolute(t))return{withinRoot:!0,relativePath:t};let n;try{n=Sr.realpathSync(t)}catch{n=$n.resolve(t)}return Zn(n,e)?{withinRoot:!0,relativePath:Jo(n.slice(e.length))||"/"}:{withinRoot:!1,safeName:$n.basename(t)}}function p1(t,e,n,r){let s=t;if(s.path===void 0){for(let o of r)if(s.message?.includes(o))throw t}let i=s.code||"EIO";throw new D(i,`${n} '${e}'`)}async function Js(t){return oF(await Sr.promises.lstat(t))}function V7(t){return oF(Sr.lstatSync(t))}function oF(t){return process.platform==="win32"&&t.isDirectory()&&(t.mode=t.mode&-512|493),t}bn();us();function m1(t){let e=t.content.byteLength;for(let n of t.appendChunks??[])e+=n.byteLength;return e}function cF(t){return m1(t)}function y1(t,e){if(!t.appendChunks||t.appendChunks.length===0)return t.content;let n=t.appendChunks.reduce((i,o)=>i+o.byteLength,t.content.byteLength);if(!Number.isSafeInteger(n))throw new D("EFBIG",`file too large, read '${e}'`);let r=new Uint8Array(n);r.set(t.content);let s=t.content.byteLength;for(let i of t.appendChunks)r.set(i,s),s+=i.byteLength;return t.content=r,t.appendChunks=void 0,r}function aF(t){return!t||t.type!=="file"?0:m1(t)}function Pf(){return{type:"directory",children:new Map,changedAt:Date.now(),mode:Rs,mtime:new Date}}function $f(t){return t.split("/").filter(Boolean)}var g1=class t{maxMemoryBytes;rootNode=Pf();bytes=0;mutationSeq_=0;constructor(e){this.maxMemoryBytes=e}get root(){return this.rootNode}get retainedBytes(){return this.bytes}descend(e){let n=$f(e),r=[this.rootNode],s=this.rootNode;for(let i=0;i<n.length;i++){let o=s.children.get(n[i]);if(o===void 0)return{kind:"missing",stack:r,missingAt:i};if(i===n.length-1)return{kind:"found",stack:r,node:o};if(o.type==="whiteout")return{kind:"blocked",stack:r,blockedAt:i};if(o.type!=="directory")return{kind:"notdir",stack:r,notdirAt:i};r.push(o),s=o}return{kind:"found",stack:[],node:this.rootNode}}ensureDirs(e,n){let r=this.rootNode,s="";for(let i of $f(e)){s=`${s}/${i}`;let o=r.children.get(i);if(o===void 0)o=Pf(),r.children.set(i,o);else if(o.type==="whiteout")o=this.resurrectDir(r,i,s,o.changedAt??0,n);else if(o.type!=="directory")throw new D("ENOTDIR",`not a directory, mkdir '${e}'`);r=o}return r}resurrectDir(e,n,r,s,i){let o=Pf();e.children.set(n,o);let a=i?.(r);if(a)for(let l of a)o.children.has(l)||o.children.set(l,{type:"whiteout",changedAt:s});return o}attach(e,n){n.changedAt=Date.now();let r=$f(e);if(r.length===0)throw new D("EINVAL",`cannot attach at root, attach '${e}'`);let s=this.parentDirOf(r,e),i=s.children.get(r[r.length-1]);if(i?.type==="directory"&&n.type!=="directory")throw new D("EISDIR",`cannot replace directory with ${n.type}, attach '${e}'`);if(i!==void 0&&n.type==="directory")throw new D("EEXIST",`cannot replace ${i.type} with directory, attach '${e}'`);let o=aF(i),a=aF(n);this.assertCapacity(a,o),s.children.set(r[r.length-1],n),this.bytes+=a-o}detach(e){let n=$f(e);if(n.length===0)return;let r=this.descend(e);return r.kind!=="found"?void 0:(r.stack[r.stack.length-1].children.delete(n[n.length-1]),this.bytes-=t.subtreeBytes(r.node),r.node)}putWhiteout(e){let n=$f(e);if(n.length===0)throw new D("EINVAL",`cannot whiteout the root, rm '${e}'`);let r=this.rootNode;for(let o=0;o<n.length-1;o++)r=this.ensureChildDir(r,n[o],e);let s=n[n.length-1],i=r.children.get(s);i?.type!=="whiteout"&&(this.bytes-=t.subtreeBytes(i),r.children.set(s,{type:"whiteout",changedAt:Date.now()}))}appendChunk(e,n){this.assertCapacity(n.byteLength),e.appendChunks||(e.appendChunks=[]),e.appendChunks.push(n),this.bytes+=n.byteLength,this.touch(e)}touch(e){e.seq=++this.mutationSeq_,e.changedAt=Date.now()}detachIfUnchanged(e,n,r){let s=this.descend(e);return s.kind!=="found"||s.node!==n||n.seq!==r||n.type==="directory"&&n.children.size>0?!1:(this.detach(e),!0)}*preOrder(){let e=[{path:"/",node:this.rootNode}];for(;e.length>0;){let n=e.pop();if(yield n,n.node.type==="directory"){let r=[...n.node.children.entries()];for(let s=r.length-1;s>=0;s--){let[i,o]=r[s];e.push({path:lF(n.path,i),node:o})}}}}*postOrder(){let e=[],n=[{path:"/",node:this.rootNode}];for(;n.length>0;){let r=n.pop();if(e.push(r),r.node.type==="directory")for(let[s,i]of r.node.children)n.push({path:lF(r.path,s),node:i})}for(let r=e.length-1;r>=0;r--)yield e[r]}clear(){this.rootNode=Pf(),this.bytes=0}static subtreeBytes(e){if(e===void 0)return 0;if(e.type==="file")return m1(e);if(e.type!=="directory")return 0;let n=0,r=[e];for(;r.length>0;){let s=r.pop();for(let i of s.children.values())i.type==="file"?n+=m1(i):i.type==="directory"&&r.push(i)}return n}parentDirOf(e,n){let r=this.rootNode;for(let s=0;s<e.length-1;s++){let i=r.children.get(e[s]);if(i?.type!=="directory")throw new D("ENOTDIR",`not a directory, attach '${n}'`);r=i}return r}ensureChildDir(e,n,r){let s=e.children.get(n);if(s===void 0||s.type==="whiteout")s=Pf(),e.children.set(n,s);else if(s.type!=="directory")throw new D("ENOTDIR",`not a directory, rm '${r}'`);return s}assertCapacity(e,n=0){if(!Number.isSafeInteger(e)||e<0||e>this.maxMemoryBytes-this.bytes+n)throw new D("ENOSPC",`overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}};function lF(t,e){return t==="/"?`/${e}`:`${t}/${e}`}var wre=["ELOOP","EFBIG","EPERM"],bre="/home/user/project",Ts=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;tree;nextMemoryIdentity=1;get rootDir(){return this.root}restamp(e,n,r="full"){let s=ce(e),i=c=>{let u=this.tree.descend(c);u.kind==="found"&&(u.node.changedAt=n)},o=c=>{let u=this.tree.descend(c);if(u.kind==="found"){let f=u.node;(f.changedAt??0)>n&&(f.changedAt=n,f.mtime=new Date(n))}};r==="full"&&i(s);let a=s;for(;;){let c=a.lastIndexOf("/");if(c<=0)break;a=a.slice(0,c),o(a)}if(r==="ancestors")return;let l=[s];for(;l.length>0;){let c=l.pop(),u=this.tree.descend(c);if(!(u.kind!=="found"||u.node.type!=="directory"))for(let f of u.node.children.keys()){let d=`${c==="/"?"":c}/${f}`;o(d),l.push(d)}}}identityFor(e){return e.type==="symlink"?"":(e.identity||(e.identity=`overlay:${this.nextMemoryIdentity++}`),e.identity)}constructor(e){this.root=Xn.resolve(e.root);let n=e.mountPoint??bre;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=e.readOnly??!1,this.maxFileReadSize=e.maxFileReadSize??10485760,this.maxMemoryBytes=e.maxMemoryBytes??1024*1024*1024,!Number.isSafeInteger(this.maxMemoryBytes)||this.maxMemoryBytes<0)throw new Error("OverlayFs: invalid maxMemoryBytes");this.allowSymlinks=e.allowSymlinks??!1,h1(this.root,"OverlayFs"),this.canonicalRoot=sn.realpathSync(this.root),this.tree=new g1(this.maxMemoryBytes),this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new D("EROFS",`read-only file system, ${e}`)}createMountPointDirs(){this.tree.ensureDirs(this.mountPoint)}getMountPoint(){return this.mountPoint}diff(){let e=[],n=[],r=[];for(let{path:i,node:o}of this.tree.preOrder()){let a=this.getRelativeToMount(i);if(!(a===null||a==="/")){if(o.type==="whiteout"){this.existsOnRealFs(i)&&(n.push(a),r.push(o.changedAt??0));continue}if(o.type==="file")if(o.metacopy){if(!this.existsOnRealFs(i))continue;e.push({path:a,nodeType:"file",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0,metadataOnly:!0})}else e.push({path:a,nodeType:"file",content:y1(o,i),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0});else o.type==="directory"?e.push({path:a,nodeType:"directory",content:new Uint8Array(0),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0}):e.push({path:a,nodeType:"symlink",content:new TextEncoder().encode(o.target),mode:o.mode,mtime:o.mtime,changedAt:o.changedAt??0})}}e.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0);let s=n.map((i,o)=>({path:i,changedAt:r[o]}));return s.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),{writes:e,deletions:s.map(i=>i.path),...s.length>0&&{deletionChangedAt:s.map(i=>i.changedAt)}}}async sync(){for(let{path:e,node:n}of this.tree.postOrder()){let r=this.getRelativeToMount(e);if(r===null||r==="/")continue;if(n.type==="whiteout"){this.existsOnRealFs(e)||this.tree.detach(e);continue}if(n.type==="directory"&&n.children.size>0)continue;let s=n.seq;await this.nodeMatchesDisk(e,n)&&this.tree.detachIfUnchanged(e,n,s)}}reset(){this.tree.clear(),this.createMountPointDirs()}drop(e){let n=e.map(r=>{let s=ce(r);if(s==="/")throw new D("EINVAL",`invalid argument, drop '${r}'`);return this.mountPoint==="/"?s:`${this.mountPoint}${s}`});n.sort((r,s)=>s.length-r.length);for(let r of n){let s=this.tree.descend(r);if(s.kind!=="found")continue;let i=s.node;i.type==="directory"&&i.children.size>0||this.tree.detach(r)}}async lstatLower(e){let n=this.resolveRealPathParent_(this.toRealPath(e));if(!n)return null;try{return{canonical:n,stat:await Js(n)}}catch{return null}}async nodeMatchesDisk(e,n){if(n.type==="directory")return(await this.lstatLower(e))?.stat.isDirectory()??!1;if(n.type==="symlink"){if(!this.allowSymlinks)return!1;let s=await this.lstatLower(e);if(!s?.stat.isSymbolicLink())return!1;try{let i=await sn.promises.readlink(s.canonical);return this.realTargetToVirtual(i)===n.target}catch{return!1}}if(n.metacopy){let s=await this.lstatLower(e);if(!s?.stat.isFile())return!1;let{stat:i}=s;return!(i.mtime.getTime()!==n.mtime.getTime()||process.platform!=="win32"&&(i.mode&4095)!==(n.mode&4095))}let r=this.resolveRealPath_(this.toRealPath(e));if(!r)return!1;try{let s=await Js(r);if(!s.isFile())return!1;let i=y1(n,e);if(s.size!==i.byteLength)return!1;let o=this.allowSymlinks?sn.constants.O_RDONLY:sn.constants.O_RDONLY|sn.constants.O_NOFOLLOW,a=await sn.promises.open(r,o),l;try{l=new Uint8Array(await a.readFile())}finally{await a.close()}for(let c=0;c<l.byteLength;c++)if(l[c]!==i[c])return!1;return!0}catch{return!1}}mkdirSync(e,n){this.tree.ensureDirs(ce(e),r=>this.lowerChildren(r))}writeFileSync(e,n){let r=ce(e);this.ensureParentDirs(r);let s=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.tree.attach(r,{type:"file",content:s,mode:so,mtime:new Date})}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let n=ce(e),r=this.getRelativeToMount(n);if(r===null)return null;let s=Xn.join(this.root,r),i=Xn.resolve(s);return Zn(i,this.root)?i:null}resolveRealPath_(e){return e?this.allowSymlinks?Ha(e,this.canonicalRoot):d1(e,this.root,this.canonicalRoot):null}resolveRealPathParent_(e){if(!e)return null;let n=Xn.dirname(e),r=this.resolveRealPath_(n);return r===null?null:Xn.join(r,Xn.basename(e))}sanitizeError(e,n,r){p1(e,n,r,wre)}ensureParentDirs(e){let n=kr(e);n!=="/"&&this.tree.ensureDirs(n,r=>this.lowerChildren(r))}lowerChildren(e){let n=this.resolveRealPath_(this.toRealPath(e));if(!n)return null;try{return sn.readdirSync(n)}catch{return null}}async existsInOverlay(e){let n=ce(e),r=this.tree.descend(n);if(r.kind==="found")return r.node.type!=="whiteout";if(r.kind==="blocked"||r.kind==="notdir")return!1;let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)return!1;try{return await Js(s),!0}catch{return!1}}async readFile(e,n){let r=await this.readFileBuffer(e),s=As(n);return ts(r,s)}async readFileBytes(e){let n=await this.readFileBuffer(e);return ts(n,"binary")}async readFileBuffer(e,n=new Set){Ce(e,"open");let r=ce(e);if(n.has(r))throw new D("ELOOP",`too many levels of symbolic links, open '${e}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new D("ENOENT",`no such file or directory, open '${e}'`);if(s.kind==="notdir")throw new D("ENOTDIR",`not a directory, open '${e}'`);if(s.kind==="found"){let i=s.node;if(i.type==="whiteout")throw new D("ENOENT",`no such file or directory, open '${e}'`);if(i.type==="symlink"){let a=this.resolveSymlink(r,i.target);return this.readFileBuffer(a,n)}if(i.type!=="file")throw new D("EISDIR",`illegal operation on a directory, read '${e}'`);if(!i.metacopy)return y1(i,e);let o=await this.readLowerFileBytes(r,e,n);if(process.platform==="win32")try{this.tree.attach(r,{type:"file",content:o,mode:i.mode,mtime:i.mtime})}catch(a){if(!st(a,"ENOSPC"))throw a}return o}return this.readLowerFileBytes(r,e,n)}async readLowerFileBytes(e,n,r){let s=this.resolveRealPath_(this.toRealPath(e));if(!s)throw new D("ENOENT",`no such file or directory, open '${n}'`);try{let i=await Js(s);if(i.isSymbolicLink()){if(!this.allowSymlinks)throw new D("ENOENT",`no such file or directory, open '${n}'`);let l=await sn.promises.readlink(s),c=this.realTargetToVirtual(l),u=this.resolveSymlink(e,c);return this.readFileBuffer(u,r)}if(i.isDirectory())throw new D("EISDIR",`illegal operation on a directory, read '${n}'`);if(this.maxFileReadSize>0&&i.size>this.maxFileReadSize)throw new D("EFBIG",`file too large, read '${n}' (${i.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?sn.constants.O_RDONLY:sn.constants.O_RDONLY|sn.constants.O_NOFOLLOW,a=await sn.promises.open(s,o);try{let l=await a.readFile();return new Uint8Array(l)}finally{await a.close()}}catch(i){let o=i.code;if(o==="ENOENT")throw new D("ENOENT",`no such file or directory, open '${n}'`);if(o==="ELOOP")throw new D("ENOENT",`no such file or directory, open '${n}'`);this.sanitizeError(i,n,"open")}}async writeFile(e,n,r){Ce(e,"write"),this.assertWritable(`write '${e}'`);let s=ce(e);this.ensureParentDirs(s);let i=As(r),o=Hs(n,i);this.tree.attach(s,{type:"file",content:o,mode:await this.inheritedMode(s),mtime:new Date})}async inheritedMode(e){let n=this.entryAt(e);if(n?.type==="file")return n.mode;if(n?.type==="directory")return so;if(process.platform==="win32")return so;try{let r=await this.stat(e);if(r.isFile)return r.mode}catch{}return so}async appendFile(e,n,r){Ce(e,"append"),this.assertWritable(`append '${e}'`);let s=ce(e),i=As(r),o=Hs(n,i),a=this.tree.descend(s);if(a.kind==="found"&&a.node.type==="file"){await this.appendToExisting_(s,a.node,o,e);return}if(a.kind==="blocked")throw new D("ENOENT",`no such file or directory, append '${e}'`);if(a.kind==="notdir")throw new D("ENOTDIR",`not a directory, append '${e}'`);let l;try{l=await this.readFileBuffer(s)}catch(f){if(!st(f,"ENOENT"))throw f;l=new Uint8Array(0)}let c=await this.inheritedMode(s),u=this.tree.descend(s);if(u.kind==="found"&&u.node.type==="file"){await this.appendToExisting_(s,u.node,o,e);return}this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,appendChunks:[o],mode:c,mtime:new Date})}async appendToExisting_(e,n,r,s){if(n.metacopy){let i=await this.readLowerFileBytes(e,s,new Set),o=this.tree.descend(e);if(o.kind==="found"&&o.node.type==="file"&&!o.node.metacopy){this.tree.appendChunk(o.node,r),o.node.mtime=new Date;return}this.tree.attach(e,{type:"file",content:i,appendChunks:[r],mode:n.mode,mtime:new Date});return}this.tree.appendChunk(n,r),n.mtime=new Date}async exists(e){return e.includes("\0")?!1:this.existsInOverlay(e)}async stat(e,n=new Set){Ce(e,"stat");let r=ce(e);if(n.has(r))throw new D("ELOOP",`too many levels of symbolic links, stat '${e}'`);n.add(r);let s=this.tree.descend(r);if(s.kind==="blocked")throw new D("ENOENT",`no such file or directory, stat '${e}'`);if(s.kind==="notdir")throw new D("ENOTDIR",`not a directory, stat '${e}'`);if(s.kind==="found"){let o=s.node;if(o.type==="whiteout")throw new D("ENOENT",`no such file or directory, stat '${e}'`);if(o.type==="symlink"){let a=this.resolveSymlink(r,o.target);return this.stat(a,n)}return this.memoryEntryStat(o)}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new D("ENOENT",`no such file or directory, stat '${e}'`);try{let o=await Js(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new D("ENOENT",`no such file or directory, stat '${e}'`);let a=await sn.promises.readlink(i),l=this.realTargetToVirtual(a),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime,dev:o.dev,ino:o.ino}}catch(o){if(o.code==="ENOENT")throw new D("ENOENT",`no such file or directory, stat '${e}'`);this.sanitizeError(o,e,"stat")}}async lstat(e){Ce(e,"lstat");let n=ce(e),r=this.tree.descend(n);if(r.kind==="blocked")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);if(r.kind==="notdir")throw new D("ENOTDIR",`not a directory, lstat '${e}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);return this.memoryEntryStat(i)}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new D("ENOENT",`no such file or directory, lstat '${e}'`);try{let i=await Js(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);this.sanitizeError(i,e,"lstat")}}memoryEntryStat(e){if(e.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:e.mode,size:e.target.length,mtime:e.mtime};let n=0;return e.type==="file"&&(n=e.metacopy?e.lowerSize??0:cF(e)),{isFile:e.type==="file",isDirectory:e.type==="directory",isSymbolicLink:!1,mode:e.mode,size:n,mtime:e.mtime,identity:this.identityFor(e)}}resolveSymlink(e,n){return nl(e,n)}realTargetToVirtual(e){let n=iF(e,this.canonicalRoot);if(n.withinRoot){if(!Xn.isAbsolute(e))return e;let r=n.relativePath;return this.mountPoint==="/"?r:`${this.mountPoint}${r}`}return n.safeName}async mkdir(e,n){Ce(e,"mkdir"),this.assertWritable(`mkdir '${e}'`);let r=ce(e);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new D("EEXIST",`file already exists, mkdir '${e}'`);return}let i=kr(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new D("ENOENT",`no such file or directory, mkdir '${e}'`);this.tree.ensureDirs(r,o=>this.lowerChildren(o))}async createExclusive(e,n){let r=n.directory?"mkdir":"open";Ce(e,r),this.assertWritable(`${r} '${e}'`);let s=ce(e);if(await this.existsInOverlay(s))throw new D("EEXIST",`file already exists, ${r} '${e}'`);let i=kr(s),o=s;if(i!=="/"){let l;try{l=await this.realpath(i)}catch{throw new D("ENOENT",`no such file or directory, ${r} '${e}'`)}let c=await this.stat(l).catch(()=>null);if(!c)throw new D("ENOENT",`no such file or directory, ${r} '${e}'`);if(!c.isDirectory)throw new D("ENOTDIR",`not a directory, ${r} '${e}'`);if(o=rr(l,s.slice(s.lastIndexOf("/")+1)),o!==s&&await this.existsInOverlay(o))throw new D("EEXIST",`file already exists, ${r} '${e}'`)}if(n.directory){let l=this.tree.descend(o);if(l.kind==="found"&&l.node.type!=="whiteout")throw new D("EEXIST",`file already exists, ${r} '${e}'`);let c=this.tree.ensureDirs(o,u=>this.lowerChildren(u));c.mode=n.mode;return}this.ensureParentDirs(o);let a=this.tree.descend(o);if(a.kind==="found"&&a.node.type!=="whiteout")throw new D("EEXIST",`file already exists, ${r} '${e}'`);this.tree.attach(o,{type:"file",content:new Uint8Array(0),mode:n.mode,mtime:new Date})}async readdirCore(e,n){let r=new Map,s=new Set,i=this.tree.descend(n);if(i.kind==="blocked")throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(i.kind==="notdir")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);let o;if(i.kind==="found"){let l=i.node;if(l.type==="whiteout")throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(l.type!=="directory")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);o=l;for(let[c,u]of l.children){if(u.type==="whiteout"){s.add(c);continue}r.set(c,{name:c,isFile:u.type==="file",isDirectory:u.type==="directory",isSymbolicLink:u.type==="symlink"})}}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await Js(a)).isSymbolicLink()){if(!o)throw new D("ENOENT",`no such file or directory, scandir '${e}'`);return r}let l=await sn.promises.readdir(a,{withFileTypes:!0});for(let c of l)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(l){if(l.code==="ENOENT"){if(!o)throw new D("ENOENT",`no such file or directory, scandir '${e}'`)}else l.code!=="ENOTDIR"&&this.sanitizeError(l,e,"scandir")}return r}async resolveForReaddir(e,n=!1){let r=ce(e),s=new Set,i=n;for(;;){let l=this.tree.descend(r);if(l.kind!=="found")break;let c=l.node;if(c.type!=="symlink")return{normalized:r,outsideOverlay:!1};if(s.has(r))throw new D("ELOOP",`too many levels of symbolic links, scandir '${e}'`);s.add(r),i=!0,r=this.resolveSymlink(r,c.target)}if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let a=this.resolveRealPath_(this.toRealPath(r));if(!a)return{normalized:r,outsideOverlay:!0};try{if((await Js(a)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let c=await sn.promises.readlink(a),u=this.realTargetToVirtual(c),f=this.resolveSymlink(r,u);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(e){Ce(e,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(e){Ce(e,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(e,n){Ce(e,"rm"),this.assertWritable(`rm '${e}'`);let r=ce(e);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new D("ENOENT",`no such file or directory, rm '${e}'`)}let i=!1;try{(await this.stat(r)).isDirectory&&(i=(await this.readdir(r)).length>0)}catch{}if(i&&!n?.recursive)throw new D("ENOTEMPTY",`directory not empty, rm '${e}'`);this.existsOnRealFs(r)?this.tree.putWhiteout(r):this.tree.detach(r)}existsOnRealFs(e){let n=this.toRealPath(e),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return V7(r),!0}catch{return!1}}async cp(e,n,r){Ce(e,"cp"),Ce(n,"cp"),this.assertWritable(`cp '${n}'`);let s=ce(e),i=ce(n);if(!await this.existsInOverlay(s))throw new D("ENOENT",`no such file or directory, cp '${e}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new D("EISDIR",`is a directory, cp '${e}'`);if(ur(s,i))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(e,n){this.assertWritable(`mv '${n}'`),await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){return io(e,n)}getAllPaths(){let e=new Set;for(let{path:n,node:r}of this.tree.preOrder())r.type!=="whiteout"&&e.add(n);return this.scanRealFs(this.mountPoint,e),Array.from(e)}scanRealFs(e,n){if(this.lowerHidden(e))return;let r=this.resolveRealPath_(this.toRealPath(e));if(r)try{let s=sn.readdirSync(r);for(let i of s){let o=e==="/"?`/${i}`:`${e}/${i}`;if(this.lowerHidden(o))continue;n.add(o);let a=Xn.join(r,i);V7(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}lowerHidden(e){let n=this.tree.descend(e);switch(n.kind){case"blocked":case"notdir":return!0;case"found":return n.node.type!=="directory";default:return!1}}entryAt(e){let n=this.tree.descend(e);if(n.kind==="found"&&n.node.type!=="whiteout")return n.node}async chmod(e,n){Ce(e,"chmod"),this.assertWritable(`chmod '${e}'`);let r=ce(e);if(!await this.existsInOverlay(r))throw new D("ENOENT",`no such file or directory, chmod '${e}'`);let i=this.entryAt(r);if(i){i.mode=n,this.tree.touch(i);return}let o=await this.stat(r);this.attachMetacopyShadow(r,o,n,o.isFile?o.mtime:new Date)}attachMetacopyShadow(e,n,r,s){this.ensureParentDirs(e),n.isFile?this.tree.attach(e,{type:"file",content:new Uint8Array(0),metacopy:!0,lowerSize:n.size,mode:r,mtime:s}):n.isDirectory&&this.tree.attach(e,{type:"directory",children:new Map,mode:r,mtime:s})}async symlink(e,n){if(!this.allowSymlinks)throw new D("EPERM",`operation not permitted, symlink '${n}'`);Ce(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=ce(n);if(await this.existsInOverlay(r))throw new D("EEXIST",`file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.tree.attach(r,{type:"symlink",target:e,mode:Vf,mtime:new Date})}async link(e,n){Ce(e,"link"),Ce(n,"link"),this.assertWritable(`link '${n}'`);let r=ce(e),s=ce(n);if(!await this.existsInOverlay(r))throw new D("ENOENT",`no such file or directory, link '${e}'`);let o=await this.stat(r);if(!o.isFile)throw new D("EPERM",`operation not permitted, link '${e}'`);if(await this.existsInOverlay(s))throw new D("EEXIST",`file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.tree.attach(s,{type:"file",content:l,mode:o.mode,mtime:new Date,identity:o.identity??`overlay:${this.nextMemoryIdentity++}`})}async readlink(e){Ce(e,"readlink");let n=ce(e),r=this.tree.descend(n);if(r.kind==="blocked")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(r.kind==="notdir")throw new D("ENOTDIR",`not a directory, readlink '${e}'`);if(r.kind==="found"){let i=r.node;if(i.type==="whiteout")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(i.type!=="symlink")throw new D("EINVAL",`invalid argument, readlink '${e}'`);return i.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new D("ENOENT",`no such file or directory, readlink '${e}'`);try{let i=await sn.promises.readlink(s);if(!Xn.isAbsolute(i)){let o=Xn.resolve(Xn.dirname(s),i),a;try{a=sn.realpathSync(o)}catch{a=o}if(!Zn(a,this.canonicalRoot))return Xn.basename(i)}return this.realTargetToVirtual(i)}catch(i){if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(i.code==="EINVAL")throw new D("EINVAL",`invalid argument, readlink '${e}'`);this.sanitizeError(i,e,"readlink")}}async realpath(e){Ce(e,"realpath");let n=ce(e),r=new Set,s=l=>{let c=this.tree.descend(l);if(c.kind==="blocked"||c.kind==="found"&&c.node.type==="whiteout")throw new D("ENOENT",`no such file or directory, realpath '${e}'`);return c.kind==="found"?c.node:void 0},i=async l=>{let c=l==="/"?[]:l.slice(1).split("/"),u="";for(let f of c){if(u=`${u}/${f}`,r.has(u))throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);let d=s(u),h=0,p=Nc;for(;d&&d.type==="symlink"&&h<p;){if(r.add(u),u=this.resolveSymlink(u,d.target),h++,r.has(u))throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);d=s(u)}if(h>=p)throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);if(!d){let m=this.toRealPath(u),g=this.resolveRealPath_(m);if(g)try{if((await Js(g)).isSymbolicLink()){if(!this.allowSymlinks)throw new D("ENOENT",`no such file or directory, realpath '${e}'`);let w=await sn.promises.readlink(g),b=this.realTargetToVirtual(w);return r.add(u),u=this.resolveSymlink(u,b),i(u)}}catch(y){if(y.code==="ENOENT")throw new D("ENOENT",`no such file or directory, realpath '${e}'`);this.sanitizeError(y,e,"realpath")}else if(!this.allowSymlinks){let y=this.resolveRealPathParent_(m);if(y)try{if((await Js(y)).isSymbolicLink())throw new D("ENOENT",`no such file or directory, realpath '${e}'`)}catch(w){if(st(w,"ENOENT")||st(w,"ELOOP"))throw new D("ENOENT",`no such file or directory, realpath '${e}'`);this.sanitizeError(w,e,"realpath")}}}}return u||"/"},o=await i(n);if(!await this.existsInOverlay(o))throw new D("ENOENT",`no such file or directory, realpath '${e}'`);return o}async utimes(e,n,r){Ce(e,"utimes"),this.assertWritable(`utimes '${e}'`);let s=ce(e);if(!await this.existsInOverlay(s))throw new D("ENOENT",`no such file or directory, utimes '${e}'`);let o=this.entryAt(s);if(o){o.mtime=r,this.tree.touch(o);return}let a=await this.stat(s);this.attachMetacopyShadow(s,a,a.mode,r)}};var Lf=class{bash;overlays;constructor(e={}){let{home:n,project:r,cwd:s,env:i,...o}=e,a=new Map,l=[],c=n?bc(n):null,u=r?bc(r):null,f=c&&u&&(()=>{let p=Yn.relative(c,u);return p!==".."&&!p.startsWith(`..${Yn.sep}`)&&!Yn.isAbsolute(p)})();if(c){let p=new Ts({root:c,mountPoint:"/"});a.set("/home/user",{root:c,fs:p}),l.push({mountPoint:"/home/user",filesystem:p})}let d="/home/user";if(u)if(f&&c){let p=Yn.relative(c,u);d=p?`/home/user/${p.split(Yn.sep).join("/")}`:"/home/user"}else{let p=new Ts({root:u,mountPoint:"/"});a.set("/project",{root:u,fs:p}),l.push({mountPoint:"/project",filesystem:p}),d="/project"}let h=new Wr({base:new ir,mounts:l});this.overlays=a,this.bash=new Xo({...o,env:{HOME:"/home/user",...i},cwd:s??d,fs:h})}analyzeCommands(e){return this.bash.analyzeCommands(e)}exec(e){return this.bash.exec(e)}diff(){let e=[],n=[];for(let{root:r,fs:s}of this.overlays.values()){let i=s.diff();for(let{path:o,...a}of i.writes)e.push({...a,path:Yn.join(r,o)});for(let o=0;o<i.deletions.length;o++)n.push({path:Yn.join(r,i.deletions[o]),changedAt:i.deletionChangedAt?.[o]})}return e.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),n.sort((r,s)=>r.path<s.path?-1:r.path>s.path?1:0),{writes:e,deletions:n.map(r=>r.path),...n.length>0&&{deletionChangedAt:n.map(r=>r.changedAt??0)}}}async applyChanges(e=this.diff()){let n=new Map,r=s=>{let i=this.findOverlay(s);if(!i)return;let o=`/${Yn.relative(i.root,s).split(Yn.sep).join("/")}`;if(o==="/")return;let a=n.get(i.fs);a?a.push(o):n.set(i.fs,[o])};try{for(let s of e.deletions)j7(s),r(s);for(let s of e.writes)q7(s.path,s),r(s.path)}finally{for(let[s,i]of n)s.drop(i)}}findOverlayEntry(e){let n=null;for(let[r,s]of this.overlays)(e===s.root||e.startsWith(s.root+Yn.sep))&&(!n||s.root.length>n.root.length)&&(n={mountPoint:r,root:s.root,fs:s.fs});return n}findOverlay(e){return this.findOverlayEntry(e)}resolveRealPath(e){let n=this.findOverlayEntry(e);if(!n)return null;let r=`/${Yn.relative(n.root,e).split(Yn.sep).join("/")}`;return{mountPoint:n.mountPoint,overlay:n.fs,path:r}}toRealPath(e){let n=e.startsWith("/")?e:`/${e}`,r=null;for(let[s,i]of this.overlays)(n===s||n.startsWith(`${s}/`))&&(!r||s.length>r.mountPoint.length)&&(r={mountPoint:s,root:i.root});return r?Yn.join(r.root,n.slice(r.mountPoint.length)):null}async sync(){for(let{fs:e}of this.overlays.values())await e.sync()}reset(){for(let{fs:e}of this.overlays.values())e.reset()}};function uF(t={}){return new Lf(t)}pe();bn();var fF=require("node:crypto"),Q=jt(require("node:fs"),1),De=jt(require("node:path"),1);pe();Jl();bn();us();var xre=["EACCES","escaping sandbox","EFBIG","ENOTSUP"],Ff=class t{static activeMutationRoots=new Set;static pendingMutations=[];root;canonicalRoot;maxFileReadSize;maxCopyOnWriteSize;maxCopySize;allowSymlinks;constructor(e){this.root=De.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.maxCopyOnWriteSize=e.maxCopyOnWriteSize??104857600,this.maxCopySize=e.maxCopySize??0,this.allowSymlinks=e.allowSymlinks??!1,h1(this.root,"ReadWriteFs"),this.canonicalRoot=Q.realpathSync(this.root)}resolveAndValidate(e,n){let r=this.allowSymlinks?Ha(e,this.canonicalRoot):d1(e,this.root,this.canonicalRoot);if(r===null)throw new D("EACCES",`permission denied, '${n}' resolves outside sandbox`);return r}validateParent(e,n){let r=De.dirname(e),s=this.resolveAndValidate(r,n);return De.join(s,De.basename(e))}toRealPath(e){let n=ce(e),r=De.join(this.root,n);return De.resolve(r)}async readFile(e,n){let r=await this.readFileBuffer(e),s=As(n);return ts(r,s)}async readFileBytes(e){let n=await this.readFileBuffer(e);return ts(n,"binary")}async readFileBuffer(e){Ce(e,"open");let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let s=this.allowSymlinks?Q.constants.O_RDONLY:Q.constants.O_RDONLY|Q.constants.O_NOFOLLOW,i=await Q.promises.open(r,s);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new D("EFBIG",`file too large, read '${e}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, open '${e}'`);if(i.code==="EISDIR")throw new D("EISDIR",`illegal operation on a directory, read '${e}'`);if(i.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(s,e,"open")}}async writeFile(e,n,r){await this.withFilesystemMutation(()=>this.writeFileUnlocked(e,n,r))}async writeFileUnlocked(e,n,r){Ce(e,"write");let s=this.toRealPath(e),i=this.resolveAndValidate(s,e),o=As(r),a=Hs(n,o),l=De.dirname(i);try{await Q.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,e);let c=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,u=null;try{let f=await Q.promises.lstat(i);if(!f.isFile()&&!f.isDirectory())throw new D("EACCES",`cannot write special file '${e}'`);let d=await Q.promises.open(i,Q.constants.O_WRONLY|Q.constants.O_NONBLOCK|c);try{if(u=await d.stat(),!u.isFile())throw new D("EACCES",`cannot write special file '${e}'`);if(u.nlink<=1){await d.truncate(0),await d.writeFile(a);return}}finally{await d.close()}}catch(f){if(f.code!=="ENOENT")throw f}await this.replaceFile(i,a,u)}catch(c){if(c.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(c,e,"write")}}async appendFile(e,n,r){await this.withFilesystemMutation(()=>this.appendFileUnlocked(e,n,r))}async appendFileUnlocked(e,n,r){Ce(e,"append");let s=this.toRealPath(e),i=As(r),o=Hs(n,i),a=this.resolveAndValidate(s,e),l=De.dirname(a);try{await Q.promises.mkdir(l,{recursive:!0}),a=this.resolveAndValidate(s,e);let c=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,u=null;try{let d=await Q.promises.lstat(a);if(!d.isFile()&&!d.isDirectory())throw new D("EACCES",`cannot append special file '${e}'`);let h=await Q.promises.open(a,Q.constants.O_WRONLY|Q.constants.O_APPEND|Q.constants.O_NONBLOCK|c);try{if(u=await h.stat(),!u.isFile())throw new D("EACCES",`cannot append special file '${e}'`);if(u.nlink<=1){await h.writeFile(o);return}}finally{await h.close()}}catch(d){if(d.code!=="ENOENT")throw d}if(!u){await this.replaceFile(a,o,null);return}this.assertCopyOnWriteSize(u.size,"append",e);let f=await this.openCopySource(a);try{let d=await f.stat();if(!d.isFile()||d.dev!==u.dev||d.ino!==u.ino)throw new D("EACCES",`file identity changed, append '${e}'`);await this.replaceFile(a,o,d,{handle:f,size:u.size})}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(c,e,"append")}}async withFilesystemMutation(e){return new Promise((n,r)=>{t.pendingMutations.push({root:this.canonicalRoot,start:()=>{t.activeMutationRoots.add(this.canonicalRoot),e().then(n,r).finally(()=>{t.activeMutationRoots.delete(this.canonicalRoot),t.drainMutationQueue()})}}),t.drainMutationQueue()})}static drainMutationQueue(){for(let e=0;e<t.pendingMutations.length;){let n=t.pendingMutations[e];if([...t.activeMutationRoots].some(s=>Zn(n.root,s)||Zn(s,n.root))){e++;continue}t.pendingMutations.splice(e,1),n.start()}}assertCopyOnWriteSize(e,n,r){if(this.maxCopyOnWriteSize>0&&e>this.maxCopyOnWriteSize)throw new D("EFBIG",`file too large for copy-on-write ${n} '${r}' (${e} bytes, max ${this.maxCopyOnWriteSize})`)}assertCopySize(e,n){if(this.maxCopySize>0&&e.size>this.maxCopySize)throw new D("EFBIG",`file too large to copy '${n}' (${e.size} bytes, max ${this.maxCopySize})`)}randomTransactionToken(){return(0,fF.randomBytes)(16).toString("hex")}async openCopySource(e){let n=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,r=Q.constants.O_RDONLY|Q.constants.O_NONBLOCK|n,s=Q.constants.O_NOATIME;if(process.platform!=="linux"||s===void 0)return Q.promises.open(e,r);try{return await Q.promises.open(e,r|s)}catch(i){if(i.code!=="EPERM")throw i;return Q.promises.open(e,r)}}async replaceFile(e,n,r,s,i,o=!1){let a=De.dirname(e),l="",c=null,u=r===null?438:384;for(let p=0;p<16;p++){l=De.join(a,`.just-bash-write-${this.randomTransactionToken()}`);try{c=await Q.promises.open(l,Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL,u);break}catch(m){if(m.code!=="EEXIST")throw m}}if(!c)throw new D("EEXIST",`replacement write '${e}'`);let f=c,d=await f.stat(),h=!1;try{try{let m=0,g=async y=>{let w=0;for(;w<y.byteLength;){let{bytesWritten:b}=await f.write(y,w,y.byteLength-w,m+w);if(b===0)throw new D("EIO","replacement write made no progress");w+=b}m+=w};if(s){let y=Buffer.allocUnsafe(65536),w=0,b=s.size;for(;b>0;){let x=Math.min(y.length,b),{bytesRead:S}=await s.handle.read(y,0,x,w);if(S===0)break;await g(y.subarray(0,S)),w+=S,b-=S}}if(await g(n),r!==null&&await f.chmod(r.mode&(o?4095:511)),i)await f.utimes(i.atime,i.mtime);else if(r!==null){let y=await f.stat();await f.utimes(r.atime,y.mtime)}}finally{await f.close(),c=null}let p=await Q.promises.lstat(l);if(!p.isFile()||p.dev!==d.dev||p.ino!==d.ino)throw new D("EACCES","replacement staging entry changed");await Q.promises.rename(l,e),h=!0}finally{c&&await c.close().catch(()=>{}),h||await Q.promises.rm(l,{force:!0}).catch(()=>{})}}async exists(e){if(e.includes("\0"))return!1;let n=this.toRealPath(e);try{let r=this.resolveAndValidate(n,e);return await Q.promises.access(r),!0}catch{return!1}}async stat(e){Ce(e,"stat");let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let s=await Q.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new D("EACCES",`permission denied, '${e}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new D("ENOENT",`no such file or directory, stat '${e}'`);this.sanitizeError(s,e,"stat")}}async lstat(e){Ce(e,"lstat");let n=this.toRealPath(e),r=n===this.root?this.resolveAndValidate(n,e):this.validateParent(n,e);try{let s=await Q.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new D("ENOENT",`no such file or directory, lstat '${e}'`);this.sanitizeError(s,e,"lstat")}}async mkdir(e,n){await this.withFilesystemMutation(()=>this.mkdirUnlocked(e,n))}async createExclusive(e,n){await this.withFilesystemMutation(()=>this.createExclusiveUnlocked(e,n))}async createExclusiveUnlocked(e,n){let r=n.directory?"mkdir":"open";Ce(e,r);let s=this.toRealPath(e),i=s===this.root?this.resolveAndValidate(s,e):this.validateParent(s,e);try{if(n.directory){await Q.promises.mkdir(i,{mode:n.mode});let l=await Q.promises.open(i,Q.constants.O_RDONLY|(Q.constants.O_DIRECTORY??0)|(this.allowSymlinks?0:Q.constants.O_NOFOLLOW));try{await this.assertCreatedInsideRoot(i,s,e,r,await l.stat())}finally{await l.close()}return}let o=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,a=await Q.promises.open(i,Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|o,n.mode);try{await this.assertCreatedInsideRoot(i,s,e,r,await a.stat())}finally{await a.close()}}catch(o){let a=o;if(a.code==="EEXIST")throw new D("EEXIST",`file already exists, ${r} '${e}'`);if(a.code==="ENOENT")throw new D("ENOENT",`no such file or directory, ${r} '${e}'`);this.sanitizeError(o,e,r)}}async assertCreatedInsideRoot(e,n,r,s,i){let o=!1;try{let a=this.resolveAndValidate(n,r),l=await Q.promises.lstat(a);o=a===e&&l.dev===i.dev&&l.ino===i.ino}catch{o=!1}if(!o)throw new D("EACCES",`permission denied, '${r}' resolves outside sandbox during ${s}`)}async mkdirUnlocked(e,n){Ce(e,"mkdir");let r=this.toRealPath(e),s=r===this.root?this.resolveAndValidate(r,e):this.validateParent(r,e);try{await Q.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new D("EEXIST",`file already exists, mkdir '${e}'`);if(o.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mkdir '${e}'`);this.sanitizeError(i,e,"mkdir")}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){Ce(e,"scandir");let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{if(!this.allowSymlinks&&(await Q.promises.lstat(r)).isSymbolicLink())throw new D("EACCES",`permission denied, '${e}' is a symlink`);return(await Q.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, scandir '${e}'`);if(i.code==="ENOTDIR")throw new D("ENOTDIR",`not a directory, scandir '${e}'`);this.sanitizeError(s,e,"scandir")}}async rm(e,n){await this.withFilesystemMutation(()=>this.rmUnlocked(e,n))}async rmUnlocked(e,n){Ce(e,"rm");let r=this.toRealPath(e),s=this.validateParent(r,e);try{let i=await Q.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new D("EACCES",`permission denied, '${e}' is a symlink`);await Q.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"){if(n?.force)return;throw new D("ENOENT",`no such file or directory, rm '${e}'`)}if(o.code==="ENOTEMPTY")throw new D("ENOTEMPTY",`directory not empty, rm '${e}'`);this.sanitizeError(i,e,"rm")}}async cp(e,n,r){await this.withFilesystemMutation(()=>this.cpUnlocked(e,n,r))}async cpUnlocked(e,n,r){Ce(e,"cp"),Ce(n,"cp");let s=this.toRealPath(e),i=this.toRealPath(n),o=this.validateParent(s,e),a=this.resolveAndValidate(i,n),l;try{l=await Q.promises.lstat(o)}catch(c){if(c.code==="ENOENT")throw new D("ENOENT",`no such file or directory, cp '${e}'`);this.sanitizeError(c,e,"cp")}if(l.isDirectory()&&Zn(a,o))throw new D("EINVAL",`cannot copy '${e}' into itself, '${n}'`);if(!l.isDirectory())try{let c=this.validateParent(i,n),u=await Q.promises.lstat(c);if(l.dev===u.dev&&l.ino===u.ino)throw new D("EINVAL",`cannot copy '${e}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}if(l.isFile())try{let c=await Q.promises.stat(a);if(l.dev===c.dev&&l.ino===c.ino)throw new D("EINVAL",`cannot copy '${e}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}try{await this.preflightCopyTree(o,e)}catch(c){this.sanitizeError(c,e,"cp")}if(l.isFile()||l.isSymbolicLink())try{await Q.promises.mkdir(De.dirname(a),{recursive:!0}),this.resolveAndValidate(i,n)}catch(c){this.sanitizeError(c,n,"cp")}try{await this.copyTreeEntry(o,i,e,n,r?.recursive??!1)}catch(c){let u=c;if(u.code==="ENOENT")throw new D("ENOENT",`no such file or directory, cp '${e}'`);if(u.code==="EISDIR")throw new D("EISDIR",`is a directory, cp '${e}'`);this.sanitizeError(c,e,"cp")}}async copyTreeEntry(e,n,r,s,i){let o=await Q.promises.lstat(e);if(o.isFile()){this.assertCopySize(o,r);let a=this.resolveAndValidate(n,s),l=await this.assertCopyDestinationWritable(a,s),c=await this.openCopySource(e);try{let u=await c.stat();if(!u.isFile()||u.dev!==o.dev||u.ino!==o.ino)throw new D("EACCES",`file identity changed, cp '${r}'`);await this.replaceFile(a,new Uint8Array(0),l??o,{handle:c,size:o.size})}finally{await c.close()}return}if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new D("EACCES",`permission denied, cp '${r}' contains a symlink`);let a=await Q.promises.readlink(e),l=De.isAbsolute(a)?await this.toVirtualAbsoluteSymlinkTarget(a,r):a;await this.replaceSymlink(n,s,l);return}if(o.isDirectory()){if(!i)throw new D("EISDIR",`is a directory, cp '${r}'`);let a=this.resolveAndValidate(n,s);await Q.promises.mkdir(a,{recursive:!0}),a=this.resolveAndValidate(n,s);for(let l of await Q.promises.readdir(e))await this.copyTreeEntry(De.join(e,l),De.join(n,l),De.join(r,l),De.join(s,l),!0);await Q.promises.chmod(a,o.mode&4095);return}throw new D("EINVAL",`unsupported file type, cp '${r}'`)}async assertCopyDestinationWritable(e,n){let r;try{r=await Q.promises.lstat(e)}catch(o){if(o.code==="ENOENT")return null;throw o}if(!r.isFile()){if(r.isDirectory())return r;throw new D("EACCES",`cannot copy over special file '${n}'`)}let s=this.allowSymlinks?0:Q.constants.O_NOFOLLOW,i=await Q.promises.open(e,Q.constants.O_WRONLY|Q.constants.O_NONBLOCK|s);try{let o=await i.stat();if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)throw new D("EACCES",`destination changed, cp '${n}'`)}finally{await i.close()}return r}async replaceSymlink(e,n,r){let s=this.validateParent(e,n),i=De.dirname(ce(n)),o="",a="",l="",c=null;for(let f=0;f<16;f++){let d=`.just-bash-copy-link-${this.randomTransactionToken()}`;o=i==="/"?`/${d}`:`${i}/${d}`,a=this.toRealPath(o);try{await this.symlinkUnlocked(r,o),l=this.validateParent(a,o),c=await Q.promises.lstat(l);break}catch(h){if(!st(h,"EEXIST"))throw h}}if(!c)throw new D("EEXIST",`replacement symlink '${n}'`);let u=!1;try{let f=await Q.promises.lstat(l);if(!f.isSymbolicLink()||f.dev!==c.dev||f.ino!==c.ino)throw new D("EACCES","replacement symlink entry changed");await Q.promises.rename(l,s),u=!0}finally{!u&&l&&await Q.promises.rm(l,{force:!0}).catch(()=>{})}}async toVirtualAbsoluteSymlinkTarget(e,n){let r=De.resolve(e),s=await Q.promises.realpath(r),i=await Q.promises.realpath(De.dirname(r)),o=De.join(i,De.basename(r));if(!Zn(s,this.canonicalRoot)||!Zn(o,this.canonicalRoot))throw new D("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return Jo(o.slice(this.canonicalRoot.length))||"/"}async preflightCopyTree(e,n,r=new Set){let s=await Q.promises.lstat(e),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new D("ELOOP",`cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new D("EACCES",`permission denied, cp '${n}' contains a symlink`);let o=await Q.promises.realpath(e);if(!Zn(o,this.canonicalRoot))throw new D("EACCES",`permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let o=await Q.promises.readdir(e);for(let a of o)await this.preflightCopyTree(De.join(e,a),De.join(n,a),r)}finally{r.delete(i)}}}async mv(e,n){await this.withFilesystemMutation(()=>this.mvUnlocked(e,n))}async mvUnlocked(e,n){Ce(e,"mv"),Ce(n,"mv");let r=this.toRealPath(e),s=this.toRealPath(n),i=this.validateParent(r,e),o=this.validateParent(s,n),a;try{a=await Q.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mv '${e}'`);this.sanitizeError(c,e,"mv")}if(a.isDirectory()&&this.isSameOrDescendantIdentity(i,o))throw new D("EINVAL",`cannot move '${e}' into itself, '${n}'`);try{if(a.isSymbolicLink()){let c=await Q.promises.readlink(i),u=De.resolve(De.dirname(o),c),f=await Q.promises.realpath(u).catch(()=>u);if(!Zn(f,this.canonicalRoot))throw new D("EACCES",`permission denied, mv '${e}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mv '${e}'`);if(st(u,"EACCES"))throw c}let l=De.dirname(o);try{await Q.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await Q.promises.rename(i,o)}catch(c){let u=c;if(u.code==="ENOENT")throw new D("ENOENT",`no such file or directory, mv '${e}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(e,n);return}this.sanitizeError(c,e,"mv")}try{if(Q.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await Q.promises.rename(o,i),new D("EACCES",`permission denied, mv '${e}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(st(c,"EACCES"))throw c;await Q.promises.rename(o,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(e,n){let r=e,s=n;try{r=Q.realpathSync(e)}catch{}try{s=Q.realpathSync(n)}catch{try{let i=Q.realpathSync(De.dirname(n));s=De.join(i,De.basename(n))}catch{}}return Zn(s,r)}async uniqueTransactionPath(e,n){let r=De.posix.dirname(e);for(let s=0;s<16;s++){let i=De.posix.join(r,`.just-bash-mv-${n}-${this.randomTransactionToken()}`);if(!await this.exists(i))return i}throw new D("EEXIST",`mv '${e}'`)}async moveAcrossDevices(e,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(e,"source"),o=this.validateParent(this.toRealPath(r),r),a=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(e),e),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,h=!1,p=async()=>{h&&await Q.promises.rename(c,l).catch(()=>{}),d&&await Q.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await Q.promises.rename(a,u).catch(()=>{}),await Q.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cpUnlocked(e,r,{recursive:!0}),(await Q.promises.lstat(o)).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw new D("EACCES",`permission denied, mv '${e}' -> '${n}' would create symlinks escaping sandbox`);try{await Q.promises.rename(u,a),f=!0}catch(g){if(g.code!=="ENOENT")throw g}await Q.promises.rename(o,u),d=!0,await Q.promises.rename(l,c),h=!0,await Q.promises.rm(c,{recursive:!0,force:!1}),h=!1,f&&await Q.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await p(),this.sanitizeError(m,e,"mv")}}resolvePath(e,n){return io(e,n)}getAllPaths(){let e=[];return this.scanDir("/",e),e}sanitizeError(e,n,r){p1(e,n,r,xre)}findEscapingSymlinks(e){let n=[],r=Q.readdirSync(e);for(let s of r){let i=De.join(e,s),o=Q.lstatSync(i);if(o.isSymbolicLink()){let a=Q.readlinkSync(i),l=De.resolve(e,a),c;try{c=Q.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}Zn(c,this.canonicalRoot)||n.push(i)}else o.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(e,n){let r=this.toRealPath(e),s;try{s=this.resolveAndValidate(r,e)}catch{return}try{let i=Q.readdirSync(s);for(let o of i){let a=e==="/"?`/${o}`:`${e}/${o}`;n.push(a);let l=De.join(s,o);Q.lstatSync(l).isDirectory()&&this.scanDir(a,n)}}catch{}}async chmod(e,n){await this.withFilesystemMutation(()=>this.chmodUnlocked(e,n))}async chmodUnlocked(e,n){Ce(e,"chmod");let r=this.toRealPath(e),s=this.resolveAndValidate(r,e);try{let i=await Q.promises.lstat(s);if(!i.isFile()){if(!i.isDirectory()&&i.nlink>1)throw new D("EACCES",`cannot chmod multiply-linked special file '${e}'`);await Q.promises.chmod(s,n);return}if(i.nlink<=1){await Q.promises.chmod(s,n);return}this.assertCopyOnWriteSize(i.size,"chmod",e);let o=await this.openCopySource(s);try{let a=await o.stat();if(!a.isFile())throw new D("EACCES",`file type changed, chmod '${e}'`);await this.replaceFile(s,new Uint8Array(0),{mode:n,atime:a.atime,mtime:a.mtime},{handle:o,size:a.size},{atime:a.atime,mtime:a.mtime},!0)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new D("ENOENT",`no such file or directory, chmod '${e}'`);if(o.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(i,e,"chmod")}}async symlink(e,n){await this.withFilesystemMutation(()=>this.symlinkUnlocked(e,n))}async symlinkUnlocked(e,n){if(!this.allowSymlinks)throw new D("EPERM",`operation not permitted, symlink '${n}'`);Ce(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=ce(n),o=ce(De.dirname(i)),a=e.startsWith("/")?ce(e):ce(o==="/"?`/${e}`:`${o}/${e}`),l=De.join(this.canonicalRoot,a),c=De.dirname(s),u=e.startsWith("/")?l:De.relative(c,l)||".";try{await Q.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new D("EEXIST",`file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(e,n){await this.withFilesystemMutation(()=>this.linkUnlocked(e,n))}async linkUnlocked(e,n){Ce(e,"link"),Ce(n,"link");let r=this.toRealPath(e),s=this.toRealPath(n),i=this.resolveAndValidate(r,e),o=s===this.root?this.resolveAndValidate(s,n):this.validateParent(s,n);try{await Q.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new D("ENOENT",`no such file or directory, link '${e}'`);if(l.code==="EEXIST")throw new D("EEXIST",`file already exists, link '${n}'`);if(l.code==="EPERM")throw new D("EPERM",`operation not permitted, link '${e}'`);this.sanitizeError(a,e,"link")}}async readlink(e){Ce(e,"readlink");let n=this.toRealPath(e),r=n===this.root?this.resolveAndValidate(n,e):this.validateParent(n,e);try{let s=await Q.promises.readlink(r),i=ce(e),o=De.dirname(i),a=De.isAbsolute(s)?s:De.resolve(De.dirname(r),s),l=await Q.promises.realpath(a).catch(()=>a);if(Zn(l,this.canonicalRoot)){let c=Jo(l.slice(this.canonicalRoot.length))||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:Jo(De.relative(o,c))}return De.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, readlink '${e}'`);if(i.code==="EINVAL")throw new D("EINVAL",`invalid argument, readlink '${e}'`);this.sanitizeError(s,e,"readlink")}}async realpath(e){Ce(e,"realpath");let n=this.toRealPath(e);try{this.resolveAndValidate(n,e)}catch{throw new D("ENOENT",`no such file or directory, realpath '${e}'`)}let r;try{r=await Q.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new D("ENOENT",`no such file or directory, realpath '${e}'`);if(i.code==="ELOOP")throw new D("ELOOP",`too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(s,e,"realpath")}if(Zn(r,this.canonicalRoot))return Jo(r.slice(this.canonicalRoot.length))||"/";throw new D("ENOENT",`no such file or directory, realpath '${e}'`)}async utimes(e,n,r){await this.withFilesystemMutation(()=>this.utimesUnlocked(e,n,r))}async utimesUnlocked(e,n,r){Ce(e,"utimes");let s=this.toRealPath(e),i=this.resolveAndValidate(s,e);try{let o=await Q.promises.lstat(i);if(!o.isFile()){if(!o.isDirectory()&&o.nlink>1)throw new D("EACCES",`cannot change times on multiply-linked special file '${e}'`);await Q.promises.utimes(i,n,r);return}if(o.nlink<=1){await Q.promises.utimes(i,n,r);return}this.assertCopyOnWriteSize(o.size,"utimes",e);let a=await this.openCopySource(i);try{let l=await a.stat();if(!l.isFile())throw new D("EACCES",`file type changed, utimes '${e}'`);await this.replaceFile(i,new Uint8Array(0),l,{handle:a,size:l.size},{atime:n,mtime:r},!0)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new D("ENOENT",`no such file or directory, utimes '${e}'`);if(a.code==="ELOOP")throw new D("EACCES",`permission denied, '${e}' is a symlink`);this.sanitizeError(o,e,"utimes")}}};var Xi=jt(require("node:path"),1);bn();function dF(t){if(t.mounts.length===0)throw new D("EINVAL","createVfsTemplate needs at least one mount");let e=t.mounts.map(({at:c,root:u})=>{let f=bc(u);return{at:(c.startsWith("/")?c:`/${c}`).replace(/\/+$/,"")||"/",root:f}}),n=new Set;for(let{at:c}of e){if(n.has(c))throw new D("EINVAL",`duplicate mount point '${c}' in createVfsTemplate`);if(n.add(c),c==="/")throw new D("EINVAL","mount point '/' would swallow the shared scratch space");for(let u of n)if(u!==c&&c.startsWith(`${u}/`))throw new D("EINVAL",`mount point '${c}' is nested inside '${u}'`)}let r=[];for(let{root:c}of e){for(let u of r){let f=Xi.default.sep;if(c!==u&&(c.startsWith(u+f)||u.startsWith(c+f)))throw new D("EINVAL",`nested template roots share one real subtree: '${c}' and '${u}'`)}r.push(c)}let s=new ir,i=()=>{let c=new Wr({base:s});for(let{at:u,root:f}of e)c.mount(u,new Ts({root:f,mountPoint:"/",...t.readOnly!==void 0&&{readOnly:t.readOnly},...t.maxMemoryBytes!==void 0&&{maxMemoryBytes:t.maxMemoryBytes}}));return c};return{fork:()=>i(),merge:async c=>{let u=[],f=0;for(let h of c){let p=h instanceof Wr?h.diff({space:"vfs"}):h;for(let m of p.writes){let g=m.changedAt??0;u.push({kind:"write",changedAt:g,order:f++,write:m})}for(let m=0;m<p.deletions.length;m++){let g=p.deletionChangedAt?.[m]??0;u.push({kind:"delete",changedAt:g,order:f++,path:p.deletions[m]})}}u.sort((h,p)=>h.changedAt!==p.changedAt?h.changedAt-p.changedAt:h.order-p.order);let d=i();for(let h of u){if(h.kind==="write"&&h.write.metadataOnly&&h.write.mode===void 0&&h.write.mtime===void 0)continue;let p=!1;try{if(h.kind==="delete")await d.rm(h.path,{recursive:!0});else{let m=h.write;m.metadataOnly?(m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="directory"?(await d.mkdir(m.path,{recursive:!0}),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime)):m.nodeType==="symlink"?await d.symlink(new TextDecoder().decode(m.content),m.path):(await d.writeFile(m.path,m.content),m.mode!==void 0&&await d.chmod(m.path,m.mode),m.mtime!==void 0&&await d.utimes(m.path,m.mtime,m.mtime))}p=!0}catch{}p?d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt):d.restamp(h.kind==="delete"?h.path:h.write.path,h.changedAt,"ancestors")}return d},apply:c=>{let u={writes:c.writes.map(f=>({...f,path:Xi.default.normalize(f.path)})),deletions:c.deletions.map(f=>Xi.default.normalize(f)),...c.deletionChangedAt&&{deletionChangedAt:c.deletionChangedAt}};for(let f of u.writes)if(f.nodeType==="symlink")throw new D("EINVAL",`change-set contains a symlink write: '${f.path}'`);for(let f of[...u.deletions,...u.writes.map(d=>d.path)]){if(!e.some(({root:m})=>f===m||f.startsWith(m+Xi.default.sep)))throw new D("EINVAL",`change-set entry outside every template root: '${f}'`);if(u.deletions.includes(f)&&e.some(({root:g})=>f===g))throw new D("EINVAL",`change-set deletes a registered root: '${f}'`);let h=Ere(f);if(!e.some(({root:m})=>h===m||h.startsWith(m+Xi.default.sep)))throw new D("EINVAL",`change-set entry escapes its root through a symlink: '${f}'`)}Rf(u)}}}function Ere(t){let e=t,n=[];for(;;)try{let r=bc(e);return n.length===0?r:Xi.default.join(r,...n.reverse())}catch{let r=Xi.default.dirname(e);if(r===e)return t;n.push(Xi.default.basename(e)),e=r}}Fi();Os();var Ga=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(e,n,r,s,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=e,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let e=Math.max(0,this.timeoutMs);this.timeoutId=Ti(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${e}ms`))},e)}}cleanupCancellation(){this.timeoutId!==void 0&&(Hr(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener("abort",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let e={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let n=await this.bashEnv.exec(this.cmdLine,e);return this.exitCode=n.exitCode,n}finally{this.cleanupCancellation()}}async*logs(){let e=await this.resultPromise;e.stdout&&(yield{type:"stdout",data:e.stdout,timestamp:new Date}),e.stderr&&(yield{type:"stderr",data:e.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let e=await this.resultPromise;return e.stdout+e.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error("command killed"))}};var Df=class t{bashEnv;timeoutMs;constructor(e,n){this.bashEnv=e,this.timeoutMs=n}static async create(e){let n=e?.fs;if(e?.overlayRoot){if(e?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Ts({root:e.overlayRoot})}let r=new Xo({env:e?.env,cwd:e?.cwd,fs:n,maxCallDepth:e?.maxCallDepth,maxCommandCount:e?.maxCommandCount,maxLoopIterations:e?.maxLoopIterations,network:e?.network,defenseInDepth:e?.defenseInDepth,python:e?.python,javascript:e?.javascript,commands:e?.commands,customCommands:e?.customCommands,fetch:e?.fetch});return new t(r,e?.timeoutMs)}async runCommand(e,n,r){let s,i,o,a,l=!1,c,u;if(typeof e=="object"){let m=e,g=[m.cmd,...m.args??[]];s=Fn(g),i=m.cwd,o=m.env,a=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=Fn([e,...n]),a=m?.signal}else{s=e;let m=n;i=m?.cwd,o=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new Ga(this.bashEnv,s,f,o,d,a,this.timeoutMs);if(l)return h;let p=await h.wait();if(c){let m=await h.stdout();m&&c.write(m)}if(u){let m=await h.stderr();m&&u.write(m)}return p}async writeFiles(e){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(e)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let o=this.bashEnv.fs.resolvePath(n,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(e,n){let r=await this.bashEnv.readFile(e);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(e,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),e);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(e){}get domain(){}get bashEnvInstance(){return this.bashEnv}};cn();var _f=class{violations=[];violationsByType=new Map;options;constructor(e={}){this.options={maxViolationsPerType:e.maxViolationsPerType??100,maxViolationsTotal:e.maxViolationsTotal??1e3,includeStackTraces:e.includeStackTraces??!0,onViolation:e.onViolation??(()=>{}),logToConsole:e.logToConsole??!1}}record(e){let n=this.options.includeStackTraces?e:{...e,stack:void 0};this.violations.unshift(n),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(e.type);r||(r=[],this.violationsByType.set(e.type,r)),r.length<this.options.maxViolationsPerType&&r.push(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${e.type}: ${e.message}`,e.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(e){return[...this.violationsByType.get(e)??[]]}getSummary(){let e=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)s.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);e.push({type:n,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(s)})}return e.sort((n,r)=>r.count-n.count),e}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return e=>this.record(e)}};function H7(){return t=>{console.warn("[DefenseInDepth] Security violation detected:",`
|
|
2233
2233
|
Type: ${t.type}`,`
|
|
2234
2234
|
Path: ${t.path}`,`
|
|
2235
2235
|
Message: ${t.message}`,t.executionId?`
|
|
2236
|
-
ExecutionId: ${t.executionId}`:"")}}v1();k1();O1();var hF=null;try{let t=process.getBuiltinModule,e=typeof t=="function"?t("module"):typeof require=="function"?require("node:module"):null;hF=e?.Module??e?.default??null,typeof t=="function"&&t("worker_threads")?.isMainThread===!1&&t("crypto")?.randomUUID?.()}catch{hF=null}hs();var w1=class{maxSourceBytes;plugins=[];constructor(e=67108864){if(this.maxSourceBytes=e,!Number.isSafeInteger(e)||e<0)throw new Error("BashTransformPipeline: invalid maxSourceBytes")}use(e){return this.plugins.push(e),this}transform(e){wc(e,this.maxSourceBytes);let n=or(e),r=Object.create(null);for(let s of this.plugins){let i=s.transform({ast:n,metadata:r});n=i.ast,i.metadata&&(r=Di(r,i.metadata))}return{script:sc(n),ast:n,metadata:r}}};var b1=class{name="command-collector";transform(e){let{commands:n}=tm(e.ast);return{ast:e.ast,metadata:{commands:n.sort()}}}};us();var x1=class{name="tee";options;counter=0;constructor(e){this.options=e}transform(e){let n=[],r=this.options.timestamp??new Date;return{ast:this.transformScript(e.ast,n,r),metadata:{teeFiles:n}}}formatTimestamp(e){return e.toISOString().replace(/:/g,"-")}generateStdoutPath(e,n,r){let s=this.formatTimestamp(r),i=String(e).padStart(3,"0");if(
|
|
2236
|
+
ExecutionId: ${t.executionId}`:"")}}v1();k1();O1();var hF=null;try{let t=process.getBuiltinModule,e=typeof t=="function"?t("module"):typeof require=="function"?require("node:module"):null;hF=e?.Module??e?.default??null,typeof t=="function"&&t("worker_threads")?.isMainThread===!1&&t("crypto")?.randomUUID?.()}catch{hF=null}hs();var w1=class{maxSourceBytes;plugins=[];constructor(e=67108864){if(this.maxSourceBytes=e,!Number.isSafeInteger(e)||e<0)throw new Error("BashTransformPipeline: invalid maxSourceBytes")}use(e){return this.plugins.push(e),this}transform(e){wc(e,this.maxSourceBytes);let n=or(e),r=Object.create(null);for(let s of this.plugins){let i=s.transform({ast:n,metadata:r});n=i.ast,i.metadata&&(r=Di(r,i.metadata))}return{script:sc(n),ast:n,metadata:r}}};var b1=class{name="command-collector";transform(e){let{commands:n}=tm(e.ast);return{ast:e.ast,metadata:{commands:n.sort()}}}};us();var x1=class{name="tee";options;counter=0;constructor(e){this.options=e}transform(e){let n=[],r=this.options.timestamp??new Date;return{ast:this.transformScript(e.ast,n,r),metadata:{teeFiles:n}}}formatTimestamp(e){return e.toISOString().replace(/:/g,"-")}generateStdoutPath(e,n,r){let s=this.formatTimestamp(r),i=String(e).padStart(3,"0");if(Ce(this.options.outputDir,"create tee output"),!this.options.outputDir.startsWith("/")||this.options.outputDir.split("/").includes(".."))throw new Error("tee output directory must be an absolute safe path");let o=ce(this.options.outputDir),a=this.encodeCommandName(n),l=ce(`${o}/${s}-${i}-${a}.stdout.txt`);if(o!=="/"&&!l.startsWith(`${o}/`))throw new Error("tee output path escapes configured output directory");return l}encodeCommandName(e){if(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(e))return e;let n=2166136261;for(let s=0;s<e.length;s++)n^=e.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return`${e.replace(/[^A-Za-z0-9_-]/g,"_").replace(/^_+|_+$/g,"").slice(0,32)||"command"}-${n.toString(16).padStart(8,"0")}`}transformScript(e,n,r){return{...e,statements:e.statements.map(s=>this.transformStatement(s,n,r))}}transformStatement(e,n,r){let s=[],i=[];for(let o=0;o<e.pipelines.length;o++){let a=e.pipelines[o];o>0&&i.push(e.operators[o-1]);let l=this.transformPipeline(a,n,r);s.push(l.pipeline),l.origCmdNewIndices!==null&&(i.push(";"),s.push(this.makePipestatusRestore(l.origCmdNewIndices,l.negated)))}return{...e,pipelines:s,operators:i}}transformPipeline(e,n,r){if(e.commands.length<=1)return{pipeline:e,origCmdNewIndices:null,negated:!1};let s=[],i=[],o=[],a=!1;for(let l=0;l<e.commands.length;l++){let c=e.commands[l],u=l===e.commands.length-1;if(c.type!=="SimpleCommand"||!c.name||!this.shouldTarget(c)){o.push(s.length),s.push(c),u||i.push(e.pipeStderr?.[l]??!1);continue}let f=this.getCommandName(c.name)??"unknown",d=this.counter++,h=this.generateStdoutPath(d,f,r),p=this.makeTeeCommand(h),m=this.serializeCommand(c);n.push({commandIndex:d,commandName:f,command:m,stdoutFile:h}),o.push(s.length),s.push(c),i.push(e.pipeStderr?.[l]??!1),s.push(p),u||i.push(!1),a=!0}return a?{pipeline:{...e,negated:!1,commands:s,pipeStderr:i.length>0?i:void 0},origCmdNewIndices:o,negated:e.negated}:{pipeline:e,origCmdNewIndices:null,negated:!1}}makePipestatusRestore(e,n){return{type:"Pipeline",commands:[{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"builtin"}]},args:[{type:"Word",parts:[{type:"Literal",value:"__just_bash_tee_restore"}]},...e.map(r=>({type:"Word",parts:[{type:"ParameterExpansion",parameter:`PIPESTATUS[${r}]`,operation:null}]}))],redirections:[]}],negated:n}}shouldTarget(e){if(!this.options.targetCommandPattern)return!0;let n=this.getCommandName(e.name);return n!==null&&this.options.targetCommandPattern.test(n)}getCommandName(e){return e&&e.parts.length===1&&e.parts[0].type==="Literal"?e.parts[0].value:null}serializeCommand(e){let n=[];e.name&&n.push(rn(e.name));for(let r of e.args)n.push(rn(r));return n.join(" ")}makeTeeCommand(e){return{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"tee"}]},args:[{type:"Word",parts:[{type:"Literal",value:e}]}],redirections:[]}}};0&&(module.exports={AgentSandbox,Bash,BashTransformPipeline,CommandCollectorPlugin,DefenseInDepthBox,EMPTY_BYTES,FsError,InMemoryFs,MountableFs,NetworkAccessDeniedError,OverlayFs,ReadWriteFs,RedirectNotAllowedError,Sandbox,SandboxCommand,SecurityViolationError,SecurityViolationLogger,TeePlugin,TooManyRedirectsError,applyDiffToRealFs,bytesOutput,createAgentSandbox,createCommandContext,createConsoleViolationCallback,createVfsTemplate,decodeBytesToUtf8,defineCommand,encodeUtf8ToBytes,fsErrorCode,getCommandNames,getJavaScriptCommandNames,getNetworkCommandNames,getPythonCommandNames,isFsErrorCode,latin1FromBytes,parse,serialize,stdoutAsBytes,stdoutKind,textOutput,toFsError,unsafeBytesFromLatin1});
|
|
2237
2237
|
/*! Bundled license information:
|
|
2238
2238
|
|
|
2239
2239
|
re2js/build/index.esm.js:
|