#!/usr/bin/env node import{text}from"node:stream/consumers";function opPrec(op){switch(op){case`,`:return 1;case`=`:case`+=`:case`-=`:case`*=`:case`/=`:case`%=`:case`<<=`:case`>>=`:case`&=`:case`|=`:case`^=`:return 2;case`||`:return 4;case`&&`:return 5;case`|`:return 6;case`^`:return 7;case`&`:return 8;case`==`:case`!=`:return 9;case`<`:case`<=`:case`>`:case`>=`:return 10;case`<<`:case`>>`:return 11;case`+`:case`-`:return 12;case`*`:case`/`:case`%`:return 13;case`**`:return 14;default:return-1}}function opRightAssoc(op){switch(op){case`=`:case`+=`:case`-=`:case`*=`:case`/=`:case`%=`:case`<<=`:case`>>=`:case`&=`:case`|=`:case`^=`:case`**`:return!0;default:return!1}}let pendingArithCmdExps=null;function drainArithCmdExps(){let out=pendingArithCmdExps;return pendingArithCmdExps=null,out}function parseArithmeticExpression(src,offset=0){pendingArithCmdExps=null;let pos=0,len=src.length;function skipWS(){for(;pos=len)return null;let c=src.charCodeAt(pos),nc=pos+1>=`):(pos+=2,`>>`):nc===61?(pos+=2,`>=`):(pos++,`>`);case 43:return nc===61?(pos+=2,`+=`):nc===43?null:(pos++,`+`);case 45:return nc===61?(pos+=2,`-=`):nc===45?null:(pos++,`-`);case 42:return nc===42?(pos+=2,`**`):nc===61?(pos+=2,`*=`):(pos++,`*`);case 47:return nc===61?(pos+=2,`/=`):(pos++,`/`);case 37:return nc===61?(pos+=2,`%=`):(pos++,`%`);case 124:return nc===124?(pos+=2,`||`):nc===61?(pos+=2,`|=`):(pos++,`|`);case 38:return nc===38?(pos+=2,`&&`):nc===61?(pos+=2,`&=`):(pos++,`&`);case 94:return nc===61?(pos+=2,`^=`):(pos++,`^`);case 63:return pos++,`?`;default:return null}}function parseBinExpr(minPrec){let left=parseUnaryExpr();for(;skipWS(),!(pos>=len);){let saved=pos,op=tryReadBinOp();if(!op)break;if(op===`?`){if(3=len)return{type:`ArithmeticWord`,pos:pos+offset,end:pos+offset,value:``};let start=pos,c=src.charCodeAt(pos),nc=pos+1=len)return{type:`ArithmeticWord`,pos:pos+offset,end:pos+offset,value:``};let c=src.charCodeAt(pos);if(c===40){let start=pos;pos++;let expr=parseBinExpr(0);return skipWS(),pos=len)return{type:`ArithmeticWord`,pos:start+offset,end:pos+offset,value:`$`};let c=src.charCodeAt(pos);if(c===40)if(pos+10;)src.charCodeAt(pos)===40&&pos+10;){let ch=src.charCodeAt(pos);ch===40?depth++:ch===41&&depth--,pos++}let text=src.slice(start,pos),inner=text.slice(2,-1),node={type:`ArithmeticCommandExpansion`,pos:start+offset,end:pos+offset,text,inner,script:void 0};return(pendingArithCmdExps??=[]).push(node),node}else if(c===123){pos++;let depth=1;for(;pos0;){let ch=src.charCodeAt(pos);ch===123?depth++:ch===125&&depth--,pos++}}else for(;pos=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===95)pos++;else break}return{type:`ArithmeticWord`,pos:start+offset,end:pos+offset,value:src.slice(start,pos)}}function readWordAtom(){let start=pos;for(;pos=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||c===95||c===35)pos++;else break}if(pos>start&&pos0;){let c=src.charCodeAt(pos);c===91?depth++:c===93&&depth--,pos++}}return pos===start&&pos++,{type:`ArithmeticWord`,pos:start+offset,end:pos+offset,value:src.slice(start,pos)}}if(skipWS(),pos>=len)return null;let result=parseBinExpr(0);return skipWS(),result}function dequoteValue(parts){let s=``;for(let c of parts)s+=c.type===`Literal`?c.value:c.text;return s}function unescapeBareValue(text){let first=text.indexOf(`\\`);if(first===-1)return text;let s=``,start=0;for(let i=first;i=text.length){s+=`\\`,start=i;break}text.charCodeAt(i)!==10&&(s+=text[i]),start=i+1}return s+text.slice(start)}var WordImpl=class WordImpl{static _resolveWord;static _resolveHeredocBody;text;pos;end;#source;#resolver;#parts;#value=null;constructor(text,pos,end,source,resolver){this.text=text,this.pos=pos,this.end=end,this.#source=source??``,this.#resolver=resolver??WordImpl._resolveWord,this.#parts=source===void 0?void 0:null}get value(){if(this.#value===null){let parts=this.parts;if(!parts)this.#value=unescapeBareValue(this.text);else{let s=``;for(let p of parts)switch(p.type){case`Literal`:case`SingleQuoted`:case`AnsiCQuoted`:s+=p.value;break;case`DoubleQuoted`:case`LocaleString`:s+=dequoteValue(p.parts);break;default:s+=p.text;break}this.#value=s}}return this.#value}get parts(){return this.#parts===null&&(this.#parts=this.#resolver(this.#source,this)??void 0),this.#parts}set parts(v){this.#parts=v??void 0}toJSON(){return{text:this.text,pos:this.pos,end:this.end,parts:this.parts,value:this.value}}};const Token={Word:0,Assignment:1,Semi:2,Newline:3,Pipe:4,And:5,Or:6,Amp:7,LParen:8,RParen:9,LBrace:10,RBrace:11,Bang:12,If:13,Then:14,Else:15,Elif:16,Fi:17,Do:18,Done:19,For:20,While:21,Until:22,In:23,Case:24,Esac:25,Function:26,DoubleSemi:27,SemiAmp:28,DoubleSemiAmp:29,Select:30,DblLBracket:31,DblRBracket:32,EOF:33,ArithCmd:34,Coproc:35,Redirect:36};var TokenValue=class{token=Token.EOF;value=``;pos=0;end=0;fileDescriptor=void 0;variableName=void 0;content=void 0;targetPos=0;targetEnd=0;reset(){this.token=Token.EOF,this.value=``,this.pos=0,this.end=0,this.fileDescriptor=void 0,this.variableName=void 0,this.content=void 0,this.targetPos=0,this.targetEnd=0}copyFrom(other){this.token=other.token,this.value=other.value,this.pos=other.pos,this.end=other.end,this.fileDescriptor=other.fileDescriptor,this.variableName=other.variableName,this.content=other.content,this.targetPos=other.targetPos,this.targetEnd=other.targetEnd}};const RESERVED_WORDS={if:Token.If,then:Token.Then,else:Token.Else,elif:Token.Elif,fi:Token.Fi,do:Token.Do,done:Token.Done,for:Token.For,while:Token.While,until:Token.Until,in:Token.In,case:Token.Case,esac:Token.Esac,function:Token.Function,select:Token.Select,coproc:Token.Coproc,"!":Token.Bang,"{":Token.LBrace,"}":Token.RBrace},charType=new Uint8Array(128);charType[124]=1,charType[38]=1,charType[59]=1,charType[40]=1,charType[41]=1,charType[60]=1,charType[62]=1,charType[32]=1,charType[9]=1,charType[10]=1,charType[92]=2,charType[39]=2,charType[34]=2,charType[36]=2,charType[96]=2,charType[123]=2;function findUnnested(s,target){let depth=0;for(let i=0;i0&&depth--;continue}if(c===39){for(i++;i57)return!1}return text.length>0}function isAssignmentWord(text){let eqIdx=text.indexOf(`=`);if(eqIdx<=0)return!1;let c=text.charCodeAt(0);if(c>=128||!(isIdChar[c]&1))return!1;let i=1;for(;i=128||!(isIdChar[c]&2)));i++);if(i===eqIdx||c===43&&i+1===eqIdx)return!0;if(c===91){let rbIdx=text.indexOf(`]`,i+1);if(rbIdx>i&&(rbIdx+1===eqIdx||text.charCodeAt(rbIdx+1)===43&&rbIdx+2===eqIdx))return!0}return!1}function setToken(out,token,value,pos=0,end=0){out.token=token,out.value=value,out.pos=pos,out.end=end,out.fileDescriptor=void 0,out.variableName=void 0,out.content=void 0}const LexContext={Normal:0,CommandStart:1,TestMode:2};function scanBraceExpansion(src,pos,len){let nextCh=pos+10;){let bc=src.charCodeAt(scanPos);if(bc===123)depth++;else if(bc===125){if(--depth===0)break}else if(bc<=32||bc===59||bc===124||bc===38)return-1;else depth===1&&(bc===44||bc===46&&scanPos+1`,script:void 0,inner:inner??void 0,innerStart:startPos+2};this.collectedExpansions.push(part),this.pos{litBuf&&=(parts.push({type:`Literal`,value:litBuf,text:src.slice(litStart,i)}),``)};for(;i1||parts.length===1&&parts[0].type!==`Literal`?parts:null}registerHereDocTarget(target){for(let hd of this.pendingHereDocs)if(!hd.target){hd.target=target;return}}readTestRegexWord(){this.hasPeek=!1;let chars=[40,41,124,60,62],saved=chars.map(c=>charType[c]);for(let c of chars)charType[c]=0;try{return this.skipSpacesAndTabs(),this.readWord(this.current,LexContext.Normal,this.pos),this.current}finally{for(let i=0;i0;){let c=src.charCodeAt(this.pos);if(c===40)depth++,this.pos++;else if(c===41){if(depth--,depth===0){let raw=src.slice(partStart,this.pos);for(parts[partIdx]=raw.trim(),parts[3+partIdx]=starts[partIdx]+raw.length-raw.trimStart().length,this.pos++;this.pos=len){setToken(out,Token.EOF,``,pos,pos);return}let tokenStart=pos,ch=src.charCodeAt(pos);if(ch===35){for(;this.pos`,tokenStart,this.pos);return}this.tryReadOperator(out,ch,ctx,tokenStart)||this.readWord(out,ctx,tokenStart)}tryReadOperator(out,ch,ctx,tokenStart){let src=this.src,pos=this.pos,next=pos+1>`:`&>`,tokenStart),!0}return this.pos++,setToken(out,Token.Amp,`&`,tokenStart,this.pos),!0;case 40:return ctx===LexContext.CommandStart&&next===40?(this.readArithmeticCommand(out,tokenStart),!0):(this.pos++,setToken(out,Token.LParen,`(`,tokenStart,this.pos),!0);case 41:return this.pos++,setToken(out,Token.RParen,`)`,tokenStart,this.pos),!0;case 60:case 62:return this.readRedirection(out,tokenStart);default:return!1}}readRedirection(out,tokenStart){let src=this.src,ch=src.charCodeAt(this.pos),op=``;if(ch===60){this.pos++;let next=this.pos`,this.pos++):next===38?(op=`<&`,this.pos++):op=`<`}else if(ch===62){this.pos++;let next=this.pos`,tokenStart),!0;next===62?(op=`>>`,this.pos++):next===38?(op=`>&`,this.pos++):next===124?(op=`>|`,this.pos++):op=`>`}if(this.skipSpacesAndTabs(),this.pos=97&&next<=122||next>=65&&next<=90||next===95||next===33||next===35||next===64||next===42||next===63||next===45||next>=48&&next<=57){hasExpansion=!0;break}}c===92&&i++}return hasExpansion?new WordImpl(body,bodyPos,bodyPos+body.length,this.src,WordImpl._resolveHeredocBody):null}_wordText=``;_wordQuoted=!1;_wordHasExpansions=!1;_wordParts=null;_redirectTargetPos=0;_resultText=``;_resultHasExpansion=!1;_resultPart;_dqText=``;_dqHasExpansions=!1;_dqParts=null;_hereDelim=``;_hereQuoted=!1;readWord(out,ctx,tokenStart=0){this.readWordText();let text=this._wordText,hasExpansions=this._wordHasExpansions,quoted=this._wordQuoted,wordEnd=this.pos;if(ctx===LexContext.CommandStart){if(!hasExpansions&&!quoted){let fc=text.charCodeAt(0);if((fc>=97&&fc<=122&&text.length<=8||fc===33||fc===123||fc===125)&&text in RESERVED_WORDS){setToken(out,RESERVED_WORDS[text],text,tokenStart,wordEnd);return}if(fc===91&&text===`[[`){setToken(out,Token.DblLBracket,text,tokenStart,wordEnd);return}}if(isAssignmentWord(text)){setToken(out,Token.Assignment,text,tokenStart,wordEnd);return}}if(!hasExpansions&&!quoted&&text===`]]`){setToken(out,Token.DblRBracket,text,tokenStart,wordEnd);return}if(!hasExpansions&&this.pos=48&&text.charCodeAt(0)<=57&&isAllDigits(text)){let fd=Number.parseInt(text,10);if(this.readRedirection(out,tokenStart)){out.fileDescriptor=fd;return}}if(text.charCodeAt(0)===123&&text.charCodeAt(text.length-1)===125&&text.length>2){let varname=text.slice(1,-1);if(this.readRedirection(out,tokenStart)){out.variableName=varname;return}}}}setToken(out,Token.Word,text,tokenStart,wordEnd)}readWordText(){let src=this.src,len=this.srcEnd,pos=this.pos,fastStart=pos;for(;pos=len||charType[exitCh]&1&&!(exitCh===40&&pos>fastStart&&extglobPrefix[src.charCodeAt(pos-1)])){this.pos=pos,this._wordText=pos>fastStart?src.slice(fastStart,pos):``,this._wordQuoted=!1,this._wordHasExpansions=!1,this._buildParts&&(this._wordParts=null);return}let text=pos>fastStart?src.slice(fastStart,pos):``,quoted=!1,hasExpansions=!1,bp=this._buildParts,parts,litBuf=``,litStart=0;for(bp&&(parts=[],litBuf=text,litStart=fastStart);pos=128||!charType[ch]){let runStart=pos;for(pos++;pos0&&extglobPrefix[text.charCodeAt(text.length-1)]){let prefixChar=text.charCodeAt(text.length-1);pos++;let innerStart=pos,depth=1;for(;pos0;){let c=src.charCodeAt(pos);c===40?depth++:c===41&&depth--,pos++}let pattern=src.slice(innerStart,pos-1),eg=`(`+src.slice(innerStart,pos);if(text+=eg,bp&&prefixChar!==61){if(litBuf.length>0){let trimmed=litBuf.slice(0,-1);trimmed&&parts.push({type:`Literal`,value:trimmed,text:src.slice(litStart,innerStart-2)}),litBuf=``}let op=extglobOp[prefixChar],fullText=op+eg;parts.push({type:`ExtendedGlob`,text:fullText,operator:op,pattern}),litStart=pos}else bp&&(litBuf+=eg);continue}break}if(ch===92){if(pos++,pos0){let braceText=src.slice(pos,braceEnd);text+=braceText,bp&&(litBuf&&=(parts.push({type:`Literal`,value:litBuf,text:src.slice(litStart,pos)}),``),parts.push({type:`BraceExpansion`,text:braceText}),litStart=braceEnd),pos=braceEnd;continue}text+=`{`,bp&&(litBuf+=`{`),pos++;continue}pos++}bp&&litBuf&&parts.push({type:`Literal`,value:litBuf,text:src.slice(litStart,pos)}),this.pos=pos,this._wordText=text,this._wordQuoted=quoted,this._wordHasExpansions=hasExpansions,bp&&(this._wordParts=parts.length>1||parts.length===1&&parts[0].type!==`Literal`?parts:null)}readInnerWordText(){let src=this.src,len=this.srcEnd,pos=this.pos,text=``,bp=this._buildParts,parts,litBuf=``,litStart=0;for(bp&&(parts=[],litStart=pos);pos1||parts.length===1&&parts[0].type!==`Literal`?parts:null)}parseSubFieldWord(start,end){if(start>=end)return new WordImpl(``,start,start);let savedEnd=this.srcEnd,savedPos=this.pos,savedText=this._wordText,savedParts=this._wordParts,savedQuoted=this._wordQuoted;this.srcEnd=end,this.pos=start,this.readInnerWordText();let word=new WordImpl(this.src.slice(start,end),start,end);return this._buildParts&&this._wordParts&&(word.parts=this._wordParts),this.srcEnd=savedEnd,this.pos=savedPos,this._wordText=savedText,this._wordParts=savedParts,this._wordQuoted=savedQuoted,word}skipSQ(){for(;this.pos0;){let c=src.charCodeAt(this.pos);if(c===125){if(--d===0){this.pos++;break}}else if(c===123&&this.pos>0&&src.charCodeAt(this.pos-1)===36)d++;else if(c===92)this.pos++;else if(c===39){this.pos++,this.skipSQ();continue}else if(c===34){this.pos++,this.skipDQ();continue}this.pos++}continue}}if(ch===96){for(this.pos++;this.posrunStart){let chunk=src.slice(runStart,this.pos);text+=chunk,bp&&(litBuf+=chunk)}if(this.pos>=len||src.charCodeAt(this.pos)===34)break;let ch=src.charCodeAt(this.pos);if(ch===92){if(this.pos++,this.pos=len){this._resultText=`$`,this._resultHasExpansion=!1,this._resultPart=void 0;return}let ch=src.charCodeAt(this.pos);if(ch===40){if(this.pos+1=48&&ch<=57){this.pos++;let text=src.slice(this.pos-2,this.pos);this._resultText=text,this._resultHasExpansion=!1,this._resultPart=this._buildParts?{type:`SimpleExpansion`,text}:void 0;return}if(ch<128&&isIdChar[ch]&1){let dollarPos=this.pos-1;for(;this.pos0;){let c=src.charCodeAt(this.pos);if(c===40&&this.pos+10;){let ch=src.charCodeAt(this.pos);if(ch===123&&this.pos>0&&src.charCodeAt(this.pos-1)===36)depth++;else if(ch===125){if(--depth===0){this.pos++;break}}else if(ch===92)this.pos++;else if(ch===39){this.pos++,this.skipSQ();continue}else if(ch===34){this.pos++,this.skipDQ();continue}this.pos++}let text=src.slice(start-1,this.pos);if(this._resultText=text,this._resultHasExpansion=!1,this._buildParts){let inner=src.slice(start+1,this.pos-1);this._resultPart=this.parseParamInner(text,inner,start+1)}else this._resultPart=void 0}parseParamInner(text,inner,innerStart){let result={type:`ParameterExpansion`,text,parameter:``,index:void 0,indirect:void 0,length:void 0,operator:void 0,operand:void 0,slice:void 0,replace:void 0},ilen=inner.length;if(ilen===0)return result;let sub=(a,b)=>this.parseSubFieldWord(innerStart+a,innerStart+b),i=0;if(inner.charCodeAt(0)===33&&(result.indirect=!0,i=1),!result.indirect&&inner.charCodeAt(0)===35){if(ilen===1)return result.parameter=`#`,result;if(inner.charCodeAt(1)===35)result.parameter=`#`,i=1;else{let tryI=this.scanParamName(inner,1);if(tryI>1){let endI=tryI;if(endI=ilen){if(result.length=!0,result.parameter=inner.slice(1,tryI),tryI=ilen)return result;let opChar=inner.charCodeAt(i);if(opChar===58){if(i+1=s.length)return i;let c=s.charCodeAt(i);if(c===64||c===42||c===35||c===63||c===45||c===36||c===33)return i+1;if(c>=48&&c<=57){for(;i=48&&s.charCodeAt(i)<=57;)i++;return i}if(c>=97&&c<=122||c>=65&&c<=90||c===95)for(i++;i=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===95)i++;else break}return i}findCloseBracket(s,start){let depth=1;for(let i=start;i0;){let c=src.charCodeAt(this.pos);if(c===41){if(depth--,depth===0){let result=src.slice(start,this.pos);return this.pos++,result}this.pos++}else if(c===40||c===92||c===39||c===34||c===96)break;else if(c===99&&(this.pos===start||src.charCodeAt(this.pos-1)<128&&charType[src.charCodeAt(this.pos-1)]!==0)&&this.pos+3=len||src.charCodeAt(this.pos+4)<128&&charType[src.charCodeAt(this.pos+4)]&1))break;else this.pos++}if(depth===0)return src.slice(start,this.pos);let caseDepth=0;for(;this.pos0;){let ch=src.charCodeAt(this.pos);if(ch===40)depth++,this.pos++;else if(ch===41)if(caseDepth>0)this.pos++;else{if(depth--,depth===0){let result=src.slice(start,this.pos);return this.pos++,result}this.pos++}else if(ch===92)this.pos++,this.poswStart){if(this.pos-wStart===4){let c0=src.charCodeAt(wStart);c0===99&&src.charCodeAt(wStart+1)===97&&src.charCodeAt(wStart+2)===115&&src.charCodeAt(wStart+3)===101?caseDepth++:c0===101&&src.charCodeAt(wStart+1)===115&&src.charCodeAt(wStart+2)===97&&src.charCodeAt(wStart+3)===99&&caseDepth>0&&caseDepth--}}else this.pos++}}return src.slice(start,this.pos)}};function computeWordParts(source,word){let lexer=new Lexer(source,word.pos,word.end),parts=lexer.buildWordParts(word.pos);if(parts)return resolveCollected(lexer),parts}function computeHereDocBodyParts(source,word){let lexer=new Lexer(source,word.pos,word.end),parts=lexer.buildHereDocParts(word.pos,word.end);if(parts)return resolveCollected(lexer),parts}function resolveCollected(lexer){let source=lexer.getSource();for(let e of lexer.getCollectedExpansions())e.inner!==void 0&&(e.script=e.innerStart===void 0?parse(e.inner):parseRegion(source,e.innerStart,e.innerStart+e.inner.length),e.inner=void 0,e.innerStart=void 0)}WordImpl._resolveWord=computeWordParts,WordImpl._resolveHeredocBody=computeHereDocBodyParts;var ArithmeticCommandImpl=class{type=`ArithmeticCommand`;pos;end;body;#expression=null;constructor(pos,end,body){this.pos=pos,this.end=end,this.body=body}get expression(){return this.#expression===null&&(this.#expression=parseArithmeticExpression(this.body,this.pos+2)??void 0,resolveDrainedArithCmdExps()),this.#expression}set expression(v){this.#expression=v??void 0}},ArithmeticForImpl=class{type=`ArithmeticFor`;pos;end;body;#initStr;#testStr;#updateStr;#initPos;#testPos;#updatePos;#initialize=null;#test=null;#update=null;constructor(pos,end,body,initStr,testStr,updateStr,initPos,testPos,updatePos){this.pos=pos,this.end=end,this.body=body,this.#initStr=initStr,this.#testStr=testStr,this.#updateStr=updateStr,this.#initPos=initPos,this.#testPos=testPos,this.#updatePos=updatePos}get initialize(){if(this.#initialize===null)if(this.#initStr){let expr=parseArithmeticExpression(this.#initStr);expr&&offsetArith(expr,this.#initPos),resolveDrainedArithCmdExps(),this.#initialize=expr??void 0}else this.#initialize=void 0;return this.#initialize}set initialize(v){this.#initialize=v??void 0}get test(){if(this.#test===null)if(this.#testStr){let expr=parseArithmeticExpression(this.#testStr);expr&&offsetArith(expr,this.#testPos),resolveDrainedArithCmdExps(),this.#test=expr??void 0}else this.#test=void 0;return this.#test}set test(v){this.#test=v??void 0}get update(){if(this.#update===null)if(this.#updateStr){let expr=parseArithmeticExpression(this.#updateStr);expr&&offsetArith(expr,this.#updatePos),resolveDrainedArithCmdExps(),this.#update=expr??void 0}else this.#update=void 0;return this.#update}set update(v){this.#update=v??void 0}};const CASE_TERMINATORS={[Token.DoubleSemi]:`;;`,[Token.SemiAmp]:`;&`,[Token.DoubleSemiAmp]:`;;&`},REDIRECT_OPS={">":`>`,">>":`>>`,"<":`<`,"<<":`<<`,"<<-":`<<-`,"<<<":`<<<`,"<>":`<>`,"<&":`<&`,">&":`>&`,">|":`>|`,"&>":`&>`,"&>>":`&>>`};function offsetArith(node,base){switch(node.pos+=base,node.end+=base,node.type){case`ArithmeticBinary`:offsetArith(node.left,base),offsetArith(node.right,base);break;case`ArithmeticUnary`:offsetArith(node.operand,base);break;case`ArithmeticTernary`:offsetArith(node.test,base),offsetArith(node.consequent,base),offsetArith(node.alternate,base);break;case`ArithmeticGroup`:offsetArith(node.expression,base);break}}function resolveDrainedArithCmdExps(){let list=drainArithCmdExps();if(list)for(let node of list)node.inner!==void 0&&(node.script=parse(node.inner),node.inner=void 0)}const listTerminators=new Uint8Array(37);listTerminators[Token.EOF]=1,listTerminators[Token.RParen]=1,listTerminators[Token.RBrace]=1,listTerminators[Token.Then]=1,listTerminators[Token.Else]=1,listTerminators[Token.Elif]=1,listTerminators[Token.Fi]=1,listTerminators[Token.Do]=1,listTerminators[Token.Done]=1,listTerminators[Token.Esac]=1,listTerminators[Token.DoubleSemi]=1,listTerminators[Token.SemiAmp]=1,listTerminators[Token.DoubleSemiAmp]=1;const commandStarts=new Uint8Array(37);commandStarts[Token.Word]=1,commandStarts[Token.Assignment]=1,commandStarts[Token.Bang]=1,commandStarts[Token.LParen]=1,commandStarts[Token.LBrace]=1,commandStarts[Token.DblLBracket]=1,commandStarts[Token.If]=1,commandStarts[Token.For]=1,commandStarts[Token.While]=1,commandStarts[Token.Until]=1,commandStarts[Token.Case]=1,commandStarts[Token.Function]=1,commandStarts[Token.Select]=1,commandStarts[Token.ArithCmd]=1,commandStarts[Token.Coproc]=1,commandStarts[Token.Redirect]=1;const UNARY_TEST_OPS={"-a":1,"-b":1,"-c":1,"-d":1,"-e":1,"-f":1,"-g":1,"-h":1,"-k":1,"-p":1,"-r":1,"-s":1,"-t":1,"-u":1,"-v":1,"-w":1,"-x":1,"-z":1,"-n":1,"-N":1,"-S":1,"-L":1,"-G":1,"-O":1,"-R":1},BINARY_TEST_OPS={"==":1,"!=":1,"=~":1,"=":1,"-eq":1,"-ne":1,"-lt":1,"-le":1,"-gt":1,"-ge":1,"-nt":1,"-ot":1,"-ef":1,"<":1,">":1},EMPTY_PREFIX=[],EMPTY_SUFFIX=[],EMPTY_REDIRECTS$1=[];function parse(source){return new Parser(source,0,source.length).run()}function parseRegion(source,start,end){return new Parser(source,start,end).run()}var Parser=class{tok;source;start;end;errors=[];_redirects=[];constructor(source,start,end){this.tok=new Lexer(source,start,end),this.source=source,this.start=start,this.end=end}run(){let start=this.start,shebang;if(start===0&&this.source.charCodeAt(0)===35&&this.source.charCodeAt(1)===33){let nl=this.source.indexOf(` `);shebang=nl===-1?this.source:this.source.slice(0,nl)}let commands=this.list(),lexerErrors=this.tok._errors;if(lexerErrors!==null)for(let i=0;i0?this.errors:void 0}}error(message,pos){this.errors.push({message,pos})}skipSemi(){this.tok.peek(LexContext.Normal).token===Token.Semi&&this.tok.next(LexContext.Normal)}accept(token,ctx=LexContext.Normal){return this.tok.peek(ctx).token===token?this.tok.next(ctx):null}acceptEnd(token,ctx=LexContext.Normal){return this.tok.peek(ctx).token===token?this.tok.next(ctx).end:-1}skipNewlines(ctx=LexContext.Normal){for(;this.tok.peek(ctx).token===Token.Newline;)this.tok.next(ctx)}makeStatement(command,redirects){let end=redirects.length>0?redirects[redirects.length-1].end:command.end;return{type:`Statement`,pos:command.pos,end,command,background:void 0,redirects}}list(){let commands=[];this.skipNewlines(LexContext.CommandStart);let t=this.tok.peek(LexContext.CommandStart).token;if(listTerminators[t]||!commandStarts[t])return commands;let first=this.andOr();if(first){let redirects=this._redirects;this._redirects=[],commands.push(this.makeStatement(first,redirects))}for(;t=this.tok.peek(LexContext.Normal).token,!(t!==Token.Semi&&t!==Token.Newline&&t!==Token.Amp);){let isBackground=t===Token.Amp,sepEnd=this.tok.next(LexContext.Normal).end;if(isBackground){let stmt=commands[commands.length-1];stmt.background=!0,stmt.end=sepEnd}if(this.skipNewlines(LexContext.CommandStart),t=this.tok.peek(LexContext.CommandStart).token,listTerminators[t]||!commandStarts[t])break;let node=this.andOr();if(node){let redirects=this._redirects;this._redirects=[],commands.push(this.makeStatement(node,redirects))}}return commands}andOr(){let first=this.pipeline();if(!first)return null;let t=this.tok.peek(LexContext.Normal).token;if(t!==Token.And&&t!==Token.Or)return first;let wrappedFirst=first;this._redirects.length>0&&(wrappedFirst=this.makeStatement(first,this._redirects),this._redirects=[]);let commands=[wrappedFirst],operators=[];do{operators.push(this.tok.next(LexContext.Normal).token===Token.And?`&&`:`||`),this.skipNewlines(LexContext.CommandStart);let next=this.pipeline();if(!next)break;commands.push(next),t=this.tok.peek(LexContext.Normal).token}while(t===Token.And||t===Token.Or);return{type:`AndOr`,pos:first.pos,end:commands[commands.length-1].end,commands,operators}}wrapCompoundRedirects(node){let redirects=this._redirects;return this._redirects=[],redirects.length===0?node:this.makeStatement(node,redirects)}pipeline(){let time=!1,pipelinePos=0;this.tok.peek(LexContext.CommandStart).token===Token.Word&&this.tok.peek(LexContext.CommandStart).value===`time`&&(time=!0,pipelinePos=this.tok.next(LexContext.CommandStart).pos,this.tok.peek(LexContext.CommandStart).token===Token.Word&&this.tok.peek(LexContext.CommandStart).value===`-p`&&this.tok.next(LexContext.CommandStart));let negated=this.tok.peek(LexContext.CommandStart).token===Token.Bang;negated&&(time||(pipelinePos=this.tok.peek(LexContext.CommandStart).pos),this.tok.next(LexContext.CommandStart));let first=this.command();if(!first)return time||negated?{type:`Pipeline`,pos:pipelinePos,end:pipelinePos,commands:[],negated:negated?!0:void 0,operators:[],time:time?!0:void 0}:null;!time&&!negated&&(pipelinePos=first.pos);let commands=[first],operators=[],firstRedirects=this._redirects;for(this._redirects=[];this.tok.peek(LexContext.Normal).token===Token.Pipe;){commands.length===1&&firstRedirects.length>0&&(commands[0]=this.makeStatement(first,firstRedirects),firstRedirects=[]);let pipeVal=this.tok.next(LexContext.Normal).value;operators.push(pipeVal===`|&`?`|&`:`|`),this.skipNewlines(LexContext.CommandStart);let cmd=this.command();cmd&&commands.push(this.wrapCompoundRedirects(cmd))}return commands.length===1&&!negated&&!time?(this._redirects=firstRedirects,commands[0]):(firstRedirects.length>0&&(commands[0]=this.makeStatement(first,firstRedirects)),{type:`Pipeline`,pos:pipelinePos,end:commands[commands.length-1].end,commands,negated:negated?!0:void 0,operators,time:time?!0:void 0})}command(){switch(this.tok.peek(LexContext.CommandStart).token){case Token.LParen:return this.subshell();case Token.LBrace:return this.braceGroup();case Token.If:return this.ifClause();case Token.For:return this.forClause();case Token.While:return this.whileClause();case Token.Until:return this.untilClause();case Token.Case:return this.caseClause();case Token.Function:return this.functionDef();case Token.Select:return this.selectClause();case Token.DblLBracket:return this.testCommand();case Token.ArithCmd:return this.arithCommand();case Token.Coproc:return this.coprocCommand();case Token.Word:case Token.Assignment:case Token.Redirect:return this.simpleCommandOrFunction();default:return null}}collectTrailingRedirects(){let redirects=[];for(;this.tok.peek(LexContext.Normal).token===Token.Redirect;)redirects=this.collectRedirect(redirects,LexContext.Normal);return redirects}arithCommand(){let tok=this.tok.next(LexContext.CommandStart);return this._redirects=this.collectTrailingRedirects(),new ArithmeticCommandImpl(tok.pos,tok.end,tok.value)}coprocCommand(){let startTok=this.tok.next(LexContext.CommandStart),pos=startTok.pos,startEnd=startTok.end,t=this.tok.peek(LexContext.CommandStart);if(t.token!==Token.Word&&t.token!==Token.Assignment&&t.token!==Token.Redirect){let body=this.pipeline()??{type:`Command`,pos,end:startEnd,name:void 0,prefix:EMPTY_PREFIX,suffix:EMPTY_SUFFIX,redirects:EMPTY_REDIRECTS$1},bodyRedirects=this._redirects;this._redirects=[];let redirects=this.collectTrailingRedirects(),allRedirects=[...bodyRedirects,...redirects];return{type:`Coproc`,pos,end:allRedirects.length>0?allRedirects[allRedirects.length-1].end:body.end,name:void 0,body,redirects:allRedirects}}let tentativeWord=this.toWord(this.tok.next(LexContext.CommandStart)),body=this.pipeline();if(body===null){let cmd={type:`Command`,pos:tentativeWord.pos,end:tentativeWord.end,name:tentativeWord,prefix:EMPTY_PREFIX,suffix:EMPTY_SUFFIX,redirects:EMPTY_REDIRECTS$1},redirects=this.collectTrailingRedirects();return{type:`Coproc`,pos,end:redirects.length>0?redirects[redirects.length-1].end:cmd.end,name:void 0,body:cmd,redirects}}if(body.type===`Command`){let cmd=body;cmd.name&&(cmd.suffix=[cmd.name,...cmd.suffix]),cmd.name=tentativeWord,cmd.pos=tentativeWord.pos;let redirects=this.collectTrailingRedirects();return{type:`Coproc`,pos,end:redirects.length>0?redirects[redirects.length-1].end:cmd.end,name:void 0,body:cmd,redirects}}let bodyRedirects=this._redirects;this._redirects=[];let redirects=this.collectTrailingRedirects(),allRedirects=[...bodyRedirects,...redirects];return{type:`Coproc`,pos,end:allRedirects.length>0?allRedirects[allRedirects.length-1].end:body.end,name:tentativeWord,body,redirects:allRedirects}}subshell(){let pos=this.tok.next(LexContext.CommandStart).pos,commands=this.list(),closeEnd=this.acceptEnd(Token.RParen,LexContext.Normal);closeEnd<0&&this.error(`expected ')' to close subshell`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),{type:`Subshell`,pos,end,body:this.makeCompoundList(commands)}}braceGroup(){let pos=this.tok.next(LexContext.CommandStart).pos,commands=this.list(),closeEnd=this.acceptEnd(Token.RBrace,LexContext.Normal);closeEnd<0&&this.error(`expected '}' to close brace group`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),{type:`BraceGroup`,pos,end,body:this.makeCompoundList(commands)}}ifClause(){let pos=this.tok.next(LexContext.CommandStart).pos,clause=this.makeCompoundList(this.list());this.skipSemi(),this.accept(Token.Then,LexContext.CommandStart)||this.error(`expected 'then'`,this.tok.getPos());let then_=this.makeCompoundList(this.list());this.skipSemi();let else_,end;if(this.tok.peek(LexContext.CommandStart).token===Token.Elif)else_=this.ifClause(),end=else_.end;else if(this.accept(Token.Else,LexContext.CommandStart)){else_=this.makeCompoundList(this.list()),this.skipSemi();let closeEnd=this.acceptEnd(Token.Fi,LexContext.CommandStart);closeEnd<0&&this.error(`expected 'fi' to close 'if'`,this.tok.getPos()),end=closeEnd>=0?closeEnd:pos}else{let closeEnd=this.acceptEnd(Token.Fi,LexContext.CommandStart);closeEnd<0&&this.error(`expected 'fi' to close 'if'`,this.tok.getPos()),end=closeEnd>=0?closeEnd:pos}return this._redirects=this.collectTrailingRedirects(),{type:`If`,pos,end,clause,then:then_,else:else_}}forClause(){let pos=this.tok.next(LexContext.CommandStart).pos;if(this.tok.peek(LexContext.Normal).token===Token.LParen)return this.cStyleFor(pos);let name=this.readWord(LexContext.Normal),wordlist=[];if(this.skipNewlines(LexContext.CommandStart),this.tok.peek(LexContext.CommandStart).token===Token.In)for(this.tok.next(LexContext.CommandStart);this.tok.peek(LexContext.Normal).token===Token.Word;)wordlist.push(this.readWord(LexContext.Normal));this.skipSemi(),this.skipNewlines(LexContext.CommandStart),this.accept(Token.Do,LexContext.CommandStart)||this.error(`expected 'do'`,this.tok.getPos());let body=this.list();this.skipSemi();let closeEnd=this.acceptEnd(Token.Done,LexContext.CommandStart);closeEnd<0&&this.error(`expected 'done' to close 'for'`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),{type:`For`,pos,end,name,wordlist,body:this.makeCompoundList(body)}}cStyleFor(pos){let[initStr,testStr,updateStr,initPos,testPos,updatePos]=this.tok.readCStyleForExprs();if(this.tok.peek(LexContext.CommandStart).token===Token.Semi&&this.tok.next(LexContext.CommandStart),this.skipNewlines(LexContext.CommandStart),this.tok.peek(LexContext.CommandStart).token===Token.LBrace){let bg=this.braceGroup();return new ArithmeticForImpl(pos,bg.end,bg.body,initStr,testStr,updateStr,initPos,testPos,updatePos)}this.accept(Token.Do,LexContext.CommandStart)||this.error(`expected 'do'`,this.tok.getPos());let body=this.list(),closeEnd=this.acceptEnd(Token.Done,LexContext.CommandStart);closeEnd<0&&this.error(`expected 'done' to close 'for'`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),new ArithmeticForImpl(pos,end,this.makeCompoundList(body),initStr,testStr,updateStr,initPos,testPos,updatePos)}whileClause(){return this.whileOrUntil(`while`)}untilClause(){return this.whileOrUntil(`until`)}whileOrUntil(kind){let pos=this.tok.next(LexContext.CommandStart).pos,clause=this.makeCompoundList(this.list());this.skipSemi(),this.accept(Token.Do,LexContext.CommandStart)||this.error(`expected 'do'`,this.tok.getPos());let body=this.list();this.skipSemi();let closeEnd=this.acceptEnd(Token.Done,LexContext.CommandStart);closeEnd<0&&this.error(`expected 'done' to close '${kind}'`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),{type:`While`,pos,end,kind,clause,body:this.makeCompoundList(body)}}caseClause(){let pos=this.tok.next(LexContext.CommandStart).pos,word=this.readWord(LexContext.Normal);this.skipNewlines(LexContext.CommandStart),this.accept(Token.In,LexContext.CommandStart)||this.error(`expected 'in' after 'case' word`,this.tok.getPos()),this.skipNewlines(LexContext.CommandStart);let items=[],t=this.tok.peek(LexContext.CommandStart).token;for(;t!==Token.Esac&&t!==Token.EOF;){let itemPos=this.tok.peek(LexContext.Normal).pos;this.accept(Token.LParen,LexContext.Normal);let pattern=[];for(t=this.tok.peek(LexContext.Normal).token;t!==Token.RParen&&t!==Token.EOF;)t===Token.Pipe?this.tok.next(LexContext.Normal):pattern.push(this.toWord(this.tok.next(LexContext.Normal))),t=this.tok.peek(LexContext.Normal).token;let rparenEnd=this.acceptEnd(Token.RParen,LexContext.Normal),cmds=this.list(),itemEnd=rparenEnd>=0?rparenEnd:itemPos;cmds.length>0&&(itemEnd=cmds[cmds.length-1].end);let item={type:`CaseItem`,pos:itemPos,end:itemEnd,pattern,body:this.makeCompoundList(cmds),terminator:void 0};if(t=this.tok.peek(LexContext.CommandStart).token,t===Token.DoubleSemi||t===Token.SemiAmp||t===Token.DoubleSemiAmp){let termTok=this.tok.next(LexContext.CommandStart);item.terminator=CASE_TERMINATORS[termTok.token],item.end=termTok.end}items.push(item),this.skipNewlines(LexContext.CommandStart),t=this.tok.peek(LexContext.CommandStart).token}let closeEnd=this.acceptEnd(Token.Esac,LexContext.CommandStart);closeEnd<0&&this.error(`expected 'esac' to close 'case'`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),{type:`Case`,pos,end,word,items}}selectClause(){let pos=this.tok.next(LexContext.CommandStart).pos,name=this.readWord(LexContext.Normal),wordlist=[];if(this.skipNewlines(LexContext.CommandStart),this.tok.peek(LexContext.CommandStart).token===Token.In)for(this.tok.next(LexContext.CommandStart);this.tok.peek(LexContext.Normal).token===Token.Word;)wordlist.push(this.readWord(LexContext.Normal));this.skipSemi(),this.skipNewlines(LexContext.CommandStart),this.accept(Token.Do,LexContext.CommandStart)||this.error(`expected 'do'`,this.tok.getPos());let body=this.list();this.skipSemi();let closeEnd=this.acceptEnd(Token.Done,LexContext.CommandStart);closeEnd<0&&this.error(`expected 'done' to close 'select'`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),{type:`Select`,pos,end,name,wordlist,body:this.makeCompoundList(body)}}testCommand(){let pos=this.tok.next(LexContext.CommandStart).pos,expr=this.parseTestOr(),closeEnd=this.acceptEnd(Token.DblRBracket,LexContext.TestMode);closeEnd<0&&this.tok.peek(LexContext.Normal).token===Token.EOF&&this.error(`expected ']]' to close '[['`,this.tok.getPos());let end=closeEnd>=0?closeEnd:pos;return this._redirects=this.collectTrailingRedirects(),{type:`TestCommand`,pos,end,expression:expr}}parseTestOr(){let left=this.parseTestAnd();for(;this.tok.peek(LexContext.TestMode).token===Token.Or;){this.tok.next(LexContext.TestMode);let right=this.parseTestAnd();left={type:`TestLogical`,pos:left.pos,end:right.end,operator:`||`,left,right}}return left}parseTestAnd(){let left=this.parseTestNot();for(;this.tok.peek(LexContext.TestMode).token===Token.And;){this.tok.next(LexContext.TestMode);let right=this.parseTestNot();left={type:`TestLogical`,pos:left.pos,end:right.end,operator:`&&`,left,right}}return left}parseTestNot(){if(this.tok.peek(LexContext.TestMode).token===Token.Word&&this.tok.peek(LexContext.TestMode).value===`!`){let notPos=this.tok.next(LexContext.TestMode).pos,operand=this.parseTestNot();return{type:`TestNot`,pos:notPos,end:operand.end,operand}}return this.parseTestPrimary()}parseTestPrimary(){if(this.tok.peek(LexContext.TestMode).token===Token.LParen){let openPos=this.tok.next(LexContext.TestMode).pos,expr=this.parseTestOr(),closeEnd=this.acceptEnd(Token.RParen,LexContext.TestMode);return closeEnd<0&&this.error(`expected ')' to close test group`,this.tok.getPos()),{type:`TestGroup`,pos:openPos,end:closeEnd>=0?closeEnd:openPos,expression:expr}}let first=this.tok.next(LexContext.TestMode),val=first.value,firstPos=first.pos,firstEnd=first.end;if(UNARY_TEST_OPS[val]===1&&this.tok.peek(LexContext.TestMode).token===Token.Word){let operand=this.readWord(LexContext.TestMode);return{type:`TestUnary`,pos:firstPos,end:operand.end,operator:val,operand}}let nt=this.tok.peek(LexContext.TestMode);if(nt.token===Token.Word&&BINARY_TEST_OPS[nt.value]===1){let op=this.tok.next(LexContext.TestMode).value,right;right=op===`=~`?this.toWord(this.tok.readTestRegexWord()):this.readWord(LexContext.TestMode);let left=this.toWordFromPosEnd(first,firstPos,firstEnd);return{type:`TestBinary`,pos:firstPos,end:right.end,operator:op,left,right}}let w=this.toWordFromPosEnd(first,firstPos,firstEnd);return{type:`TestUnary`,pos:firstPos,end:w.end,operator:`-n`,operand:w}}functionDef(){let pos=this.tok.next(LexContext.CommandStart).pos,name=this.readWord(LexContext.Normal);this.tok.peek(LexContext.CommandStart).token===Token.LParen&&(this.tok.next(LexContext.CommandStart),this.accept(Token.RParen,LexContext.CommandStart)||this.error(`expected ')' after '('`,this.tok.getPos())),this.skipNewlines(LexContext.CommandStart);let body=this.commandAsBody(),redirects=this._redirects;return this._redirects=[],{type:`Function`,pos,end:redirects.length>0?redirects[redirects.length-1].end:body.end,name,body,redirects}}simpleCommandOrFunction(){let prefix=[],redirects=[],cmdPos=this.tok.peek(LexContext.CommandStart).pos,lastEnd=cmdPos;for(;this.tok.peek(LexContext.CommandStart).token===Token.Assignment;){let t=this.tok.next(LexContext.CommandStart);lastEnd=t.end,prefix.push(this.parseAssignment(t))}for(;this.tok.peek(LexContext.CommandStart).token===Token.Redirect;)redirects=this.collectRedirect(redirects,LexContext.CommandStart),lastEnd=redirects[redirects.length-1].end;if(this.tok.peek(LexContext.Normal).token!==Token.Word)return prefix.length>0?{type:`Command`,pos:cmdPos,end:lastEnd,name:void 0,prefix,suffix:EMPTY_SUFFIX,redirects}:{type:`Command`,pos:cmdPos,end:lastEnd,name:void 0,prefix:EMPTY_PREFIX,suffix:EMPTY_SUFFIX,redirects:EMPTY_REDIRECTS$1};let name=this.readWord(LexContext.Normal);if(lastEnd=name.end,this.tok.peek(LexContext.Normal).token===Token.LParen&&(this.tok.next(LexContext.Normal),this.tok.peek(LexContext.Normal).token===Token.RParen)){this.tok.next(LexContext.Normal),this.skipNewlines(LexContext.CommandStart);let body=this.commandAsBody(),bodyRedirects=this._redirects;this._redirects=[];let end=bodyRedirects.length>0?bodyRedirects[bodyRedirects.length-1].end:body.end;return{type:`Function`,pos:name.pos,end,name,body,redirects:bodyRedirects}}let suffix=[];for(;;){let st=this.tok.peek(LexContext.Normal).token;if(st===Token.Word||st===Token.Assignment){let w=this.readWord(LexContext.Normal);suffix.push(w),lastEnd=w.end}else if(st===Token.Redirect)redirects=this.collectRedirect(redirects,LexContext.Normal),lastEnd=redirects[redirects.length-1].end;else break}return{type:`Command`,pos:cmdPos,end:lastEnd,name,prefix,suffix,redirects}}collectRedirect(redirects,ctx){let t=this.tok.next(ctx),r={pos:t.pos,end:t.end,operator:REDIRECT_OPS[t.value]??`>`,target:void 0,fileDescriptor:t.fileDescriptor,variableName:t.variableName,content:t.content,heredocQuoted:void 0,body:void 0};return t.content!=null&&(r.target=new WordImpl(t.content,t.targetPos,t.targetEnd,this.source)),(t.value===`<<`||t.value===`<<-`)&&this.tok.registerHereDocTarget(r),redirects.push(r),redirects}commandAsBody(){let t=this.tok.peek(LexContext.CommandStart).token;if(t===Token.LBrace)return this.braceGroup();if(t===Token.LParen)return this.subshell();let cmd=this.command(),p=this.tok.getPos();return cmd??{type:`CompoundList`,pos:p,end:p,commands:[]}}readWord(ctx){return this.toWord(this.tok.next(ctx))}toWord(tok){return new WordImpl(this.source.slice(tok.pos,tok.end),tok.pos,tok.end,this.source)}toWordFromPosEnd(tok,pos,end){return new WordImpl(this.source.slice(pos,end),pos,end,this.source)}parseAssignment(tok){let text=this.source.slice(tok.pos,tok.end),tokPos=tok.pos,tokEnd=tok.end,result={type:`Assignment`,pos:tokPos,end:tokEnd,text,name:void 0,value:void 0,append:void 0,index:void 0,array:void 0},eqIdx=text.indexOf(`=`);if(eqIdx<=0)return result;let nameEnd=eqIdx,append=!1,index;text.charCodeAt(eqIdx-1)===43&&(append=!0,nameEnd=eqIdx-1);let bracketIdx=text.indexOf(`[`);if(bracketIdx>0&&bracketIdxbracketIdx&&rbracketIdx+1===nameEnd&&(index=text.slice(bracketIdx+1,rbracketIdx),nameEnd=bracketIdx)}result.name=text.slice(0,nameEnd),append&&(result.append=!0),index!==void 0&&(result.index=index);let valStart=eqIdx+1,valueStart=tokPos+valStart;return text.charCodeAt(valStart)===40&&text.charCodeAt(text.length-1)===41?result.array=this.parseArrayElements(valueStart+1,tokEnd-1):result.value=new WordImpl(text.slice(valStart),valueStart,tokEnd,this.source),result}parseArrayElements(start,end){let subTok=new Lexer(this.source,start,end),elements=[];for(;subTok.peek(LexContext.Normal).token!==Token.EOF;){if(subTok.peek(LexContext.Normal).token===Token.Newline){subTok.next(LexContext.Normal);continue}let t=subTok.next(LexContext.Normal);(t.token===Token.Word||t.token===Token.Assignment)&&elements.push(new WordImpl(this.source.slice(t.pos,t.end),t.pos,t.end,this.source))}return elements}makeCompoundList(commands){let p=this.tok.getPos();return{type:`CompoundList`,pos:commands.length>0?commands[0].pos:p,end:commands.length>0?commands[commands.length-1].end:p,commands}}};function caughtValueText(value){return Error.isError(value)?value.message:String(value)}function reportLoggerInternalError({context,error}){console.warn(`logger internal error: ${context}: ${caughtValueText(error)}`)}async function trackWrite({writePromise}){try{await writePromise}catch(error){reportLoggerInternalError({context:`sink write promise rejected while being tracked`,error})}}function createLogger({sinks}){let entries=sinks.map(function(sink){return{available:!1,sink}}),startupRecords=[],pendingWrites=new Set,state={hasAvailableSink:!1,initialized:!1};function recomputeAvailability(){state.hasAvailableSink=entries.some(function(entry){return entry.available})}function getSinkEntry({entryIndex}){let entry=entries[entryIndex];if(entry===void 0)throw Error(`Missing logger sink entry at index ${entryIndex}.`);return entry}function markEntryUnavailable({entryIndex}){let entry=getSinkEntry({entryIndex});entry.available=!1,recomputeAvailability()}async function removePendingWriteWhenSettled({trackedWrite}){await trackedWrite,pendingWrites.delete(trackedWrite)}function writeRecordToEntry({entryIndex,record}){try{let trackedWrite=trackWrite({writePromise:getSinkEntry({entryIndex}).sink.write(record)});pendingWrites.add(trackedWrite),removePendingWriteWhenSettled({trackedWrite})}catch(error){reportLoggerInternalError({context:`sink write threw synchronously while dispatching record`,error})}}function replayStartupRecordsToEntry({entryIndex}){startupRecords.forEach(function(record){writeRecordToEntry({entryIndex,record})})}function setEntryAvailability({entryIndex,available}){let entry=getSinkEntry({entryIndex});entry.available=available,recomputeAvailability(),available&&replayStartupRecordsToEntry({entryIndex})}async function verifyAndApply({entryIndex}){try{setEntryAvailability({available:await getSinkEntry({entryIndex}).sink.verify(),entryIndex})}catch(error){reportLoggerInternalError({context:`sink verification failed for entry ${entryIndex}`,error}),markEntryUnavailable({entryIndex})}}async function initialize(){if(!state.initialized){for(let[entryIndex]of entries.entries())await verifyAndApply({entryIndex});state.initialized=!0,startupRecords.length=0}}let initPromise=initialize();async function drainPendingWrites(){let writes=[...pendingWrites];await Promise.all(writes)}function createMethod(level){return function(message){if(!state.hasAvailableSink&&state.initialized)throw Error(`No logging backends available`);let record={level,message,timestamp:Date.now()};state.initialized||startupRecords.push(record),entries.map(function(_entry,entryIndex){return entryIndex}).filter(function(entryIndex){return getSinkEntry({entryIndex}).available}).forEach(function(entryIndex){writeRecordToEntry({entryIndex,record})})}}async function flushAll(){await initPromise,await drainPendingWrites(),await Promise.all(entries.map(async function(entry,entryIndex){let sinkFlush=entry.sink.flush;if(!(!entry.available||typeof sinkFlush!=`function`))try{await sinkFlush()}catch(error){reportLoggerInternalError({context:`sink flush failed for entry ${entryIndex}`,error}),markEntryUnavailable({entryIndex})}}))}return{initPromise,logger:{debug:createMethod(`debug`),error:createMethod(`error`),fatal:createMethod(`fatal`),flush:flushAll,info:createMethod(`info`),trace:createMethod(`trace`),warn:createMethod(`warn`)}}}const VERBOSE_UNCOMPUTED=Symbol(`logger:verbose-detection-uncomputed`),SILENT_LEVELS=new Set([`debug`,`trace`]);function detectVerbose(){try{if(typeof process<`u`&&process.env.MONOCHROMATIC_VERBOSE===`true`)return!0}catch(error){reportLoggerInternalError({context:`MONOCHROMATIC_VERBOSE environment probe failed during verbose detection`,error})}try{if(typeof process<`u`&&Array.isArray(process.argv)&&process.argv.includes(`--verbose`))return!0}catch(error){reportLoggerInternalError({context:`process argv probe failed during verbose detection`,error})}try{if(`window`in globalThis)return!0}catch(error){reportLoggerInternalError({context:`window probe failed during verbose detection`,error})}return!1}function isWarnSuppressed(){try{return typeof process<`u`&&process.env.MONOCHROMATIC_WARN===`false`}catch(error){return reportLoggerInternalError({context:`MONOCHROMATIC_WARN environment probe failed during warn suppression detection`,error}),!1}}const LEVEL_TO_CONSOLE_METHOD={debug:`debug`,error:`error`,fatal:`error`,info:`info`,trace:`trace`,warn:`warn`};function formatRecord(record){return`[${record.level}] [${new Date(record.timestamp).toISOString()}] ${record.message}`}function hasProcessStderr(){try{return typeof process>`u`?!1:typeof process.stderr.write==`function`}catch(error){return reportLoggerInternalError({context:`process stderr availability probe failed`,error}),!1}}function writeDebugRunToProcessStderr(text){try{return hasProcessStderr()?(process.stderr.write(`${text}\n`),!0):!1}catch(error){return reportLoggerInternalError({context:`debug run process stderr write failed`,error}),!1}}function emitRun({records,level}){let text=records.map(function(r){return formatRecord(r)}).join(` `);if(!(level===`debug`&&writeDebugRunToProcessStderr(text)))try{let method=LEVEL_TO_CONSOLE_METHOD[level],consoleFn=console[method];typeof consoleFn==`function`&&consoleFn.call(console,text)}catch(error){reportLoggerInternalError({context:`console method call failed while emitting log run`,error})}}function groupRuns(records){return records.reduce(function(runs,record){let tail=runs.at(-1);return tail!==void 0&&tail.level===record.level?(tail.records.push(record),runs):(runs.push({level:record.level,records:[record]}),runs)},[])}function verifyConsole(){try{return typeof console>`u`||typeof(hasProcessStderr()?console.info:console.debug)!=`function`||typeof queueMicrotask!=`function`?Promise.resolve(!1):Promise.resolve(!0)}catch(error){return reportLoggerInternalError({context:`console sink verification failed`,error}),Promise.resolve(!1)}}function createConsoleSink(){let state={buffer:[],scheduled:!1,verboseCache:VERBOSE_UNCOMPUTED};function getVerbose(){let cached=state.verboseCache;if(cached!==VERBOSE_UNCOMPUTED)return cached;let computed=detectVerbose();return state.verboseCache=computed,computed}function flushBuffer(){if(state.scheduled=!1,state.buffer.length===0)return;let records=state.buffer.splice(0);for(let run of groupRuns(records))emitRun({level:run.level,records:run.records})}function write(record){return!getVerbose()&&SILENT_LEVELS.has(record.level)||record.level===`warn`&&isWarnSuppressed()?Promise.resolve():(state.buffer.push(record),state.scheduled||(state.scheduled=!0,queueMicrotask(flushBuffer)),Promise.resolve())}function flush(){return flushBuffer(),Promise.resolve()}return{flush,verify:verifyConsole,write}}const NO_NODE_MODULES_FOUND=Symbol(`logger:no-node-modules-found`);async function findNodeModulesUp({cwd,stat,dirname,join,reportError=reportLoggerInternalError}){let candidate=join(cwd,`node_modules`);try{if((await stat(candidate)).isDirectory())return candidate}catch(error){Error.isError(error)&&`code`in error&&error.code===`ENOENT`||reportError({context:`node_modules candidate ${candidate} unavailable during file sink search`,error})}let parent=dirname(cwd);return parent===cwd?NO_NODE_MODULES_FOUND:await findNodeModulesUp({cwd:parent,stat,dirname,join,reportError})}function createFileSink(){let state={};async function runVerify(){if(globalThis.process===void 0||globalThis.process.versions?.node===void 0)return!1;try{let fs=await import(`node:fs/promises`),{dirname,join}=await import(`node:path`);state.appendFile=fs.appendFile;let nodeModulesDir=await findNodeModulesUp({cwd:process.cwd(),stat:fs.stat,dirname,join});if(nodeModulesDir===NO_NODE_MODULES_FOUND)return!1;let LOG_DIR=join(nodeModulesDir,`.monochromatic`);await fs.mkdir(LOG_DIR,{recursive:!0});let timestamp=new Date().toISOString().replaceAll(`:`,`-`);state.filePath=join(LOG_DIR,`${timestamp}.log.jsonl`);let testData=`{"test":true,"timestamp":${Date.now()}}\n`;return await state.appendFile(state.filePath,testData),(await fs.readFile(state.filePath,`utf8`)).includes(`"test":true`)}catch(error){return reportLoggerInternalError({context:`file sink verification failed`,error}),!1}}function verify(){return state.verifyPromise===void 0&&(state.verifyPromise=runVerify()),state.verifyPromise}async function write(record){if(!(!state.filePath||!state.appendFile))try{await state.appendFile(state.filePath,`${JSON.stringify(record)}\n`)}catch(error){reportLoggerInternalError({context:`file sink record append failed`,error})}}return{verify,write}}function createOpfsSink(){let state={};async function verify(){try{let opfsRoot=await navigator.storage.getDirectory(),timestamp=new Date().toISOString().replaceAll(`:`,`-`),fileHandle=await opfsRoot.getFileHandle(`monochromatic-${timestamp}.log.jsonl`,{create:!0}),probeWritable=await fileHandle.createWritable({keepExistingData:!0}),testData=`{"test":true,"timestamp":${Date.now()}}\n`;await probeWritable.write(testData),await probeWritable.close();let available=(await(await fileHandle.getFile()).text()).includes(`"test":true`);return available&&(state.writable=await fileHandle.createWritable({keepExistingData:!0})),available}catch(error){let opfsStorage=globalThis.navigator?.storage;return opfsStorage!==void 0&&`getDirectory`in opfsStorage&&reportLoggerInternalError({context:`OPFS sink verification failed`,error}),!1}}async function write(record){if(state.writable)try{await state.writable.write(`${JSON.stringify(record)}\n`)}catch(error){reportLoggerInternalError({context:`OPFS sink record write failed`,error})}}return{verify,write}}const RUNTIME_QUOTA_CHARS={deno:10485760,node:5242880,browser:5242880};function detectSessionStorageQuotaChars(){return`Deno`in globalThis?RUNTIME_QUOTA_CHARS.deno:`Bun`in globalThis?1/0:typeof process<`u`&&typeof process.versions.node==`string`?RUNTIME_QUOTA_CHARS.node:`document`in globalThis?RUNTIME_QUOTA_CHARS.browser:1/0}const QUOTA_EXCEEDED_NAMES=new Set([`QuotaExceededError`,`NS_ERROR_DOM_QUOTA_REACHED`]);function storageKey(index){return`monochromatic.log.${index}`}function isQuotaExceededError(error){return typeof error==`object`&&!!error&&`name`in error&&typeof error.name==`string`&"A_EXCEEDED_NAMES.has(error.name)}function verifySessionStorage(){try{let testKey=`__monochromatic_verify__`,testValue=`test-${Date.now()}`;globalThis.sessionStorage.setItem(testKey,testValue);let readBack=globalThis.sessionStorage.getItem(testKey);return globalThis.sessionStorage.removeItem(testKey),Promise.resolve(readBack===testValue)}catch(error){return`sessionStorage`in globalThis&&reportLoggerInternalError({context:`sessionStorage sink verification failed`,error}),Promise.resolve(!1)}}function createSessionStorageSink(){let state={lineCounter:0,oldestIndex:0,usedChars:0,reportedFailure:!1},capChars=detectSessionStorageQuotaChars()/2;function evictOldest(){let key=storageKey(state.oldestIndex),evicted=globalThis.sessionStorage.getItem(key);globalThis.sessionStorage.removeItem(key),state.oldestIndex++,evicted!==null&&(state.usedChars=Math.max(0,state.usedChars-evicted.length))}function write(record){let serialized=JSON.stringify(record),recordChars=serialized.length;for(;state.oldestIndexcapChars;)evictOldest();for(;;)try{return globalThis.sessionStorage.setItem(storageKey(state.lineCounter),serialized),state.lineCounter++,state.usedChars+=recordChars,state.reportedFailure=!1,Promise.resolve()}catch(error){if(isQuotaExceededError(error)&&state.oldestIndex=`A`&&c<=`Z`||c>=`a`&&c<=`z`||c===`_`}function isIdentifierContinue(c){return isIdentifierStart(c)||c>=`0`&&c<=`9`}const IDENTIFIER_NOT_FOUND=Symbol(`shell identifier not found at requested offset`);function identifierEnd({source,start}){for(let cursor=start+1;;cursor+=1)if(!isIdentifierContinue(source.charAt(cursor)))return cursor}function readIdentifier({source,start}){if(!isIdentifierStart(source.charAt(start)))return IDENTIFIER_NOT_FOUND;let cursor=identifierEnd({source,start});return{name:source.slice(start,cursor),next:cursor}}function extractParamRefs(command){let refs=new Set;for(let cursor=0;cursor`,`>>`,`<>`,`>|`,`&>`,`&>>`]),READ_FILE_OPERATORS=new Set([`<`,`<>`]),DESCRIPTOR_OPERATORS=new Set([`<&`,`>&`]);function isNumericDescriptor(target){if(target.length===0)return!1;for(let c of target)if(c<`0`||c>`9`)return!1;return!0}function redirectKind({operator,target}){return operator===`<<`||operator===`<<-`?`heredoc`:operator===`<<<`?`hereString`:DESCRIPTOR_OPERATORS.has(operator)&&target!==void 0&&isNumericDescriptor(target)?`fileDescriptor`:`file`}function redirectWritesFile({operator,kind}){return kind===`file`?WRITE_FILE_OPERATORS.has(operator)||operator===`>&`:!1}function redirectReadsFile({operator,kind}){return kind===`file`?READ_FILE_OPERATORS.has(operator)||operator===`<&`:!1}function redirectToInfo(redirect){let target=redirect.target?.value,kind=redirectKind({operator:redirect.operator,...target===void 0?{}:{target}});return{operator:redirect.operator,...target===void 0?{}:{target},...redirect.fileDescriptor===void 0?{}:{fileDescriptor:redirect.fileDescriptor},kind,writesFile:redirectWritesFile({operator:redirect.operator,kind}),readsFile:redirectReadsFile({operator:redirect.operator,kind})}}function redirectTargets(redirects){return redirects.flatMap(function(redirect){return redirect.kind!==`file`||redirect.target===void 0?[]:[redirect.target]})}function wordToArg(word){return(word.parts??[]).some(function(part){return part.type===`ProcessSubstitution`})?[]:[word.value]}function assignmentValue(assignment){return assignment.value===void 0?assignment.array===void 0?``:assignment.array.map(function(word){return word.value}).join(` `):assignment.value.value}function assignmentToEnvAssignment(assignment){return assignment.name===void 0?[]:[{name:assignment.name,value:assignmentValue(assignment)}]}function commandToInfo({command,inheritedRedirects,paramRefs,context}){let redirects=[...command.redirects,...inheritedRedirects].map(function(redirect){return redirectToInfo(redirect)});return{name:command.name?.value??``,envAssignments:command.prefix.flatMap(assignmentToEnvAssignment),args:command.suffix.flatMap(wordToArg),redirects,redirectTargets:redirectTargets(redirects),paramRefs:[...paramRefs],context}}function redirectOnlyCommand({redirects,paramRefs,context}){let convertedRedirects=redirects.map(function(redirect){return redirectToInfo(redirect)});return{name:``,envAssignments:[],args:[],redirects:convertedRedirects,redirectTargets:redirectTargets(convertedRedirects),paramRefs:[...paramRefs],context}}function visitRedirectsItem({redirects,paramRefs,context}){return redirects.length===0?EMPTY_VISIT_RESULT:{...EMPTY_VISIT_RESULT,commands:[redirectOnlyCommand({redirects,paramRefs,context})],workItems:redirectWordItems({redirects,context})}}function visitRemainingAfterCase({node,redirects,paramRefs,context}){return node.type===`Coproc`?{...EMPTY_VISIT_RESULT,workItems:[...node.name===void 0?[]:wordWorkItems({word:node.name,context}),{kind:`node`,node:node.body,redirects:EMPTY_REDIRECTS,context},...redirectWorkItems({redirects:[...redirects,...node.redirects],context})]}:node.type===`ArithmeticFor`?{...EMPTY_VISIT_RESULT,workItems:[...node.initialize===void 0?[]:[{kind:`arithmetic`,expression:node.initialize,context}],...node.test===void 0?[]:[{kind:`arithmetic`,expression:node.test,context}],...node.update===void 0?[]:[{kind:`arithmetic`,expression:node.update,context}],...statementWorkItems({statements:node.body.commands,context}),...redirectWorkItems({redirects,context})]}:node.type===`TestCommand`?{...EMPTY_VISIT_RESULT,workItems:[{kind:`test`,expression:node.expression,context},...redirectWorkItems({redirects,context})]}:node.type===`ArithmeticCommand`?{...EMPTY_VISIT_RESULT,workItems:[...node.expression===void 0?[]:[{kind:`arithmetic`,expression:node.expression,context}],...redirectWorkItems({redirects,context})]}:visitRedirectsItem({redirects,paramRefs,context})}function visitRemainingNode({node,redirects,paramRefs,context}){if(node.type===`Function`){let functionContext={kind:`functionDefinition`,functionName:node.name.value};return{...EMPTY_VISIT_RESULT,workItems:[...wordWorkItems({word:node.name,context}),{kind:`node`,node:node.body,redirects:node.redirects,context:functionContext},...redirectWorkItems({redirects,context})]}}return node.type===`Subshell`||node.type===`BraceGroup`?{...EMPTY_VISIT_RESULT,workItems:[...statementWorkItems({statements:node.body.commands,context}),...redirectWorkItems({redirects,context})]}:node.type===`CompoundList`?{...EMPTY_VISIT_RESULT,workItems:[...statementWorkItems({statements:node.commands,context}),...redirectWorkItems({redirects,context})]}:node.type===`Case`?{...EMPTY_VISIT_RESULT,workItems:[...wordWorkItems({word:node.word,context}),...caseItemWorkItems({node,context}),...redirectWorkItems({redirects,context})]}:visitRemainingAfterCase({node,redirects,paramRefs,context})}function visitNode({node,redirects,paramRefs,context}){return node.type===`Statement`?{...EMPTY_VISIT_RESULT,workItems:[{kind:`node`,node:node.command,redirects:[...node.redirects,...redirects],context}],flags:{...EMPTY_VISIT_RESULT.flags,hasBackground:node.background===!0}}:node.type===`Command`?{...EMPTY_VISIT_RESULT,commands:[commandToInfo({command:node,inheritedRedirects:redirects,paramRefs,context})],workItems:commandWordItems({command:node,redirects,context})}:node.type===`Pipeline`?{...EMPTY_VISIT_RESULT,flags:{...EMPTY_VISIT_RESULT.flags,isPipeline:node.operators.length>0},workItems:[...nodeWorkItems({nodes:node.commands,context}),...redirectWorkItems({redirects,context})]}:node.type===`AndOr`?{...EMPTY_VISIT_RESULT,workItems:[...nodeWorkItems({nodes:node.commands,context}),...redirectWorkItems({redirects,context})]}:node.type===`If`?{...EMPTY_VISIT_RESULT,workItems:[...statementWorkItems({statements:node.clause.commands,context}),...statementWorkItems({statements:node.then.commands,context}),...node.else===void 0?[]:[{kind:`node`,node:node.else,redirects:EMPTY_REDIRECTS,context}],...redirectWorkItems({redirects,context})]}:node.type===`For`||node.type===`Select`?{...EMPTY_VISIT_RESULT,workItems:[...wordWorkItems({word:node.name,context}),...wordsWorkItems({words:node.wordlist,context}),...statementWorkItems({statements:node.body.commands,context}),...redirectWorkItems({redirects,context})]}:node.type===`While`?{...EMPTY_VISIT_RESULT,workItems:[...statementWorkItems({statements:node.clause.commands,context}),...statementWorkItems({statements:node.body.commands,context}),...redirectWorkItems({redirects,context})]}:visitRemainingNode({node,redirects,paramRefs,context})}function visitWord({word,context}){return{...EMPTY_VISIT_RESULT,workItems:[{kind:`parts`,parts:word.parts??[],context}]}}function visitPart({part,context}){return part.type===`DoubleQuoted`||part.type===`LocaleString`?{...EMPTY_VISIT_RESULT,workItems:[{kind:`parts`,parts:part.parts,context}]}:part.type===`ParameterExpansion`?{...EMPTY_VISIT_RESULT,workItems:parameterWordItems({part,context})}:part.type===`CommandExpansion`||part.type===`ProcessSubstitution`?visitExpansion({expansion:part,context}):part.type===`ArithmeticExpansion`&&part.expression!==void 0?{...EMPTY_VISIT_RESULT,workItems:[{kind:`arithmetic`,expression:part.expression,context}]}:EMPTY_VISIT_RESULT}function visitParts({parts,context}){let results=parts.map(function(part){return visitPart({part,context})});return{...EMPTY_VISIT_RESULT,workItems:results.flatMap(function(result){return result.workItems}),flags:{isPipeline:!1,hasBackground:!1,hasCommandSubstitution:results.some(function(result){return result.flags.hasCommandSubstitution}),hasProcessSubstitution:results.some(function(result){return result.flags.hasProcessSubstitution})},parseErrors:results.flatMap(function(result){return result.parseErrors})}}function visitRedirectsWorkItem({item,paramRefs}){return visitRedirectsItem({redirects:item.redirects,paramRefs,context:item.context})}function visitWorkItem({item,paramRefs}){return item.kind===`node`?visitNode({node:item.node,redirects:item.redirects,paramRefs,context:item.context}):item.kind===`word`?visitWord({word:item.word,context:item.context}):item.kind===`parts`?visitParts({parts:item.parts,context:item.context}):item.kind===`arithmetic`?visitArithmetic({expression:item.expression,context:item.context}):item.kind===`test`?visitTest({expression:item.expression,context:item.context}):visitRedirectsWorkItem({item,paramRefs})}function collectCommandInfoFromScript({script,paramRefs}){let commands=[],parseErrors=[],flags={isPipeline:!1,hasBackground:!1,hasCommandSubstitution:!1,hasProcessSubstitution:!1},stack=statementWorkItems({statements:script.commands,context:EXECUTED_CONTEXT}).toReversed();for(let item=stack.pop();item!==void 0;item=stack.pop()){let result=visitWorkItem({item,paramRefs});commands.push(...result.commands),parseErrors.push(...result.parseErrors),flags.isPipeline||=result.flags.isPipeline,flags.hasBackground||=result.flags.hasBackground,flags.hasCommandSubstitution||=result.flags.hasCommandSubstitution,flags.hasProcessSubstitution||=result.flags.hasProcessSubstitution;for(let workItem of result.workItems.toReversed())stack.push(workItem)}return{commands,flags,parseErrors}}const moduleLogger=tagged({tag:`analyzer`,l:tagged({tag:`shell-command-analyzer`})});function thrownParseError(){return{message:`unbash parse threw`,pos:0}}function tryParseScript(command){try{let script=parse(command),parseErrors=parseErrorsFromScript(script);return parseErrors.length>0?{ok:!1,parseErrors}:{ok:!0,script}}catch(error){return tagged({tag:tryParseScript.name,l:moduleLogger}).debug(`unbash parse threw value type: ${typeof error}`),{ok:!1,parseErrors:[thrownParseError()]}}}function failedAnalysis({parseErrors,paramRefs}){return{parsed:!1,parseErrors,commands:[],executedCommands:[],functionDefinitionCommands:[],isPipeline:!1,hasBackground:!1,hasCommandSubstitution:!1,hasProcessSubstitution:!1,hasHeredoc:!1,allFiles:[],allParamRefs:paramRefs}}function analyzeShellCommand(command){let preScanRefs=extractParamRefs(command),parsed=tryParseScript(command);if(!parsed.ok)return failedAnalysis({parseErrors:parsed.parseErrors,paramRefs:preScanRefs});let collection=collectCommandInfoFromScript({script:parsed.script,paramRefs:preScanRefs});if(collection.parseErrors.length>0)return failedAnalysis({parseErrors:collection.parseErrors,paramRefs:preScanRefs});let executedCommands=collection.commands.filter(function(info){return info.context.kind===`executed`}),functionDefinitionCommands=collection.commands.filter(function(info){return info.context.kind===`functionDefinition`}),allFiles=collection.commands.flatMap(function(info){return[...info.envAssignments.map(function(assignment){return assignment.value}).filter(function(value){return looksLikePath(value)}),...info.args.filter(function(arg){return looksLikePath(arg)}),...info.redirectTargets]}),allParamRefs=[...new Set(collection.commands.flatMap(function(info){return info.paramRefs}))];return allParamRefs.length===0&&preScanRefs.length>0&&allParamRefs.push(...preScanRefs),{parsed:!0,parseErrors:[],commands:collection.commands,executedCommands,functionDefinitionCommands,isPipeline:collection.flags.isPipeline,hasBackground:collection.flags.hasBackground,hasCommandSubstitution:collection.flags.hasCommandSubstitution,hasProcessSubstitution:collection.flags.hasProcessSubstitution,hasHeredoc:collection.commands.some(function(info){return info.redirects.some(function(redirect){return redirect.kind===`heredoc`||redirect.kind===`hereString`})}),allFiles,allParamRefs}}const BUN_TEST_BAN_REASON=["Blocked: `bun test` invocations are banned in this repo.","The custom `@monochromatic-dev/module-test` harness runs tests as a side effect of module import,","so `bun test ` reports `0 pass / 0 fail` even when every test passed (the harness's `PASS`",`log lines are not measured by bun's test runner).`,"Use `mise run //package/:test:unit` instead. When no such task exists, add one to the","target package's `mise.toml` first. For ad-hoc single-file runs use `node ` directly","(no `test` subcommand)."].join(` `);function invokesBunTest(command){let analysis=analyzeShellCommand(command);return analysis.parsed?analysis.commands.some(function(info){return info.name===`bun`&&info.args[0]===`test`}):!1}const BUN_TEST_DENY_OUTPUT={hookSpecificOutput:{hookEventName:`PreToolUse`,permissionDecision:`deny`,permissionDecisionReason:BUN_TEST_BAN_REASON}};function agentResumeDenyOutput(resume){return{hookSpecificOutput:{hookEventName:`PreToolUse`,permissionDecision:`deny`,permissionDecisionReason:[`Blocked: Agent resume call (agent ID: ${resume}).`,`Background agents notify automatically on completion.`,`Do not poll or resume running agents; wait for the notification.`,`If you need the result now, use TaskOutput to check the agent's status.`].join(` `)}}}function guardrailHandler(event){if(event.tool_name===`Bash`){let command=`command`in event.tool_input?event.tool_input.command:void 0;return typeof command==`string`&&invokesBunTest(command)?BUN_TEST_DENY_OUTPUT:{}}if(event.tool_name!==`Agent`)return{};let resume=`resume`in event.tool_input?event.tool_input.resume:void 0;return typeof resume==`string`?agentResumeDenyOutput(resume):{}}function guardrailParser(raw){return JSON.parse(raw)}function guardrailWriter(output){return JSON.stringify(output)}const NO_STDOUT=Symbol(`claude-code-plugin-runtime/hook-intentionally-emits-no-stdout-bytes`);async function runHookPlugin({parser,handler,writer}){let serialized=writer(await handler(parser(await text(process.stdin))));serialized!==NO_STDOUT&&process.stdout.write(serialized)}await runHookPlugin({parser:guardrailParser,handler:guardrailHandler,writer:guardrailWriter});export{};