@magic5644/graph-it-live 1.25.5 → 1.25.6

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/dist/graph-it.js CHANGED
@@ -45436,7 +45436,7 @@ Node text: ${this.#t}`),new fe.errors.InvalidOperationError(o)}return this.#e}co
45436
45436
  `)}}function K(Y){let ue=fe.ArrayUtils.groupBy(Y,Re=>Re.getSpan().getStart()),ie=0;for(let Re of ue){let Ie=Re[0].getSpan().getStart()+ie,Ne=Re.map(bt=>bt.getNewText()).join("");Rhr({sourceFile:I,insertPos:Ie,newText:Ne}),ie+=Ne.length}}}applyTextChanges(p){return p.length===0?this:(this.forgetDescendants(),Bnt({sourceFile:this._sourceFile,start:0,replacingLength:this.getFullWidth(),newText:_pn(this,p)}),this)}set(p){return a_(tzt.prototype,this,p),this}getStructure(){return D_(tzt.prototype,this,{kind:Dt.StructureKind.SourceFile})}#a(p){if(p===!1)return this.forget(),Dt.FileSystemRefreshResult.Deleted;let y=p;return y===this.getFullText()?Dt.FileSystemRefreshResult.NoChange:(this.replaceText([0,this.getEnd()],y),this._setIsSaved(!0),Dt.FileSystemRefreshResult.Updated)}_isLibFileInMemory(){return this.compilerNode.fileName.startsWith(fe.libFolderInMemoryPath)}_throwIfIsInMemoryLibFile(){if(this._isLibFileInMemory())throw new fe.errors.InvalidOperationError("This operation is not permitted on an in memory lib folder file.")}_isInProject(){return this._context.inProjectCoordinator.isSourceFileInProject(this)}_markAsInProject(){this._context.inProjectCoordinator.markSourceFileAsInProject(this)}}})();function Ddn(c){for(let[o,a]of c)T3e.isModuleSpecifierRelative(o.getLiteralText())&&o.setLiteralValue(o._sourceFile.getRelativePathAsModuleSpecifierTo(a))}function n7n(c){let o=c.getParentOrThrow(),a=o.getParent();return a!=null&&qo.isImportEqualsDeclaration(a)?a:o}var egr=c=>znt(LM(w3e(C3e(DW(c))))),nzt=egr(HC),sUt=class extends nzt{getDeclarationList(){return this._getNodeFromCompilerNode(this.compilerNode.declarationList)}getDeclarations(){return this.getDeclarationList().getDeclarations()}getDeclarationKind(){return this.getDeclarationList().getDeclarationKind()}getDeclarationKindKeywords(){return this.getDeclarationList().getDeclarationKindKeywords()}setDeclarationKind(o){return this.getDeclarationList().setDeclarationKind(o)}addDeclaration(o){return this.getDeclarationList().addDeclaration(o)}addDeclarations(o){return this.getDeclarationList().addDeclarations(o)}insertDeclaration(o,a){return this.getDeclarationList().insertDeclaration(o,a)}insertDeclarations(o,a){return this.getDeclarationList().insertDeclarations(o,a)}set(o){if(a_(nzt.prototype,this,o),o.declarationKind!=null&&this.setDeclarationKind(o.declarationKind),o.declarations!=null){let a=this.getDeclarations();this.addDeclarations(o.declarations),a.forEach(d=>d.remove())}return this}getStructure(){return D_(nzt.prototype,this,{kind:Dt.StructureKind.VariableStatement,declarationKind:this.getDeclarationKind(),declarations:this.getDeclarations().map(o=>o.getStructure())})}},u9n=o7(Fnt),aUt=class extends u9n{},d9n=o7(HC),cUt=class extends d9n{getStatement(){return this._getNodeFromCompilerNode(this.compilerNode.statement)}};function b_t(c){return LM(wme(v2e(R3e(DW(c)))))}var tgr=c=>h9(zHt(p_t(b_t(c)))),f9n=tgr(MM),lUt=class extends f9n{getEqualsGreaterThan(){return this._getNodeFromCompilerNode(this.compilerNode.equalsGreaterThanToken)}};function XHt(c){return class extends c{getOverloads(){return r7n(this).filter(o=>o.isOverload())}getImplementation(){return this.isImplementation()?this:r7n(this).find(o=>o.isImplementation())}getImplementationOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getImplementation(),o??"Expected to find a corresponding implementation for the overload.",this)}isOverload(){return!this.isImplementation()}isImplementation(){return this.getBody()!=null}}}function r7n(c){let o=c.getParentOrThrow(),a=i7n(c),d=o7n(c),p=c.getKind();return o.forEachChildAsArray().filter(y=>i7n(y)===a&&y.getKind()===p&&o7n(y)===d)}function i7n(c){let o=c;if(o.getName instanceof Function)return o.getName()}function o7n(c){let o=c;return o.isStatic instanceof Function?o.isStatic():!1}function QHt(c){if(c.structures.length===0)return[];let o=c.node.getParentSyntaxListOrThrow(),a=c.node.getImplementation()||c.node,d=c.node.getOverloads(),p=d.length,y=d.length>0?d[0].getChildIndex():a.getChildIndex(),E=kR(c.index,p),I=y+E,B=c.getThisStructure(a),K=c.structures.map(ue=>Object.assign(Object.assign({},B),ue)),Y=a._getWriterWithQueuedIndentation();for(let ue of K)Y.getLength()>0&&Y.newLine(),c.printStructure(Y,ue);return Y.newLine(),Y.write(""),jm({parent:o,insertPos:(d[E]||a).getNonWhitespaceStart(),newText:Y.toString()}),N7n(o.getChildren(),I,K.length,c.expectedSyntaxKind)}var ngr=c=>qHt(h9(XHt(m_t(p_t(g_t(w3e(C3e(b_t(znt($Ht(c))))))))))),rzt=ngr(HC),rgr=c=>qHt(h9(p_t(g_t(v2e(w3e(znt(LM(wme(C3e(DW(c))))))))))),p9n=rgr(HC),uUt=class extends rzt{addOverload(o){return this.addOverloads([o])[0]}addOverloads(o){return this.insertOverloads(this.getOverloads().length,o)}insertOverload(o,a){return this.insertOverloads(o,[a])[0]}insertOverloads(o,a){let d=this.getName(),p=this._context.structurePrinterFactory.forFunctionDeclaration({isAmbient:this.isAmbient()});return QHt({node:this,index:o,structures:a,printStructure:(y,E)=>{p.printOverload(y,d,E)},getThisStructure:Ihr,expectedSyntaxKind:fe.SyntaxKind.FunctionDeclaration})}remove(){Bhr(this)}set(o){return a_(rzt.prototype,this,o),o.overloads!=null&&(this.getOverloads().forEach(a=>a.remove()),this.addOverloads(o.overloads)),this}getStructure(){let o=this.isOverload(),a=this.getImplementation(),d=o&&a?p9n.prototype:rzt.prototype;return D_(d,this,p(this));function p(y){if(a&&o)return E();return I();function E(){return{kind:Dt.StructureKind.FunctionOverload}}function I(){return a?{kind:Dt.StructureKind.Function,overloads:y.getOverloads().map(B=>B.getStructure())}:{kind:Dt.StructureKind.Function}}}}},igr=c=>LM(h9(zHt(p_t(g_t(R3e(wme(v2e(DW($Ht(c)))))))))),m9n=igr(m9),dUt=class extends m9n{},ogr=c=>J4t(P3e(h_t(Z7n(q4t(DW($4t(N3e(y_t(HHt(c)))))))))),izt=ogr(qo),fUt=class extends izt{isRestParameter(){return this.compilerNode.dotDotDotToken!=null}isParameterProperty(){return this.getScope()!=null||this.isReadonly()||this.hasOverrideKeyword()}setIsRestParameter(o){return this.isRestParameter()===o?this:(o?($jt(this),jm({insertPos:this.getNameNode().getStart(),parent:this,newText:"..."})):oT({children:[this.getDotDotDotTokenOrThrow()]}),this)}isOptional(){return this.compilerNode.questionToken!=null||this.isRestParameter()||this.hasInitializer()}remove(){g2e(this)}set(o){return a_(izt.prototype,this,o),o.isRestParameter!=null&&this.setIsRestParameter(o.isRestParameter),this}getStructure(){return D_(izt.prototype,this,{kind:Dt.StructureKind.Parameter,isRestParameter:this.isRestParameter()})}setHasQuestionToken(o){return o&&$jt(this),super.setHasQuestionToken(o),this}setInitializer(o){return $jt(this),super.setInitializer(o),this}setType(o){return $jt(this),super.setType.call(this,o),this}};function $jt(c){let o=c.getParentOrThrow();a()&&d();function a(){return qo.isArrowFunction(o)&&o.compilerNode.parameters.length===1&&c.getParentSyntaxListOrThrow().getPreviousSiblingIfKind(fe.SyntaxKind.OpenParenToken)==null}function d(){let p=c.getText();jm({parent:o,insertPos:c.getStart(),newText:`(${p})`,replacing:{textLength:p.length},customMappings:y=>[{currentNode:c,newNode:y.parameters[0]}]})}}var Y1e=class extends qo{remove(){let o=this.getParentOrThrow();qo.isClassDeclaration(o)||qo.isClassExpression(o)?Ohr(this):qo.isObjectLiteralExpression(o)?g2e(this):qo.isInterfaceDeclaration(o)?O7n(this):fe.errors.throwNotImplementedForSyntaxKindError(o.getKind())}},sgr=c=>Wne(h9(J4t(XHt(m_t(h_t(jnt(Wnt(P3e(Ywt(p_t(g_t(b_t(uVe(c)))))))))))))),ozt=sgr(Y1e),agr=c=>LM(Wne(h9(J4t(Wnt(wme(jnt(P3e(Ywt(p_t(DW(g_t(v2e(c))))))))))))),h9n=agr(Y1e),$wt=class extends ozt{set(o){return a_(ozt.prototype,this,o),o.overloads!=null&&(this.getOverloads().forEach(a=>a.remove()),this.addOverloads(o.overloads)),this}addOverload(o){return this.addOverloads([o])[0]}addOverloads(o){return this.insertOverloads(this.getOverloads().length,o)}insertOverload(o,a){return this.insertOverloads(o,[a])[0]}insertOverloads(o,a){let d=this.getName(),p=this._context.structurePrinterFactory.forMethodDeclaration({isAmbient:Yce(this)});return QHt({node:this,index:o,structures:a,printStructure:(y,E)=>{p.printOverload(y,d,E)},getThisStructure:khr,expectedSyntaxKind:fe.SyntaxKind.MethodDeclaration})}getStructure(){let o=this.getImplementation()!=null,a=this.isOverload(),d=a&&o?h9n.prototype:ozt.prototype;return D_(d,this,p(this));function p(y){if(o&&a)return E();return I();function E(){return{kind:Dt.StructureKind.MethodOverload}}function I(){return o?{kind:Dt.StructureKind.Method,overloads:y.getOverloads().map(B=>B.getStructure())}:{kind:Dt.StructureKind.Method}}}}};function Dpn(c){return _9n($Ht(h9(q7n(xpn(jnt(LM(wme(h_t(DW(c))))))))))}function _9n(c){return class extends c{setExtends(o){if(o=this._getTextWithQueuedChildIndentation(o),fe.StringUtils.isNullOrWhitespace(o))return this.removeExtends();let a=this.getHeritageClauseByKind(fe.SyntaxKind.ExtendsKeyword);if(a!=null){let d=a.getFirstChildByKindOrThrow(fe.SyntaxKind.SyntaxList),p=d.getStart();jm({parent:a,newText:o,insertPos:p,replacing:{textLength:d.getEnd()-p}})}else{let d=this.getHeritageClauseByKind(fe.SyntaxKind.ImplementsKeyword),p;d!=null?p=d.getStart():p=this.getFirstChildByKindOrThrow(fe.SyntaxKind.OpenBraceToken).getStart();let y=/\s/.test(this.getSourceFile().getFullText()[p-1]),E=`extends ${o} `;y||(E=" "+E),jm({parent:d==null?this:d.getParentSyntaxListOrThrow(),insertPos:p,newText:E})}return this}removeExtends(){let o=this.getHeritageClauseByKind(fe.SyntaxKind.ExtendsKeyword);return o==null?this:(o.removeExpression(0),this)}getExtendsOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getExtends(),o??`Expected to find the extends expression for the class ${this.getName()}.`,this)}getExtends(){let o=this.getHeritageClauseByKind(fe.SyntaxKind.ExtendsKeyword);if(o==null)return;let a=o.getTypeNodes();return a.length===0?void 0:a[0]}addMembers(o){return this.insertMembers(L3(this.getMembersWithComments()),o)}addMember(o){return this.insertMember(L3(this.getMembersWithComments()),o)}insertMember(o,a){return this.insertMembers(o,[a])[0]}insertMembers(o,a){let d=Yce(this);return L7n({getIndexedChildren:()=>this.getMembersWithComments(),index:o,parent:this,write:(y,E)=>{let I=!d&&E.previousMember!=null&&qo.isBodyable(E.previousMember)&&E.previousMember.hasBody(),B=!d&&a instanceof Array&&p(a[0]);I||E.previousMember!=null&&B?y.blankLineIfLastNot():y.newLineIfLastNot();let K=this._getWriter();this._context.structurePrinterFactory.forClassMember({isAmbient:d}).printTexts(K,a),y.write(K.toString());let ue=!d&&a instanceof Array&&p(a[a.length-1]),ie=!d&&E.nextMember!=null&&qo.isBodyable(E.nextMember)&&E.nextMember.hasBody();E.nextMember!=null&&ue||ie?y.blankLineIfLastNot():y.newLineIfLastNot()}});function p(y){if(d||y==null||typeof y.kind!="number")return!1;let E=y;return k4t.isMethod(E)||k4t.isGetAccessor(E)||k4t.isSetAccessor(E)||k4t.isConstructor(E)}}addConstructor(o={}){return this.insertConstructor(L3(this.getMembersWithComments()),o)}addConstructors(o){return this.insertConstructors(L3(this.getMembersWithComments()),o)}insertConstructor(o,a={}){return this.insertConstructors(o,[a])[0]}insertConstructors(o,a){let d=Yce(this);return Wwt(this,{index:o,structures:a,expectedKind:fe.SyntaxKind.Constructor,write:(p,y)=>{!d&&y.previousMember!=null&&!qo.isCommentNode(y.previousMember)?p.blankLineIfLastNot():p.newLineIfLastNot(),this._context.structurePrinterFactory.forConstructorDeclaration({isAmbient:d}).printTexts(p,a),!d&&y.nextMember!=null?p.blankLineIfLastNot():p.newLineIfLastNot()}})}getConstructors(){return this.getMembers().filter(o=>qo.isConstructorDeclaration(o))}addStaticBlock(o={}){return this.insertStaticBlock(L3(this.getMembersWithComments()),o)}addStaticBlocks(o){return this.insertStaticBlocks(L3(this.getMembersWithComments()),o)}insertStaticBlock(o,a={}){return this.insertStaticBlocks(o,[a])[0]}insertStaticBlocks(o,a){let d=Yce(this);return Wwt(this,{index:o,structures:a,expectedKind:fe.SyntaxKind.ClassStaticBlockDeclaration,write:(p,y)=>{!d&&y.previousMember!=null&&!qo.isCommentNode(y.previousMember)?p.blankLineIfLastNot():p.newLineIfLastNot(),this._context.structurePrinterFactory.forClassStaticBlockDeclaration().printTexts(p,a),!d&&y.nextMember!=null?p.blankLineIfLastNot():p.newLineIfLastNot()}})}getStaticBlocks(){return this.getMembers().filter(o=>qo.isClassStaticBlockDeclaration(o))}addGetAccessor(o){return this.addGetAccessors([o])[0]}addGetAccessors(o){return this.insertGetAccessors(L3(this.getMembersWithComments()),o)}insertGetAccessor(o,a){return this.insertGetAccessors(o,[a])[0]}insertGetAccessors(o,a){return Wwt(this,{index:o,structures:a,expectedKind:fe.SyntaxKind.GetAccessor,write:(d,p)=>{p.previousMember!=null&&!qo.isCommentNode(p.previousMember)?d.blankLineIfLastNot():d.newLineIfLastNot(),this._context.structurePrinterFactory.forGetAccessorDeclaration({isAmbient:Yce(this)}).printTexts(d,a),p.nextMember!=null?d.blankLineIfLastNot():d.newLineIfLastNot()}})}addSetAccessor(o){return this.addSetAccessors([o])[0]}addSetAccessors(o){return this.insertSetAccessors(L3(this.getMembersWithComments()),o)}insertSetAccessor(o,a){return this.insertSetAccessors(o,[a])[0]}insertSetAccessors(o,a){return Wwt(this,{index:o,structures:a,expectedKind:fe.SyntaxKind.SetAccessor,write:(d,p)=>{p.previousMember!=null&&!qo.isCommentNode(p.previousMember)?d.blankLineIfLastNot():d.newLineIfLastNot(),this._context.structurePrinterFactory.forSetAccessorDeclaration({isAmbient:Yce(this)}).printTexts(d,a),p.nextMember!=null?d.blankLineIfLastNot():d.newLineIfLastNot()}})}addProperty(o){return this.addProperties([o])[0]}addProperties(o){return this.insertProperties(L3(this.getMembersWithComments()),o)}insertProperty(o,a){return this.insertProperties(o,[a])[0]}insertProperties(o,a){return Wwt(this,{index:o,structures:a,expectedKind:fe.SyntaxKind.PropertyDeclaration,write:(d,p)=>{p.previousMember!=null&&qo.hasBody(p.previousMember)?d.blankLineIfLastNot():d.newLineIfLastNot(),this._context.structurePrinterFactory.forPropertyDeclaration().printTexts(d,a),p.nextMember!=null&&qo.hasBody(p.nextMember)?d.blankLineIfLastNot():d.newLineIfLastNot()}})}addMethod(o){return this.addMethods([o])[0]}addMethods(o){return this.insertMethods(L3(this.getMembersWithComments()),o)}insertMethod(o,a){return this.insertMethods(o,[a])[0]}insertMethods(o,a){let d=Yce(this);return a=a.map(p=>({...p})),Wwt(this,{index:o,write:(p,y)=>{!d&&y.previousMember!=null&&!qo.isCommentNode(y.previousMember)?p.blankLineIfLastNot():p.newLineIfLastNot(),this._context.structurePrinterFactory.forMethodDeclaration({isAmbient:d}).printTexts(p,a),!d&&y.nextMember!=null?p.blankLineIfLastNot():p.newLineIfLastNot()},structures:a,expectedKind:fe.SyntaxKind.MethodDeclaration})}getInstanceProperty(o){return IR(this.getInstanceProperties(),o)}getInstancePropertyOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getInstanceProperty(o),()=>zD("class instance property",o))}getInstanceProperties(){return this.getInstanceMembers().filter(o=>c7n(o))}getStaticProperty(o){return IR(this.getStaticProperties(),o)}getStaticPropertyOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getStaticProperty(o),()=>zD("class static property",o))}getStaticProperties(){return this.getStaticMembers().filter(o=>c7n(o))}getProperty(o){return IR(this.getProperties(),o)}getPropertyOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getProperty(o),()=>zD("class property declaration",o))}getProperties(){return this.getMembers().filter(o=>qo.isPropertyDeclaration(o))}getGetAccessor(o){return IR(this.getGetAccessors(),o)}getGetAccessorOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getGetAccessor(o),()=>zD("class getAccessor declaration",o))}getGetAccessors(){return this.getMembers().filter(o=>qo.isGetAccessorDeclaration(o))}getSetAccessor(o){return IR(this.getSetAccessors(),o)}getSetAccessorOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getSetAccessor(o),()=>zD("class setAccessor declaration",o))}getSetAccessors(){return this.getMembers().filter(o=>qo.isSetAccessorDeclaration(o))}getMethod(o){return IR(this.getMethods(),o)}getMethodOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getMethod(o),()=>zD("class method declaration",o))}getMethods(){return this.getMembers().filter(o=>qo.isMethodDeclaration(o))}getInstanceMethod(o){return IR(this.getInstanceMethods(),o)}getInstanceMethodOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getInstanceMethod(o),()=>zD("class instance method",o))}getInstanceMethods(){return this.getInstanceMembers().filter(o=>o instanceof $wt)}getStaticMethod(o){return IR(this.getStaticMethods(),o)}getStaticMethodOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getStaticMethod(o),()=>zD("class static method",o))}getStaticMethods(){return this.getStaticMembers().filter(o=>o instanceof $wt)}getInstanceMember(o){return IR(this.getInstanceMembers(),o)}getInstanceMemberOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getInstanceMember(o),()=>zD("class instance member",o))}getInstanceMembers(){return this.getMembersWithParameterProperties().filter(o=>qo.isConstructorDeclaration(o)?!1:qo.isParameterDeclaration(o)||!o.isStatic())}getStaticMember(o){return IR(this.getStaticMembers(),o)}getStaticMemberOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getStaticMember(o),()=>zD("class static member",o))}getStaticMembers(){return this.getMembers().filter(o=>qo.isConstructorDeclaration(o)?!1:!qo.isParameterDeclaration(o)&&o.isStatic())}getMembersWithParameterProperties(){let o=this.getMembers(),a=o.filter(d=>qo.isConstructorDeclaration(d)&&d.isImplementation());for(let d of a){let p=o.indexOf(d)+1;for(let y of d.getParameters())y.isParameterProperty()&&(o.splice(p,0,y),p++)}return o}getMembers(){return s7n(this,this.compilerNode.members).filter(o=>l7n(o))}getMembersWithComments(){let o=this.compilerNode,a=i7.getContainerArray(o,this.getSourceFile().compilerNode);return s7n(this,a).filter(d=>l7n(d)||qo.isCommentClassElement(d))}getMember(o){return IR(this.getMembers(),o)}getMemberOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getMember(o),()=>zD("class member",o))}getBaseTypes(){return this.getType().getBaseTypes()}getBaseClassOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getBaseClass(),o??`Expected to find the base class of ${this.getName()}.`,this)}getBaseClass(){let a=this.getBaseTypes().map(d=>d.isIntersection()?d.getIntersectionTypes():[d]).flat().map(d=>d.getSymbol()).filter(d=>d!=null).map(d=>d.getDeclarations()).reduce((d,p)=>d.concat(p),[]).filter(d=>d.getKind()===fe.SyntaxKind.ClassDeclaration);if(a.length===1)return a[0]}getDerivedClasses(){let o=a7n(this);for(let a=0;a<o.length;a++){let d=a7n(o[a]);for(let p of d)p!==this&&o.indexOf(p)===-1&&o.push(p)}return o}}}function s7n(c,o){let a=Yce(c),d=o.map(p=>c._getNodeFromCompilerNode(p));return a?d:d.filter(p=>!(qo.isConstructorDeclaration(p)||qo.isMethodDeclaration(p))||qo.isMethodDeclaration(p)&&p.isAbstract()?!0:p.isImplementation())}function a7n(c){let o=[],a=c.getNameNode();if(a==null)return o;for(let d of a.findReferencesAsNodes()){d=d.getParentWhileKind(fe.SyntaxKind.PropertyAccessExpression)??d;let p=d.getParentIfKind(fe.SyntaxKind.ExpressionWithTypeArguments);if(p==null)continue;let y=p.getParentIfKind(fe.SyntaxKind.HeritageClause);if(y==null||y.getToken()!==fe.SyntaxKind.ExtendsKeyword)continue;let E=y.getParentIfKind(fe.SyntaxKind.ClassDeclaration);E!=null&&o.push(E)}return o}function c7n(c){return qo.isPropertyDeclaration(c)||qo.isSetAccessorDeclaration(c)||qo.isGetAccessorDeclaration(c)||qo.isParameterDeclaration(c)}function l7n(c){return qo.isMethodDeclaration(c)||qo.isPropertyDeclaration(c)||qo.isGetAccessorDeclaration(c)||qo.isSetAccessorDeclaration(c)||qo.isConstructorDeclaration(c)||qo.isClassStaticBlockDeclaration(c)}function Wwt(c,o){return ypn({getIndexedChildren:()=>c.getMembersWithComments(),parent:c,...o})}var cgr=c=>znt(w3e(C3e(Dpn(c)))),szt=cgr(HC),pUt=class extends szt{set(o){return a_(szt.prototype,this,o),o.extends!=null?this.setExtends(o.extends):o.hasOwnProperty(fe.nameof(o,"extends"))&&this.removeExtends(),o.ctors!=null&&(this.getConstructors().forEach(a=>a.remove()),this.addConstructors(o.ctors)),o.staticBlocks!=null&&(this.getStaticBlocks().forEach(a=>a.remove()),this.addStaticBlocks(o.staticBlocks)),o.properties!=null&&(this.getProperties().forEach(a=>a.remove()),this.addProperties(o.properties)),o.getAccessors!=null&&(this.getGetAccessors().forEach(a=>a.remove()),this.addGetAccessors(o.getAccessors)),o.setAccessors!=null&&(this.getSetAccessors().forEach(a=>a.remove()),this.addSetAccessors(o.setAccessors)),o.methods!=null&&(this.getMethods().forEach(a=>a.remove()),this.addMethods(o.methods)),this}getStructure(){let o=this.getExtends(),a=this.isAmbient();return D_(szt.prototype,this,{kind:Dt.StructureKind.Class,ctors:this.getConstructors().filter(d=>a||!d.isOverload()).map(d=>d.getStructure()),staticBlocks:this.getStaticBlocks().map(d=>d.getStructure()),methods:this.getMethods().filter(d=>a||!d.isOverload()).map(d=>d.getStructure()),properties:this.getProperties().map(d=>d.getStructure()),extends:o?o.getText():void 0,getAccessors:this.getGetAccessors().map(d=>d.getStructure()),setAccessors:this.getSetAccessors().map(d=>d.getStructure())})}extractInterface(o){let{constructors:a,properties:d,methods:p,accessors:y}=u7n(this,!1),E=a.map(I=>I.getParameters().filter(B=>B.isParameterProperty())).flat().filter(I=>I.getName()!=null&&I.getScope()===Dt.Scope.Public);return{kind:Dt.StructureKind.Interface,name:d7n(o,this),docs:this.getJsDocs().map(I=>I.getStructure()),typeParameters:this.getTypeParameters().map(I=>I.getStructure()),properties:[...E.map(I=>{let B=I.getParentOrThrow().getJsDocs().map(K=>K.getTags()).flat().filter(qo.isJSDocParameterTag).filter(K=>K.getTagName()==="param"&&K.getName()===I.getName()&&K.getComment()!=null).map(K=>K.getCommentText().trim())[0];return{kind:Dt.StructureKind.PropertySignature,docs:B==null?[]:[{kind:Dt.StructureKind.JSDoc,description:B}],name:I.getName(),type:I.getType().getText(I),hasQuestionToken:I.hasQuestionToken(),isReadonly:I.isReadonly()}}),...d.map(f7n),...y.map(p7n)],methods:p.map(m7n)}}extractStaticInterface(o){let{constructors:a,properties:d,methods:p,accessors:y}=u7n(this,!0),E=d7n(void 0,this);return{kind:Dt.StructureKind.Interface,name:o,properties:[...d.map(f7n),...y.map(p7n)],methods:p.map(m7n),constructSignatures:a.map(I=>({kind:Dt.StructureKind.ConstructSignature,docs:I.getJsDocs().map(B=>B.getStructure()),parameters:I.getParameters().map(B=>({...g9n(B),scope:void 0,isReadonly:!1})),returnType:E}))}}};function u7n(c,o){let a=c.getConstructors().map(E=>E.getOverloads().length>0?E.getOverloads():[E]).flat(),d=c.getProperties().filter(E=>E.isStatic()===o&&E.getScope()===Dt.Scope.Public),p=c.getMethods().filter(E=>E.isStatic()===o&&E.getScope()===Dt.Scope.Public).map(E=>E.getOverloads().length>0?E.getOverloads():[E]).flat();return{constructors:a,properties:d,methods:p,accessors:y()};function y(){let E=new fe.KeyValueCache;for(let I of[...c.getGetAccessors(),...c.getSetAccessors()])I.isStatic()===o&&I.getScope()===Dt.Scope.Public&&E.getOrCreate(I.getName(),()=>[]).push(I);return E.getValuesAsArray()}}function d7n(c,o){return c=fe.StringUtils.isNullOrWhitespace(c)?void 0:c,c||o.getName()||o.getSourceFile().getBaseNameWithoutExtension().replace(/[^a-zA-Z0-9_$]/g,"")}function f7n(c){return{kind:Dt.StructureKind.PropertySignature,docs:c.getJsDocs().map(o=>o.getStructure()),name:c.getName(),type:c.getType().getText(c),hasQuestionToken:c.hasQuestionToken(),isReadonly:c.isReadonly()}}function p7n(c){return{kind:Dt.StructureKind.PropertySignature,docs:c[0].getJsDocs().map(o=>o.getStructure()),name:c[0].getName(),type:c[0].getType().getText(c[0]),hasQuestionToken:!1,isReadonly:c.every(qo.isGetAccessorDeclaration)}}function m7n(c){return{kind:Dt.StructureKind.MethodSignature,docs:c.getJsDocs().map(o=>o.getStructure()),name:c.getName(),hasQuestionToken:c.hasQuestionToken(),returnType:c.getReturnType().getText(c),parameters:c.getParameters().map(g9n),typeParameters:c.getTypeParameters().map(o=>o.getStructure())}}function g9n(c){return{...c.getStructure(),decorators:[]}}var y9n=Dpn(m9),mUt=class extends y9n{},lgr=c=>Wne(h9(R3e(LM(zHt(c))))),azt=lgr(Y1e),hUt=class extends azt{getName(){return"static"}isStatic(){return!0}set(o){return a_(azt.prototype,this,o),this}getStructure(){return D_(azt.prototype,this,{kind:Dt.StructureKind.ClassStaticBlock})}},_Ut=class extends Y1e{},ugr=c=>k3e(Wne(h9(XHt(Wnt(b_t(m_t(c))))))),czt=ugr(Y1e),dgr=c=>wme(LM(Wne(h9(Wnt(DW(v2e(c))))))),v9n=dgr(Y1e),gUt=class extends czt{set(o){return a_(czt.prototype,this,o),o.overloads!=null&&(this.getOverloads().forEach(a=>a.remove()),this.addOverloads(o.overloads)),this}addOverload(o){return this.addOverloads([o])[0]}addOverloads(o){return this.insertOverloads(this.getOverloads().length,o)}insertOverload(o,a){return this.insertOverloads(o,[a])[0]}insertOverloads(o,a){let d=this._context.structurePrinterFactory.forConstructorDeclaration({isAmbient:Yce(this)});return QHt({node:this,index:o,structures:a,printStructure:(p,y)=>{d.printOverload(p,y)},getThisStructure:Chr,expectedSyntaxKind:fe.SyntaxKind.Constructor})}getStructure(){let o=this.getImplementation()!=null,a=this.isOverload(),d=a&&o?v9n.prototype:czt.prototype;return D_(d,this,p(this));function p(y){if(o&&a)return E();return I();function E(){return{kind:Dt.StructureKind.ConstructorOverload}}function I(){return o?{kind:Dt.StructureKind.Constructor,overloads:y.getOverloads().map(B=>B.getStructure())}:{kind:Dt.StructureKind.Constructor}}}}},fgr=c=>Wne(h9(h_t(jnt(Wnt(Ywt(b_t(m_t(uVe(c))))))))),lzt=fgr(Y1e),yUt=class extends lzt{set(o){return a_(lzt.prototype,this,o),this}getSetAccessor(){let o=this.getName(),a=this.isStatic();return this.getParentOrThrow().forEachChild(d=>{if(qo.isSetAccessorDeclaration(d)&&d.getName()===o&&d.isStatic()===a)return d})}getSetAccessorOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getSetAccessor(),o??(()=>`Expected to find a corresponding set accessor for ${this.getName()}.`),this)}getStructure(){return D_(lzt.prototype,this,{kind:Dt.StructureKind.GetAccessor})}},pgr=c=>Wne(J4t(w3e(h_t(jnt(Wnt(Ywt(LM(q4t(Spn(P3e(y_t(N3e(uVe(DW(c))))))))))))))),uzt=pgr(Y1e),vUt=class extends uzt{hasAccessorKeyword(){return this.hasModifier(fe.SyntaxKind.AccessorKeyword)}setHasAccessorKeyword(o){return this.toggleModifier("accessor",o)}set(o){return a_(uzt.prototype,this,o),o.hasAccessorKeyword!=null&&this.setHasAccessorKeyword(o.hasAccessorKeyword),this}remove(){let o=this.getParentOrThrow();if(o.getKind()===fe.SyntaxKind.ClassDeclaration)super.remove();else throw new fe.errors.NotImplementedError(`Not implemented parent syntax kind: ${o.getKindName()}`)}getStructure(){return D_(uzt.prototype,this,{kind:Dt.StructureKind.Property,hasAccessorKeyword:this.hasAccessorKeyword()})}},mgr=c=>Wne(h9(h_t(jnt(Wnt(Ywt(b_t(m_t(uVe(c))))))))),dzt=mgr(Y1e),bUt=class extends dzt{set(o){return a_(dzt.prototype,this,o),this}getGetAccessor(){let o=this.getName(),a=this.isStatic();return this.getParentOrThrow().forEachChild(d=>{if(qo.isGetAccessorDeclaration(d)&&d.getName()===o&&d.isStatic()===a)return d})}getGetAccessorOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getGetAccessor(),o??(()=>`Expected to find a corresponding get accessor for ${this.getName()}.`),this)}getStructure(){return D_(dzt.prototype,this,{kind:Dt.StructureKind.SetAccessor})}},fzt=v_t(qo),SUt=class extends fzt{getName(){return this.getNameNode().getText()}getNameNode(){let o=this.getCallExpression();if(o)return a(o.getExpression());return a(this._getInnerExpression());function a(p){let y=d(p);if(!qo.isIdentifier(y))throw new fe.errors.NotImplementedError(`Expected the decorator expression '${y.getText()}' to be an identifier. Please deal directly with 'getExpression()' on the decorator to handle more complex scenarios.`);return y}function d(p){return qo.isPropertyAccessExpression(p)?p.getNameNode():p}}getFullName(){let o=this.getSourceFile();return this.isDecoratorFactory()?this.getCallExpression().getExpression().getText():this.compilerNode.expression.getText(o.compilerNode)}isDecoratorFactory(){return qo.isCallExpression(this._getInnerExpression())}setIsDecoratorFactory(o){if(this.isDecoratorFactory()===o)return this;if(o){let a=this._getInnerExpression(),d=a.getText();jm({parent:this,insertPos:a.getStart(),newText:`${d}()`,replacing:{textLength:d.length},customMappings:p=>[{currentNode:a,newNode:p.expression.expression}]})}else{let a=this.getCallExpressionOrThrow(),d=a.getExpression(),p=d.getText();jm({parent:this,insertPos:a.getStart(),newText:`${p}`,replacing:{textLength:a.getWidth()},customMappings:y=>[{currentNode:d,newNode:y.expression}]})}return this}getCallExpressionOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getCallExpression(),o??"Expected to find a call expression.",this)}getCallExpression(){let o=this._getInnerExpression();return qo.isCallExpression(o)?o:void 0}getArguments(){return this.getCallExpression()?.getArguments()??[]}getTypeArguments(){return this.getCallExpression()?.getTypeArguments()??[]}addTypeArgument(o){return this.getCallExpressionOrThrow().addTypeArgument(o)}addTypeArguments(o){return this.getCallExpressionOrThrow().addTypeArguments(o)}insertTypeArgument(o,a){return this.getCallExpressionOrThrow().insertTypeArgument(o,a)}insertTypeArguments(o,a){return this.getCallExpressionOrThrow().insertTypeArguments(o,a)}removeTypeArgument(o){let a=this.getCallExpression();if(a==null)throw new fe.errors.InvalidOperationError("Cannot remove a type argument from a decorator that has no type arguments.");return a.removeTypeArgument(o),this}addArgument(o){return this.addArguments([o])[0]}addArguments(o){return this.insertArguments(this.getArguments().length,o)}insertArgument(o,a){return this.insertArguments(o,[a])[0]}insertArguments(o,a){return this.setIsDecoratorFactory(!0),this.getCallExpressionOrThrow().insertArguments(o,a)}removeArgument(o){let a=this.getCallExpression();if(a==null)throw new fe.errors.InvalidOperationError("Cannot remove an argument from a decorator that has no arguments.");return a.removeArgument(o),this}remove(){let o=this.getStartLinePos(),a=this.getPreviousSiblingIfKind(fe.SyntaxKind.Decorator);a!=null&&a.getStartLinePos()===o?oT({children:[this],removePrecedingSpaces:!0}):Lhr({children:[this],getSiblingFormatting:(d,p)=>p.getStartLinePos()===o?uC.Space:uC.Newline})}_getInnerExpression(){let o=this.getExpression();for(;qo.isParenthesizedExpression(o);)o=o.getExpression();return o}set(o){return a_(fzt.prototype,this,o),o.name!=null&&this.getNameNode().replaceWithText(o.name),o.arguments!=null&&(this.setIsDecoratorFactory(!0),this.getArguments().map(a=>this.removeArgument(a)),this.addArguments(o.arguments)),o.typeArguments!=null&&o.typeArguments.length>0&&(this.setIsDecoratorFactory(!0),this.getTypeArguments().map(a=>this.removeTypeArgument(a)),this.addTypeArguments(o.typeArguments)),this}getStructure(){let o=this.isDecoratorFactory();return D_(fzt.prototype,this,{kind:Dt.StructureKind.Decorator,name:this.getName(),arguments:o?this.getArguments().map(a=>a.getText()):void 0,typeArguments:o?this.getTypeArguments().map(a=>a.getText()):void 0})}};function Ppn(c){return class extends c{getTypeExpression(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.typeExpression)}getTypeExpressionOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getTypeExpression(),o??"Expected to find a JS doc type expression.",this)}getName(){return this.getNameNode().getText()}getNameNode(){return this._getNodeFromCompilerNode(this.compilerNode.name)}isBracketed(){return this.compilerNode.isBracketed}}}function S_t(c){return class extends c{getTypeExpression(){let o=this._getNodeFromCompilerNodeIfExists(this.compilerNode.typeExpression);if(!(o!=null&&o.getWidth()===0))return o}getTypeExpressionOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getTypeExpression(),o??"Expected to find the JS doc tag's type expression.",this)}}}function b9n(c){return class extends c{getTypeParameters(){return this.compilerNode.typeParameters.map(o=>this._getNodeFromCompilerNode(o)).filter(o=>o.getWidth()>0)}}}function spn(c){return c.replace(/^\/\*\*[^\S\n]*\n?/,"").replace(/(\r?\n)?[^\S\n]*\*\/$/,"").split(/\n/).map(d=>{let p=a(d);if(p===-1)return d;let y=d[p+1]===" "?p+2:p+1;return d.substring(y)}).join(`
45437
45437
  `);function a(d){for(let p=0;p<d.length;p++){let y=d.charCodeAt(p);if(y===ZL.ASTERISK)return p;if(!fe.StringUtils.isWhitespaceCharCode(y))break}return-1}}var pzt=qo,TUt=class extends pzt{isMultiLine(){return this.getText().includes(`
45438
45438
  `)}getTags(){return this.compilerNode.tags?.map(o=>this._getNodeFromCompilerNode(o))??[]}getInnerText(){return spn(this.getText())}getComment(){if(this.compilerNode.comment!=null)return typeof this.compilerNode.comment=="string"?this.compilerNode.comment:this.compilerNode.comment.map(o=>this._getNodeFromCompilerNodeIfExists(o))}getCommentText(){return typeof this.compilerNode.comment=="string"?this.compilerNode.comment:fe.ts.getTextOfJSDocComment(this.compilerNode.comment)}getDescription(){let o=this.getSourceFile().getFullText(),a=this.getTags()[0]?.getStart()??this.getEnd()-2,d=p(this);return spn(o.substring(d,Math.max(d,y())));function p(E){let I=E.getStart()+3;return o.charCodeAt(I)===ZL.SPACE?I+1:I}function y(){let E=h2e(o,a,I=>I===ZL.NEWLINE||!fe.StringUtils.isWhitespaceCharCode(I)&&I!==ZL.ASTERISK);return h2e(o,E,I=>I!==ZL.NEWLINE&&I!==ZL.CARRIAGE_RETURN)}}setDescription(o){let a=this.getTags(),d=this.getStart()+3,p=a.length>0?h2e(this._sourceFile.getFullText(),a[0].getStart(),E=>E===ZL.ASTERISK)-1:this.getEnd()-2;return Ghr({parent:this,newText:y.call(this),replacePos:d,replacingLength:p-d}),this;function y(){let E=this.getIndentationText(),I=this._context.manipulationSettings.getNewLineKindAsString(),B=Z1e(this._getWriter(),o).split(/\r?\n/),K=B[0].length===0,Y=B.length===1&&(this.compilerNode.tags?.length??0)===0,ue=Y?B[0]:B.map(ie=>ie.length===0?`${E} *`:`${E} * ${ie}`).slice(K?1:0).join(I);return Y?" "+ue+" ":I+ue+I+E+" "}}addTag(o){return this.addTags([o])[0]}addTags(o){return this.insertTags(this.compilerNode.tags?.length??0,o)}insertTag(o,a){return this.insertTags(o,[a])[0]}insertTags(o,a){if(fe.ArrayUtils.isNullOrEmpty(a))return[];let d=this._getWriterWithQueuedIndentation(),p=this.getTags();if(o=kR(o,p.length),p.length===0&&!this.isMultiLine()){let I=this._context.structurePrinterFactory.forJSDoc();this.replaceWithText(B=>{I.printText(B,{description:this.getDescription(),tags:a})})}else{let I=this._context.structurePrinterFactory.forJSDocTag({printStarsOnNewLine:!0});d.newLine().write(" * "),I.printTexts(d,a),d.newLine().write(" *"),d.conditionalWrite(o<p.length," ");let B=y.call(this),K=E.call(this);jm({parent:this,insertPos:B,replacing:{textLength:K-B},newText:d.toString()})}return xG(p,this.getTags(),o,!1);function y(){let I=o<p.length?p[o].getStart():this.getEnd()-2,B=this.getStart()+3;return Math.max(B,h2e(this.getSourceFile().getFullText(),I,K=>!fe.StringUtils.isWhitespaceCharCode(K)&&K!==ZL.ASTERISK))}function E(){return o<p.length?p[o].getStart():this.getEnd()-1}}remove(){oT({children:[this],removeFollowingSpaces:!0,removeFollowingNewLines:!0})}set(o){return a_(pzt.prototype,this,o),o.tags!=null?this.replaceWithText(a=>{this._context.structurePrinterFactory.forJSDoc().printText(a,{description:o.description??this.getDescription(),tags:o.tags})}):(o.description!=null&&this.setDescription(o.description),this)}getStructure(){return D_(pzt.prototype,this,{kind:Dt.StructureKind.JSDoc,description:this.getDescription(),tags:this.getTags().map(o=>o.getStructure())})}},eO=class extends qo{},S9n=JHt(eO),f_t=class extends S9n{},EUt=class extends eO{getElementTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.elementType)}},xUt=class extends eO{getCheckType(){return this._getNodeFromCompilerNode(this.compilerNode.checkType)}getExtendsType(){return this._getNodeFromCompilerNode(this.compilerNode.extendsType)}getTrueType(){return this._getNodeFromCompilerNode(this.compilerNode.trueType)}getFalseType(){return this._getNodeFromCompilerNode(this.compilerNode.falseType)}},T9n=v2e(eO),B4t=class extends T9n{},E9n=jnt(DW(B4t)),AUt=class extends E9n{},x9n=v_t(f_t),wUt=class extends x9n{},A9n=wme(B4t),CUt=class extends A9n{},IUt=class extends f_t{setArgument(o){let a=this.getArgument();if(qo.isLiteralTypeNode(a)){let d=a.getLiteral();if(qo.isStringLiteral(d))return d.setLiteralValue(o),this}return a.replaceWithText(d=>d.quote(o),this._getWriterWithQueuedChildIndentation()),this}getArgument(){return this._getNodeFromCompilerNode(this.compilerNode.argument)}setQualifier(o){let a=this.getQualifier();if(a!=null)a.replaceWithText(o,this._getWriterWithQueuedChildIndentation());else{let d=this.getFirstChildByKindOrThrow(fe.SyntaxKind.CloseParenToken);jm({insertPos:d.getEnd(),parent:this,newText:this._getWriterWithQueuedIndentation().write(".").write(o).toString()})}return this}getQualifierOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getQualifier(),o??(()=>`Expected to find a qualifier for the import type: ${this.getText()}`),this)}getQualifier(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.qualifier)}getAttributes(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.attributes)}getAttributesOrThrow(o){return fe.errors.throwIfNullOrUndefined(this._getNodeFromCompilerNodeIfExists(this.compilerNode.attributes),o??"Could not find import type assertion container.",this)}},kUt=class extends eO{getObjectTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.objectType)}getIndexTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.indexType)}},DUt=class extends eO{getTypeParameter(){return this._getNodeFromCompilerNode(this.compilerNode.typeParameter)}},PUt=class extends eO{getTypeNodes(){return this.compilerNode.types.map(o=>this._getNodeFromCompilerNode(o))}},NUt=class extends eO{getLiteral(){let o=this.compilerNode.literal;return this._getNodeFromCompilerNode(o)}},RUt=class extends eO{getNameTypeNode(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.nameType)}getNameTypeNodeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getNameTypeNode(),o??"Type did not exist.",this)}getReadonlyToken(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.readonlyToken)}getReadonlyTokenOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getReadonlyToken(),o??"Readonly token did not exist.",this)}getQuestionToken(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.questionToken)}getQuestionTokenOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getQuestionToken(),o??"Question token did not exist.",this)}getTypeParameter(){return this._getNodeFromCompilerNode(this.compilerNode.typeParameter)}getTypeNode(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type)}getTypeNodeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getTypeNode(),o??"Type did not exist, but was expected to exist.",this)}},hgr=c=>N3e(P3e($4t(LM(D3e(c))))),w9n=hgr(eO),MUt=class extends w9n{getTypeNode(){return super.getTypeNode()}removeType(){throw new fe.errors.InvalidOperationError("Cannot remove the type of a named tuple member.")}},LUt=class extends eO{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}},OUt=class extends eO{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}setType(o){return this.getTypeNode().replaceWithText(o),this}},FUt=class extends eO{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}},BUt=class extends eO{getHead(){return this._getNodeFromCompilerNode(this.compilerNode.head)}getTemplateSpans(){return this.compilerNode.templateSpans.map(o=>this._getNodeFromCompilerNode(o))}setLiteralValue(o){let a=this.getChildIndex(),d=this.getParentSyntaxList()??this.getParentOrThrow();return Bnt({sourceFile:this._sourceFile,start:this.getStart()+1,replacingLength:this.getWidth()-2,newText:o}),d.getChildAtIndex(a)}},WUt=class extends eO{},jUt=class extends eO{getElements(){return this.compilerNode.elements.map(o=>this._getNodeFromCompilerNode(o))}},_gr=c=>wme(N3e(LM(w3e(C3e(DW(D3e(c))))))),mzt=_gr(HC),zUt=class extends mzt{set(o){return a_(mzt.prototype,this,o),this}getStructure(){return D_(mzt.prototype,this,{kind:Dt.StructureKind.TypeAlias,type:this.getTypeNodeOrThrow().getText()})}},C9n=Ipn(eO),GUt=class extends C9n{},UUt=class extends eO{getOperator(){return this.compilerNode.operator}getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}};Dt.TypeParameterVariance=void 0;(function(c){c[c.None=0]="None",c[c.In=1]="In",c[c.Out=2]="Out",c[c.InOut=3]="InOut"})(Dt.TypeParameterVariance||(Dt.TypeParameterVariance={}));var ggr=c=>DW(D3e(c)),hzt=ggr(qo),VUt=class extends hzt{isConst(){return this.hasModifier(fe.SyntaxKind.ConstKeyword)}setIsConst(o){return this.toggleModifier("const",o)}getConstraint(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.constraint)}getConstraintOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getConstraint(),o??"Expected to find the type parameter's constraint.",this)}setConstraint(o){if(o=this.getParentOrThrow()._getTextWithQueuedChildIndentation(o),fe.StringUtils.isNullOrWhitespace(o))return this.removeConstraint(),this;let a=this.getConstraint();if(a!=null)return a.replaceWithText(o),this;let d=this.getNameNode();return jm({parent:this,insertPos:d.getEnd(),newText:` extends ${o}`}),this}removeConstraint(){return h7n(this.getConstraint(),fe.SyntaxKind.ExtendsKeyword),this}getDefault(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.default)}getDefaultOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getDefault(),o??"Expected to find the type parameter's default.",this)}setDefault(o){if(o=this.getParentOrThrow()._getTextWithQueuedChildIndentation(o),fe.StringUtils.isNullOrWhitespace(o))return this.removeDefault(),this;let a=this.getDefault();if(a!=null)return a.replaceWithText(o),this;let d=this.getConstraint()||this.getNameNode();return jm({parent:this,insertPos:d.getEnd(),newText:` = ${o}`}),this}removeDefault(){return h7n(this.getDefault(),fe.SyntaxKind.EqualsToken),this}setVariance(o){return this.toggleModifier("in",(o&Dt.TypeParameterVariance.In)!==0),this.toggleModifier("out",(o&Dt.TypeParameterVariance.Out)!==0),this}getVariance(){let o=Dt.TypeParameterVariance.None;return this.hasModifier(fe.SyntaxKind.InKeyword)&&(o|=Dt.TypeParameterVariance.In),this.hasModifier(fe.SyntaxKind.OutKeyword)&&(o|=Dt.TypeParameterVariance.Out),o}remove(){let o=this.getParentSyntaxListOrThrow();o.getChildrenOfKind(fe.SyntaxKind.TypeParameter).length===1?d():g2e(this);function d(){let p=[o.getPreviousSiblingIfKindOrThrow(fe.SyntaxKind.LessThanToken),o,o.getNextSiblingIfKindOrThrow(fe.SyntaxKind.GreaterThanToken)];oT({children:p})}}set(o){return a_(hzt.prototype,this,o),o.isConst!=null&&this.setIsConst(o.isConst),o.constraint!=null?this.setConstraint(o.constraint):o.hasOwnProperty(fe.nameof(o,"constraint"))&&this.removeConstraint(),o.default!=null?this.setDefault(o.default):o.hasOwnProperty(fe.nameof(o,"default"))&&this.removeDefault(),o.variance!=null&&this.setVariance(o.variance),this}getStructure(){let o=this.getConstraint(),a=this.getDefault();return D_(hzt.prototype,this,{kind:Dt.StructureKind.TypeParameter,isConst:this.isConst(),constraint:o?.getText({trimLeadingIndentation:!0}),default:a?a.getText({trimLeadingIndentation:!0}):void 0,variance:this.getVariance()})}};function h7n(c,o){c!=null&&oT({children:[c.getPreviousSiblingIfKindOrThrow(o),c],removePrecedingSpaces:!0})}var HUt=class extends eO{getParameterNameNode(){return this._getNodeFromCompilerNode(this.compilerNode.parameterName)}hasAssertsModifier(){return this.compilerNode.assertsModifier!=null}getAssertsModifier(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.assertsModifier)}getAssertsModifierOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getAssertsModifier(),o??"Expected to find an asserts modifier.",this)}getTypeNode(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type)}getTypeNodeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getTypeNode(),o??"Expected to find a type node.",this)}},$Ut=class extends f_t{getExprName(){return this._getNodeFromCompilerNode(this.compilerNode.exprName)}},KUt=class extends f_t{getTypeName(){return this._getNodeFromCompilerNode(this.compilerNode.typeName)}},JUt=class extends eO{getTypeNodes(){return this.compilerNode.types.map(o=>this._getNodeFromCompilerNode(o))}},Ame=class extends eO{},qUt=class extends Ame{},_zt=qo,lN=class extends _zt{getTagName(){return this.getTagNameNode().getText()}getTagNameNode(){return this._getNodeFromCompilerNode(this.compilerNode.tagName)}setTagName(o){return this.set({tagName:o})}getComment(){if(this.compilerNode.comment!=null)return typeof this.compilerNode.comment=="string"?this.compilerNode.comment:this.compilerNode.comment.map(o=>this._getNodeFromCompilerNodeIfExists(o))}getCommentText(){return typeof this.compilerNode.comment=="string"?this.compilerNode.comment:fe.ts.getTextOfJSDocComment(this.compilerNode.comment)}remove(){let o=this.getParentOrThrow().getStart()+3,a=D9n(this),d=a==null,p=y.call(this);oT({children:[this],customRemovalPos:p,customRemovalEnd:k9n(this,a),replaceTrivia:E.call(this)});function y(){return Math.max(o,P9n(this,this.getStart()))}function E(){if(p===o&&d)return"";let I=this._context.manipulationSettings.getNewLineKindAsString(),B=this.getParentOrThrow().getIndentationText();return`${I}${B} `+(d?"":"* ")}}set(o){return a_(_zt.prototype,this,o),o.text!=null||o.tagName!=null?this.replaceWithText(a=>{this._context.structurePrinterFactory.forJSDocTag({printStarsOnNewLine:!0}).printText(a,{tagName:o.tagName??this.getTagName(),text:o.text!=null?o.text:_7n(this)})}):this}replaceWithText(o){let a=Z1e(this._getWriterWithQueuedIndentation(),o),d=this.getParentOrThrow(),p=this.getChildIndex(),y=this.getStart();return jm({parent:d,insertPos:y,newText:a,replacing:{textLength:I9n(this)-y}}),d.getChildren()[p]}getStructure(){let o=_7n(this);return D_(_zt.prototype,this,{kind:Dt.StructureKind.JSDocTag,tagName:this.getTagName(),text:o.length===0?void 0:o})}};function _7n(c){let o=c.getSourceFile().getFullText(),a=c.getTagNameNode().getEnd(),d=I9n(c),p=Math.min(o.charCodeAt(a)===ZL.SPACE?a+1:a,d);return spn(o.substring(p,d))}function I9n(c){return P9n(c,k9n(c))}function k9n(c,o){return o=o??D9n(c),o!=null?o.getStart():c.getParentOrThrow().getEnd()-2}function D9n(c){let a=c.getParentIfKindOrThrow(fe.SyntaxKind.JSDoc).getTags(),d=a.indexOf(c);return a[d+1]}function P9n(c,o){let a=c.getSourceFile().getFullText();return h2e(a,o,d=>d!==ZL.ASTERISK&&!fe.StringUtils.isWhitespaceCharCode(d))}var XUt=class extends lN{},QUt=class extends lN{},YUt=class extends lN{},ZUt=class extends lN{},eVt=class extends lN{},tVt=class extends lN{},N9n=v2e(Ame),nVt=class extends N9n{},rVt=class extends lN{},iVt=class extends lN{},oVt=class extends qo{},sVt=class extends qo{},aVt=class extends qo{},cVt=class extends qo{},lVt=class extends Ame{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}},uVt=class extends qo{getName(){return this._getNodeFromCompilerNode(this.compilerNode.name)}},dVt=class extends Ame{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}isPostfix(){return this.compilerNode.postfix}},fVt=class extends Ame{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}isPostfix(){return this.compilerNode.postfix}},pVt=class extends Ame{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}},R9n=S_t(lN),mVt=class extends R9n{},hVt=class extends lN{},M9n=Ppn(lN),_Vt=class extends M9n{},gVt=class extends lN{},L9n=Ppn(lN),yVt=class extends L9n{},vVt=class extends lN{},bVt=class extends lN{},SVt=class extends lN{},O9n=S_t(lN),TVt=class extends O9n{},F9n=S_t(lN),EVt=class extends F9n{},B9n=S_t(lN),xVt=class extends B9n{},AVt=class extends Ame{getTypeNode(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type)}},W4t=class{#e;constructor(o){this.#e=o}get compilerObject(){return this.#e}getName(){return this.compilerObject.name}getText(){return this.compilerObject.text??[]}},W9n=b9n(lN),wVt=class extends W9n{getConstraint(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.constraint)}getConstraintOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getConstraint(),o??"Expected to find the JS doc template tag's constraint.",this)}},CVt=class extends qo{},j9n=S_t(lN),IVt=class extends j9n{},z9n=S_t(lN),kVt=class extends z9n{},DVt=class extends lN{},PVt=class extends eO{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}},NVt=class extends Ame{isArrayType(){return this.compilerNode.isArrayType}getPropertyTags(){return this.compilerNode.jsDocPropertyTags?this.compilerNode.jsDocPropertyTags.map(o=>this._getNodeFromCompilerNode(o)):void 0}},RVt=class extends lN{getTypeExpression(){let o=this.compilerNode.typeExpression;if(!(o!=null&&o.pos===o.end))return this._getNodeFromCompilerNodeIfExists(this.compilerNode.typeExpression)}},MVt=class extends lN{},LVt=class extends Ame{},OVt=class extends Ame{getTypeNode(){return this._getNodeFromCompilerNode(this.compilerNode.type)}},FVt=class extends qo{remove(){x3e({children:[this],getSiblingFormatting:()=>uC.Newline})}},ygr=c=>h9(znt(LM(w3e(C3e(DW(D3e(c))))))),gzt=ygr(HC),BVt=class extends gzt{set(o){return a_(gzt.prototype,this,o),o.isConst!=null&&this.setIsConstEnum(o.isConst),o.members!=null&&(this.getMembers().forEach(a=>a.remove()),this.addMembers(o.members)),this}addMember(o){return this.addMembers([o])[0]}addMembers(o){return this.insertMembers(this.getMembers().length,o)}insertMember(o,a){return this.insertMembers(o,[a])[0]}insertMembers(o,a){if(a.length===0)return[];let d=this.getMembersWithComments();o=kR(o,d.length);let p=this._getWriterWithChildIndentation();return this._context.structurePrinterFactory.forEnumMember().printTexts(p,a),xme({parent:this.getChildSyntaxListOrThrow(),currentNodes:d,insertIndex:o,newText:p.toString(),useNewLines:!0,useTrailingCommas:this._context.manipulationSettings.getUseTrailingCommas()}),xG(d,this.getMembersWithComments(),o,!E());function E(){return a instanceof Array?a.every(I=>typeof I=="object"):!1}}getMember(o){return IR(this.getMembers(),o)}getMemberOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getMember(o),()=>zD("enum member",o))}getMembers(){return this.compilerNode.members.map(o=>this._getNodeFromCompilerNode(o))}getMembersWithComments(){let o=this.compilerNode;return i7.getContainerArray(o,this.getSourceFile().compilerNode).map(a=>this._getNodeFromCompilerNode(a))}setIsConstEnum(o){return this.toggleModifier("const",o)}isConstEnum(){return this.getConstKeyword()!=null}getConstKeyword(){return this.getFirstModifierByKind(fe.SyntaxKind.ConstKeyword)}getStructure(){return D_(gzt.prototype,this,{kind:Dt.StructureKind.Enum,isConst:this.isConstEnum(),members:this.getMembers().map(o=>o.getStructure())})}},vgr=c=>LM(y_t(uVe(c))),yzt=vgr(qo),WVt=class extends yzt{getValue(){return this._context.typeChecker.getConstantValue(this)}setValue(o){let a;if(typeof o=="string"){let d=this._context.manipulationSettings.getQuoteKind();a=d+fe.StringUtils.escapeForWithinString(o,d)+d}else a=o.toString();return this.setInitializer(a),this}remove(){let o=[this],a=this.getNextSiblingIfKind(fe.SyntaxKind.CommaToken);a!=null&&o.push(a),x3e({children:o,getSiblingFormatting:()=>uC.Newline})}set(o){return a_(yzt.prototype,this,o),o.value!=null?this.setValue(o.value):o.hasOwnProperty(fe.nameof(o,"value"))&&o.initializer==null&&this.removeInitializer(),this}getStructure(){return D_(yzt.prototype,this,{kind:Dt.StructureKind.EnumMember,value:void 0})}},jVt=class extends qo{getTypeNodes(){return this.compilerNode.types?.map(o=>this._getNodeFromCompilerNode(o))??[]}getToken(){return this.compilerNode.token}removeExpression(o){let a=this.getTypeNodes(),d=typeof o=="number"?p(o):o;if(a.length===1){let y=this.getParentSyntaxListOrThrow().getChildren();y.length===1?oT({children:[y[0].getParentSyntaxListOrThrow()],removePrecedingSpaces:!0}):oT({children:[this],removePrecedingSpaces:!0})}else g2e(d);return this;function p(y){return a[kR(y,a.length-1)]}}},cVe=class extends qo{remove(){O7n(this)}},bgr=c=>wme(Wne(LM(v2e(c)))),vzt=bgr(cVe),zVt=class extends vzt{set(o){return a_(vzt.prototype,this,o),this}getStructure(){return D_(vzt.prototype,this,{kind:Dt.StructureKind.CallSignature})}},GVt=class extends cVe{},Sgr=c=>wme(Wne(LM(v2e(c)))),bzt=Sgr(cVe),UVt=class extends bzt{set(o){return a_(bzt.prototype,this,o),this}getStructure(){return D_(bzt.prototype,this,{kind:Dt.StructureKind.ConstructSignature})}},Tgr=c=>wpn(Wne(LM(q4t(DW(c))))),Szt=Tgr(cVe),VVt=class extends Szt{getKeyName(){return this.getKeyNameNode().getText()}setKeyName(o){fe.errors.throwIfWhitespaceOrNotString(o,"name"),this.getKeyName()!==o&&this.getKeyNameNode().replaceWithText(o,this._getWriterWithQueuedChildIndentation())}getKeyNameNode(){let o=this.compilerNode.parameters[0];return this._getNodeFromCompilerNode(o.name)}getKeyType(){return this.getKeyNameNode().getType()}setKeyType(o){fe.errors.throwIfWhitespaceOrNotString(o,"type");let a=this.getKeyTypeNode();return a.getText()===o?this:(a.replaceWithText(o,this._getWriterWithQueuedChildIndentation()),this)}getKeyTypeNode(){let o=this.compilerNode.parameters[0];return this._getNodeFromCompilerNode(o.type)}set(o){return a_(Szt.prototype,this,o),o.keyName!=null&&this.setKeyName(o.keyName),o.keyType!=null&&this.setKeyType(o.keyType),this}getStructure(){let o=this.getKeyTypeNode();return D_(Szt.prototype,this,{kind:Dt.StructureKind.IndexSignature,keyName:this.getKeyName(),keyType:o.getText()})}},Egr=c=>Ipn(h9(J7n(xpn(wme(LM(w3e(znt(C3e(DW(D3e(c))))))))))),Tzt=Egr(HC),HVt=class extends Tzt{getBaseTypes(){return this.getType().getBaseTypes()}getBaseDeclarations(){return this.getType().getBaseTypes().map(o=>o.getSymbol()?.getDeclarations()??[]).flat()}getImplementations(){return this.getNameNode().getImplementations()}set(o){return a_(Tzt.prototype,this,o),this}getStructure(){return D_(Tzt.prototype,this,{kind:Dt.StructureKind.Interface})}},xgr=c=>Wne(LM(P3e(wme(v2e(uVe(c)))))),Ezt=xgr(cVe),$Vt=class extends Ezt{set(o){return a_(Ezt.prototype,this,o),this}getStructure(){return D_(Ezt.prototype,this,{kind:Dt.StructureKind.MethodSignature})}},Agr=c=>Wne(LM(q4t(P3e(y_t(N3e(uVe(DW(c)))))))),xzt=Agr(cVe),KVt=class extends xzt{set(o){return a_(xzt.prototype,this,o),this}getStructure(){return D_(xzt.prototype,this,{kind:Dt.StructureKind.PropertySignature})}};function Npn(c){return class extends c{getAttributes(){return this.compilerNode.attributes.properties.map(o=>this._getNodeFromCompilerNode(o))}getAttributeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getAttribute(o),()=>zD("attribute",o))}getAttribute(o){return IR(this.getAttributes(),o)}addAttribute(o){return this.addAttributes([o])[0]}addAttributes(o){return this.insertAttributes(this.compilerNode.attributes.properties.length,o)}insertAttribute(o,a){return this.insertAttributes(o,[a])[0]}insertAttributes(o,a){if(a.length===0)return[];let d=this.compilerNode.attributes.properties.length;o=kR(o,d);let p=o===0?this.getTagNameNode().getEnd():this.getAttributes()[o-1].getEnd(),y=this._getWriterWithQueuedChildIndentation();return new sfn(this._context.structurePrinterFactory.forJsxAttributeDecider()).printText(y,a),jm({insertPos:p,newText:" "+y.toString(),parent:this.getNodeProperty("attributes").getFirstChildByKindOrThrow(fe.SyntaxKind.SyntaxList)}),xG(d,this.getAttributes(),o,!1)}set(o){return a_(c.prototype,this,o),o.attributes!=null&&(this.getAttributes().forEach(a=>a.remove()),this.addAttributes(o.attributes)),this}getStructure(){return D_(c.prototype,this,{attributes:this.getAttributes().map(o=>o.getStructure())})}}}function YHt(c){return class extends c{getTagNameNode(){return this._getNodeFromCompilerNode(this.compilerNode.tagName)}set(o){return a_(c.prototype,this,o),o.name!=null&&this.getTagNameNode().replaceWithText(o.name),this}getStructure(){return D_(c.prototype,this,{name:this.getTagNameNode().getText()})}}}function Rpn(c){return class extends c{getText(){return this.compilerNode.text}getDefinitionNodes(){return this.getDefinitions().map(o=>o.getDeclarationNode()).filter(o=>o!=null)}getDefinitions(){return this._context.languageService.getDefinitions(this)}}}var G9n=o7(qo),JVt=class extends G9n{},U9n=Rpn(k3e(y2e(m9))),j4t=class extends U9n{getImplementations(){return this._context.languageService.getImplementations(this)}},V9n=Rpn(k3e(y2e(qo))),qVt=class extends V9n{},XVt=class extends qo{getLeft(){return this._getNodeFromCompilerNode(this.compilerNode.left)}getRight(){return this._getNodeFromCompilerNode(this.compilerNode.right)}},Azt=qo,QVt=class extends Azt{getNameNode(){return this._getNodeFromCompilerNode(this.compilerNode.name)}setName(o){return this.getNameNode().replaceWithText(a=>{typeof o=="object"?this._context.structurePrinterFactory.forJsxNamespacedName().printText(a,o):a.write(o)}),this}getInitializerOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getInitializer(),o??`Expected to find an initializer for the JSX attribute '${this.getNameNode().getText()}'`,this)}getInitializer(){return this._getNodeFromCompilerNodeIfExists(this.compilerNode.initializer)}setInitializer(o){let a=Z1e(this._getWriterWithQueuedIndentation(),o);if(fe.StringUtils.isNullOrWhitespace(a))return this.removeInitializer(),this;let d=this.getInitializer();return d!=null?(d.replaceWithText(a),this):(jm({insertPos:this.getNameNode().getEnd(),parent:this,newText:`=${a}`}),this)}removeInitializer(){let o=this.getInitializer();return o==null?this:(oT({children:[o.getPreviousSiblingIfKindOrThrow(fe.SyntaxKind.EqualsToken),o],removePrecedingSpaces:!0,removePrecedingNewLines:!0}),this)}remove(){oT({children:[this],removePrecedingNewLines:!0,removePrecedingSpaces:!0})}set(o){return a_(Azt.prototype,this,o),o.name!=null&&this.setName(o.name),o.initializer!=null?this.setInitializer(o.initializer):o.hasOwnProperty(fe.nameof(o,"initializer"))&&this.removeInitializer(),this}getStructure(){let o=this.getInitializer(),a=this.getNameNode();return D_(Azt.prototype,this,{name:a instanceof j4t?a.getText():a.getStructure(),kind:Dt.StructureKind.JsxAttribute,initializer:o?.getText()})}},wgr=c=>YHt(c),H9n=wgr(qo),YVt=class extends H9n{},ZVt=class extends MM{},wzt=m9,eHt=class extends wzt{getJsxChildren(){return this.compilerNode.children.map(o=>this._getNodeFromCompilerNode(o))}getOpeningElement(){return this._getNodeFromCompilerNode(this.compilerNode.openingElement)}getClosingElement(){return this._getNodeFromCompilerNode(this.compilerNode.closingElement)}setBodyText(o){let a=G7n(this._getWriterWithIndentation(),o);return g7n(this,a),this}setBodyTextInline(o){let a=this._getWriterWithQueuedChildIndentation();return lVe(a,o),a.isLastNewLine()&&(a.setIndentationLevel(Math.max(0,this.getIndentationLevel()-1)),a.write("")),g7n(this,a.toString()),this}set(o){if(a_(wzt.prototype,this,o),o.attributes!=null){let a=this.getOpeningElement();a.getAttributes().forEach(d=>d.remove()),a.addAttributes(o.attributes)}if(o.children!=null)throw new fe.errors.NotImplementedError("Setting JSX children is currently not implemented. Please open an issue if you need this.");return o.bodyText!=null?this.setBodyText(o.bodyText):o.hasOwnProperty(fe.nameof(o,"bodyText"))&&this.setBodyTextInline(""),o.name!=null&&(this.getOpeningElement().getTagNameNode().replaceWithText(o.name),this.getClosingElement().getTagNameNode().replaceWithText(o.name)),this}getStructure(){let o=this.getOpeningElement(),a=D_(wzt.prototype,this,{kind:Dt.StructureKind.JsxElement,name:o.getTagNameNode().getText(),attributes:o.getAttributes().map(d=>d.getStructure()),children:void 0,bodyText:bpn(this)});return delete a.children,a}};function g7n(c,o){let a=c.getOpeningElement(),d=c.getClosingElement();jm({insertPos:a.getEnd(),newText:o,parent:c.getChildSyntaxListOrThrow(),replacing:{textLength:d.getStart()-a.getEnd()}})}var $9n=X4t($4t(MM)),tHt=class extends $9n{},nHt=class extends m9{getJsxChildren(){return this.compilerNode.children.map(o=>this._getNodeFromCompilerNode(o))}getOpeningFragment(){return this._getNodeFromCompilerNode(this.compilerNode.openingFragment)}getClosingFragment(){return this._getNodeFromCompilerNode(this.compilerNode.closingFragment)}},K9n=qo,rHt=class extends K9n{getNamespaceNode(){return this._getNodeFromCompilerNode(this.compilerNode.namespace)}getNameNode(){return this._getNodeFromCompilerNode(this.compilerNode.name)}set(o){return this.getNamespaceNode().replaceWithText(o.namespace),this.getNameNode().replaceWithText(o.name),this}getStructure(){return{namespace:this.getNamespaceNode().getText(),name:this.getNameNode().getText()}}},Cgr=c=>Npn(YHt(c)),J9n=Cgr(MM),iHt=class extends J9n{},oHt=class extends MM{},Igr=c=>Npn(YHt(c)),Czt=Igr(m9),sHt=class extends Czt{set(o){return a_(Czt.prototype,this,o),this}getStructure(){return D_(Czt.prototype,this,{kind:Dt.StructureKind.JsxSelfClosingElement})}},Izt=o7(qo),aHt=class extends Izt{remove(){oT({children:[this],removePrecedingNewLines:!0,removePrecedingSpaces:!0})}set(o){return a_(Izt.prototype,this,o),o.expression!=null&&this.setExpression(o.expression),this}getStructure(){return D_(Izt.prototype,this,{kind:Dt.StructureKind.JsxSpreadAttribute,expression:this.getExpression().getText()})}},q9n=Xwt(qo),cHt=class extends q9n{containsOnlyTriviaWhiteSpaces(){let o=this.compilerNode;return typeof o.containsOnlyWhiteSpaces=="boolean"?o.containsOnlyWhiteSpaces:this.compilerNode.containsOnlyTriviaWhiteSpaces}},X9n=Ont,lHt=class extends X9n{getLiteralValue(){let o=this.compilerNode.text;if(typeof BigInt>"u")throw new fe.errors.InvalidOperationError("Runtime environment does not support BigInts. Perhaps work with the text instead?");let a=o.substring(0,o.length-1);return BigInt(a)}setLiteralValue(o){if(typeof o!="bigint")throw new fe.errors.ArgumentTypeError("value","bigint",typeof o);return Bnt({sourceFile:this._sourceFile,start:this.getStart(),replacingLength:this.getWidth(),newText:o.toString()+"n"}),this}},Q9n=m9,uHt=class extends Q9n{getLiteralValue(){return Mpn(this)}setLiteralValue(o){return Z9n(this,o)}},Y9n=m9,dHt=class extends Y9n{getLiteralValue(){return Mpn(this)}setLiteralValue(o){return Z9n(this,o)}};function Z9n(c,o){if(Mpn(c)===o)return c;let a=c.getParentSyntaxList()||c.getParentOrThrow(),d=c.getChildIndex();return c.replaceWithText(o?"true":"false"),a.getChildAtIndex(d)}function Mpn(c){return c.getKind()===fe.SyntaxKind.TrueKeyword}var eBn=m9,fHt=class extends eBn{},tBn=Ont,pHt=class extends tBn{getLiteralValue(){let o=this.compilerNode.text;return o.indexOf(".")>=0?parseFloat(o):parseInt(o,10)}setLiteralValue(o){return Bnt({sourceFile:this._sourceFile,start:this.getStart(),replacingLength:this.getWidth(),newText:o.toString(10)}),this}};Dt.QuoteKind=void 0;(function(c){c.Single="'",c.Double='"'})(Dt.QuoteKind||(Dt.QuoteKind={}));var nBn=Ont,mHt=class extends nBn{getLiteralValue(){let o=/^\/(.*)\/([^\/]*)$/,a=this.compilerNode.text,d=o.exec(a);return new RegExp(d[1],d[2])}setLiteralValue(o,a){let d;return typeof o=="string"?d=o:(d=o.source,a=o.flags),Bnt({sourceFile:this._sourceFile,start:this.getStart(),replacingLength:this.getWidth(),newText:`/${d}/${a||""}`}),this}},rBn=Ont,hHt=class extends rBn{getLiteralValue(){return this.compilerNode.text}setLiteralValue(o){return Bnt({sourceFile:this._sourceFile,start:this.getStart()+1,replacingLength:this.getWidth()-2,newText:fe.StringUtils.escapeForWithinString(o,this.getQuoteKind())}),this}getQuoteKind(){return this.getText()[0]==="'"?Dt.QuoteKind.Single:Dt.QuoteKind.Double}},iBn=Ont,_Ht=class extends iBn{getLiteralValue(){return this.compilerNode.text}setLiteralValue(o){let a=this.getChildIndex(),d=this.getParentSyntaxList()||this.getParentOrThrow();return Bnt({sourceFile:this._sourceFile,start:this.getStart()+1,replacingLength:this.getWidth()-2,newText:o}),d.getChildAtIndex(a)}},gHt=class extends u_t{getTag(){return this._getNodeFromCompilerNode(this.compilerNode.tag)}getTemplate(){return this._getNodeFromCompilerNode(this.compilerNode.template)}removeTag(){let o=this.getParentSyntaxList()??this.getParentOrThrow(),a=this.getChildIndex(),d=this.getTemplate();return jm({customMappings:(p,y)=>[{currentNode:d,newNode:p.getChildren(y)[a]}],parent:o,insertPos:this.getStart(),newText:this.getTemplate().getText(),replacing:{textLength:this.getWidth(),nodes:[this]}}),o.getChildAtIndex(a)}},oBn=m9,yHt=class extends oBn{getHead(){return this._getNodeFromCompilerNode(this.compilerNode.head)}getTemplateSpans(){return this.compilerNode.templateSpans.map(o=>this._getNodeFromCompilerNode(o))}setLiteralValue(o){let a=this.getChildIndex(),d=this.getParentSyntaxList()??this.getParentOrThrow();return Bnt({sourceFile:this._sourceFile,start:this.getStart()+1,replacingLength:this.getWidth()-2,newText:o}),d.getChildAtIndex(a)}},sBn=Xwt(qo),vHt=class extends sBn{},aBn=Xwt(qo),bHt=class extends aBn{},cBn=o7(qo),SHt=class extends cBn{getLiteral(){return this._getNodeFromCompilerNode(this.compilerNode.literal)}},lBn=Xwt(qo),THt=class extends lBn{},kgr=c=>Tpn(Spn(N3e(y_t(HHt(c))))),kzt=kgr(qo),EHt=class extends kzt{remove(){let o=this.getParentOrThrow();switch(o.getKind()){case fe.SyntaxKind.VariableDeclarationList:a(this);break;case fe.SyntaxKind.CatchClause:d(this);break;default:throw new fe.errors.NotImplementedError(`Not implemented for syntax kind: ${o.getKindName()}`)}function a(p){let y=o.getParentIfKindOrThrow(fe.SyntaxKind.VariableStatement);y.getDeclarations().length===1?y.remove():g2e(p)}function d(p){oT({children:[p.getPreviousSiblingIfKindOrThrow(fe.SyntaxKind.OpenParenToken),p,p.getNextSiblingIfKindOrThrow(fe.SyntaxKind.CloseParenToken)],removePrecedingSpaces:!0})}}getVariableStatementOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getVariableStatement(),o??"Expected the grandparent to be a variable statement.",this)}getVariableStatement(){let o=this.getParentOrThrow().getParentOrThrow();return qo.isVariableStatement(o)?o:void 0}set(o){return a_(kzt.prototype,this,o),this}getStructure(){return D_(kzt.prototype,this,{kind:Dt.StructureKind.VariableDeclaration})}},uBn=DW(qo),xHt=class extends uBn{getDeclarations(){return this.compilerNode.declarations.map(o=>this._getNodeFromCompilerNode(o))}getDeclarationKind(){let o=this.compilerNode.flags;return o&fe.ts.NodeFlags.Let?Dt.VariableDeclarationKind.Let:(o&fe.ts.NodeFlags.AwaitUsing)===fe.ts.NodeFlags.AwaitUsing?Dt.VariableDeclarationKind.AwaitUsing:(o&fe.ts.NodeFlags.Using)===fe.ts.NodeFlags.Using?Dt.VariableDeclarationKind.Using:o&fe.ts.NodeFlags.Const?Dt.VariableDeclarationKind.Const:Dt.VariableDeclarationKind.Var}getDeclarationKindKeywords(){let o=this.getDeclarationKind();switch(o){case Dt.VariableDeclarationKind.Const:return[this.getFirstChildByKindOrThrow(fe.SyntaxKind.ConstKeyword)];case Dt.VariableDeclarationKind.Let:return[this.getFirstChildByKindOrThrow(fe.SyntaxKind.LetKeyword)];case Dt.VariableDeclarationKind.Var:return[this.getFirstChildByKindOrThrow(fe.SyntaxKind.VarKeyword)];case Dt.VariableDeclarationKind.Using:return[this.getFirstChildByKindOrThrow(fe.SyntaxKind.UsingKeyword)];case Dt.VariableDeclarationKind.AwaitUsing:let a=this.getFirstChildByKindOrThrow(fe.SyntaxKind.AwaitKeyword),d=a.getNextSiblingIfKindOrThrow(fe.SyntaxKind.UsingKeyword);return[a,d];default:return fe.errors.throwNotImplementedForNeverValueError(o)}}setDeclarationKind(o){if(this.getDeclarationKind()===o)return this;let a=this.getDeclarationKindKeywords(),d=a[0].getStart(),p=a[a.length-1].getEnd();return jm({insertPos:d,newText:o,parent:this,replacing:{textLength:p-d}}),this}addDeclaration(o){return this.addDeclarations([o])[0]}addDeclarations(o){return this.insertDeclarations(this.getDeclarations().length,o)}insertDeclaration(o,a){return this.insertDeclarations(o,[a])[0]}insertDeclarations(o,a){let d=this._getWriterWithQueuedChildIndentation(),p=new A3e(this._context.structurePrinterFactory.forVariableDeclaration()),y=this.compilerNode.declarations.length;return o=kR(o,y),p.printText(d,a),xme({parent:this.getFirstChildByKindOrThrow(fe.SyntaxKind.SyntaxList),currentNodes:this.getDeclarations(),insertIndex:o,newText:d.toString(),useTrailingCommas:!1}),xG(y,this.getDeclarations(),o,!1)}},AHt=class{#e;#t;constructor(o,a){this.#e=o,this.#t=a}get compilerSignature(){return this.#t}getTypeParameters(){return(this.compilerSignature.typeParameters||[]).map(a=>this.#e.compilerFactory.getTypeParameter(a))}getParameters(){return this.compilerSignature.parameters.map(o=>this.#e.compilerFactory.getSymbol(o))}getReturnType(){return this.#e.compilerFactory.getType(this.compilerSignature.getReturnType())}getDocumentationComments(){return this.compilerSignature.getDocumentationComment(this.#e.typeChecker.compilerObject).map(a=>this.#e.compilerFactory.getSymbolDisplayPart(a))}getJsDocTags(){return this.compilerSignature.getJsDocTags().map(a=>this.#e.compilerFactory.getJSDocTagInfo(a))}getDeclaration(){let{compilerFactory:o}=this.#e,a=this.compilerSignature.getDeclaration();return o.getNodeFromCompilerNode(a,o.getSourceFileForNode(a))}},dBn=class{#e;#t;get compilerSymbol(){return this.#t}constructor(o,a){this.#e=o,this.#t=a,this.getValueDeclaration(),this.getDeclarations()}getName(){return this.compilerSymbol.getName()}getEscapedName(){return this.compilerSymbol.getEscapedName()}getAliasedSymbolOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getAliasedSymbol(),o??"Expected to find an aliased symbol.")}getImmediatelyAliasedSymbol(){return this.#e.typeChecker.getImmediatelyAliasedSymbol(this)}getImmediatelyAliasedSymbolOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getImmediatelyAliasedSymbol(),o??"Expected to find an immediately aliased symbol.")}getAliasedSymbol(){return this.#e.typeChecker.getAliasedSymbol(this)}getExportSymbol(){return this.#e.typeChecker.getExportSymbolOfSymbol(this)}isAlias(){return(this.getFlags()&fe.SymbolFlags.Alias)===fe.SymbolFlags.Alias}isOptional(){return(this.getFlags()&fe.SymbolFlags.Optional)===fe.SymbolFlags.Optional}getFlags(){return this.compilerSymbol.getFlags()}hasFlags(o){return(this.compilerSymbol.flags&o)===o}getValueDeclarationOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getValueDeclaration(),o??(()=>`Expected to find the value declaration of symbol '${this.getName()}'.`))}getValueDeclaration(){let o=this.compilerSymbol.valueDeclaration;if(o!=null)return this.#e.compilerFactory.getNodeFromCompilerNode(o,this.#e.compilerFactory.getSourceFileForNode(o))}getDeclarations(){return(this.compilerSymbol.declarations??[]).map(o=>this.#e.compilerFactory.getNodeFromCompilerNode(o,this.#e.compilerFactory.getSourceFileForNode(o)))}getExportOrThrow(o,a){return fe.errors.throwIfNullOrUndefined(this.getExport(o),a??(()=>`Expected to find export with name: ${o}`))}getExport(o){if(this.compilerSymbol.exports==null)return;let a=this.compilerSymbol.exports.get(fe.ts.escapeLeadingUnderscores(o));return a==null?void 0:this.#e.compilerFactory.getSymbol(a)}getExports(){return this.compilerSymbol.exports==null?[]:Array.from(this.compilerSymbol.exports.values()).map(o=>this.#e.compilerFactory.getSymbol(o))}getGlobalExportOrThrow(o,a){return fe.errors.throwIfNullOrUndefined(this.getGlobalExport(o),a??(()=>`Expected to find global export with name: ${o}`))}getGlobalExport(o){if(this.compilerSymbol.globalExports==null)return;let a=this.compilerSymbol.globalExports.get(fe.ts.escapeLeadingUnderscores(o));return a==null?void 0:this.#e.compilerFactory.getSymbol(a)}getGlobalExports(){return this.compilerSymbol.globalExports==null?[]:Array.from(this.compilerSymbol.globalExports.values()).map(o=>this.#e.compilerFactory.getSymbol(o))}getMemberOrThrow(o,a){return fe.errors.throwIfNullOrUndefined(this.getMember(o),a??`Expected to find member with name: ${o}`)}getMember(o){if(this.compilerSymbol.members==null)return;let a=this.compilerSymbol.members.get(fe.ts.escapeLeadingUnderscores(o));return a==null?void 0:this.#e.compilerFactory.getSymbol(a)}getMembers(){return this.compilerSymbol.members==null?[]:Array.from(this.compilerSymbol.members.values()).map(o=>this.#e.compilerFactory.getSymbol(o))}getDeclaredType(){return this.#e.typeChecker.getDeclaredTypeOfSymbol(this)}getTypeAtLocation(o){return this.#e.typeChecker.getTypeOfSymbolAtLocation(this,o)}getFullyQualifiedName(){return this.#e.typeChecker.getFullyQualifiedName(this)}getJsDocTags(){return this.compilerSymbol.getJsDocTags(this.#e.typeChecker.compilerObject).map(o=>new W4t(o))}},Kwt=class{#e;constructor(o){this.#e=o}get compilerObject(){return this.#e}getStart(){return this.compilerObject.start}getEnd(){return this.compilerObject.start+this.compilerObject.length}getLength(){return this.compilerObject.length}},Jwt=(()=>{let c=[],o;return class{static{let d=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getSpan",static:!1,private:!1,access:{has:p=>"getSpan"in p,get:p=>p.getSpan},metadata:d},null,c),d&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})}#e=jne(this,c);constructor(d){this.#e=d}get compilerObject(){return this.#e}getSpan(){return new Kwt(this.compilerObject.span)}getNewText(){return this.compilerObject.newText}}})(),Q4t=(()=>{let c=[],o;return class{static{let d=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getTextChanges",static:!1,private:!1,access:{has:p=>"getTextChanges"in p,get:p=>p.getTextChanges},metadata:d},null,c),d&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})}#e=jne(this,c);#t;#n;#r;#i;constructor(d,p){this.#e=d,this.#t=p;let y=d.compilerFactory.addOrGetSourceFileFromFilePath(d.fileSystemWrapper.getStandardizedAbsolutePath(p.fileName),{markInProject:!1,scriptKind:void 0});this.#r=y!=null,p.isNewFile||(this.#n=y)}getFilePath(){return this.#t.fileName}getSourceFile(){return this.#n}getTextChanges(){return this.#t.textChanges.map(d=>new Jwt(d))}applyChanges(d={}){if(this.#i)return;if(this.isNewFile()&&this.#r&&!d.overwrite)throw new fe.errors.InvalidOperationError(`Cannot apply file text change for creating a new file when the file exists at path ${this.getFilePath()}. Did you mean to provide the overwrite option?`);let p;if(this.isNewFile()?p=this.#e.project.createSourceFile(this.getFilePath(),"",{overwrite:d.overwrite}):p=this.getSourceFile(),p==null)throw new fe.errors.InvalidOperationError(`Cannot apply file text change to modify existing file that doesn't exist at path: ${this.getFilePath()}`);return p.applyTextChanges(this.getTextChanges()),p._markAsInProject(),this.#i=!0,this}isNewFile(){return!!this.#t.isNewFile}}})(),wHt=class{#e;#t;constructor(o,a){this.#e=o,this.#t=a}get compilerObject(){return this.#t}getDescription(){return this.compilerObject.description}getChanges(){return this.compilerObject.changes.map(o=>new Q4t(this.#e,o))}},CHt=class extends wHt{getFixName(){return this.compilerObject.fixName}getFixId(){return this.compilerObject.fixId}getFixAllDescription(){return this.compilerObject.fixAllDescription}},fBn=(()=>{let c=[],o;return class{static{let d=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getChanges",static:!1,private:!1,access:{has:p=>"getChanges"in p,get:p=>p.getChanges},metadata:d},null,c),d&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})}#e=jne(this,c);#t;constructor(d,p){this.#e=d,this.#t=p}get compilerObject(){return this.#t}getChanges(){return this.compilerObject.changes.map(d=>new Q4t(this.#e,d))}applyChanges(d){for(let p of this.getChanges())p.applyChanges(d);return this}}})(),tCt=(()=>{let c=[],o,a,d;return class{static{let y=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],a=[fe.Memoize],d=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getTextSpan",static:!1,private:!1,access:{has:E=>"getTextSpan"in E,get:E=>E.getTextSpan},metadata:y},null,c),s_(this,null,a,{kind:"method",name:"getNode",static:!1,private:!1,access:{has:E=>"getNode"in E,get:E=>E.getNode},metadata:y},null,c),s_(this,null,d,{kind:"method",name:"getOriginalTextSpan",static:!1,private:!1,access:{has:E=>"getOriginalTextSpan"in E,get:E=>E.getOriginalTextSpan},metadata:y},null,c),y&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:y})}_context=jne(this,c);_compilerObject;_sourceFile;constructor(y,E){this._context=y,this._compilerObject=E,this._sourceFile=this._context.compilerFactory.addOrGetSourceFileFromFilePath(y.fileSystemWrapper.getStandardizedAbsolutePath(this.compilerObject.fileName),{markInProject:!1,scriptKind:void 0}),this._sourceFile._doActionPreNextModification(()=>this.getNode())}get compilerObject(){return this._compilerObject}getSourceFile(){return this._sourceFile}getTextSpan(){return new Kwt(this.compilerObject.textSpan)}getNode(){let y=this.getTextSpan(),E=this.getSourceFile(),I=y.getStart(),B=y.getEnd();return K();function K(){let Y;return E._context.compilerFactory.forgetNodesCreatedInBlock(ue=>{let ie,Re=E;for(;Re!=null;){if(ie==null&&(Y=Re),Re.getStart()===I&&Re.getWidth()===B)Y=ie=Re;else if(ie!=null)break;Re=Re.getChildAtPos(I)}Y!=null&&ue(Y)}),Y}}getOriginalTextSpan(){let{originalTextSpan:y}=this.compilerObject;return y==null?void 0:new Kwt(y)}getOriginalFileName(){return this.compilerObject.originalFileName}}})(),Lpn=(()=>{let c=tCt,o=[],a;return class extends c{static{let p=typeof Symbol=="function"&&Symbol.metadata?Object.create(c[Symbol.metadata]??null):void 0;a=[fe.Memoize],s_(this,null,a,{kind:"method",name:"getDeclarationNode",static:!1,private:!1,access:{has:y=>"getDeclarationNode"in y,get:y=>y.getDeclarationNode},metadata:p},null,o),p&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:p})}constructor(p,y){super(p,y),jne(this,o),this.getSourceFile()._doActionPreNextModification(()=>this.getDeclarationNode())}getKind(){return this.compilerObject.kind}getName(){return this.compilerObject.name}getContainerKind(){return this.compilerObject.containerKind}getContainerName(){return this.compilerObject.containerName}getDeclarationNode(){if(this.getKind()==="module"&&this.getTextSpan().getLength()===this.getSourceFile().getFullWidth())return this.getSourceFile();let p=this.getTextSpan().getStart(),y=E(this.getSourceFile());return y?.getParentOrThrow();function E(I){if(I.getKind()===fe.SyntaxKind.Identifier&&I.getStart()===p)return I;for(let B of I._getChildrenIterator())if(B.getPos()<=p&&B.getEnd()>p)return E(B)}}}})(),z4t=class c{_compilerObject;constructor(o){this._compilerObject=o}get compilerObject(){return this._compilerObject}getMessageText(){return this.compilerObject.messageText}getNext(){let o=this.compilerObject.next;if(o!=null)return o instanceof Array?o.map(a=>new c(a)):[new c(o)]}getCode(){return this.compilerObject.code}getCategory(){return this.compilerObject.category}},ZHt=(()=>{let c=[],o;return class{static{let d=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getSourceFile",static:!1,private:!1,access:{has:p=>"getSourceFile"in p,get:p=>p.getSourceFile},metadata:d},null,c),d&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})}_context=jne(this,c);_compilerObject;constructor(d,p){this._context=d,this._compilerObject=p,this.getSourceFile()}get compilerObject(){return this._compilerObject}getSourceFile(){if(this._context==null)return;let d=this.compilerObject.file;return d==null?void 0:this._context.compilerFactory.getSourceFile(d,{markInProject:!1})}getMessageText(){let d=this._compilerObject.messageText;return typeof d=="string"?d:this._context==null?new z4t(d):this._context.compilerFactory.getDiagnosticMessageChain(d)}getLineNumber(){let d=this.getSourceFile(),p=this.getStart();if(!(d==null||p==null))return fe.StringUtils.getLineNumberAtPos(d.getFullText(),p)}getStart(){return this.compilerObject.start}getLength(){return this.compilerObject.length}getCategory(){return this.compilerObject.category}getCode(){return this.compilerObject.code}getSource(){return this.compilerObject.source}}})(),G4t=class extends ZHt{constructor(o,a){super(o,a)}getLineNumber(){return super.getLineNumber()}getStart(){return super.getStart()}getLength(){return super.getLength()}getSourceFile(){return super.getSourceFile()}},IHt=class{#e;#t;constructor(o,a){this.#e=a,this.#t=o}get compilerObject(){return this.#e}getFilePath(){return this.#t.fileSystemWrapper.getStandardizedAbsolutePath(this.compilerObject.name)}getWriteByteOrderMark(){return this.compilerObject.writeByteOrderMark||!1}getText(){return this.compilerObject.text}},pBn=(()=>{let c=[],o,a;return class{static{let p=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],a=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getDiagnostics",static:!1,private:!1,access:{has:y=>"getDiagnostics"in y,get:y=>y.getDiagnostics},metadata:p},null,c),s_(this,null,a,{kind:"method",name:"getOutputFiles",static:!1,private:!1,access:{has:y=>"getOutputFiles"in y,get:y=>y.getOutputFiles},metadata:p},null,c),p&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:p})}#e=jne(this,c);#t;constructor(p,y){this.#e=p,this.#t=y}get compilerObject(){return this.#t}getDiagnostics(){return this.compilerObject.diagnostics.map(p=>this.#e.compilerFactory.getDiagnostic(p))}getEmitSkipped(){return this.compilerObject.emitSkipped}getOutputFiles(){return this.compilerObject.outputFiles.map(p=>new IHt(this.#e,p))}}})(),kHt=(()=>{let c=[],o;return class{static{let d=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getDiagnostics",static:!1,private:!1,access:{has:p=>"getDiagnostics"in p,get:p=>p.getDiagnostics},metadata:d},null,c),d&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})}_context=jne(this,c);_compilerObject;constructor(d,p){this._context=d,this._compilerObject=p,this.getDiagnostics()}get compilerObject(){return this._compilerObject}getEmitSkipped(){return this.compilerObject.emitSkipped}getDiagnostics(){return this.compilerObject.diagnostics.map(d=>this._context.compilerFactory.getDiagnostic(d))}}})(),mBn=(()=>{let c=tCt,o=[],a;return class extends c{static{let p=typeof Symbol=="function"&&Symbol.metadata?Object.create(c[Symbol.metadata]??null):void 0;a=[fe.Memoize],s_(this,null,a,{kind:"method",name:"getDisplayParts",static:!1,private:!1,access:{has:y=>"getDisplayParts"in y,get:y=>y.getDisplayParts},metadata:p},null,o),p&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:p})}constructor(p,y){super(p,y),jne(this,o)}getKind(){return this.compilerObject.kind}getDisplayParts(){return this.compilerObject.displayParts.map(p=>this._context.compilerFactory.getSymbolDisplayPart(p))}}})(),DHt=class extends kHt{#e;constructor(o,a,d){super(o,a),this.#e=d}getFiles(){return this.#e}saveFiles(){let o=this._context.fileSystemWrapper,a=this.#e.map(d=>o.writeFile(d.filePath,d.writeByteOrderMark?"\uFEFF"+d.text:d.text));return Promise.all(a)}saveFilesSync(){let o=this._context.fileSystemWrapper;for(let a of this.#e)o.writeFileSync(a.filePath,a.writeByteOrderMark?"\uFEFF"+a.text:a.text)}},hBn=(()=>{let c=[],o;return class{static{let d=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getEdits",static:!1,private:!1,access:{has:p=>"getEdits"in p,get:p=>p.getEdits},metadata:d},null,c),d&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})}#e=jne(this,c);#t;constructor(d,p){this.#e=d,this.#t=p}get compilerObject(){return this.#t}getEdits(){return this.compilerObject.edits.map(d=>new Q4t(this.#e,d))}getRenameFilePath(){return this.compilerObject.renameFilename}getRenameLocation(){return this.compilerObject.renameLocation}applyChanges(d){for(let p of this.getEdits())p.applyChanges(d);return this}}})(),_Bn=(()=>{let c=[],o;return class{static{let d=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getDefinition",static:!1,private:!1,access:{has:p=>"getDefinition"in p,get:p=>p.getDefinition},metadata:d},null,c),d&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})}_context=jne(this,c);#e;#t;constructor(d,p){this._context=d,this.#e=p,this.#t=this.compilerObject.references.map(y=>d.compilerFactory.getReferencedSymbolEntry(y))}get compilerObject(){return this.#e}getDefinition(){return this._context.compilerFactory.getReferencedSymbolDefinitionInfo(this.compilerObject.definition)}getReferences(){return this.#t}}})(),gBn=(()=>{let c=Lpn,o=[],a;return class extends c{static{let p=typeof Symbol=="function"&&Symbol.metadata?Object.create(c[Symbol.metadata]??null):void 0;a=[fe.Memoize],s_(this,null,a,{kind:"method",name:"getDisplayParts",static:!1,private:!1,access:{has:y=>"getDisplayParts"in y,get:y=>y.getDisplayParts},metadata:p},null,o),p&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:p})}constructor(p,y){super(p,y),jne(this,o)}getDisplayParts(){return this.compilerObject.displayParts.map(p=>this._context.compilerFactory.getSymbolDisplayPart(p))}}})(),PHt=class extends tCt{constructor(o,a){super(o,a)}isWriteAccess(){return this.compilerObject.isWriteAccess}isInString(){return this.compilerObject.isInString}},NHt=class extends PHt{constructor(o,a){super(o,a)}isDefinition(){return this.compilerObject.isDefinition}},RHt=class extends tCt{getPrefixText(){return this._compilerObject.prefixText}getSuffixText(){return this._compilerObject.suffixText}},MHt=class{#e;constructor(o){this.#e=o}get compilerObject(){return this.#e}getText(){return this.compilerObject.text}getKind(){return this.compilerObject.kind}},U4t=class{#e;#t;constructor(o){this.#e=o}get compilerObject(){return this.#t()}_reset(o){this.#t=o}getAmbientModules(){return this.compilerObject.getAmbientModules().map(o=>this.#e.compilerFactory.getSymbol(o))}getApparentType(o){return this.#e.compilerFactory.getType(this.compilerObject.getApparentType(o.compilerType))}getAwaitedType(o){let a=this.compilerObject.getAwaitedType(o.compilerType);return a?this.#e.compilerFactory.getType(a):void 0}getConstantValue(o){return this.compilerObject.getConstantValue(o.compilerNode)}getFullyQualifiedName(o){return this.compilerObject.getFullyQualifiedName(o.compilerSymbol)}getTypeAtLocation(o){return this.#e.compilerFactory.getType(this.compilerObject.getTypeAtLocation(o.compilerNode))}getContextualType(o){let a=this.compilerObject.getContextualType(o.compilerNode);return a==null?void 0:this.#e.compilerFactory.getType(a)}getTypeOfSymbolAtLocation(o,a){return this.#e.compilerFactory.getType(this.compilerObject.getTypeOfSymbolAtLocation(o.compilerSymbol,a.compilerNode))}getDeclaredTypeOfSymbol(o){return this.#e.compilerFactory.getType(this.compilerObject.getDeclaredTypeOfSymbol(o.compilerSymbol))}getSymbolAtLocation(o){let a=this.compilerObject.getSymbolAtLocation(o.compilerNode);return a==null?void 0:this.#e.compilerFactory.getSymbol(a)}getAliasedSymbol(o){if(!o.hasFlags(fe.SymbolFlags.Alias))return;let a=this.compilerObject.getAliasedSymbol(o.compilerSymbol);return a==null?void 0:this.#e.compilerFactory.getSymbol(a)}getImmediatelyAliasedSymbol(o){let a=this.compilerObject.getImmediateAliasedSymbol(o.compilerSymbol);return a==null?void 0:this.#e.compilerFactory.getSymbol(a)}getExportSymbolOfSymbol(o){return this.#e.compilerFactory.getSymbol(this.compilerObject.getExportSymbolOfSymbol(o.compilerSymbol))}getPropertiesOfType(o){return this.compilerObject.getPropertiesOfType(o.compilerType).map(a=>this.#e.compilerFactory.getSymbol(a))}getTypeText(o,a,d){return d==null&&(d=this.#n(a)),this.compilerObject.typeToString(o.compilerType,a?.compilerNode,d)}getReturnTypeOfSignature(o){return this.#e.compilerFactory.getType(this.compilerObject.getReturnTypeOfSignature(o.compilerSignature))}getSignatureFromNode(o){let a=this.compilerObject.getSignatureFromDeclaration(o.compilerNode);return a==null?void 0:this.#e.compilerFactory.getSignature(a)}getExportsOfModule(o){return(this.compilerObject.getExportsOfModule(o.compilerSymbol)||[]).map(d=>this.#e.compilerFactory.getSymbol(d))}getExportSpecifierLocalTargetSymbol(o){let a=this.compilerObject.getExportSpecifierLocalTargetSymbol(o.compilerNode);return a==null?void 0:this.#e.compilerFactory.getSymbol(a)}getResolvedSignature(o){let a=this.compilerObject.getResolvedSignature(o.compilerNode);if(!(!a||!a.declaration))return this.#e.compilerFactory.getSignature(a)}getResolvedSignatureOrThrow(o,a){return fe.errors.throwIfNullOrUndefined(this.getResolvedSignature(o),a??"Signature could not be resolved.",o)}getBaseTypeOfLiteralType(o){return this.#e.compilerFactory.getType(this.compilerObject.getBaseTypeOfLiteralType(o.compilerType))}getSymbolsInScope(o,a){return this.compilerObject.getSymbolsInScope(o.compilerNode,a).map(d=>this.#e.compilerFactory.getSymbol(d))}getTypeArguments(o){return this.compilerObject.getTypeArguments(o.compilerType).map(a=>this.#e.compilerFactory.getType(a))}isTypeAssignableTo(o,a){return this.compilerObject.isTypeAssignableTo(o.compilerType,a.compilerType)}#n(o){let a=fe.TypeFormatFlags.UseTypeOfFunction|fe.TypeFormatFlags.NoTruncation|fe.TypeFormatFlags.UseFullyQualifiedType|fe.TypeFormatFlags.WriteTypeArgumentsOfSignature;return o!=null&&o.getKind()===fe.SyntaxKind.TypeAliasDeclaration&&(a|=fe.TypeFormatFlags.InTypeAlias),a}getShorthandAssignmentValueSymbol(o){let a=this.compilerObject.getShorthandAssignmentValueSymbol(o.compilerNode);return a?this.#e.compilerFactory.getSymbol(a):void 0}resolveName(o,a,d,p){let y=this.compilerObject.resolveName(o,a?.compilerNode,d,p);return y?this.#e.compilerFactory.getSymbol(y):void 0}},LHt=class{#e;#t;#n;#r;#i;#o;constructor(o){this.#e=o.context,this.#o=o.configFileParsingDiagnostics,this.#t=new U4t(this.#e),this._reset(o.rootNames,o.host)}get compilerObject(){return this.#i()}_isCompilerProgramCreated(){return this.#n!=null}_reset(o,a){let d=this.#e.compilerOptions.get();this.#i=()=>(this.#n==null&&(this.#n=fe.ts.createProgram(o,d,a,this.#r,this.#o),this.#r=void 0),this.#n),this.#n!=null&&(this.#r=this.#n,this.#n=void 0),this.#t._reset(()=>this.compilerObject.getTypeChecker())}getTypeChecker(){return this.#t}async emit(o={}){if(o.writeFile){let y=`Cannot specify a ${fe.nameof(o,"writeFile")} option when emitting asynchrously. Use ${fe.nameof(this,"emitSync")}() instead.`;throw new fe.errors.InvalidOperationError(y)}let{fileSystemWrapper:a}=this.#e,d=[],p=this.#s({writeFile:(y,E,I)=>{d.push(a.writeFile(a.getStandardizedAbsolutePath(y),I?"\uFEFF"+E:E))},...o});return await Promise.all(d),new kHt(this.#e,p)}emitSync(o={}){return new kHt(this.#e,this.#s(o))}emitToMemory(o={}){let a=[],{fileSystemWrapper:d}=this.#e,p=this.#s({writeFile:(y,E,I)=>{a.push({filePath:d.getStandardizedAbsolutePath(y),text:E,writeByteOrderMark:I||!1})},...o});return new DHt(this.#e,p,a)}#s(o={}){let a=o.targetSourceFile!=null?o.targetSourceFile.compilerNode:void 0,{emitOnlyDtsFiles:d,customTransformers:p,writeFile:y}=o;return this.compilerObject.emit(a,y,void 0,d,p)}getSyntacticDiagnostics(o){return this.compilerObject.getSyntacticDiagnostics(o?.compilerNode).map(d=>this.#e.compilerFactory.getDiagnosticWithLocation(d))}getSemanticDiagnostics(o){return this.compilerObject.getSemanticDiagnostics(o?.compilerNode).map(d=>this.#e.compilerFactory.getDiagnostic(d))}getDeclarationDiagnostics(o){return this.compilerObject.getDeclarationDiagnostics(o?.compilerNode).map(d=>this.#e.compilerFactory.getDiagnosticWithLocation(d))}getGlobalDiagnostics(){return this.compilerObject.getGlobalDiagnostics().map(a=>this.#e.compilerFactory.getDiagnostic(a))}getConfigFileParsingDiagnostics(){return this.compilerObject.getConfigFileParsingDiagnostics().map(a=>this.#e.compilerFactory.getDiagnostic(a))}getEmitModuleResolutionKind(){return fe.getEmitModuleResolutionKind(this.compilerObject.getCompilerOptions())}isSourceFileFromExternalLibrary(o){return o.isFromExternalLibrary()}},OHt=class{#e;#t;#n;#r;#i=0;get compilerObject(){return this.#e}constructor(o){this.#r=o.context;let{languageServiceHost:a,compilerHost:d}=fe.createHosts({transactionalFileSystem:this.#r.fileSystemWrapper,sourceFileContainer:this.#r.getSourceFileContainer(),compilerOptions:this.#r.compilerOptions,getNewLine:()=>this.#r.manipulationSettings.getNewLineKindAsString(),getProjectVersion:()=>`${this.#i}`,resolutionHost:o.resolutionHost??{},libFolderPath:o.libFolderPath,skipLoadingLibFiles:o.skipLoadingLibFiles});this.#t=d,this.#e=fe.ts.createLanguageService(a,this.#r.compilerFactory.documentRegistry),this.#n=new LHt({context:this.#r,rootNames:Array.from(this.#r.compilerFactory.getSourceFilePaths()),host:this.#t,configFileParsingDiagnostics:o.configFileParsingDiagnostics}),this.#r.compilerFactory.onSourceFileAdded(p=>{p._isInProject()&&this._reset()}),this.#r.compilerFactory.onSourceFileRemoved(()=>this._reset())}_reset(){this.#i+=1,this.#n._reset(Array.from(this.#r.compilerFactory.getSourceFilePaths()),this.#t)}getProgram(){return this.#n}getDefinitions(o){return this.getDefinitionsAtPosition(o._sourceFile,o.getStart())}getDefinitionsAtPosition(o,a){return(this.compilerObject.getDefinitionAtPosition(o.getFilePath(),a)||[]).map(p=>this.#r.compilerFactory.getDefinitionInfo(p))}getImplementations(o){return this.getImplementationsAtPosition(o._sourceFile,o.getStart())}getImplementationsAtPosition(o,a){return(this.compilerObject.getImplementationAtPosition(o.getFilePath(),a)||[]).map(p=>new mBn(this.#r,p))}findReferences(o){return this.findReferencesAtPosition(o._sourceFile,o.getStart())}findReferencesAsNodes(o){let a=this.findReferences(o);return Array.from(d());function*d(){for(let p of a){let y=p.getDefinition().getKind()===fe.ts.ScriptElementKind.alias,E=p.getReferences();for(let I=0;I<E.length;I++){let B=E[I];(y||!B.isDefinition()||I>0)&&(yield B.getNode())}}}}findReferencesAtPosition(o,a){return(this.compilerObject.findReferences(o.getFilePath(),a)||[]).map(p=>this.#r.compilerFactory.getReferencedSymbol(p))}findRenameLocations(o,a={}){let d=a.usePrefixAndSuffixText==null?this.#r.manipulationSettings.getUsePrefixAndSuffixTextForRename():a.usePrefixAndSuffixText;return(this.compilerObject.findRenameLocations(o._sourceFile.getFilePath(),o.getStart(),a.renameInStrings||!1,a.renameInComments||!1,d)||[]).map(y=>new RHt(this.#r,y))}getSuggestionDiagnostics(o){let a=this.#o(o);return this.compilerObject.getSuggestionDiagnostics(a).map(p=>this.#r.compilerFactory.getDiagnosticWithLocation(p))}getFormattingEditsForRange(o,a,d){return(this.compilerObject.getFormattingEditsForRange(o,a[0],a[1],this.#s(d))||[]).map(p=>new Jwt(p))}getFormattingEditsForDocument(o,a){let d=this.#r.fileSystemWrapper.getStandardizedAbsolutePath(o);return(this.compilerObject.getFormattingEditsForDocument(d,this.#s(a))||[]).map(p=>new Jwt(p))}getFormattedDocumentText(o,a){let d=this.#r.fileSystemWrapper.getStandardizedAbsolutePath(o),p=this.#r.compilerFactory.getSourceFileFromCacheFromFilePath(d);if(p==null)throw new fe.errors.FileNotFoundError(d);a=this.#s(a);let y=this.getFormattingEditsForDocument(d,a),E=_pn(p,y),I=a.newLineCharacter;return a.ensureNewLineAtEndOfFile&&!E.endsWith(I)&&(E+=I),E.replace(/\r?\n/g,I)}getEmitOutput(o,a){let d=this.#o(o),p=this.compilerObject;return new pBn(this.#r,y());function y(){let E=p.getProgram();return E==null||E.getSourceFile(d)==null?{emitSkipped:!0,outputFiles:[],diagnostics:[]}:p.getEmitOutput(d,a)}}getIdentationAtPosition(o,a,d){let p=this.#o(o);return d==null?d=this.#r.manipulationSettings.getEditorSettings():hpn(d,this.#r.manipulationSettings),this.compilerObject.getIndentationAtPosition(p,a,d)}organizeImports(o,a={},d={}){let p={type:"file",fileName:this.#o(o)};return this.compilerObject.organizeImports(p,this.#s(a),this.#a(d)).map(y=>new Q4t(this.#r,y))}getEditsForRefactor(o,a,d,p,y,E={}){let I=this.#o(o),B=typeof d=="number"?d:{pos:d.getPos(),end:d.getEnd()},K=this.compilerObject.getEditsForRefactor(I,this.#s(a),B,p,y,this.#a(E));return K!=null?new hBn(this.#r,K):void 0}getCombinedCodeFix(o,a,d={},p={}){let y=this.compilerObject.getCombinedCodeFix({type:"file",fileName:this.#o(o)},a,this.#s(d),this.#a(p||{}));return new fBn(this.#r,y)}getCodeFixesAtPosition(o,a,d,p,y={},E={}){let I=this.#o(o);return this.compilerObject.getCodeFixesAtPosition(I,a,d,p,this.#s(y),this.#a(E||{})).map(K=>new CHt(this.#r,K))}#o(o){let a=typeof o=="string"?this.#r.fileSystemWrapper.getStandardizedAbsolutePath(o):o.getFilePath();if(!this.#r.compilerFactory.containsSourceFileAtPath(a))throw new fe.errors.FileNotFoundError(a);return a}#s(o){return o._filled||(o=Object.assign(this.#r.getFormatCodeSettings(),o),ohr(o,this.#r.manipulationSettings),o._filled=!0),o}#a(o){return Object.assign(this.#r.getUserPreferences(),o)}},V4t=class{_context;#e;get compilerType(){return this.#e}constructor(o,a){this._context=o,this.#e=a}getText(o,a){return this._context.typeChecker.getTypeText(this,o,a)}getAliasSymbol(){return this.compilerType.aliasSymbol==null?void 0:this._context.compilerFactory.getSymbol(this.compilerType.aliasSymbol)}getAliasSymbolOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getAliasSymbol(),"Expected to find an alias symbol.")}getAliasTypeArguments(){return(this.compilerType.aliasTypeArguments||[]).map(a=>this._context.compilerFactory.getType(a))}getApparentType(){return this._context.typeChecker.getApparentType(this)}getAwaitedType(){return this._context.typeChecker.getAwaitedType(this)}getArrayElementTypeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getArrayElementType(),o??"Expected to find an array element type.")}getArrayElementType(){if(this.isArray())return this.getTypeArguments()[0]}getBaseTypes(){return(this.compilerType.getBaseTypes()||[]).map(a=>this._context.compilerFactory.getType(a))}getBaseTypeOfLiteralType(){return this._context.typeChecker.getBaseTypeOfLiteralType(this)}getCallSignatures(){return this.compilerType.getCallSignatures().map(o=>this._context.compilerFactory.getSignature(o))}getConstructSignatures(){return this.compilerType.getConstructSignatures().map(o=>this._context.compilerFactory.getSignature(o))}getConstraintOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getConstraint(),o??"Expected to find a constraint.")}getConstraint(){let o=this.compilerType.getConstraint();return o==null?void 0:this._context.compilerFactory.getType(o)}getDefaultOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getDefault(),o??"Expected to find a default type.")}getDefault(){let o=this.compilerType.getDefault();return o==null?void 0:this._context.compilerFactory.getType(o)}getProperties(){return this.compilerType.getProperties().map(o=>this._context.compilerFactory.getSymbol(o))}getPropertyOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getProperty(o),()=>zD("symbol property",o))}getProperty(o){return V8n(this.getProperties(),o)}getApparentProperties(){return this.compilerType.getApparentProperties().map(o=>this._context.compilerFactory.getSymbol(o))}getApparentProperty(o){return V8n(this.getApparentProperties(),o)}isNullable(){return this.getUnionTypes().some(o=>o.isNull()||o.isUndefined())}getNonNullableType(){return this._context.compilerFactory.getType(this.compilerType.getNonNullableType())}getNumberIndexType(){let o=this.compilerType.getNumberIndexType();return o==null?void 0:this._context.compilerFactory.getType(o)}getStringIndexType(){let o=this.compilerType.getStringIndexType();return o==null?void 0:this._context.compilerFactory.getType(o)}getTargetType(){let o=this.compilerType.target||void 0;return o==null?void 0:this._context.compilerFactory.getType(o)}getTargetTypeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getTargetType(),o??"Expected to find the target type.")}getTypeArguments(){return this._context.typeChecker.getTypeArguments(this)}getTupleElements(){return this.isTuple()?this.getTypeArguments():[]}getUnionTypes(){return this.isUnion()?this.compilerType.types.map(o=>this._context.compilerFactory.getType(o)):[]}getIntersectionTypes(){return this.isIntersection()?this.compilerType.types.map(o=>this._context.compilerFactory.getType(o)):[]}getLiteralValue(){return this.compilerType?.value}getLiteralValueOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getLiteralValue(),o??"Type was not a literal type.")}getLiteralFreshType(){let o=this.compilerType?.freshType;return o==null?void 0:this._context.compilerFactory.getType(o)}getLiteralFreshTypeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getLiteralFreshType(),o??"Type was not a literal type.")}getLiteralRegularType(){let o=this.compilerType?.regularType;return o==null?void 0:this._context.compilerFactory.getType(o)}getLiteralRegularTypeOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getLiteralRegularType(),o??"Type was not a literal type.")}getSymbol(){let o=this.compilerType.getSymbol();return o==null?void 0:this._context.compilerFactory.getSymbol(o)}getSymbolOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getSymbol(),o??"Expected to find a symbol.")}isAssignableTo(o){return this._context.typeChecker.isTypeAssignableTo(this,o)}isAnonymous(){return this.#n(fe.ObjectFlags.Anonymous)}isAny(){return this.#t(fe.TypeFlags.Any)}isNever(){return this.#t(fe.TypeFlags.Never)}isArray(){let o=this.getSymbol();return o==null?!1:(o.getName()==="Array"||o.getName()==="ReadonlyArray")&&this.getTypeArguments().length===1}isReadonlyArray(){let o=this.getSymbol();return o==null?!1:o.getName()==="ReadonlyArray"&&this.getTypeArguments().length===1}isTemplateLiteral(){return this.#t(fe.TypeFlags.TemplateLiteral)}isBoolean(){return this.#t(fe.TypeFlags.Boolean)}isString(){return this.#t(fe.TypeFlags.String)}isNumber(){return this.#t(fe.TypeFlags.Number)}isBigInt(){return this.#t(fe.TypeFlags.BigInt)}isLiteral(){let o=this.isBooleanLiteral();return this.compilerType.isLiteral()||o}isBooleanLiteral(){return this.#t(fe.TypeFlags.BooleanLiteral)}isBigIntLiteral(){return this.#t(fe.TypeFlags.BigIntLiteral)}isEnumLiteral(){return this.#t(fe.TypeFlags.EnumLiteral)&&!this.isUnion()}isNumberLiteral(){return this.#t(fe.TypeFlags.NumberLiteral)}isStringLiteral(){return this.compilerType.isStringLiteral()}isClass(){return this.compilerType.isClass()}isClassOrInterface(){return this.compilerType.isClassOrInterface()}isEnum(){if(this.#t(fe.TypeFlags.Enum))return!0;if(this.isEnumLiteral()&&!this.isUnion())return!1;let a=this.getSymbol();if(a==null)return!1;let d=a.getValueDeclaration();return d!=null&&qo.isEnumDeclaration(d)}isInterface(){return this.#n(fe.ObjectFlags.Interface)}isObject(){return this.#t(fe.TypeFlags.Object)}isTypeParameter(){return this.compilerType.isTypeParameter()}isTuple(){let o=this.getTargetType();return o==null?!1:o.#n(fe.ObjectFlags.Tuple)}isUnion(){return this.compilerType.isUnion()}isIntersection(){return this.compilerType.isIntersection()}isUnionOrIntersection(){return this.compilerType.isUnionOrIntersection()}isUnknown(){return this.#t(fe.TypeFlags.Unknown)}isNull(){return this.#t(fe.TypeFlags.Null)}isUndefined(){return this.#t(fe.TypeFlags.Undefined)}isVoid(){return this.#t(fe.TypeFlags.Void)}getFlags(){return this.compilerType.flags}getObjectFlags(){return this.isObject()&&this.compilerType.objectFlags||0}#t(o){return(this.compilerType.flags&o)===o}#n(o){return(this.getObjectFlags()&o)===o}},FHt=class extends V4t{getConstraintOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getConstraint(),o??"Expected type parameter to have a constraint.")}getConstraint(){let o=this.#e();if(o==null)return;let a=o.getConstraint();if(a!=null)return this._context.typeChecker.getTypeAtLocation(a)}getDefaultOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getDefault(),o??"Expected type parameter to have a default type.")}getDefault(){let o=this.#e();if(o==null)return;let a=o.getDefault();if(a!=null)return this._context.typeChecker.getTypeAtLocation(a)}#e(){let o=this.getSymbol();if(o==null)return;let a=o.getDeclarations()[0];if(a!=null&&qo.isTypeParameterDeclaration(a))return a}},H4t=class{#e;#t;constructor(o,a){this.#t=o,this.#e=a}getSkippedFilePaths(){return this.#t}getOutputFilePaths(){return this.#e}},BHt=class c{#e;#t;#n;constructor(o,a){this.#e=o,this._setPathInternal(a)}_setPathInternal(o){this.#t=o,this.#n=o.split("/").filter(a=>a.length>0)}get _context(){return this.#a(),this.#e}isAncestorOf(o){return c.#_(this,o)}isDescendantOf(o){return c.#_(o,this)}_getDepth(){return this.#n.length}getPath(){return this.#a(),this.#t}getBaseName(){return this.#n[this.#n.length-1]}getParentOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getParent(),o??(()=>`Parent directory of ${this.getPath()} does not exist or was never added.`))}getParent(){if(!fe.FileUtils.isRootDirPath(this.getPath()))return this.addDirectoryAtPathIfExists(fe.FileUtils.getDirPath(this.getPath()))}getDirectoryOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getDirectory(o),()=>typeof o=="string"?`Could not find a directory at path '${this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath())}'.`:"Could not find child directory that matched condition.")}getDirectory(o){if(typeof o=="string"){let a=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.compilerFactory.getDirectoryFromCache(a)}return this.getDirectories().find(o)}getSourceFileOrThrow(o){return fe.errors.throwIfNullOrUndefined(this.getSourceFile(o),()=>typeof o=="string"?`Could not find child source file at path '${this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath())}'.`:"Could not find child source file that matched condition.")}getSourceFile(o){if(typeof o=="string"){let a=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.compilerFactory.getSourceFileFromCacheFromFilePath(a)}for(let a of this._getSourceFilesIterator())if(o(a))return a}getDirectories(){return Array.from(this._getDirectoriesIterator())}_getDirectoriesIterator(){return this._context.compilerFactory.getChildDirectoriesOfDirectory(this.getPath())}getSourceFiles(o){let{compilerFactory:a,fileSystemWrapper:d}=this._context,p=this;if(typeof o=="string"||o instanceof Array)return Array.from(y(typeof o=="string"?[o]:o));return Array.from(this._getSourceFilesIterator());function*y(E){let I=Array.from(K()),B=fe.matchGlobs(I,E,p.getPath());for(let Y of B)yield a.getSourceFileFromCacheFromFilePath(d.getStandardizedAbsolutePath(Y));function*K(){for(let Y of p._getDescendantSourceFilesIterator())yield Y.getFilePath()}}}_getSourceFilesIterator(){return this._context.compilerFactory.getChildSourceFilesOfDirectory(this.getPath())}getDescendantSourceFiles(){return Array.from(this._getDescendantSourceFilesIterator())}*_getDescendantSourceFilesIterator(){for(let o of this._getSourceFilesIterator())yield o;for(let o of this._getDirectoriesIterator())yield*o._getDescendantSourceFilesIterator()}getDescendantDirectories(){return Array.from(this._getDescendantDirectoriesIterator())}*_getDescendantDirectoriesIterator(){for(let o of this.getDirectories())yield o,yield*o._getDescendantDirectoriesIterator()}addSourceFilesAtPaths(o){return o=typeof o=="string"?[o]:o,o=o.map(a=>fe.FileUtils.pathIsAbsolute(a)?a:fe.FileUtils.pathJoin(this.getPath(),a)),this._context.directoryCoordinator.addSourceFilesAtPaths(o,{markInProject:this._isInProject()})}addDirectoryAtPathIfExists(o,a={}){let d=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.directoryCoordinator.addDirectoryAtPathIfExists(d,{...a,markInProject:this._isInProject()})}addDirectoryAtPath(o,a={}){let d=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.directoryCoordinator.addDirectoryAtPath(d,{...a,markInProject:this._isInProject()})}createDirectory(o){let a=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.directoryCoordinator.createDirectoryOrAddIfExists(a,{markInProject:this._isInProject()})}createSourceFile(o,a,d){let p=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.compilerFactory.createSourceFile(p,a||"",{...d||{},markInProject:this._isInProject()})}addSourceFileAtPathIfExists(o){let a=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.directoryCoordinator.addSourceFileAtPathIfExists(a,{markInProject:this._isInProject()})}addSourceFileAtPath(o){let a=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return this._context.directoryCoordinator.addSourceFileAtPath(a,{markInProject:this._isInProject()})}async emit(o={}){let{fileSystemWrapper:a}=this._context,d=[],p=[],y=[];for(let E of this.#r(o))y7n(E)?y.push(E):(d.push(a.writeFile(E.filePath,E.fileText)),p.push(E.filePath));return await Promise.all(d),new H4t(y,p)}emitSync(o={}){let{fileSystemWrapper:a}=this._context,d=[],p=[];for(let y of this.#r(o))y7n(y)?p.push(y):(a.writeFileSync(y.filePath,y.fileText),d.push(y.filePath));return new H4t(p,d)}#r(o={}){let{emitOnlyDtsFiles:a=!1}=o,d=o.outDir==null?void 0:/\.js$/i,p=o.outDir==null?void 0:/\.js\.map$/i,y=o.declarationDir==null&&o.outDir==null?void 0:/\.d\.ts$/i,E=Y=>Y==null?void 0:this._context.fileSystemWrapper.getStandardizedAbsolutePath(Y,this.getPath()),I=(Y,ue)=>Y==null?void 0:fe.FileUtils.pathJoin(Y,ue.getBaseName()),B=this._context.compilerOptions.get().declarationDir!=null||o.declarationDir!=null;return K(this,E(o.outDir),E(o.declarationDir));function*K(Y,ue,ie){for(let Re of Y.getSourceFiles()){let Ie=Re.getEmitOutput({emitOnlyDtsFiles:a});if(Ie.getEmitSkipped()){yield Re.getFilePath();continue}for(let Ne of Ie.getOutputFiles()){let bt=Ne.getFilePath(),Qt=Ne.getWriteByteOrderMark()?fe.FileUtils.getTextWithByteOrderMark(Ne.getText()):Ne.getText();ue!=null&&(d.test(bt)||p.test(bt)||!B&&y.test(bt))?bt=fe.FileUtils.pathJoin(ue,fe.FileUtils.getBaseName(bt)):ie!=null&&y.test(bt)&&(bt=fe.FileUtils.pathJoin(ie,fe.FileUtils.getBaseName(bt))),yield{filePath:bt,fileText:Qt}}}for(let Re of Y.getDirectories())yield*K(Re,I(ue,Re),I(ie,Re))}}copyToDirectory(o,a){let d=typeof o=="string"?o:o.getPath();return this.copy(fe.FileUtils.pathJoin(d,this.getBaseName()),a)}copy(o,a){let d=this.getPath(),p=this._context.fileSystemWrapper,y=this._context.fileSystemWrapper.getStandardizedAbsolutePath(o,this.getPath());return d===y?this:(a=Pdn(a),a.includeUntrackedFiles&&p.queueCopyDirectory(d,y),this.#i(y,a))}async copyImmediately(o,a){let d=this._context.fileSystemWrapper,p=this.getPath(),y=d.getStandardizedAbsolutePath(o,p);if(p===y)return await this.save(),this;a=Pdn(a);let E=this.#i(y,a);return a.includeUntrackedFiles&&await d.copyDirectoryImmediately(p,y),await E.save(),E}copyImmediatelySync(o,a){let d=this._context.fileSystemWrapper,p=this.getPath(),y=d.getStandardizedAbsolutePath(o,p);if(p===y)return this.saveSync(),this;a=Pdn(a);let E=this.#i(y,a);return a.includeUntrackedFiles&&d.copyDirectoryImmediatelySync(p,y),E.saveSync(),E}#i(o,a){if(this.getPath()===o)return this;let{fileSystemWrapper:p,compilerFactory:y}=this._context,E=[this,...this.getDescendantDirectories()].map(B=>({newDirPath:B===this?o:p.getStandardizedAbsolutePath(this.getRelativePathTo(B),o)})),I=this.getDescendantSourceFiles().map(B=>({sourceFile:B,newFilePath:p.getStandardizedAbsolutePath(this.getRelativePathTo(B),o),references:this.#c(B)}));for(let{newDirPath:B}of E)this._context.compilerFactory.createDirectoryOrAddIfExists(B,{markInProject:this._isInProject()});for(let{sourceFile:B,newFilePath:K}of I)B._copyInternal(K,a);for(let{references:B,newFilePath:K}of I)this.getSourceFileOrThrow(K)._updateReferencesForCopyInternal(B);return y.getDirectoryFromCache(o)}moveToDirectory(o,a){let d=typeof o=="string"?o:o.getPath();return this.move(fe.FileUtils.pathJoin(d,this.getBaseName()),a)}move(o,a){let d=this._context.fileSystemWrapper,p=this.getPath(),y=d.getStandardizedAbsolutePath(o,p);return p===y?this:this.#o(y,a,()=>d.queueMoveDirectory(p,y))}async moveImmediately(o,a){let d=this._context.fileSystemWrapper,p=this.getPath(),y=d.getStandardizedAbsolutePath(o,p);return p===y?(await this.save(),this):(this.#o(y,a),await d.moveDirectoryImmediately(p,y),await this.save(),this)}moveImmediatelySync(o,a){let d=this._context.fileSystemWrapper,p=this.getPath(),y=d.getStandardizedAbsolutePath(o,p);return p===y?(this.saveSync(),this):(this.#o(y,a),d.moveDirectoryImmediatelySync(p,y),this.saveSync(),this)}#o(o,a,d){let p=this.getPath();if(p===o)return this;let y=this._context.compilerFactory.getDirectoryFromCacheOnlyIfInCache(o),E=y!=null&&y._isInProject();d&&d();let I=this._context.fileSystemWrapper,B=this._context.compilerFactory,K=[this,...this.getDescendantDirectories()].map(ue=>({directory:ue,oldPath:ue.getPath(),newDirPath:ue===this?o:I.getStandardizedAbsolutePath(this.getRelativePathTo(ue),o)})),Y=this.getDescendantSourceFiles().map(ue=>({sourceFile:ue,newFilePath:I.getStandardizedAbsolutePath(this.getRelativePathTo(ue),o),references:this.#h(ue)}));for(let{directory:ue,oldPath:ie,newDirPath:Re}of K){B.removeDirectoryFromCache(ie);let Ie=B.getDirectoryFromCache(Re);Ie?._forgetOnlyThis(),ue._setPathInternal(Re),B.addDirectoryToCache(ue)}for(let{sourceFile:ue,newFilePath:ie}of Y)ue._moveInternal(ie,a);for(let{sourceFile:ue,references:ie}of Y)ue._updateReferencesForMoveInternal(ie,p);return E&&this._markAsInProject(),this}clear(){let o=this.getPath();this.#s(),this._context.fileSystemWrapper.queueDirectoryDelete(o),this._context.fileSystemWrapper.queueMkdir(o)}async clearImmediately(){let o=this.getPath();this.#s(),await this._context.fileSystemWrapper.clearDirectoryImmediately(o)}clearImmediatelySync(){let o=this.getPath();this.#s(),this._context.fileSystemWrapper.clearDirectoryImmediatelySync(o)}delete(){let o=this.getPath();this.#s(),this._context.fileSystemWrapper.queueDirectoryDelete(o),this.forget()}#s(){for(let o of this.getSourceFiles())o.delete();for(let o of this.getDirectories())o.delete()}async deleteImmediately(){let{fileSystemWrapper:o}=this._context,a=this.getPath();this.forget(),await o.deleteDirectoryImmediately(a)}deleteImmediatelySync(){let{fileSystemWrapper:o}=this._context,a=this.getPath();this.forget(),o.deleteDirectoryImmediatelySync(a)}forget(){if(!this.wasForgotten()){for(let o of this.getSourceFiles())o.forget();for(let o of this.getDirectories())o.forget();this._forgetOnlyThis()}}_forgetOnlyThis(){this.wasForgotten()||(this._context.compilerFactory.removeDirectoryFromCache(this.getPath()),this.#e=void 0)}async save(){await this._context.fileSystemWrapper.saveForDirectory(this.getPath());let o=this.getDescendantSourceFiles().filter(a=>!a.isSaved());await Promise.all(o.map(a=>a.save()))}saveSync(){this._context.fileSystemWrapper.saveForDirectorySync(this.getPath()),this.getDescendantSourceFiles().filter(a=>!a.isSaved()).forEach(a=>a.saveSync())}getRelativePathTo(o){let a=this;return fe.FileUtils.getRelativePathTo(this.getPath(),d());function d(){return o instanceof Uwt?o.getFilePath():o instanceof c?o.getPath():a._context.fileSystemWrapper.getStandardizedAbsolutePath(o,a.getPath())}}getRelativePathAsModuleSpecifierTo(o){let a=this._context.program.getEmitModuleResolutionKind(),d=this,p=fe.FileUtils.getRelativePathTo(this.getPath(),y()).replace(/((\.d\.ts$)|(\.[^/.]+$))/i,"");return p.startsWith("../")?p:"./"+p;function y(){return o instanceof Uwt?E(o):o instanceof c?I(o):B(d._context.fileSystemWrapper.getStandardizedAbsolutePath(o,d.getPath()));function E(K){return B(K.getFilePath())}function I(K){switch(a){case fe.ModuleResolutionKind.Node10:return K===d?fe.FileUtils.pathJoin(K.getPath(),"index.ts"):K.getPath();case fe.ModuleResolutionKind.Classic:case fe.ModuleResolutionKind.Node16:case fe.ModuleResolutionKind.NodeNext:case fe.ModuleResolutionKind.Bundler:return fe.FileUtils.pathJoin(K.getPath(),"index.ts");default:return fe.errors.throwNotImplementedForNeverValueError(a)}}function B(K){let Y=fe.FileUtils.getDirPath(K);switch(a){case fe.ModuleResolutionKind.Node10:return Y===d.getPath()?K:K.replace(/\/index?(\.d\.ts|\.ts|\.js)$/i,"");case fe.ModuleResolutionKind.Classic:case fe.ModuleResolutionKind.Node16:case fe.ModuleResolutionKind.NodeNext:case fe.ModuleResolutionKind.Bundler:return K;default:return fe.errors.throwNotImplementedForNeverValueError(a)}}}}getProject(){return this._context.project}wasForgotten(){return this.#e==null}_isInProject(){return this._context.inProjectCoordinator.isDirectoryInProject(this)}_markAsInProject(){this._context.inProjectCoordinator.markDirectoryAsInProject(this)}_hasLoadedParent(){return this._context.compilerFactory.containsDirectoryAtPath(fe.FileUtils.getDirPath(this.getPath()))}#a(){if(this.wasForgotten())throw new fe.errors.InvalidOperationError("Cannot use a directory that was deleted, removed, or overwritten.")}#c(o){return o._getReferencesForCopyInternal().filter(d=>!this.isAncestorOf(d[1]))}#h(o){let{literalReferences:a,referencingLiterals:d}=o._getReferencesForMoveInternal();return{literalReferences:a.filter(p=>!this.isAncestorOf(p[1])),referencingLiterals:d.filter(p=>!this.isAncestorOf(p._sourceFile))}}static#_(o,a){if(a instanceof Uwt&&(a=a.getDirectory(),o===a))return!0;if(o.#n.length>=a.#n.length)return!1;for(let d=o.#n.length-1;d>=0;d--)if(o.#n[d]!==a.#n[d])return!1;return!0}};function Pdn(c){return c=fe.ObjectUtils.clone(c||{}),jD(c,"includeUntrackedFiles",!0),c}function y7n(c){return typeof c=="string"}var apn=class{#e;#t;constructor(o,a){this.#t=o,this.#e=a}addDirectoryAtPathIfExists(o,a){let d=this.#t.getDirectoryFromPath(o,a);if(d!=null){if(a.recursive)for(let p of fe.FileUtils.getDescendantDirectories(this.#e,o))this.#t.createDirectoryOrAddIfExists(p,a);return d}}addDirectoryAtPath(o,a){let d=this.addDirectoryAtPathIfExists(o,a);if(d==null)throw new fe.errors.DirectoryNotFoundError(o);return d}createDirectoryOrAddIfExists(o,a){return this.#t.createDirectoryOrAddIfExists(o,a)}addSourceFileAtPathIfExists(o,a){return this.#t.addOrGetSourceFileFromFilePath(o,{markInProject:a.markInProject,scriptKind:void 0})}addSourceFileAtPath(o,a){let d=this.addSourceFileAtPathIfExists(o,a);if(d==null)throw new fe.errors.FileNotFoundError(this.#e.getStandardizedAbsolutePath(o));return d}addSourceFilesAtPaths(o,a){typeof o=="string"&&(o=[o]);let d=[],p=new Set;for(let y of this.#e.globSync(o)){let E=this.addSourceFileAtPathIfExists(y,a);E!=null&&d.push(E),p.add(fe.FileUtils.getDirPath(y))}for(let y of fe.FileUtils.getParentMostPaths(Array.from(p)))this.addDirectoryAtPathIfExists(y,{recursive:!0,markInProject:a.markInProject});return d}},cpn=class{#e;#t=new fe.KeyValueCache;#n=new fe.KeyValueCache;#r=new fe.KeyValueCache;#i=new fe.KeyValueCache;constructor(o){this.#e=o}has(o){return this.#t.has(o)}get(o){if(!this.#t.has(o)){for(let a of this.#i.getValues())if(fe.FileUtils.pathStartsWith(a.getPath(),o))return this.createOrAddIfExists(o);return}return this.#t.get(o)}getOrphans(){return this.#i.getValues()}getAll(){return this.#t.getValuesAsArray()}*getAllByDepth(){let o=new fe.KeyValueCache,a=0;for(let p of this.getOrphans())d(p);for(a=Math.min(...Array.from(o.getKeys()));o.getSize()>0;){for(let p of o.get(a)||[])yield p,p.getDirectories().forEach(d);o.removeByKey(a),a++}function d(p){let y=p._getDepth();if(a>y)throw new Error(`For some reason a subdirectory had a lower depth than the parent directory: ${p.getPath()}`);o.getOrCreate(y,()=>[]).push(p)}}remove(o){this.#a(o),this.#t.removeByKey(o),this.#i.removeByKey(o)}*getChildDirectoriesOfDirectory(o){let a=this.#r.get(o)?.entries();if(a!=null)for(let d of a)yield d}*getChildSourceFilesOfDirectory(o){let a=this.#n.get(o)?.entries();if(a!=null)for(let d of a)yield d}addSourceFile(o){let a=o.getDirectoryPath();this.createOrAddIfExists(a),this.#n.getOrCreate(a,()=>new fe.SortedKeyValueArray(p=>p.getBaseName(),fe.LocaleStringComparer.instance)).set(o)}removeSourceFile(o){let a=fe.FileUtils.getDirPath(o),d=this.#n.get(a);d!=null&&(d.removeByKey(fe.FileUtils.getBaseName(o)),d.hasItems()||this.#n.removeByKey(a))}createOrAddIfExists(o){return this.has(o)?this.get(o):(this.#c(o),this.#o(o))}#o(o){let a=new BHt(this.#e,o);return this.addDirectory(a),a}addDirectory(o){let a=o.getPath(),d=fe.FileUtils.getDirPath(a),p=d===a;for(let y of this.#i.getValues()){let E=y.getPath(),I=fe.FileUtils.getDirPath(E);!(I===E)&&I===a&&this.#i.removeByKey(E)}p||this.#s(o),this.has(d)||this.#i.set(a,o),this.#t.set(a,o),this.#e.fileSystemWrapper.directoryExistsSync(a)||this.#e.fileSystemWrapper.queueMkdir(a);for(let y of this.#i.getValues())o.isAncestorOf(y)&&this.#c(y.getPath())}#s(o){if(fe.FileUtils.isRootDirPath(o.getPath()))return;let a=fe.FileUtils.getDirPath(o.getPath());this.#r.getOrCreate(a,()=>new fe.SortedKeyValueArray(p=>p.getBaseName(),fe.LocaleStringComparer.instance)).set(o)}#a(o){if(fe.FileUtils.isRootDirPath(o))return;let a=fe.FileUtils.getDirPath(o),d=this.#r.get(a);d!=null&&(d.removeByKey(fe.FileUtils.getBaseName(o)),d.hasItems()||this.#r.removeByKey(a))}#c(o){let a=[],d=fe.FileUtils.getDirPath(o);for(;o!==d;){if(o=d,d=fe.FileUtils.getDirPath(o),this.#t.has(o)){for(let p of a)this.#o(p);break}a.unshift(o)}}},lpn=class extends fe.KeyValueCache{#e=[];getOrCreate(o,a){return super.getOrCreate(o,()=>{let d=a();return this.#e.length>0&&this.#e[this.#e.length-1].add(d),d})}setForgetPoint(){this.#e.push(new Set)}forgetLastPoint(){let o=this.#e.pop();o!=null&&this.#n(o.values())}rememberNode(o){if(o.wasForgotten())throw new fe.errors.InvalidOperationError("Cannot remember a node that was removed or forgotten.");let a=!1;for(let d of this.#e)if(d.delete(o)){a=!0;break}return a&&this.#t(o),a}#t(o){let a=o.getParentSyntaxList()||o.getParent();a!=null&&this.rememberNode(a)}#n(o){for(let a of o)a.wasForgotten()||a.getKind()===fe.SyntaxKind.SourceFile||a._forgetOnlyThis()}},Dgr={[fe.SyntaxKind.SourceFile]:Uwt,[fe.SyntaxKind.ArrayBindingPattern]:Uzt,[fe.SyntaxKind.ArrayLiteralExpression]:Kzt,[fe.SyntaxKind.ArrayType]:EUt,[fe.SyntaxKind.ArrowFunction]:lUt,[fe.SyntaxKind.AsExpression]:Jzt,[fe.SyntaxKind.AwaitExpression]:qzt,[fe.SyntaxKind.BigIntLiteral]:lHt,[fe.SyntaxKind.BindingElement]:Vzt,[fe.SyntaxKind.BinaryExpression]:M4t,[fe.SyntaxKind.Block]:TGt,[fe.SyntaxKind.BreakStatement]:EGt,[fe.SyntaxKind.CallExpression]:Xzt,[fe.SyntaxKind.CallSignature]:zVt,[fe.SyntaxKind.CaseBlock]:xGt,[fe.SyntaxKind.CaseClause]:AGt,[fe.SyntaxKind.CatchClause]:wGt,[fe.SyntaxKind.ClassDeclaration]:pUt,[fe.SyntaxKind.ClassExpression]:mUt,[fe.SyntaxKind.ClassStaticBlockDeclaration]:hUt,[fe.SyntaxKind.ConditionalType]:xUt,[fe.SyntaxKind.Constructor]:gUt,[fe.SyntaxKind.ConstructorType]:AUt,[fe.SyntaxKind.ConstructSignature]:UVt,[fe.SyntaxKind.ContinueStatement]:IGt,[fe.SyntaxKind.CommaListExpression]:Qzt,[fe.SyntaxKind.ComputedPropertyName]:JVt,[fe.SyntaxKind.ConditionalExpression]:Yzt,[fe.SyntaxKind.DebuggerStatement]:kGt,[fe.SyntaxKind.Decorator]:SUt,[fe.SyntaxKind.DefaultClause]:DGt,[fe.SyntaxKind.DeleteExpression]:Zzt,[fe.SyntaxKind.DoStatement]:PGt,[fe.SyntaxKind.ElementAccessExpression]:O4t,[fe.SyntaxKind.EmptyStatement]:NGt,[fe.SyntaxKind.EnumDeclaration]:BVt,[fe.SyntaxKind.EnumMember]:WVt,[fe.SyntaxKind.ExportAssignment]:VGt,[fe.SyntaxKind.ExportDeclaration]:HGt,[fe.SyntaxKind.ExportSpecifier]:$Gt,[fe.SyntaxKind.ExpressionWithTypeArguments]:wUt,[fe.SyntaxKind.ExpressionStatement]:RGt,[fe.SyntaxKind.ExternalModuleReference]:KGt,[fe.SyntaxKind.QualifiedName]:XVt,[fe.SyntaxKind.ForInStatement]:MGt,[fe.SyntaxKind.ForOfStatement]:LGt,[fe.SyntaxKind.ForStatement]:OGt,[fe.SyntaxKind.FunctionDeclaration]:uUt,[fe.SyntaxKind.FunctionExpression]:dUt,[fe.SyntaxKind.FunctionType]:CUt,[fe.SyntaxKind.GetAccessor]:yUt,[fe.SyntaxKind.HeritageClause]:jVt,[fe.SyntaxKind.Identifier]:j4t,[fe.SyntaxKind.IfStatement]:FGt,[fe.SyntaxKind.ImportClause]:XGt,[fe.SyntaxKind.ImportDeclaration]:QGt,[fe.SyntaxKind.ImportEqualsDeclaration]:YGt,[fe.SyntaxKind.ImportSpecifier]:ZGt,[fe.SyntaxKind.ImportType]:IUt,[fe.SyntaxKind.ImportAttribute]:JGt,[fe.SyntaxKind.ImportAttributes]:qGt,[fe.SyntaxKind.IndexedAccessType]:kUt,[fe.SyntaxKind.IndexSignature]:VVt,[fe.SyntaxKind.InferType]:DUt,[fe.SyntaxKind.InterfaceDeclaration]:HVt,[fe.SyntaxKind.IntersectionType]:PUt,[fe.SyntaxKind.JSDocAllType]:qUt,[fe.SyntaxKind.JSDocAugmentsTag]:XUt,[fe.SyntaxKind.JSDocAuthorTag]:QUt,[fe.SyntaxKind.JSDocCallbackTag]:YUt,[fe.SyntaxKind.JSDocClassTag]:ZUt,[fe.SyntaxKind.JSDocDeprecatedTag]:eVt,[fe.SyntaxKind.JSDocEnumTag]:tVt,[fe.SyntaxKind.JSDocFunctionType]:nVt,[fe.SyntaxKind.JSDocImplementsTag]:rVt,[fe.SyntaxKind.JSDocImportTag]:iVt,[fe.SyntaxKind.JSDocLink]:oVt,[fe.SyntaxKind.JSDocLinkCode]:sVt,[fe.SyntaxKind.JSDocLinkPlain]:aVt,[fe.SyntaxKind.JSDocMemberName]:cVt,[fe.SyntaxKind.JSDocNamepathType]:lVt,[fe.SyntaxKind.JSDocNameReference]:uVt,[fe.SyntaxKind.JSDocNonNullableType]:dVt,[fe.SyntaxKind.JSDocNullableType]:fVt,[fe.SyntaxKind.JSDocOptionalType]:pVt,[fe.SyntaxKind.JSDocOverrideTag]:hVt,[fe.SyntaxKind.JSDocParameterTag]:_Vt,[fe.SyntaxKind.JSDocPrivateTag]:gVt,[fe.SyntaxKind.JSDocPropertyTag]:yVt,[fe.SyntaxKind.JSDocProtectedTag]:vVt,[fe.SyntaxKind.JSDocPublicTag]:bVt,[fe.SyntaxKind.JSDocReturnTag]:TVt,[fe.SyntaxKind.JSDocReadonlyTag]:SVt,[fe.SyntaxKind.JSDocThrowsTag]:kVt,[fe.SyntaxKind.JSDocOverloadTag]:mVt,[fe.SyntaxKind.JSDocSatisfiesTag]:EVt,[fe.SyntaxKind.JSDocSeeTag]:xVt,[fe.SyntaxKind.JSDocSignature]:AVt,[fe.SyntaxKind.JSDocTag]:MVt,[fe.SyntaxKind.JSDocTemplateTag]:wVt,[fe.SyntaxKind.JSDocText]:CVt,[fe.SyntaxKind.JSDocThisTag]:IVt,[fe.SyntaxKind.JSDocTypeExpression]:PVt,[fe.SyntaxKind.JSDocTypeLiteral]:NVt,[fe.SyntaxKind.JSDocTypeTag]:RVt,[fe.SyntaxKind.JSDocTypedefTag]:DVt,[fe.SyntaxKind.JSDocUnknownType]:LVt,[fe.SyntaxKind.JSDocVariadicType]:OVt,[fe.SyntaxKind.JsxAttribute]:QVt,[fe.SyntaxKind.JsxClosingElement]:YVt,[fe.SyntaxKind.JsxClosingFragment]:ZVt,[fe.SyntaxKind.JsxElement]:eHt,[fe.SyntaxKind.JsxExpression]:tHt,[fe.SyntaxKind.JsxFragment]:nHt,[fe.SyntaxKind.JsxNamespacedName]:rHt,[fe.SyntaxKind.JsxOpeningElement]:iHt,[fe.SyntaxKind.JsxOpeningFragment]:oHt,[fe.SyntaxKind.JsxSelfClosingElement]:sHt,[fe.SyntaxKind.JsxSpreadAttribute]:aHt,[fe.SyntaxKind.JsxText]:cHt,[fe.SyntaxKind.LabeledStatement]:BGt,[fe.SyntaxKind.LiteralType]:NUt,[fe.SyntaxKind.MappedType]:RUt,[fe.SyntaxKind.MetaProperty]:tGt,[fe.SyntaxKind.MethodDeclaration]:$wt,[fe.SyntaxKind.MethodSignature]:$Vt,[fe.SyntaxKind.ModuleBlock]:eUt,[fe.SyntaxKind.ModuleDeclaration]:tUt,[fe.SyntaxKind.NamedExports]:nUt,[fe.SyntaxKind.NamedImports]:rUt,[fe.SyntaxKind.NamedTupleMember]:MUt,[fe.SyntaxKind.NamespaceExport]:iUt,[fe.SyntaxKind.NamespaceImport]:oUt,[fe.SyntaxKind.NewExpression]:nGt,[fe.SyntaxKind.NonNullExpression]:rGt,[fe.SyntaxKind.NotEmittedStatement]:WGt,[fe.SyntaxKind.NoSubstitutionTemplateLiteral]:_Ht,[fe.SyntaxKind.NumericLiteral]:pHt,[fe.SyntaxKind.ObjectBindingPattern]:Hzt,[fe.SyntaxKind.ObjectLiteralExpression]:oGt,[fe.SyntaxKind.OmittedExpression]:lGt,[fe.SyntaxKind.OptionalType]:LUt,[fe.SyntaxKind.Parameter]:fUt,[fe.SyntaxKind.ParenthesizedExpression]:uGt,[fe.SyntaxKind.ParenthesizedType]:OUt,[fe.SyntaxKind.PartiallyEmittedExpression]:dGt,[fe.SyntaxKind.PostfixUnaryExpression]:fGt,[fe.SyntaxKind.PrefixUnaryExpression]:pGt,[fe.SyntaxKind.PrivateIdentifier]:qVt,[fe.SyntaxKind.PropertyAccessExpression]:F4t,[fe.SyntaxKind.PropertyAssignment]:sGt,[fe.SyntaxKind.PropertyDeclaration]:vUt,[fe.SyntaxKind.PropertySignature]:KVt,[fe.SyntaxKind.RegularExpressionLiteral]:mHt,[fe.SyntaxKind.RestType]:FUt,[fe.SyntaxKind.ReturnStatement]:jGt,[fe.SyntaxKind.SatisfiesExpression]:mGt,[fe.SyntaxKind.SetAccessor]:bUt,[fe.SyntaxKind.ShorthandPropertyAssignment]:aGt,[fe.SyntaxKind.SpreadAssignment]:cGt,[fe.SyntaxKind.SpreadElement]:hGt,[fe.SyntaxKind.StringLiteral]:hHt,[fe.SyntaxKind.SwitchStatement]:zGt,[fe.SyntaxKind.SyntaxList]:Wzt,[fe.SyntaxKind.TaggedTemplateExpression]:gHt,[fe.SyntaxKind.TemplateExpression]:yHt,[fe.SyntaxKind.TemplateHead]:vHt,[fe.SyntaxKind.TemplateLiteralType]:BUt,[fe.SyntaxKind.TemplateMiddle]:bHt,[fe.SyntaxKind.TemplateSpan]:SHt,[fe.SyntaxKind.TemplateTail]:THt,[fe.SyntaxKind.ThisType]:WUt,[fe.SyntaxKind.ThrowStatement]:GGt,[fe.SyntaxKind.TryStatement]:UGt,[fe.SyntaxKind.TupleType]:jUt,[fe.SyntaxKind.TypeAliasDeclaration]:zUt,[fe.SyntaxKind.TypeAssertionExpression]:yGt,[fe.SyntaxKind.TypeLiteral]:GUt,[fe.SyntaxKind.TypeOperator]:UUt,[fe.SyntaxKind.TypeParameter]:VUt,[fe.SyntaxKind.TypePredicate]:HUt,[fe.SyntaxKind.TypeQuery]:$Ut,[fe.SyntaxKind.TypeReference]:KUt,[fe.SyntaxKind.UnionType]:JUt,[fe.SyntaxKind.VariableDeclaration]:EHt,[fe.SyntaxKind.VariableDeclarationList]:xHt,[fe.SyntaxKind.VariableStatement]:sUt,[fe.SyntaxKind.JSDoc]:TUt,[fe.SyntaxKind.TypeOfExpression]:vGt,[fe.SyntaxKind.WhileStatement]:aUt,[fe.SyntaxKind.WithStatement]:cUt,[fe.SyntaxKind.YieldExpression]:SGt,[fe.SyntaxKind.SemicolonToken]:qo,[fe.SyntaxKind.AnyKeyword]:MM,[fe.SyntaxKind.BooleanKeyword]:MM,[fe.SyntaxKind.FalseKeyword]:dHt,[fe.SyntaxKind.ImportKeyword]:eGt,[fe.SyntaxKind.InferKeyword]:qo,[fe.SyntaxKind.NeverKeyword]:qo,[fe.SyntaxKind.NullKeyword]:fHt,[fe.SyntaxKind.NumberKeyword]:MM,[fe.SyntaxKind.ObjectKeyword]:MM,[fe.SyntaxKind.StringKeyword]:MM,[fe.SyntaxKind.SymbolKeyword]:MM,[fe.SyntaxKind.SuperKeyword]:_Gt,[fe.SyntaxKind.ThisKeyword]:gGt,[fe.SyntaxKind.TrueKeyword]:uHt,[fe.SyntaxKind.UndefinedKeyword]:MM,[fe.SyntaxKind.VoidExpression]:bGt},upn=class{#e;#t=new Map;#n=new fe.WeakCache;#r=new fe.WeakCache;#i=new fe.WeakCache;#o=new fe.WeakCache;#s=new fe.WeakCache;#a=new fe.WeakCache;#c=new fe.WeakCache;#h=new fe.WeakCache;#_=new fe.WeakCache;#v=new fe.WeakCache;#y=new fe.WeakCache;#g=new fe.WeakCache;#b=new fe.WeakCache;#d=new lpn;#f;#p=new fe.EventContainer;#S=new fe.EventContainer;documentRegistry;constructor(o){this.documentRegistry=new fe.DocumentRegistry(o.fileSystemWrapper),this.#f=new cpn(o),o.compilerOptions.onModified(()=>{let a=Array.from(this.#t.values());for(let d of a)Uhr(d)}),this.#e=o}*getSourceFilesByDirectoryDepth(){for(let o of this.getDirectoriesByDepth())yield*o.getSourceFiles()}getSourceFilePaths(){return this.#t.keys()}getChildDirectoriesOfDirectory(o){return this.#f.getChildDirectoriesOfDirectory(o)}getChildSourceFilesOfDirectory(o){return this.#f.getChildSourceFilesOfDirectory(o)}onSourceFileAdded(o,a=!0){a?this.#p.subscribe(o):this.#p.unsubscribe(o)}onSourceFileRemoved(o){this.#S.subscribe(o)}createSourceFile(o,a,d){if(a=a instanceof Function?Z1e(this.#e.createWriter(),a):a||"",typeof a=="string")return this.createSourceFileFromText(o,a,d);let p=this.#e.createWriter();return this.#e.structurePrinterFactory.forSourceFile({isAmbient:fe.FileUtils.getExtension(o)===".d.ts"}).printText(p,a),this.createSourceFileFromText(o,p.toString(),d)}createSourceFileFromText(o,a,d){return o=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(o),d.overwrite===!0?this.#m(o,a,d):(this.throwIfFileExists(o,"Did you mean to provide the overwrite option?"),this.#T(o,a,d))}throwIfFileExists(o,a){if(!(!this.containsSourceFileAtPath(o)&&!this.#e.fileSystemWrapper.fileExistsSync(o)))throw a=a==null?"":a+" ",new fe.errors.InvalidOperationError(`${a}A source file already exists at the provided file path: ${o}`)}#m(o,a,d){o=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(o);let p=this.addOrGetSourceFileFromFilePath(o,d);return p!=null?(p.getChildren().forEach(y=>y.forget()),this.replaceCompilerNode(p,this.createCompilerSourceFileFromText(o,a,d.scriptKind)),p):this.#T(o,a,d)}getSourceFileFromCacheFromFilePath(o){return o=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(o),this.#t.get(o)}addOrGetSourceFileFromFilePath(o,a){o=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(o);let d=this.#t.get(o);if(d==null){let p=this.#e.fileSystemWrapper.readFileIfExistsSync(o,this.#e.getEncoding());p!=null&&(this.#e.logger.log(`Loaded file: ${o}`),d=this.#T(o,p,a),d._setIsSaved(!0))}return d!=null&&a.markInProject&&d._markAsInProject(),d}containsSourceFileAtPath(o){return o=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(o),this.#t.has(o)}containsDirectoryAtPath(o){return o=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(o),this.#f.has(o)}getSourceFileForNode(o){let a=o;for(;a.kind!==fe.SyntaxKind.SourceFile;){if(a.parent==null)return;a=a.parent}return this.getSourceFile(a,{markInProject:!1})}hasCompilerNode(o){return this.#d.has(o)}getExistingNodeFromCompilerNode(o){return this.#d.get(o)}getNodeFromCompilerNode(o,a){if(o.kind===fe.SyntaxKind.SourceFile)return this.getSourceFile(o,{markInProject:!1});return this.#d.getOrCreate(o,()=>{let E=d.call(this);return y.call(this,E),E});function d(){if(p(o))return Qce.isCommentStatement(o)?new CGt(this.#e,o,a):Qce.isCommentClassElement(o)?new _Ut(this.#e,o,a):Qce.isCommentTypeElement(o)?new GVt(this.#e,o,a):Qce.isCommentObjectLiteralElement(o)?new iGt(this.#e,o,a):Qce.isCommentEnumMember(o)?new FVt(this.#e,o,a):fe.errors.throwNotImplementedForNeverValueError(o);let E=Dgr[o.kind]||qo;return new E(this.#e,o,a)}function p(E){return E._commentKind!=null}function y(E){if(o.parent!=null){let B=this.getNodeFromCompilerNode(o.parent,a);B._wrappedChildCount++}let I=E._getParentSyntaxListIfWrapped();if(I!=null&&I._wrappedChildCount++,o.kind===fe.SyntaxKind.SyntaxList){let B=0;for(let K of E._getChildrenInCacheIterator())B++;E._wrappedChildCount=B}}}#T(o,a,d){let p=fe.StringUtils.hasBom(a);p&&(a=fe.StringUtils.stripBom(a));let y=this.getSourceFile(this.createCompilerSourceFileFromText(o,a,d.scriptKind),d);return p&&(y._hasBom=!0),y}createCompilerSourceFileFromText(o,a,d){return this.documentRegistry.createOrUpdateSourceFile(o,this.#e.compilerOptions.get(),fe.ts.ScriptSnapshot.fromString(a),d)}getSourceFile(o,a){let d=!1,p=this.#t.get(o.fileName)??this.#d.getOrCreate(o,()=>{let y=new Uwt(this.#e,o);return a.markInProject||this.#e.inProjectCoordinator.setSourceFileNotInProject(y),this.#l(y),d=!0,y});return a.markInProject&&p._markAsInProject(),d&&this.#p.fire(p),p}#l(o){this.#t.set(o.getFilePath(),o),this.#e.fileSystemWrapper.removeFileDelete(o.getFilePath()),this.#f.addSourceFile(o)}getDirectoryFromPath(o,a){o=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(o);let d=this.#f.get(o);return d==null&&this.#e.fileSystemWrapper.directoryExistsSync(o)&&(d=this.#f.createOrAddIfExists(o)),d!=null&&a.markInProject&&d._markAsInProject(),d}createDirectoryOrAddIfExists(o,a){let d=this.#f.createOrAddIfExists(o);return d!=null&&a.markInProject&&d._markAsInProject(),d}getDirectoryFromCache(o){return this.#f.get(o)}getDirectoryFromCacheOnlyIfInCache(o){return this.#f.has(o)?this.#f.get(o):void 0}getDirectoriesByDepth(){return this.#f.getAllByDepth()}getOrphanDirectories(){return this.#f.getOrphans()}getSymbolDisplayPart(o){return this.#h.getOrCreate(o,()=>new MHt(o))}getType(o){return(o.flags&fe.TypeFlags.TypeParameter)===fe.TypeFlags.TypeParameter?this.getTypeParameter(o):this.#g.getOrCreate(o,()=>new V4t(this.#e,o))}getTypeParameter(o){return this.#b.getOrCreate(o,()=>new FHt(this.#e,o))}getSignature(o){return this.#a.getOrCreate(o,()=>new AHt(this.#e,o))}getSymbol(o){return this.#c.getOrCreate(o,()=>new dBn(this.#e,o))}getDefinitionInfo(o){return this.#r.getOrCreate(o,()=>new Lpn(this.#e,o))}getDocumentSpan(o){return this.#i.getOrCreate(o,()=>new tCt(this.#e,o))}getReferencedSymbolEntry(o){return this.#_.getOrCreate(o,()=>new NHt(this.#e,o))}getReferencedSymbol(o){return this.#v.getOrCreate(o,()=>new _Bn(this.#e,o))}getReferencedSymbolDefinitionInfo(o){return this.#y.getOrCreate(o,()=>new gBn(this.#e,o))}getDiagnostic(o){return this.#n.getOrCreate(o,()=>o.start!=null?new G4t(this.#e,o):new ZHt(this.#e,o))}getDiagnosticWithLocation(o){return this.#n.getOrCreate(o,()=>new G4t(this.#e,o))}getDiagnosticMessageChain(o){return this.#o.getOrCreate(o,()=>new z4t(o))}getJSDocTagInfo(o){return this.#s.getOrCreate(o,()=>new W4t(o))}replaceCompilerNode(o,a){let d=o instanceof qo?o.compilerNode:o,p=o instanceof qo?o:this.#d.get(o);if(d.kind===fe.SyntaxKind.SourceFile&&d.fileName!==a.fileName){let y=p;this.#u(d),y._replaceCompilerNodeFromFactory(a),this.#d.set(a,y),this.#l(y),this.#p.fire(y)}else this.#d.replaceKey(d,a),p?._replaceCompilerNodeFromFactory(a)}removeNodeFromCache(o){this.#u(o.compilerNode)}#u(o){if(this.#d.removeByKey(o),o.kind===fe.SyntaxKind.SourceFile){let a=o,d=this.#e.fileSystemWrapper.getStandardizedAbsolutePath(a.fileName);this.#f.removeSourceFile(d);let p=this.#t.get(d);this.#t.delete(d),this.documentRegistry.removeSourceFile(d),p!=null&&this.#S.fire(p)}}addDirectoryToCache(o){this.#f.addDirectory(o)}removeDirectoryFromCache(o){this.#f.remove(o)}forgetNodesCreatedInBlock(o){this.#d.setForgetPoint();let a=!1,d;try{if(d=o((...y)=>{for(let E of y)this.#d.rememberNode(E)}),qo.isNode(d)&&this.#d.rememberNode(d),p(d))return a=!0,d.then(y=>(qo.isNode(y)&&this.#d.rememberNode(y),this.#d.forgetLastPoint(),y))}finally{a||this.#d.forgetLastPoint()}return d;function p(y){return y!=null&&typeof y.then=="function"}}},dpn=class{#e;#t=new Set;constructor(o){o.onSourceFileRemoved(a=>{this.#t.delete(a)}),this.#e=o}setSourceFileNotInProject(o){this.#t.add(o),o._inProject=!1}markSourceFileAsInProject(o){this.isSourceFileInProject(o)||(this.#n(o),this.#t.delete(o))}markSourceFilesAsInProjectForResolution(){let o="/node_modules/",a=this.#e,d=[],p=[];for(let E of[...this.#t.values()])y(E)?(this.#n(E),this.#t.delete(E),d.push(E)):p.push(E);return{changedSourceFiles:d,unchangedSourceFiles:p};function y(E){let I=E.getFilePath(),B=I.toLowerCase().lastIndexOf(o);if(B===-1)return!0;let K=I.substring(0,B+o.length-1),Y=a.getDirectoryFromCacheOnlyIfInCache(K);if(Y!=null&&Y._isInProject())return!0;let ue=E.getDirectory();for(;ue!=null&&ue.getPath()!==K;){if(ue._isInProject())return!0;ue=a.getDirectoryFromCacheOnlyIfInCache(fe.FileUtils.getDirPath(ue.getPath()))}return!1}}#n(o){o._inProject=!0,this.markDirectoryAsInProject(o.getDirectory())}isSourceFileInProject(o){return o._inProject===!0}setDirectoryAndFilesAsNotInProjectForTesting(o){for(let a of o.getDirectories())this.setDirectoryAndFilesAsNotInProjectForTesting(a);for(let a of o.getSourceFiles())delete a._inProject,this.#t.add(a);delete o._inProject}markDirectoryAsInProject(o){if(this.isDirectoryInProject(o))return;let a=this,d=this.#e;o._inProject=!0,p(o);function p(E){let I=Array.from(y(E)),B=I[I.length-1];if(!(B==null||!a.isDirectoryInProject(B)))for(let K of I)K._inProject=!0}function*y(E){if(fe.FileUtils.isRootDirPath(E.getPath()))return;let I=fe.FileUtils.getDirPath(E.getPath()),B=d.getDirectoryFromCacheOnlyIfInCache(I);B!=null&&(yield B,a.isDirectoryInProject(B)||(yield*y(B)))}}isDirectoryInProject(o){return o._inProject===!0}},yBn=(()=>{let c=[],o,a,d,p,y,E,I,B,K,Y,ue,ie,Re,Ie,Ne,bt,Qt,Fn,vr,Kr,jr,Tn,bn,Cr,vi,eo,Tr,ta,zo,Jn,is,pr,tr,wh,ql,Ff,Na,Av,C0,yg,W_,ys,o1,Pd,g_,zd,qh,zm,nn,tp,bs;return class{static{let wd=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],a=[fe.Memoize],d=[fe.Memoize],p=[fe.Memoize],y=[fe.Memoize],E=[fe.Memoize],I=[fe.Memoize],B=[fe.Memoize],K=[fe.Memoize],Y=[fe.Memoize],ue=[fe.Memoize],ie=[fe.Memoize],Re=[fe.Memoize],Ie=[fe.Memoize],Ne=[fe.Memoize],bt=[fe.Memoize],Qt=[fe.Memoize],Fn=[fe.Memoize],vr=[fe.Memoize],Kr=[fe.Memoize],jr=[fe.Memoize],Tn=[fe.Memoize],bn=[fe.Memoize],Cr=[fe.Memoize],vi=[fe.Memoize],eo=[fe.Memoize],Tr=[fe.Memoize],ta=[fe.Memoize],zo=[fe.Memoize],Jn=[fe.Memoize],is=[fe.Memoize],pr=[fe.Memoize],tr=[fe.Memoize],wh=[fe.Memoize],ql=[fe.Memoize],Ff=[fe.Memoize],Na=[fe.Memoize],Av=[fe.Memoize],C0=[fe.Memoize],yg=[fe.Memoize],W_=[fe.Memoize],ys=[fe.Memoize],o1=[fe.Memoize],Pd=[fe.Memoize],g_=[fe.Memoize],zd=[fe.Memoize],qh=[fe.Memoize],zm=[fe.Memoize],nn=[fe.Memoize],tp=[fe.Memoize],bs=[fe.Memoize],s_(this,null,o,{kind:"method",name:"forInitializerExpressionableNode",static:!1,private:!1,access:{has:Ts=>"forInitializerExpressionableNode"in Ts,get:Ts=>Ts.forInitializerExpressionableNode},metadata:wd},null,c),s_(this,null,a,{kind:"method",name:"forModifierableNode",static:!1,private:!1,access:{has:Ts=>"forModifierableNode"in Ts,get:Ts=>Ts.forModifierableNode},metadata:wd},null,c),s_(this,null,d,{kind:"method",name:"forReturnTypedNode",static:!1,private:!1,access:{has:Ts=>"forReturnTypedNode"in Ts,get:Ts=>Ts.forReturnTypedNode},metadata:wd},null,c),s_(this,null,p,{kind:"method",name:"forTypedNode",static:!1,private:!1,access:{has:Ts=>"forTypedNode"in Ts,get:Ts=>Ts.forTypedNode},metadata:wd},null,c),s_(this,null,y,{kind:"method",name:"forClassDeclaration",static:!1,private:!1,access:{has:Ts=>"forClassDeclaration"in Ts,get:Ts=>Ts.forClassDeclaration},metadata:wd},null,c),s_(this,null,E,{kind:"method",name:"forClassMember",static:!1,private:!1,access:{has:Ts=>"forClassMember"in Ts,get:Ts=>Ts.forClassMember},metadata:wd},null,c),s_(this,null,I,{kind:"method",name:"forClassStaticBlockDeclaration",static:!1,private:!1,access:{has:Ts=>"forClassStaticBlockDeclaration"in Ts,get:Ts=>Ts.forClassStaticBlockDeclaration},metadata:wd},null,c),s_(this,null,B,{kind:"method",name:"forConstructorDeclaration",static:!1,private:!1,access:{has:Ts=>"forConstructorDeclaration"in Ts,get:Ts=>Ts.forConstructorDeclaration},metadata:wd},null,c),s_(this,null,K,{kind:"method",name:"forGetAccessorDeclaration",static:!1,private:!1,access:{has:Ts=>"forGetAccessorDeclaration"in Ts,get:Ts=>Ts.forGetAccessorDeclaration},metadata:wd},null,c),s_(this,null,Y,{kind:"method",name:"forMethodDeclaration",static:!1,private:!1,access:{has:Ts=>"forMethodDeclaration"in Ts,get:Ts=>Ts.forMethodDeclaration},metadata:wd},null,c),s_(this,null,ue,{kind:"method",name:"forPropertyDeclaration",static:!1,private:!1,access:{has:Ts=>"forPropertyDeclaration"in Ts,get:Ts=>Ts.forPropertyDeclaration},metadata:wd},null,c),s_(this,null,ie,{kind:"method",name:"forSetAccessorDeclaration",static:!1,private:!1,access:{has:Ts=>"forSetAccessorDeclaration"in Ts,get:Ts=>Ts.forSetAccessorDeclaration},metadata:wd},null,c),s_(this,null,Re,{kind:"method",name:"forDecorator",static:!1,private:!1,access:{has:Ts=>"forDecorator"in Ts,get:Ts=>Ts.forDecorator},metadata:wd},null,c),s_(this,null,Ie,{kind:"method",name:"forJSDoc",static:!1,private:!1,access:{has:Ts=>"forJSDoc"in Ts,get:Ts=>Ts.forJSDoc},metadata:wd},null,c),s_(this,null,Ne,{kind:"method",name:"forJSDocTag",static:!1,private:!1,access:{has:Ts=>"forJSDocTag"in Ts,get:Ts=>Ts.forJSDocTag},metadata:wd},null,c),s_(this,null,bt,{kind:"method",name:"forEnumDeclaration",static:!1,private:!1,access:{has:Ts=>"forEnumDeclaration"in Ts,get:Ts=>Ts.forEnumDeclaration},metadata:wd},null,c),s_(this,null,Qt,{kind:"method",name:"forEnumMember",static:!1,private:!1,access:{has:Ts=>"forEnumMember"in Ts,get:Ts=>Ts.forEnumMember},metadata:wd},null,c),s_(this,null,Fn,{kind:"method",name:"forObjectLiteralExpressionProperty",static:!1,private:!1,access:{has:Ts=>"forObjectLiteralExpressionProperty"in Ts,get:Ts=>Ts.forObjectLiteralExpressionProperty},metadata:wd},null,c),s_(this,null,vr,{kind:"method",name:"forPropertyAssignment",static:!1,private:!1,access:{has:Ts=>"forPropertyAssignment"in Ts,get:Ts=>Ts.forPropertyAssignment},metadata:wd},null,c),s_(this,null,Kr,{kind:"method",name:"forShorthandPropertyAssignment",static:!1,private:!1,access:{has:Ts=>"forShorthandPropertyAssignment"in Ts,get:Ts=>Ts.forShorthandPropertyAssignment},metadata:wd},null,c),s_(this,null,jr,{kind:"method",name:"forSpreadAssignment",static:!1,private:!1,access:{has:Ts=>"forSpreadAssignment"in Ts,get:Ts=>Ts.forSpreadAssignment},metadata:wd},null,c),s_(this,null,Tn,{kind:"method",name:"forFunctionDeclaration",static:!1,private:!1,access:{has:Ts=>"forFunctionDeclaration"in Ts,get:Ts=>Ts.forFunctionDeclaration},metadata:wd},null,c),s_(this,null,bn,{kind:"method",name:"forParameterDeclaration",static:!1,private:!1,access:{has:Ts=>"forParameterDeclaration"in Ts,get:Ts=>Ts.forParameterDeclaration},metadata:wd},null,c),s_(this,null,Cr,{kind:"method",name:"forCallSignatureDeclaration",static:!1,private:!1,access:{has:Ts=>"forCallSignatureDeclaration"in Ts,get:Ts=>Ts.forCallSignatureDeclaration},metadata:wd},null,c),s_(this,null,vi,{kind:"method",name:"forConstructSignatureDeclaration",static:!1,private:!1,access:{has:Ts=>"forConstructSignatureDeclaration"in Ts,get:Ts=>Ts.forConstructSignatureDeclaration},metadata:wd},null,c),s_(this,null,eo,{kind:"method",name:"forIndexSignatureDeclaration",static:!1,private:!1,access:{has:Ts=>"forIndexSignatureDeclaration"in Ts,get:Ts=>Ts.forIndexSignatureDeclaration},metadata:wd},null,c),s_(this,null,Tr,{kind:"method",name:"forInterfaceDeclaration",static:!1,private:!1,access:{has:Ts=>"forInterfaceDeclaration"in Ts,get:Ts=>Ts.forInterfaceDeclaration},metadata:wd},null,c),s_(this,null,ta,{kind:"method",name:"forMethodSignature",static:!1,private:!1,access:{has:Ts=>"forMethodSignature"in Ts,get:Ts=>Ts.forMethodSignature},metadata:wd},null,c),s_(this,null,zo,{kind:"method",name:"forPropertySignature",static:!1,private:!1,access:{has:Ts=>"forPropertySignature"in Ts,get:Ts=>Ts.forPropertySignature},metadata:wd},null,c),s_(this,null,Jn,{kind:"method",name:"forTypeElementMemberedNode",static:!1,private:!1,access:{has:Ts=>"forTypeElementMemberedNode"in Ts,get:Ts=>Ts.forTypeElementMemberedNode},metadata:wd},null,c),s_(this,null,is,{kind:"method",name:"forTypeElementMember",static:!1,private:!1,access:{has:Ts=>"forTypeElementMember"in Ts,get:Ts=>Ts.forTypeElementMember},metadata:wd},null,c),s_(this,null,pr,{kind:"method",name:"forJsxAttributeDecider",static:!1,private:!1,access:{has:Ts=>"forJsxAttributeDecider"in Ts,get:Ts=>Ts.forJsxAttributeDecider},metadata:wd},null,c),s_(this,null,tr,{kind:"method",name:"forJsxAttribute",static:!1,private:!1,access:{has:Ts=>"forJsxAttribute"in Ts,get:Ts=>Ts.forJsxAttribute},metadata:wd},null,c),s_(this,null,wh,{kind:"method",name:"forJsxChildDecider",static:!1,private:!1,access:{has:Ts=>"forJsxChildDecider"in Ts,get:Ts=>Ts.forJsxChildDecider},metadata:wd},null,c),s_(this,null,ql,{kind:"method",name:"forJsxElement",static:!1,private:!1,access:{has:Ts=>"forJsxElement"in Ts,get:Ts=>Ts.forJsxElement},metadata:wd},null,c),s_(this,null,Ff,{kind:"method",name:"forJsxNamespacedName",static:!1,private:!1,access:{has:Ts=>"forJsxNamespacedName"in Ts,get:Ts=>Ts.forJsxNamespacedName},metadata:wd},null,c),s_(this,null,Na,{kind:"method",name:"forJsxSelfClosingElement",static:!1,private:!1,access:{has:Ts=>"forJsxSelfClosingElement"in Ts,get:Ts=>Ts.forJsxSelfClosingElement},metadata:wd},null,c),s_(this,null,Av,{kind:"method",name:"forJsxSpreadAttribute",static:!1,private:!1,access:{has:Ts=>"forJsxSpreadAttribute"in Ts,get:Ts=>Ts.forJsxSpreadAttribute},metadata:wd},null,c),s_(this,null,C0,{kind:"method",name:"forExportAssignment",static:!1,private:!1,access:{has:Ts=>"forExportAssignment"in Ts,get:Ts=>Ts.forExportAssignment},metadata:wd},null,c),s_(this,null,yg,{kind:"method",name:"forExportDeclaration",static:!1,private:!1,access:{has:Ts=>"forExportDeclaration"in Ts,get:Ts=>Ts.forExportDeclaration},metadata:wd},null,c),s_(this,null,W_,{kind:"method",name:"forImportAttribute",static:!1,private:!1,access:{has:Ts=>"forImportAttribute"in Ts,get:Ts=>Ts.forImportAttribute},metadata:wd},null,c),s_(this,null,ys,{kind:"method",name:"forImportDeclaration",static:!1,private:!1,access:{has:Ts=>"forImportDeclaration"in Ts,get:Ts=>Ts.forImportDeclaration},metadata:wd},null,c),s_(this,null,o1,{kind:"method",name:"forModuleDeclaration",static:!1,private:!1,access:{has:Ts=>"forModuleDeclaration"in Ts,get:Ts=>Ts.forModuleDeclaration},metadata:wd},null,c),s_(this,null,Pd,{kind:"method",name:"forNamedImportExportSpecifier",static:!1,private:!1,access:{has:Ts=>"forNamedImportExportSpecifier"in Ts,get:Ts=>Ts.forNamedImportExportSpecifier},metadata:wd},null,c),s_(this,null,g_,{kind:"method",name:"forSourceFile",static:!1,private:!1,access:{has:Ts=>"forSourceFile"in Ts,get:Ts=>Ts.forSourceFile},metadata:wd},null,c),s_(this,null,zd,{kind:"method",name:"forStatementedNode",static:!1,private:!1,access:{has:Ts=>"forStatementedNode"in Ts,get:Ts=>Ts.forStatementedNode},metadata:wd},null,c),s_(this,null,qh,{kind:"method",name:"forStatement",static:!1,private:!1,access:{has:Ts=>"forStatement"in Ts,get:Ts=>Ts.forStatement},metadata:wd},null,c),s_(this,null,zm,{kind:"method",name:"forVariableStatement",static:!1,private:!1,access:{has:Ts=>"forVariableStatement"in Ts,get:Ts=>Ts.forVariableStatement},metadata:wd},null,c),s_(this,null,nn,{kind:"method",name:"forTypeAliasDeclaration",static:!1,private:!1,access:{has:Ts=>"forTypeAliasDeclaration"in Ts,get:Ts=>Ts.forTypeAliasDeclaration},metadata:wd},null,c),s_(this,null,tp,{kind:"method",name:"forTypeParameterDeclaration",static:!1,private:!1,access:{has:Ts=>"forTypeParameterDeclaration"in Ts,get:Ts=>Ts.forTypeParameterDeclaration},metadata:wd},null,c),s_(this,null,bs,{kind:"method",name:"forVariableDeclaration",static:!1,private:!1,access:{has:Ts=>"forVariableDeclaration"in Ts,get:Ts=>Ts.forVariableDeclaration},metadata:wd},null,c),wd&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:wd})}_getFormatCodeSettings=jne(this,c);constructor(wd){this._getFormatCodeSettings=wd}getFormatCodeSettings(){return this._getFormatCodeSettings()}forInitializerExpressionableNode(){return new nfn}forModifierableNode(){return new rfn}forReturnTypedNode(wd){return new ifn(wd)}forTypedNode(wd,Ts){return new ofn(wd,Ts)}forClassDeclaration(wd){return new afn(this,wd)}forClassMember(wd){return new cfn(this,wd)}forClassStaticBlockDeclaration(){return new lfn(this)}forConstructorDeclaration(wd){return new ufn(this,wd)}forGetAccessorDeclaration(wd){return new dfn(this,wd)}forMethodDeclaration(wd){return new ffn(this,wd)}forPropertyDeclaration(){return new pfn(this)}forSetAccessorDeclaration(wd){return new mfn(this,wd)}forDecorator(){return new hfn(this)}forJSDoc(){return new _fn(this)}forJSDocTag(wd){return new gfn(this,wd)}forEnumDeclaration(){return new yfn(this)}forEnumMember(){return new vfn(this)}forObjectLiteralExpressionProperty(){return new bfn(this)}forPropertyAssignment(){return new Sfn(this)}forShorthandPropertyAssignment(){return new Tfn(this)}forSpreadAssignment(){return new Efn(this)}forFunctionDeclaration(wd){return new xfn(this,wd)}forParameterDeclaration(){return new Afn(this)}forCallSignatureDeclaration(){return new wfn(this)}forConstructSignatureDeclaration(){return new Cfn(this)}forIndexSignatureDeclaration(){return new Ifn(this)}forInterfaceDeclaration(){return new kfn(this)}forMethodSignature(){return new Dfn(this)}forPropertySignature(){return new Pfn(this)}forTypeElementMemberedNode(){return new Nfn(this)}forTypeElementMember(){return new Rfn(this)}forJsxAttributeDecider(){return new Mfn(this)}forJsxAttribute(){return new Lfn(this)}forJsxChildDecider(){return new Ofn(this)}forJsxElement(){return new Ffn(this)}forJsxNamespacedName(){return new Bfn(this)}forJsxSelfClosingElement(){return new Wfn(this)}forJsxSpreadAttribute(){return new jfn(this)}forExportAssignment(){return new zfn(this)}forExportDeclaration(){return new Gfn(this)}forImportAttribute(){return new Ufn(this)}forImportDeclaration(){return new Vfn(this)}forModuleDeclaration(wd){return new Hfn(this,wd)}forNamedImportExportSpecifier(){return new $fn(this)}forSourceFile(wd){return new Kfn(this,wd)}forStatementedNode(wd){return new Jfn(this,wd)}forStatement(wd){return new qfn(this,wd)}forVariableStatement(){return new Xfn(this)}forTypeAliasDeclaration(){return new Qfn(this)}forTypeParameterDeclaration(){return new Yfn(this)}forVariableDeclaration(){return new Zfn(this)}}})(),vBn=(()=>{let c=[],o,a;return class{static{let p=typeof Symbol=="function"&&Symbol.metadata?Object.create(null):void 0;o=[fe.Memoize],a=[fe.Memoize],s_(this,null,o,{kind:"method",name:"getSourceFileContainer",static:!1,private:!1,access:{has:y=>"getSourceFileContainer"in y,get:y=>y.getSourceFileContainer},metadata:p},null,c),s_(this,null,a,{kind:"method",name:"getModuleResolutionHost",static:!1,private:!1,access:{has:y=>"getModuleResolutionHost"in y,get:y=>y.getModuleResolutionHost},metadata:p},null,c),p&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:p})}#e=jne(this,c);#t;#n;#r;get project(){if(this.#r==null)throw new fe.errors.InvalidOperationError("This operation is not permitted in this context.");return this.#r}logger=new Mdn;lazyReferenceCoordinator;directoryCoordinator;fileSystemWrapper;manipulationSettings=new Ozt;structurePrinterFactory;compilerFactory;inProjectCoordinator;constructor(p){this.#r=p.project,this.fileSystemWrapper=p.fileSystemWrapper,this.#t=p.compilerOptionsContainer,this.compilerFactory=new upn(this),this.inProjectCoordinator=new dpn(this.compilerFactory),this.structurePrinterFactory=new yBn(()=>this.manipulationSettings.getFormatCodeSettings()),this.lazyReferenceCoordinator=new Ldn(this.compilerFactory),this.directoryCoordinator=new apn(this.compilerFactory,p.fileSystemWrapper),this.#e=p.createLanguageService?new OHt({context:this,configFileParsingDiagnostics:p.configFileParsingDiagnostics,resolutionHost:p.resolutionHost&&p.resolutionHost(this.getModuleResolutionHost(),()=>this.compilerOptions.get()),skipLoadingLibFiles:p.skipLoadingLibFiles,libFolderPath:p.libFolderPath}):void 0,p.typeChecker!=null&&(fe.errors.throwIfTrue(p.createLanguageService,"Cannot specify a type checker and create a language service."),this.#n=new U4t(this),this.#n._reset(()=>p.typeChecker))}get compilerOptions(){return this.#t}get languageService(){if(this.#e==null)throw this.#i("language service");return this.#e}get program(){if(this.#e==null)throw this.#i("program");return this.languageService.getProgram()}get typeChecker(){if(this.#n!=null)return this.#n;if(this.#e==null)throw this.#i("type checker");return this.program.getTypeChecker()}hasLanguageService(){return this.#e!=null}getEncoding(){return this.compilerOptions.getEncoding()}getFormatCodeSettings(){return this.manipulationSettings.getFormatCodeSettings()}getUserPreferences(){return this.manipulationSettings.getUserPreferences()}resetProgram(){this.languageService._reset()}createWriter(){let p=this.manipulationSettings.getIndentationText();return new Dzt.default({newLine:this.manipulationSettings.getNewLineKindAsString(),indentNumberOfSpaces:p===Dt.IndentationText.Tab?void 0:p.length,useTabs:p===Dt.IndentationText.Tab,useSingleQuote:this.manipulationSettings.getQuoteKind()===Dt.QuoteKind.Single})}getPreEmitDiagnostics(p){return fe.ts.getPreEmitDiagnostics(this.program.compilerObject,p?.compilerNode).map(E=>this.compilerFactory.getDiagnostic(E))}getSourceFileContainer(){return{addOrGetSourceFileFromFilePath:(p,y)=>Promise.resolve(this.compilerFactory.addOrGetSourceFileFromFilePath(p,y)?.compilerNode),addOrGetSourceFileFromFilePathSync:(p,y)=>this.compilerFactory.addOrGetSourceFileFromFilePath(p,y)?.compilerNode,containsDirectoryAtPath:p=>this.compilerFactory.containsDirectoryAtPath(p),containsSourceFileAtPath:p=>this.compilerFactory.containsSourceFileAtPath(p),getSourceFileFromCacheFromFilePath:p=>this.compilerFactory.getSourceFileFromCacheFromFilePath(p)?.compilerNode,getSourceFilePaths:()=>this.compilerFactory.getSourceFilePaths(),getSourceFileVersion:p=>this.compilerFactory.documentRegistry.getSourceFileVersion(p),getChildDirectoriesOfDirectory:p=>{let y=[];for(let E of this.compilerFactory.getChildDirectoriesOfDirectory(p))y.push(E.getPath());return y}}}getModuleResolutionHost(){return fe.createModuleResolutionHost({transactionalFileSystem:this.fileSystemWrapper,getEncoding:()=>this.getEncoding(),sourceFileContainer:this.getSourceFileContainer()})}#i(p){return new fe.errors.InvalidOperationError(`A ${p} is required for this operation. This might occur when manipulating or getting type information from a node that was not added to a Project object and created via createWrappedNode. Please submit a bug report if you don't believe a ${p} should be required for this operation.`)}}})(),fpn=class{_context;constructor(o={}){I();let a=B(),d=new fe.TransactionalFileSystem({fileSystem:a,skipLoadingLibFiles:o.skipLoadingLibFiles,libFolderPath:o.libFolderPath}),p=o.tsConfigFilePath==null?void 0:new fe.TsConfigResolver(d,d.getStandardizedAbsolutePath(o.tsConfigFilePath),ue()),y=K(),E=new fe.CompilerOptionsContainer(o.defaultCompilerOptions);E.set(y),this._context=new vBn({project:this,compilerOptionsContainer:E,fileSystemWrapper:d,createLanguageService:!0,resolutionHost:o.resolutionHost,configFileParsingDiagnostics:p?.getErrors()??[],skipLoadingLibFiles:o.skipLoadingLibFiles,libFolderPath:o.libFolderPath}),o.manipulationSettings!=null&&this._context.manipulationSettings.set(o.manipulationSettings),p!=null&&o.skipAddingFilesFromTsConfig!==!0&&(this.#e(p,y),o.skipFileDependencyResolution||this.resolveSourceFileDependencies());function I(){if(o.fileSystem!=null&&o.useInMemoryFileSystem)throw new fe.errors.InvalidOperationError("Cannot provide a file system when specifying to use an in-memory file system.")}function B(){return o.useInMemoryFileSystem?new fe.InMemoryFileSystemHost:o.fileSystem??new fe.RealFileSystemHost}function K(){return{...Y(),...o.compilerOptions??{}}}function Y(){return p?.getCompilerOptions()??{}}function ue(){let ie="utf-8";return o.compilerOptions!=null?o.compilerOptions.charset??ie:ie}}get manipulationSettings(){return this._context.manipulationSettings}get compilerOptions(){return this._context.compilerOptions}resolveSourceFileDependencies(){let o=new Set,a=E=>o.add(E),{compilerFactory:d,inProjectCoordinator:p}=this._context;d.onSourceFileAdded(a);try{this.getProgram().compilerObject}finally{d.onSourceFileAdded(a,!1)}let y=p.markSourceFilesAsInProjectForResolution();for(let E of y.changedSourceFiles)o.add(E);for(let E of y.unchangedSourceFiles)o.delete(E);return Array.from(o.values())}addDirectoryAtPathIfExists(o,a={}){return this._context.directoryCoordinator.addDirectoryAtPathIfExists(this._context.fileSystemWrapper.getStandardizedAbsolutePath(o),{...a,markInProject:!0})}addDirectoryAtPath(o,a={}){return this._context.directoryCoordinator.addDirectoryAtPath(this._context.fileSystemWrapper.getStandardizedAbsolutePath(o),{...a,markInProject:!0})}createDirectory(o){return this._context.directoryCoordinator.createDirectoryOrAddIfExists(this._context.fileSystemWrapper.getStandardizedAbsolutePath(o),{markInProject:!0})}getDirectoryOrThrow(o,a){return fe.errors.throwIfNullOrUndefined(this.getDirectory(o),a??(()=>`Could not find a directory at the specified path: ${this._context.fileSystemWrapper.getStandardizedAbsolutePath(o)}`))}getDirectory(o){let{compilerFactory:a}=this._context;return a.getDirectoryFromCache(this._context.fileSystemWrapper.getStandardizedAbsolutePath(o))}getDirectories(){return Array.from(this.#n())}getRootDirectories(){let{inProjectCoordinator:o}=this._context,a=[];for(let p of this._context.compilerFactory.getOrphanDirectories())for(let y of d(p))a.push(y);return a;function*d(p){if(o.isDirectoryInProject(p)){yield p;return}for(let y of p._getDirectoriesIterator())yield*d(y)}}addSourceFilesAtPaths(o){return this._context.directoryCoordinator.addSourceFilesAtPaths(o,{markInProject:!0})}addSourceFileAtPathIfExists(o){return this._context.directoryCoordinator.addSourceFileAtPathIfExists(this._context.fileSystemWrapper.getStandardizedAbsolutePath(o),{markInProject:!0})}addSourceFileAtPath(o){return this._context.directoryCoordinator.addSourceFileAtPath(this._context.fileSystemWrapper.getStandardizedAbsolutePath(o),{markInProject:!0})}addSourceFilesFromTsConfig(o){let a=new fe.TsConfigResolver(this._context.fileSystemWrapper,this._context.fileSystemWrapper.getStandardizedAbsolutePath(o),this._context.getEncoding());return this.#e(a,a.getCompilerOptions())}#e(o,a){let d=o.getPaths(a),p=d.filePaths.map(y=>this.addSourceFileAtPath(y));for(let y of d.directoryPaths)this.addDirectoryAtPathIfExists(y);return p}createSourceFile(o,a,d){return this._context.compilerFactory.createSourceFile(this._context.fileSystemWrapper.getStandardizedAbsolutePath(o),a??"",{...d??{},markInProject:!0})}removeSourceFile(o){let a=o.wasForgotten();return o.forget(),!a}getSourceFileOrThrow(o){let a=this.getSourceFile(o);if(a!=null)return a;if(typeof o=="string"){let d=fe.FileUtils.standardizeSlashes(o);if(fe.FileUtils.pathIsAbsolute(d)||d.indexOf("/")>=0){let p=this._context.fileSystemWrapper.getStandardizedAbsolutePath(d);throw new fe.errors.InvalidOperationError(`Could not find source file in project at the provided path: ${p}`)}else throw new fe.errors.InvalidOperationError(`Could not find source file in project with the provided file name: ${o}`)}else throw new fe.errors.InvalidOperationError("Could not find source file in project based on the provided condition.")}getSourceFile(o){let a=d(this._context.fileSystemWrapper);if(p(a))return this._context.compilerFactory.getSourceFileFromCacheFromFilePath(a);return fe.IterableUtils.find(this.#t(),a);function d(y){if(o instanceof Function)return o;let E=fe.FileUtils.standardizeSlashes(o);return fe.FileUtils.pathIsAbsolute(E)||E.indexOf("/")>=0?y.getStandardizedAbsolutePath(E):I=>fe.FileUtils.pathEndsWith(I.getFilePath(),E)}function p(y){return typeof y=="string"}}getSourceFiles(o){let{compilerFactory:a,fileSystemWrapper:d}=this._context,p=this.#t();if(typeof o=="string"||o instanceof Array)return Array.from(y());return Array.from(p);function*y(){let E=Array.from(B()),I=fe.matchGlobs(E,o,d.getCurrentDirectory());for(let K of I)yield a.getSourceFileFromCacheFromFilePath(d.getStandardizedAbsolutePath(K));function*B(){for(let K of p)yield K.getFilePath()}}}*#t(){let{compilerFactory:o,inProjectCoordinator:a}=this._context;for(let d of o.getSourceFilesByDirectoryDepth())a.isSourceFileInProject(d)&&(yield d)}*#n(){let{compilerFactory:o,inProjectCoordinator:a}=this._context;for(let d of o.getDirectoriesByDepth())a.isDirectoryInProject(d)&&(yield d)}getAmbientModule(o){return o=v7n(o),this.getAmbientModules().find(a=>a.getName()===o)}getAmbientModuleOrThrow(o,a){return fe.errors.throwIfNullOrUndefined(this.getAmbientModule(o),a??(()=>`Could not find ambient module with name: ${v7n(o)}`))}getAmbientModules(){return this.getTypeChecker().getAmbientModules()}async save(){await this._context.fileSystemWrapper.flush(),await Promise.all(this.#r().map(o=>o.save()))}saveSync(){this._context.fileSystemWrapper.flushSync();for(let o of this.#r())o.saveSync()}enableLogging(o=!0){this._context.logger.setEnabled(o)}#r(){return Array.from(o(this._context.compilerFactory.getSourceFilesByDirectoryDepth()));function*o(a){for(let d of a)d.isSaved()||(yield d)}}getPreEmitDiagnostics(){return this._context.getPreEmitDiagnostics()}getLanguageService(){return this._context.languageService}getProgram(){return this._context.program}getTypeChecker(){return this._context.typeChecker}getFileSystem(){return this._context.fileSystemWrapper.getFileSystem()}emit(o={}){return this._context.program.emit(o)}emitSync(o={}){return this._context.program.emitSync(o)}emitToMemory(o={}){return this._context.program.emitToMemory(o)}getCompilerOptions(){return this._context.compilerOptions.get()}getConfigFileParsingDiagnostics(){return this.getProgram().getConfigFileParsingDiagnostics()}createWriter(){return this._context.createWriter()}forgetNodesCreatedInBlock(o){return this._context.compilerFactory.forgetNodesCreatedInBlock(o)}formatDiagnosticsWithColorAndContext(o,a={}){return fe.ts.formatDiagnosticsWithColorAndContext(o.map(d=>d.compilerObject),{getCurrentDirectory:()=>this._context.fileSystemWrapper.getCurrentDirectory(),getCanonicalFileName:d=>d,getNewLine:()=>a.newLineChar??fe.runtime.getEndOfLine()})}getModuleResolutionHost(){return this._context.getModuleResolutionHost()}};function v7n(c){return o(c[0])&&o(c[c.length-1])&&(c=c.substring(1,c.length-1)),`"${c}"`;function o(a){return a==='"'||a==="'"}}function Pgr(c,o={}){let{compilerOptions:a={},sourceFile:d,typeChecker:p}=o,y=new fe.CompilerOptionsContainer;y.set(a);let E=new vBn({project:void 0,fileSystemWrapper:new fe.TransactionalFileSystem({fileSystem:new fe.RealFileSystemHost,skipLoadingLibFiles:!0,libFolderPath:void 0}),compilerOptionsContainer:y,createLanguageService:!1,typeChecker:p,configFileParsingDiagnostics:[],skipLoadingLibFiles:!0,libFolderPath:void 0}),I=E.compilerFactory.getSourceFile(B(),{markInProject:!0});return E.compilerFactory.getNodeFromCompilerNode(c,I);function B(){return d??K(c)}function K(Y){if(Y.kind===fe.SyntaxKind.SourceFile)return Y;if(Y.parent==null)throw new fe.errors.InvalidOperationError("Please ensure the node was created from a source file with 'setParentNodes' set to 'true'.");let ue=Y;for(;ue.parent!=null;)ue=ue.parent;if(ue.kind!==fe.SyntaxKind.SourceFile)throw new fe.errors.NotImplementedError("For some reason the top parent was not a source file.");return ue}}var Ngr=new yBn(()=>{throw new fe.errors.NotImplementedError("Not implemented scenario for getting code format settings when using a writer function. Please open an issue.")}),ppn=class{constructor(){}static object(o){return a=>{let d=Object.keys(o);a.write("{"),d.length>0&&a.indent(()=>{p()}),a.write("}");function p(){for(let y=0;y<d.length;y++){y>0&&a.write(",").newLine();let E=d[y],I=o[E];a.write(E),I!=null&&(a.write(": "),D4t(a,I))}a.newLine()}}}static objectType(o){return a=>{a.write("{"),Rgr(o)&&a.indent(()=>{Ngr.forTypeElementMemberedNode().printText(a,o)}),a.write("}")}}static unionType(o,a,...d){return b7n("|",[o,a,...d])}static intersectionType(o,a,...d){return b7n("&",[o,a,...d])}static assertion(o,a){return d=>{D4t(d,o),d.spaceIfLastNot().write("as "),D4t(d,a)}}static returnStatement(o){return a=>{a.write("return "),a.hangingIndentUnlessBlock(()=>{D4t(a,o),a.write(";")})}}};function b7n(c,o){return a=>{Mgr(a,` ${c} `,o)}}function Rgr(c){for(let o of Object.keys(c))if(c[o]!=null&&!(c[o]instanceof Array&&c[o].length===0))return!0;return!1}function Mgr(c,o,a){for(let d=0;d<a.length;d++)c.conditionalWrite(d>0,o),D4t(c,a[d])}function D4t(c,o){o instanceof Function?o(c):c.write(o.toString())}var{InvalidOperationError:Lgr,FileNotFoundError:Ogr,ArgumentError:Fgr,ArgumentNullOrWhitespaceError:Bgr,ArgumentOutOfRangeError:Wgr,ArgumentTypeError:jgr,BaseError:zgr,DirectoryNotFoundError:Ggr,NotImplementedError:Ugr,NotSupportedError:Vgr,PathNotFoundError:Hgr}=fe.errors;Object.defineProperty(Dt,"CompilerOptionsContainer",{enumerable:!0,get:function(){return fe.CompilerOptionsContainer}});Object.defineProperty(Dt,"DiagnosticCategory",{enumerable:!0,get:function(){return fe.DiagnosticCategory}});Object.defineProperty(Dt,"EmitHint",{enumerable:!0,get:function(){return fe.EmitHint}});Object.defineProperty(Dt,"InMemoryFileSystemHost",{enumerable:!0,get:function(){return fe.InMemoryFileSystemHost}});Object.defineProperty(Dt,"LanguageVariant",{enumerable:!0,get:function(){return fe.LanguageVariant}});Object.defineProperty(Dt,"ModuleKind",{enumerable:!0,get:function(){return fe.ModuleKind}});Object.defineProperty(Dt,"ModuleResolutionKind",{enumerable:!0,get:function(){return fe.ModuleResolutionKind}});Object.defineProperty(Dt,"NewLineKind",{enumerable:!0,get:function(){return fe.NewLineKind}});Object.defineProperty(Dt,"NodeFlags",{enumerable:!0,get:function(){return fe.NodeFlags}});Object.defineProperty(Dt,"ObjectFlags",{enumerable:!0,get:function(){return fe.ObjectFlags}});Object.defineProperty(Dt,"ResolutionHosts",{enumerable:!0,get:function(){return fe.ResolutionHosts}});Object.defineProperty(Dt,"ScriptKind",{enumerable:!0,get:function(){return fe.ScriptKind}});Object.defineProperty(Dt,"ScriptTarget",{enumerable:!0,get:function(){return fe.ScriptTarget}});Object.defineProperty(Dt,"SettingsContainer",{enumerable:!0,get:function(){return fe.SettingsContainer}});Object.defineProperty(Dt,"SymbolFlags",{enumerable:!0,get:function(){return fe.SymbolFlags}});Object.defineProperty(Dt,"SyntaxKind",{enumerable:!0,get:function(){return fe.SyntaxKind}});Object.defineProperty(Dt,"TypeFlags",{enumerable:!0,get:function(){return fe.TypeFlags}});Object.defineProperty(Dt,"TypeFormatFlags",{enumerable:!0,get:function(){return fe.TypeFormatFlags}});Object.defineProperty(Dt,"ts",{enumerable:!0,get:function(){return fe.ts}});Object.defineProperty(Dt,"CodeBlockWriter",{enumerable:!0,get:function(){return Dzt.default}});Dt.AbstractableNode=jnt;Dt.AmbientableNode=w3e;Dt.ArgumentError=Fgr;Dt.ArgumentNullOrWhitespaceError=Bgr;Dt.ArgumentOutOfRangeError=Wgr;Dt.ArgumentTypeError=jgr;Dt.ArgumentedNode=vpn;Dt.ArrayBindingPattern=Uzt;Dt.ArrayDestructuringAssignment=epn;Dt.ArrayDestructuringAssignmentBase=r5n;Dt.ArrayLiteralExpression=Kzt;Dt.ArrayTypeNode=EUt;Dt.ArrowFunction=lUt;Dt.ArrowFunctionBase=f9n;Dt.AsExpression=Jzt;Dt.AsExpressionBase=i5n;Dt.AssignmentExpression=L4t;Dt.AssignmentExpressionBase=n5n;Dt.AsyncableNode=p_t;Dt.AwaitExpression=qzt;Dt.AwaitExpressionBase=o5n;Dt.AwaitableNode=z7n;Dt.BaseError=zgr;Dt.BaseExpressionedNode=Zwt;Dt.BigIntLiteral=lHt;Dt.BigIntLiteralBase=X9n;Dt.BinaryExpression=M4t;Dt.BinaryExpressionBase=t5n;Dt.BindingElement=Vzt;Dt.BindingElementBase=e5n;Dt.BindingNamedNode=HHt;Dt.Block=TGt;Dt.BlockBase=L5n;Dt.BodiedNode=zHt;Dt.BodyableNode=m_t;Dt.BreakStatement=EGt;Dt.CallExpression=Xzt;Dt.CallExpressionBase=s5n;Dt.CallSignatureDeclaration=zVt;Dt.CallSignatureDeclarationBase=vzt;Dt.CaseBlock=xGt;Dt.CaseBlockBase=O5n;Dt.CaseClause=AGt;Dt.CaseClauseBase=F5n;Dt.CatchClause=wGt;Dt.CatchClauseBase=B5n;Dt.ChildOrderableNode=Wne;Dt.ClassDeclaration=pUt;Dt.ClassDeclarationBase=szt;Dt.ClassElement=Y1e;Dt.ClassExpression=mUt;Dt.ClassExpressionBase=y9n;Dt.ClassLikeDeclarationBase=Dpn;Dt.ClassLikeDeclarationBaseSpecific=_9n;Dt.ClassStaticBlockDeclaration=hUt;Dt.ClassStaticBlockDeclarationBase=azt;Dt.CodeAction=wHt;Dt.CodeFixAction=CHt;Dt.CombinedCodeActions=fBn;Dt.CommaListExpression=Qzt;Dt.CommaListExpressionBase=a5n;Dt.CommentClassElement=_Ut;Dt.CommentEnumMember=FVt;Dt.CommentObjectLiteralElement=iGt;Dt.CommentRange=Bzt;Dt.CommentStatement=CGt;Dt.CommentTypeElement=GVt;Dt.CommonIdentifierBase=Rpn;Dt.CompilerCommentClassElement=Nzt;Dt.CompilerCommentEnumMember=Lzt;Dt.CompilerCommentNode=Rnt;Dt.CompilerCommentObjectLiteralElement=Mzt;Dt.CompilerCommentStatement=Pzt;Dt.CompilerCommentTypeElement=Rzt;Dt.ComputedPropertyName=JVt;Dt.ComputedPropertyNameBase=G9n;Dt.ConditionalExpression=Yzt;Dt.ConditionalExpressionBase=c5n;Dt.ConditionalTypeNode=xUt;Dt.ConstructSignatureDeclaration=UVt;Dt.ConstructSignatureDeclarationBase=bzt;Dt.ConstructorDeclaration=gUt;Dt.ConstructorDeclarationBase=czt;Dt.ConstructorDeclarationOverloadBase=v9n;Dt.ConstructorTypeNode=AUt;Dt.ConstructorTypeNodeBase=E9n;Dt.ContinueStatement=IGt;Dt.DebuggerStatement=kGt;Dt.DebuggerStatementBase=W5n;Dt.DecoratableNode=h_t;Dt.Decorator=SUt;Dt.DecoratorBase=fzt;Dt.DefaultClause=DGt;Dt.DefaultClauseBase=j5n;Dt.DefinitionInfo=Lpn;Dt.DeleteExpression=Zzt;Dt.DeleteExpressionBase=l5n;Dt.Diagnostic=ZHt;Dt.DiagnosticMessageChain=z4t;Dt.DiagnosticWithLocation=G4t;Dt.Directory=BHt;Dt.DirectoryEmitResult=H4t;Dt.DirectoryNotFoundError=Ggr;Dt.DoStatement=PGt;Dt.DoStatementBase=z5n;Dt.DocumentSpan=tCt;Dt.DotDotDotTokenableNode=$4t;Dt.ElementAccessExpression=O4t;Dt.ElementAccessExpressionBase=u5n;Dt.EmitOutput=pBn;Dt.EmitResult=kHt;Dt.EmptyStatement=NGt;Dt.EmptyStatementBase=G5n;Dt.EnumDeclaration=BVt;Dt.EnumDeclarationBase=gzt;Dt.EnumMember=WVt;Dt.EnumMemberBase=yzt;Dt.ExclamationTokenableNode=Spn;Dt.ExportAssignment=VGt;Dt.ExportAssignmentBase=ipn;Dt.ExportDeclaration=HGt;Dt.ExportDeclarationBase=Xjt;Dt.ExportGetableNode=Tpn;Dt.ExportSpecifier=$Gt;Dt.ExportSpecifierBase=opn;Dt.ExportableNode=C3e;Dt.Expression=MM;Dt.ExpressionStatement=RGt;Dt.ExpressionStatementBase=U5n;Dt.ExpressionWithTypeArguments=wUt;Dt.ExpressionWithTypeArgumentsBase=x9n;Dt.ExpressionableNode=X4t;Dt.ExpressionedNode=o7;Dt.ExtendsClauseableNode=J7n;Dt.ExternalModuleReference=KGt;Dt.ExternalModuleReferenceBase=e9n;Dt.FalseLiteral=dHt;Dt.FalseLiteralBase=Y9n;Dt.FileNotFoundError=Ogr;Dt.FileReference=Gwt;Dt.FileTextChanges=Q4t;Dt.ForInStatement=MGt;Dt.ForInStatementBase=V5n;Dt.ForOfStatement=LGt;Dt.ForOfStatementBase=H5n;Dt.ForStatement=OGt;Dt.ForStatementBase=$5n;Dt.FunctionDeclaration=uUt;Dt.FunctionDeclarationBase=rzt;Dt.FunctionDeclarationOverloadBase=p9n;Dt.FunctionExpression=dUt;Dt.FunctionExpressionBase=m9n;Dt.FunctionLikeDeclaration=b_t;Dt.FunctionOrConstructorTypeNodeBase=B4t;Dt.FunctionOrConstructorTypeNodeBaseBase=T9n;Dt.FunctionTypeNode=CUt;Dt.FunctionTypeNodeBase=A9n;Dt.GeneratorableNode=g_t;Dt.GetAccessorDeclaration=yUt;Dt.GetAccessorDeclarationBase=lzt;Dt.HeritageClause=jVt;Dt.HeritageClauseableNode=xpn;Dt.Identifier=j4t;Dt.IdentifierBase=U9n;Dt.IfStatement=FGt;Dt.IfStatementBase=K5n;Dt.ImplementationLocation=mBn;Dt.ImplementsClauseableNode=q7n;Dt.ImportAttribute=JGt;Dt.ImportAttributeBase=Qjt;Dt.ImportAttributeNamedNode=X7n;Dt.ImportAttributes=qGt;Dt.ImportAttributesBase=t9n;Dt.ImportClause=XGt;Dt.ImportClauseBase=n9n;Dt.ImportDeclaration=QGt;Dt.ImportDeclarationBase=Yjt;Dt.ImportEqualsDeclaration=YGt;Dt.ImportEqualsDeclarationBase=i9n;Dt.ImportExpression=eGt;Dt.ImportExpressionBase=d5n;Dt.ImportExpressionedNode=O_r;Dt.ImportSpecifier=ZGt;Dt.ImportSpecifierBase=Zjt;Dt.ImportTypeNode=IUt;Dt.IndexSignatureDeclaration=VVt;Dt.IndexSignatureDeclarationBase=Szt;Dt.IndexedAccessTypeNode=kUt;Dt.InferTypeNode=DUt;Dt.InitializerExpressionGetableNode=VHt;Dt.InitializerExpressionableNode=y_t;Dt.InterfaceDeclaration=HVt;Dt.InterfaceDeclarationBase=Tzt;Dt.IntersectionTypeNode=PUt;Dt.InvalidOperationError=Lgr;Dt.IterationStatement=Fnt;Dt.JSDoc=TUt;Dt.JSDocAllType=qUt;Dt.JSDocAugmentsTag=XUt;Dt.JSDocAuthorTag=QUt;Dt.JSDocBase=pzt;Dt.JSDocCallbackTag=YUt;Dt.JSDocClassTag=ZUt;Dt.JSDocDeprecatedTag=eVt;Dt.JSDocEnumTag=tVt;Dt.JSDocFunctionType=nVt;Dt.JSDocFunctionTypeBase=N9n;Dt.JSDocImplementsTag=rVt;Dt.JSDocImportTag=iVt;Dt.JSDocLink=oVt;Dt.JSDocLinkCode=sVt;Dt.JSDocLinkPlain=aVt;Dt.JSDocMemberName=cVt;Dt.JSDocNameReference=uVt;Dt.JSDocNamepathType=lVt;Dt.JSDocNonNullableType=dVt;Dt.JSDocNullableType=fVt;Dt.JSDocOptionalType=pVt;Dt.JSDocOverloadTag=mVt;Dt.JSDocOverloadTagBase=R9n;Dt.JSDocOverrideTag=hVt;Dt.JSDocParameterTag=_Vt;Dt.JSDocParameterTagBase=M9n;Dt.JSDocPrivateTag=gVt;Dt.JSDocPropertyLikeTag=Ppn;Dt.JSDocPropertyTag=yVt;Dt.JSDocPropertyTagBase=L9n;Dt.JSDocProtectedTag=vVt;Dt.JSDocPublicTag=bVt;Dt.JSDocReadonlyTag=SVt;Dt.JSDocReturnTag=TVt;Dt.JSDocReturnTagBase=O9n;Dt.JSDocSatisfiesTag=EVt;Dt.JSDocSatisfiesTagBase=F9n;Dt.JSDocSeeTag=xVt;Dt.JSDocSeeTagBase=B9n;Dt.JSDocSignature=AVt;Dt.JSDocTag=lN;Dt.JSDocTagBase=_zt;Dt.JSDocTagInfo=W4t;Dt.JSDocTemplateTag=wVt;Dt.JSDocTemplateTagBase=W9n;Dt.JSDocText=CVt;Dt.JSDocThisTag=IVt;Dt.JSDocThisTagBase=j9n;Dt.JSDocThrowsTag=kVt;Dt.JSDocThrowsTagBase=z9n;Dt.JSDocType=Ame;Dt.JSDocTypeExpression=PVt;Dt.JSDocTypeExpressionableTag=S_t;Dt.JSDocTypeLiteral=NVt;Dt.JSDocTypeParameteredTag=b9n;Dt.JSDocTypeTag=RVt;Dt.JSDocTypedefTag=DVt;Dt.JSDocUnknownTag=MVt;Dt.JSDocUnknownType=LVt;Dt.JSDocVariadicType=OVt;Dt.JSDocableNode=LM;Dt.JsxAttribute=QVt;Dt.JsxAttributeBase=Azt;Dt.JsxAttributedNode=Npn;Dt.JsxClosingElement=YVt;Dt.JsxClosingElementBase=H9n;Dt.JsxClosingFragment=ZVt;Dt.JsxElement=eHt;Dt.JsxElementBase=wzt;Dt.JsxExpression=tHt;Dt.JsxExpressionBase=$9n;Dt.JsxFragment=nHt;Dt.JsxNamespacedName=rHt;Dt.JsxNamespacedNameBase=K9n;Dt.JsxOpeningElement=iHt;Dt.JsxOpeningElementBase=J9n;Dt.JsxOpeningFragment=oHt;Dt.JsxSelfClosingElement=sHt;Dt.JsxSelfClosingElementBase=Czt;Dt.JsxSpreadAttribute=aHt;Dt.JsxSpreadAttributeBase=Izt;Dt.JsxTagNamedNode=YHt;Dt.JsxText=cHt;Dt.JsxTextBase=q9n;Dt.LabeledStatement=BGt;Dt.LabeledStatementBase=J5n;Dt.LanguageService=OHt;Dt.LeftHandSideExpression=Hwt;Dt.LeftHandSideExpressionedNode=v_t;Dt.LiteralExpression=Ont;Dt.LiteralExpressionBase=f5n;Dt.LiteralLikeNode=Xwt;Dt.LiteralTypeNode=NUt;Dt.ManipulationError=Fzt;Dt.ManipulationSettingsContainer=Ozt;Dt.MappedTypeNode=RUt;Dt.MemberExpression=u_t;Dt.MemoryEmitResult=DHt;Dt.MetaProperty=tGt;Dt.MetaPropertyBase=p5n;Dt.MethodDeclaration=$wt;Dt.MethodDeclarationBase=ozt;Dt.MethodDeclarationOverloadBase=h9n;Dt.MethodSignature=$Vt;Dt.MethodSignatureBase=Ezt;Dt.ModifierableNode=DW;Dt.ModuleBlock=eUt;Dt.ModuleBlockBase=o9n;Dt.ModuleChildableNode=znt;Dt.ModuleDeclaration=tUt;Dt.ModuleDeclarationBase=ezt;Dt.ModuleNamedNode=Q7n;Dt.ModuledNode=Apn;Dt.NameableNode=$Ht;Dt.NamedExports=nUt;Dt.NamedExportsBase=s9n;Dt.NamedImports=rUt;Dt.NamedImportsBase=a9n;Dt.NamedNode=D3e;Dt.NamedNodeBase=Qwt;Dt.NamedTupleMember=MUt;Dt.NamedTupleMemberBase=w9n;Dt.NamespaceExport=iUt;Dt.NamespaceExportBase=c9n;Dt.NamespaceImport=oUt;Dt.NamespaceImportBase=l9n;Dt.NewExpression=nGt;Dt.NewExpressionBase=m5n;Dt.NoSubstitutionTemplateLiteral=_Ht;Dt.NoSubstitutionTemplateLiteralBase=iBn;Dt.Node=qo;Dt.NodeWithTypeArguments=f_t;Dt.NodeWithTypeArgumentsBase=S9n;Dt.NonNullExpression=rGt;Dt.NonNullExpressionBase=h5n;Dt.NotEmittedStatement=WGt;Dt.NotEmittedStatementBase=q5n;Dt.NotImplementedError=Ugr;Dt.NotSupportedError=Vgr;Dt.NullLiteral=fHt;Dt.NullLiteralBase=eBn;Dt.NumericLiteral=pHt;Dt.NumericLiteralBase=tBn;Dt.ObjectBindingPattern=Hzt;Dt.ObjectDestructuringAssignment=tpn;Dt.ObjectDestructuringAssignmentBase=_5n;Dt.ObjectLiteralElement=d_t;Dt.ObjectLiteralExpression=oGt;Dt.ObjectLiteralExpressionBase=g5n;Dt.OmittedExpression=lGt;Dt.OmittedExpressionBase=y5n;Dt.OptionalTypeNode=LUt;Dt.OutputFile=IHt;Dt.OverloadableNode=XHt;Dt.OverrideableNode=J4t;Dt.ParameterDeclaration=fUt;Dt.ParameterDeclarationBase=izt;Dt.ParameteredNode=Y7n;Dt.ParenthesizedExpression=uGt;Dt.ParenthesizedExpressionBase=v5n;Dt.ParenthesizedTypeNode=OUt;Dt.PartiallyEmittedExpression=dGt;Dt.PartiallyEmittedExpressionBase=b5n;Dt.PathNotFoundError=Hgr;Dt.PostfixUnaryExpression=fGt;Dt.PostfixUnaryExpressionBase=S5n;Dt.PrefixUnaryExpression=pGt;Dt.PrefixUnaryExpressionBase=T5n;Dt.PrimaryExpression=m9;Dt.PrivateIdentifier=qVt;Dt.PrivateIdentifierBase=V9n;Dt.Program=LHt;Dt.Project=fpn;Dt.PropertyAccessExpression=F4t;Dt.PropertyAccessExpressionBase=E5n;Dt.PropertyAssignment=sGt;Dt.PropertyAssignmentBase=Kjt;Dt.PropertyDeclaration=vUt;Dt.PropertyDeclarationBase=uzt;Dt.PropertyNamedNode=uVe;Dt.PropertySignature=KVt;Dt.PropertySignatureBase=xzt;Dt.QualifiedName=XVt;Dt.QuestionDotTokenableNode=KHt;Dt.QuestionTokenableNode=P3e;Dt.ReadonlyableNode=q4t;Dt.RefactorEditInfo=hBn;Dt.ReferenceEntry=PHt;Dt.ReferenceFindableNode=k3e;Dt.ReferencedSymbol=_Bn;Dt.ReferencedSymbolDefinitionInfo=gBn;Dt.ReferencedSymbolEntry=NHt;Dt.RegularExpressionLiteral=mHt;Dt.RegularExpressionLiteralBase=nBn;Dt.RenameLocation=RHt;Dt.RenameableNode=y2e;Dt.RestTypeNode=FUt;Dt.ReturnStatement=jGt;Dt.ReturnStatementBase=X5n;Dt.ReturnTypedNode=wpn;Dt.SatisfiesExpression=mGt;Dt.SatisfiesExpressionBase=x5n;Dt.ScopeableNode=Z7n;Dt.ScopedNode=Wnt;Dt.SetAccessorDeclaration=bUt;Dt.SetAccessorDeclarationBase=dzt;Dt.ShorthandPropertyAssignment=aGt;Dt.ShorthandPropertyAssignmentBase=Jjt;Dt.Signature=AHt;Dt.SignaturedDeclaration=v2e;Dt.SourceFile=Uwt;Dt.SourceFileBase=tzt;Dt.SpreadAssignment=cGt;Dt.SpreadAssignmentBase=qjt;Dt.SpreadElement=hGt;Dt.SpreadElementBase=A5n;Dt.Statement=HC;Dt.StatementBase=M5n;Dt.StatementedNode=R3e;Dt.StaticableNode=Ywt;Dt.StringLiteral=hHt;Dt.StringLiteralBase=rBn;Dt.Structure=k4t;Dt.SuperElementAccessExpression=npn;Dt.SuperElementAccessExpressionBase=w5n;Dt.SuperExpression=_Gt;Dt.SuperExpressionBase=C5n;Dt.SuperExpressionedNode=kpn;Dt.SuperPropertyAccessExpression=rpn;Dt.SuperPropertyAccessExpressionBase=I5n;Dt.SwitchStatement=zGt;Dt.SwitchStatementBase=Q5n;Dt.Symbol=dBn;Dt.SymbolDisplayPart=MHt;Dt.SyntaxList=Wzt;Dt.TaggedTemplateExpression=gHt;Dt.TemplateExpression=yHt;Dt.TemplateExpressionBase=oBn;Dt.TemplateHead=vHt;Dt.TemplateHeadBase=sBn;Dt.TemplateLiteralTypeNode=BUt;Dt.TemplateMiddle=bHt;Dt.TemplateMiddleBase=aBn;Dt.TemplateSpan=SHt;Dt.TemplateSpanBase=cBn;Dt.TemplateTail=THt;Dt.TemplateTailBase=lBn;Dt.TextChange=Jwt;Dt.TextInsertableNode=h9;Dt.TextRange=N4t;Dt.TextSpan=Kwt;Dt.ThisExpression=gGt;Dt.ThisExpressionBase=k5n;Dt.ThisTypeNode=WUt;Dt.ThrowStatement=GGt;Dt.ThrowStatementBase=Y5n;Dt.TrueLiteral=uHt;Dt.TrueLiteralBase=Q9n;Dt.TryStatement=UGt;Dt.TryStatementBase=Z5n;Dt.TupleTypeNode=jUt;Dt.Type=V4t;Dt.TypeAliasDeclaration=zUt;Dt.TypeAliasDeclarationBase=mzt;Dt.TypeArgumentedNode=JHt;Dt.TypeAssertion=yGt;Dt.TypeAssertionBase=D5n;Dt.TypeChecker=U4t;Dt.TypeElement=cVe;Dt.TypeElementMemberedNode=Ipn;Dt.TypeLiteralNode=GUt;Dt.TypeLiteralNodeBase=C9n;Dt.TypeNode=eO;Dt.TypeOfExpression=vGt;Dt.TypeOfExpressionBase=P5n;Dt.TypeOperatorTypeNode=UUt;Dt.TypeParameter=FHt;Dt.TypeParameterDeclaration=VUt;Dt.TypeParameterDeclarationBase=hzt;Dt.TypeParameteredNode=wme;Dt.TypePredicateNode=HUt;Dt.TypeQueryNode=$Ut;Dt.TypeReferenceNode=KUt;Dt.TypedNode=N3e;Dt.UnaryExpression=_2e;Dt.UnaryExpressionedNode=eCt;Dt.UnionTypeNode=JUt;Dt.UnwrappableNode=qHt;Dt.UpdateExpression=$zt;Dt.VariableDeclaration=EHt;Dt.VariableDeclarationBase=kzt;Dt.VariableDeclarationList=xHt;Dt.VariableDeclarationListBase=uBn;Dt.VariableStatement=sUt;Dt.VariableStatementBase=nzt;Dt.VoidExpression=bGt;Dt.VoidExpressionBase=N5n;Dt.WhileStatement=aUt;Dt.WhileStatementBase=u9n;Dt.WithStatement=cUt;Dt.WithStatementBase=d9n;Dt.Writers=ppn;Dt.YieldExpression=SGt;Dt.YieldExpressionBase=R5n;Dt.createWrappedNode=Pgr;Dt.forEachStructureChild=qhr;Dt.getCompilerOptionsFromTsConfig=uhr;Dt.getScopeForNode=Gzt;Dt.insertOverloads=QHt;Dt.printNode=Ndn;Dt.setScopeForNode=Cpn});function T_t(c,o){let{config:a,error:d}=SBn.ts.parseConfigFileTextToJson(fr(c),o);return d?void 0:a}function t$t(c,o){return(Array.isArray(o)?o:[o]).filter(d=>typeof d=="string"&&d.length>0).map(d=>$gr(c,d)).filter(d=>d!==void 0)}function $gr(c,o){if(o.startsWith(".")||RY.isAbsolute(o)){let d=RY.resolve(RY.dirname(c),o),p=d.endsWith(".json")?d:`${d}.json`;return e$t.existsSync(p)?p:d}let a=(0,bBn.createRequire)(c);for(let d of[o,`${o}/tsconfig.json`])try{let p=a.resolve(d);if(p.endsWith(".json"))return Kgr(RY.dirname(c),p)}catch{}}function Kgr(c,o){for(let a=c;;a=RY.dirname(a)){let d=RY.relative(e$t.realpathSync(a),o);if(d!==".."&&!d.startsWith(`..${RY.sep}`)&&!RY.isAbsolute(d))return RY.join(a,d);if(RY.dirname(a)===a)return o}}var e$t,bBn,RY,SBn,n$t=Zi(()=>{"use strict";e$t=Ec(require("node:fs")),bBn=require("node:module"),RY=Ec(require("node:path")),SBn=Ec(M3e());Pp()});function Opn(c,o){try{let a=xBn(EBn(c,o));return(0,TBn.createHash)("sha256").update(JSON.stringify([...a].sort(([d],[p])=>d.localeCompare(p)))).digest("hex")}catch(a){Jgr.info(`Index cache disabled: ${a instanceof Error?a.message:String(a)}`);return}}function Fpn(c,o){return[...xBn(EBn(c,o)).keys()]}function Bpn(c,o){return o.filter(a=>!hjt.test(a)&&wJ(a,c))}function EBn(c,o){let a=new Set([fr(c)]);for(let d of o){let p=fr(nCt.dirname(d));for(;!a.has(p);){if(!wJ(p,c))throw new Error(`source file outside the workspace: ${fr(d)}`);a.add(p),p=fr(nCt.dirname(p))}}return a}function xBn(c){let o=[...c].flatMap(p=>[nCt.join(p,"tsconfig.json"),nCt.join(p,"package.json")]),a=new Set,d=new Map;for(let p=o.shift();p;p=o.shift()){let y=fr(p);if(a.has(y)||!r$t.existsSync(p))continue;a.add(y);let E=qgr(p);d.set(y,E),o.push(...t$t(p,T_t(p,E)?.extends))}return d}function qgr(c){try{return r$t.readFileSync(c,"utf-8")}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`cannot read resolver config ${fr(c)}: ${a}`,{cause:o})}}var TBn,r$t,nCt,Jgr,Wpn=Zi(()=>{"use strict";TBn=require("node:crypto"),r$t=Ec(require("node:fs")),nCt=Ec(require("node:path"));Jce();YL();Pp();WD();n$t();Jgr=e1("configFingerprint")});function jpn(c){try{PW.writeFileSync(E_t.join(E_t.dirname(c),".gitignore"),`*
45439
- `,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o}}var kBn,PW,E_t,ABn,Y4t,x_t,wBn,DBn,i$t,Xgr,Qgr,CBn,PBn,IBn,Ygr,Zgr,eyr,tyr,o$t,zpn=Zi(()=>{"use strict";kBn=require("node:crypto"),PW=Ec(require("node:fs")),E_t=Ec(require("node:path"));YL();Pp();ABn=e1("SymbolAnalysisCache"),Y4t="1.25.5",x_t="symbols.cache",wBn=2;DBn="",i$t=" ",Xgr=1<<20,Qgr=/<template\b[^>]*\ssrc\s*=/i,CBn=c=>(0,kBn.createHash)("sha256").update(c).digest("hex"),PBn=c=>JSON.stringify(c).slice(1,-1),IBn=(c,o)=>JSON.stringify(o).replaceAll(PBn(c),DBn),Ygr=(c,o)=>JSON.parse(o.replaceAll(DBn,PBn(c))),Zgr=c=>Array.isArray(c)&&c.every(o=>typeof o=="string"),eyr=c=>typeof c=="object"&&c!==null&&Array.isArray(c.symbols)&&Array.isArray(c.dependencies),tyr=c=>Array.isArray(c)&&c.every(o=>Array.isArray(o)&&typeof o[0]=="string"&&Zgr(o[1])),o$t=class{constructor(o,a){this.dir=o;this.build=a}dir;build;entries;dirty=!1;getGraph(o,a){let d=this.read(o,a,"graph");return eyr(d)?d:this.drop(o,"graph",d)}setGraph(o,a,d){let p=fr(o);this.update(p,a,{graph:IBn(p,d)})}getInternalGraph(o,a){let d=this.read(o,a,"internal");return tyr(d)?new Map(d.map(([p,y])=>[p,new Set(y)])):this.drop(o,"internal",d)}setInternalGraph(o,a,d){let p=fr(o);this.update(p,a,{internal:IBn(p,[...d].map(([y,E])=>[y,[...E]]))})}save(){if(!this.dirty||!this.entries)return;let o=E_t.join(this.dir,x_t),a=E_t.join(this.dir,`.${x_t}.${process.pid}.tmp`),d,p=!1;try{PW.mkdirSync(this.dir,{recursive:!0}),jpn(this.dir),d=PW.openSync(a,"w"),p=!0;let y={schema:wBn,version:Y4t,build:this.build},E=JSON.stringify(y);for(let[I,B]of this.entries){if(!PW.existsSync(I)){this.entries.delete(I);continue}E+=`
45439
+ `,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o}}var kBn,PW,E_t,ABn,Y4t,x_t,wBn,DBn,i$t,Xgr,Qgr,CBn,PBn,IBn,Ygr,Zgr,eyr,tyr,o$t,zpn=Zi(()=>{"use strict";kBn=require("node:crypto"),PW=Ec(require("node:fs")),E_t=Ec(require("node:path"));YL();Pp();ABn=e1("SymbolAnalysisCache"),Y4t="1.25.6",x_t="symbols.cache",wBn=2;DBn="",i$t=" ",Xgr=1<<20,Qgr=/<template\b[^>]*\ssrc\s*=/i,CBn=c=>(0,kBn.createHash)("sha256").update(c).digest("hex"),PBn=c=>JSON.stringify(c).slice(1,-1),IBn=(c,o)=>JSON.stringify(o).replaceAll(PBn(c),DBn),Ygr=(c,o)=>JSON.parse(o.replaceAll(DBn,PBn(c))),Zgr=c=>Array.isArray(c)&&c.every(o=>typeof o=="string"),eyr=c=>typeof c=="object"&&c!==null&&Array.isArray(c.symbols)&&Array.isArray(c.dependencies),tyr=c=>Array.isArray(c)&&c.every(o=>Array.isArray(o)&&typeof o[0]=="string"&&Zgr(o[1])),o$t=class{constructor(o,a){this.dir=o;this.build=a}dir;build;entries;dirty=!1;getGraph(o,a){let d=this.read(o,a,"graph");return eyr(d)?d:this.drop(o,"graph",d)}setGraph(o,a,d){let p=fr(o);this.update(p,a,{graph:IBn(p,d)})}getInternalGraph(o,a){let d=this.read(o,a,"internal");return tyr(d)?new Map(d.map(([p,y])=>[p,new Set(y)])):this.drop(o,"internal",d)}setInternalGraph(o,a,d){let p=fr(o);this.update(p,a,{internal:IBn(p,[...d].map(([y,E])=>[y,[...E]]))})}save(){if(!this.dirty||!this.entries)return;let o=E_t.join(this.dir,x_t),a=E_t.join(this.dir,`.${x_t}.${process.pid}.tmp`),d,p=!1;try{PW.mkdirSync(this.dir,{recursive:!0}),jpn(this.dir),d=PW.openSync(a,"w"),p=!0;let y={schema:wBn,version:Y4t,build:this.build},E=JSON.stringify(y);for(let[I,B]of this.entries){if(!PW.existsSync(I)){this.entries.delete(I);continue}E+=`
45440
45440
  ${JSON.stringify(I)}${i$t}${B.hash}${i$t}${B.graph??""}${i$t}${B.internal??""}`,E.length>=Xgr&&(PW.writeSync(d,E),E="")}PW.writeSync(d,E),PW.closeSync(d),d=void 0,PW.renameSync(a,o),this.dirty=!1}catch(y){d!==void 0&&PW.closeSync(d),p&&PW.rmSync(a,{force:!0}),ABn.warn("Could not save symbol cache:",y instanceof Error?y.message:String(y))}}read(o,a,d){let p=fr(o),y=this.load().get(p),E=y?.hash===CBn(a)?y[d]:void 0;if(E!==void 0)try{return Ygr(p,E)}catch{return null}}drop(o,a,d){let p=d===void 0?void 0:this.load().get(fr(o));p&&(ABn.warn("Damaged symbol cache entry, analyzing again:",o),p[a]=void 0,this.dirty=!0)}update(o,a,d){if(o.toLowerCase().endsWith(".vue")&&Qgr.test(a))return;let p=CBn(a),y=this.load().get(o);this.load().set(o,{...y?.hash===p?y:{},...d,hash:p}),this.dirty=!0}load(){if(this.entries)return this.entries;this.entries=new Map;let o;try{o=PW.readFileSync(E_t.join(this.dir,x_t),"utf-8").split(/\r?\n/);let a=JSON.parse(o[0]);if(a.schema!==wBn||a.version!==Y4t||a.build!==this.build)return this.entries}catch{return this.entries}for(let a of o.slice(1))this.loadLine(a);return this.entries}loadLine(o){let[a,d,p,y]=o.split(i$t);if(y!==void 0)try{let E=JSON.parse(a);typeof E=="string"&&this.entries?.set(E,{hash:d,graph:p||void 0,internal:y||void 0})}catch{}}}});function LBn(){return""}function Upn(c,o){let a=GH.join(GH.dirname(c),`.${GH.basename(c)}.${process.pid}.tmp`);F3.writeFileSync(a,o),F3.renameSync(a,c)}function iyr(c){try{return process.kill(c,0),!0}catch(o){return o.code==="EPERM"}}function oyr(c,o){return c?.excludeNodeModules===o.excludeNodeModules&&c?.ignoreTypeImports===o.ignoreTypeImports}async function OBn(c,o){let{cache:a}=o,d=a?await a.lock(o.onWait):Vpn;try{c.useSymbolAnalysisCache(a?.enabled?a.dir:null);let p=a?.readReverseIndex(o.reverseIndexOptions),y=p?c.enableReverseIndex(p):!1;y&&iCt.info("Restored reverse index from cache");let E=a&&y?await syr(c,a,o):null,{deleted:I,...B}=E??await ayr(c,o),K=!B.fromCache||B.filesAnalyzed>0||I>0;if(a&&K&&!B.cancelled){let Y=c.getSerializedReverseIndex();Y&&a.save({reverseIndex:{data:Y,options:o.reverseIndexOptions}})}return B}finally{d()}}async function syr(c,o,a){let d=await c.validateReverseIndex(nyr,o.sourceFiles);if(!d?.isValid)return iCt.info("Cached index too stale, rebuilding from scratch"),null;for(let E of d.missingFiles)c.handleFileDeleted(E);d.staleFiles.length>0&&a.onReindexStart?.(d.staleFiles.length);let p=await c.reindexStaleFiles(d.staleFiles);return iCt.info(`Incremental index: ${p} changed, ${d.missingFiles.length} deleted`),{filesIndexed:c.getCacheStats().reverseIndexStats?.indexedFiles??0,filesFound:o.sourceFiles.length,filesAnalyzed:p,fromCache:!0,cancelled:!1,deleted:d.missingFiles.length}}async function ayr(c,o){c.clearCache();let a=await o.buildFullIndex();return{filesIndexed:c.getCacheStats().reverseIndexStats?.indexedFiles??a.indexedFiles,filesFound:a.indexedFiles,filesAnalyzed:a.indexedFiles,fromCache:!1,cancelled:a.cancelled,deleted:0}}var F3,GH,iCt,NBn,nyr,RBn,ryr,Gpn,Z4t,s$t,MBn,rCt,Vpn,A_t,Hpn=Zi(()=>{"use strict";F3=Ec(require("node:fs")),GH=Ec(require("node:path"));v3e();YL();Pp();Wpn();zpn();iCt=e1("IndexCache"),NBn=2,nyr=.2,RBn=10*6e4,ryr=250,Gpn="meta.json",Z4t="reverse-index.json",s$t="callgraph.db",MBn="index.lock";rCt=new Map,Vpn=()=>{};A_t=class c{dir;sourceFiles;workspaceRoot;fingerprint;constructor(o,a){this.workspaceRoot=GH.resolve(o),this.dir=c.dirFor(this.workspaceRoot),this.sourceFiles=a,this.fingerprint=Opn(this.workspaceRoot,a)}static dirFor(o){return GH.join(o,".graph-it","cache")}static async open(o){let a=await new kW({excludeNodeModules:!0,yieldIntervalMs:30,isCancelled:()=>!1}).collectAllSourceFiles(o);return new c(o,a)}get enabled(){return this.fingerprint!==void 0}get callGraphPath(){return GH.join(this.dir,s$t)}isValid(){return this.matches(this.readMeta())}readReverseIndex(o){let a=this.readMeta();if(!this.matches(a)||!oyr(a?.reverseIndexOptions,o))return null;try{return F3.readFileSync(GH.join(this.dir,Z4t),"utf-8")}catch{return null}}save(o){let a=this.currentFingerprint();if(!a)return!1;try{F3.mkdirSync(this.dir,{recursive:!0}),jpn(this.dir);let d=this.readMeta(),p=this.matches(d,a),y=GH.join(this.dir,Z4t);o.reverseIndex?Upn(y,o.reverseIndex.data):p||F3.rmSync(y,{force:!0}),o.callGraph?Upn(this.callGraphPath,o.callGraph):p||F3.rmSync(this.callGraphPath,{force:!0});let E={schema:NBn,version:Y4t,build:LBn(),savedAt:new Date().toISOString(),workspaceRoot:this.workspaceRoot,configFingerprint:a,reverseIndexOptions:o.reverseIndex?.options??(p?d?.reverseIndexOptions:void 0)};Upn(GH.join(this.dir,Gpn),JSON.stringify(E,null,2));let I=c.fileSizes(this.dir);return iCt.info(`Saved index cache: ${Z4t} ${I.reverseIndexBytes} B, ${s$t} ${I.callGraphBytes} B, ${x_t} ${I.symbolsBytes} B`),!0}catch(d){return iCt.warn("Could not save index cache:",d instanceof Error?d.message:String(d)),!1}}static fileSizes(o){let a=d=>{try{return F3.statSync(GH.join(o,d)).size}catch{return 0}};return{reverseIndexBytes:a(Z4t),callGraphBytes:a(s$t),symbolsBytes:a(x_t)}}clear(){for(let o of[Gpn,Z4t,s$t,x_t])F3.rmSync(GH.join(this.dir,o),{force:!0});try{F3.rmdirSync(this.dir)}catch{}}tryLock(){if(!this.enabled)return Vpn;let o=GH.join(this.dir,MBn),a=rCt.get(fr(o));if(a)return rCt.set(fr(o),a+1),this.releaser(o);try{if(F3.mkdirSync(this.dir,{recursive:!0}),!this.createLockFile(o)&&(!this.isLockStale(o)||(F3.rmSync(o,{force:!0}),!this.createLockFile(o))))return null}catch(d){return iCt.warn("Could not lock index cache:",d instanceof Error?d.message:String(d)),Vpn}return rCt.set(fr(o),1),this.releaser(o)}async lock(o){let a=!1;for(;;){let d=this.tryLock();if(d)return d;a||(a=!0,o?.(this.readLockHolder(GH.join(this.dir,MBn))?.pid)),await new Promise(p=>setTimeout(p,ryr))}}releaser(o){let a=!1;return()=>{if(a)return;a=!0;let d=fr(o),p=(rCt.get(d)??1)-1;if(p>0){rCt.set(d,p);return}rCt.delete(d),this.readLockHolder(o)?.pid===process.pid&&F3.rmSync(o,{force:!0})}}createLockFile(o){let a={pid:process.pid,acquiredAt:Date.now()};try{return F3.writeFileSync(o,JSON.stringify(a),{flag:"wx"}),!0}catch(d){if(d.code==="EEXIST")return!1;throw d}}readLockHolder(o){try{let a=JSON.parse(F3.readFileSync(o,"utf-8"));return typeof a.pid=="number"?a:void 0}catch{return}}isLockStale(o){let a=this.readLockHolder(o);if(!a)try{return Date.now()-F3.statSync(o).mtimeMs>RBn}catch{return!0}return a.pid===process.pid?!0:Date.now()-a.acquiredAt>RBn||!iyr(a.pid)}readMeta(){try{return JSON.parse(F3.readFileSync(GH.join(this.dir,Gpn),"utf-8"))}catch{return}}currentFingerprint(){return this.fingerprint&&Opn(this.workspaceRoot,this.sourceFiles)}matches(o,a=this.currentFingerprint()){return a!==void 0&&o?.schema===NBn&&o.version===Y4t&&(o.build??"")===LBn()&&o.configFingerprint===a&&typeof o.workspaceRoot=="string"&&fr(o.workspaceRoot)===fr(this.workspaceRoot)}}});var _E,B3=Zi(()=>{"use strict";Pp();_E=class c extends Error{code;filePath;cause;timestamp;constructor(o,a,d){super(o),this.name="SpiderError",this.code=a,this.filePath=d?.filePath,this.cause=d?.cause,this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,c)}static fromError(o,a){if(o instanceof c)return o;let d=o instanceof Error?o:void 0,p=d?.message??(o!==null&&typeof o=="object"?JSON.stringify(o):String(o)),y="UNKNOWN";if(d){let E=d.code;E==="ENOENT"?y="FILE_NOT_FOUND":E==="EACCES"||E==="EPERM"?y="PERMISSION_DENIED":p.includes("too large")||E==="EFBIG"?y="FILE_TOO_LARGE":p.includes("parse")||p.includes("syntax")?y="PARSE_ERROR":(p.includes("timeout")||E==="ETIMEDOUT")&&(y="TIMEOUT")}return new c(p,y,{filePath:a,cause:d})}isRecoverable(){return["FILE_NOT_FOUND","PERMISSION_DENIED","PARSE_ERROR","RESOLUTION_FAILED"].includes(this.code)}toUserMessage(){switch(this.code){case"FILE_NOT_FOUND":return`File not found: ${this.filePath||"unknown"}`;case"PERMISSION_DENIED":return`Permission denied: ${this.filePath||"unknown"}`;case"FILE_TOO_LARGE":return`File too large to process: ${this.filePath||"unknown"}`;case"PARSE_ERROR":return`Failed to parse: ${this.filePath||"unknown"}`;case"RESOLUTION_FAILED":return`Could not resolve module in: ${this.filePath||"unknown"}`;case"TIMEOUT":return"Operation timed out";case"CIRCULAR_DEPENDENCY":return"Circular dependency detected";default:return this.message}}toJSON(){return{name:this.name,code:this.code,message:this.message,filePath:this.filePath,timestamp:this.timestamp,stack:this.stack}}}});var w_t,a$t,cyr,lyr,uyr,dyr,s4,tSe=Zi(()=>{"use strict";w_t=Ec(require("node:fs/promises")),a$t=Ec(require("node:fs"));B3();YL();cyr=e1("FileReader"),lyr=5*1024*1024,uyr=64*1024,dyr=3e4,s4=class{maxSize;chunkSize;timeout;constructor(o={}){this.maxSize=o.maxSize??lyr,this.chunkSize=o.chunkSize??uyr,this.timeout=o.timeout??dyr}async getFileSize(o){try{let a=await w_t.stat(o);return{size:a.size,isLarge:a.size>this.maxSize,path:o}}catch(a){throw _E.fromError(a,o)}}async readFile(o,a){let d=a?.maxSize??this.maxSize,p=a?.timeout??this.timeout,y=a?.streaming??!1,E;try{E=await w_t.stat(o)}catch(K){throw _E.fromError(K,o)}if(E.size>d)throw new _E(`File too large: ${o} (${this.formatSize(E.size)} > ${this.formatSize(d)})`,"FILE_TOO_LARGE",{filePath:o});let I,B=new Promise((K,Y)=>{I=setTimeout(()=>{Y(new _E(`File read timed out after ${p}ms: ${o}`,"TIMEOUT",{filePath:o}))},p)});try{let K;return y||E.size>1024*1024?(cyr.debug(`Streaming read for large file: ${o} (${this.formatSize(E.size)})`),K=await Promise.race([this.readFileStreaming(o),B])):K=await Promise.race([w_t.readFile(o,"utf-8"),B]),clearTimeout(I),K}catch(K){throw clearTimeout(I),K instanceof _E?K:_E.fromError(K,o)}}async readFileStreaming(o){return new Promise((a,d)=>{let p=[],y=a$t.createReadStream(o,{highWaterMark:this.chunkSize});y.on("data",E=>{p.push(Buffer.isBuffer(E)?E:Buffer.from(E))}),y.on("end",()=>{let E=Buffer.concat(p).toString("utf-8");a(E)}),y.on("error",E=>{d(_E.fromError(E,o))})})}async readFileIfExists(o){try{return await this.readFile(o)}catch(a){if(a instanceof _E&&a.code==="FILE_NOT_FOUND")return null;throw a}}async canRead(o){try{return await w_t.access(o,a$t.constants.R_OK),!0}catch{return!1}}formatSize(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}}});function BBn(c){return c===void 0?!1:c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||c===95||c===36}function myr(c){return c===32||c===9||c===10||c===13}function $pn(c,o,a){a<=o||(c.parts.push(c.src.slice(c.copied,o),c.src.slice(o,a).replaceAll(/[^\n\r]/g," ")),c.copied=a)}function hyr(c){let{src:o}=c,a=c.i-1;for(;a>=0;)if(a<c.commentEnd&&a>=c.commentStart)a=c.commentStart-1;else if(myr(o.codePointAt(a)))a--;else break;if(a<0)return"";if(!BBn(o.codePointAt(a)))return o[a];let d=a;for(;d>0&&BBn(o.codePointAt(d-1));)d--;return o.slice(d,a+1)}function _yr(c){return c===""||pyr.has(c)||fyr.has(c)}function gyr(c,o){let a=c[o],d=o+1;for(;d<c.length&&c[d]!==a&&c[d]!==`
45441
45441
  `;)d+=c[d]==="\\"?2:1;return c[d]===a?d+1:Math.min(d,c.length)}function yyr(c,o){let a=!1;for(let d=o+1;d<c.length;d++){let p=c[d];if(p===`
45442
45442
  `)return-1;if(p==="\\")d++;else if(p==="[")a=!0;else if(p==="]")a=!1;else if(p==="/"&&!a)return d+1}return-1}function WBn(c){let{src:o}=c,a=c.i;for(;a<o.length&&o[a]!=="`"&&!(o[a]==="$"&&o[a+1]==="{");)a+=o[a]==="\\"?2:1;a=Math.min(a,o.length),$pn(c,c.i,a),o[a]==="$"?(c.templates.push(c.braceDepth),c.braceDepth++,c.i=a+2):c.i=a+1}function vyr(c){let{src:o,i:a}=c;if(o[a]!=="/"||o[a+1]!=="/"&&o[a+1]!=="*")return!1;let d;return o[a+1]==="/"?d=o.indexOf(`
@@ -47430,7 +47430,7 @@ Error: ${ezr(d)}`}}}async function UVe(c,o,a,d,p){let{jsonOutput:y,failure:E}=aw
47430
47430
  `)}async function azr(c,o,a,d){let p=d.trim(),y=yrr(p),E=y.tokens;if(y.error)return{command:"command",output:`Invalid command line: ${Grt(y.error)}`};if(E.length===0)return{command:"command",output:"Empty command. Try: path src/index.ts --format mermaid"};E[0]==="graph-it"&&E.shift();let[I,...B]=E,K=I?Zjr(I):"";if(!K)return{command:"command",output:"No command provided after graph-it prefix."};if(await nzr(K,c),K==="diagram")return czr(B,o,c);let{effectiveFormat:Y,cleanedArgs:ue,invalidFormatValue:ie}=gsr(B,a),Re=gzr(K,mzr(K,ue,o),o);ie&&process.stdout.write(`Unknown format "${Grt(ie)}". Valid formats: ${vwt.join(", ")}. Using ${Y}.
47431
47431
  `);let Ie=await lzr(K,Re,o,c);if(Ie)return Ie;let Ne=await xzr(K,Re,c,o,Y);if(Ne)return Ne;let bt=await Szr(K,Re,c,o,Y);if(bt)return bt;let Qt=Qjr(K),Fn=Qt?msr[Qt]:void 0;if(Qt&&Fn){let{run:vr}=await Fn(),Kr=Qt==="checkDependencies"?"check-dependencies":Qt;return UVe(Kr,bzr(Kr,Re),c,Y,vr)}return{command:K,output:`Unknown REPL command "${Grt(K)}". Try: /scope, /file, /trace, /explain, /callers, /impact, /context, /query, /review-pr, /help.`}}async function czr(c,o,a){let{effectiveFormat:d,cleanedArgs:p,invalidFormatValue:y}=gsr(c,"text");if(y)throw new Ku(`Unknown format "${Grt(y)}". /diagram writes svg, html or diagram-spec.`,Au.UNSUPPORTED_FORMAT);if(ple(p,"--output","a file of the workspace")==="-")throw new Ku("/diagram writes a file: --output - would print the markup in the terminal. Pass a file name.",Au.GENERAL_ERROR);let[E]=p,I=E!==void 0&&!E.startsWith("-"),B=o.workspaceRoot!==a.workspaceRoot,K=ple(p,"--view","units, folder or matrix")==="units",Y;I?Y=BJ.resolve(o.workspaceRoot,E.replaceAll("\\","/")):B&&!K&&!p.includes("--folder")&&(Y=o.workspaceRoot);let ue=Y===void 0?p:[BJ.relative(a.workspaceRoot,Y),...p.slice(I?1:0)],{run:ie}=await Promise.resolve().then(()=>(xAn(),EAn));return{command:"diagram",output:await ie(ue,a,d)}}async function lzr(c,o,a,d){if(c==="help")return{command:"help",output:Yjr(a)};if(c==="quit")return{command:"quit",shouldQuit:!0};if(c==="scope"||c==="path")return dzr(o,a,d);if(c==="export"){let y=BJ.basename(d.workspaceRoot),{runExportHtml:E}=await Promise.resolve().then(()=>(PAn(),DAn)),I=a.workspaceRoot!==d.workspaceRoot?a.workspaceRoot:void 0;return await E(d,y,o,a.lastFile??I),{command:"export"}}if(c!=="format")return c!=="file"?void 0:fzr(o,a,d);let p=o[0];if(p&&vwt.includes(p))a.preferredFormat=p;else return p?{command:"format",output:`Unknown format "${Grt(p)}". Valid formats: ${vwt.join(", ")}`}:{command:"format",output:`Current format: ${a.preferredFormat}. Set a value explicitly, e.g. /format markdown. Valid formats: ${vwt.join(", ")}`};return{command:"format",output:`Default format set to ${a.preferredFormat}.`}}function uzr(c,o,a){return c.workspaceRoot=a,c.lastFile=void 0,c.lastSymbol=void 0,{command:"scope",output:`Session workspace set to ${BJ.relative(o.workspaceRoot,c.workspaceRoot)||"."}.`}}async function dzr(c,o,a){if(!c[0])return{command:"scope",output:`Current workspace scope: ${BJ.relative(a.workspaceRoot,o.workspaceRoot)||"."}. Usage: /scope <directory>`};let d=BJ.isAbsolute(c[0])?BJ.resolve(c[0]):BJ.resolve(o.workspaceRoot,c[0]);return hzr(d,a.workspaceRoot)?(await psr.promises.stat(d).catch(()=>{}))?.isDirectory()?uzr(o,a,d):{command:"scope",output:`Directory not found: ${Grt(c[0],140)}`}:{command:"scope",output:"Refusing to set workspace scope outside project root."}}async function fzr(c,o,a){if(!c[0])return{command:"file",output:o.lastFile?`Current file context: ${BJ.relative(a.workspaceRoot,o.lastFile)}. Usage: /file <path>`:"No file context set. Usage: /file <path>"};let d=L2e(c[0],o.workspaceRoot).filePath;return o.lastFile=d,o.lastSymbol=void 0,{command:"file",output:`Current file context set to ${BJ.relative(a.workspaceRoot,d)}.`,contextFile:d}}function fsr(c){return c?vwt.includes(c)?{override:c}:{invalid:c}:null}function pzr(c,o){if(c==="--format"||c==="-f")return{parsed:fsr(o??"")??{invalid:"(missing value)"},skipNextArg:!0};if(c.startsWith("--format="))return{parsed:fsr(c.slice(9))??{invalid:"(missing value)"},skipNextArg:!1}}function mzr(c,o,a){return o.length>0||!a.lastFile||c!=="summary"&&c!=="check"&&c!=="check-dependencies"&&c!=="cycles"?o:[a.lastFile]}function hzr(c,o){let a=BJ.relative(o,c);return!a.startsWith("..")&&!BJ.isAbsolute(a)}function _zr(c,o,a){if(c==="trace"){let d=L2e(o,a.workspaceRoot);return d.symbolName?`${d.filePath}#${d.symbolName}`:d.filePath}return c==="check-dependencies"||c==="cycles"?L2e(o,a.workspaceRoot).filePath:o}function gzr(c,o,a){return o.length===0||!new Set(["trace","check-dependencies","cycles"]).has(c)?o:[_zr(c,o[0],a),...o.slice(1)]}function gsr(c,o){let a=[],d,p;for(let y=0;y<c.length;y+=1){let E=c[y],I=pzr(E,c[y+1]);if(I){"override"in I.parsed?d=I.parsed.override:p=I.parsed.invalid,I.skipNextArg&&(y+=1);continue}a.push(E)}return{effectiveFormat:d??o,cleanedArgs:a,invalidFormatValue:p}}function yzr(c){let o=[],a;for(let d=0;d<c.length;d+=1){let p=c[d];if(p==="--maxDepth"&&c[d+1]){let y=Number.parseInt(c[d+1],10);!Number.isNaN(y)&&y>0&&(a=y),d+=1;continue}if(p.startsWith("--maxDepth=")){let y=Number.parseInt(p.slice(11),10);!Number.isNaN(y)&&y>0&&(a=y);continue}o.push(p)}return{cleanedArgs:o,maxDepth:a}}function vzr(c){let o=[],a="both";for(let d of c){if(d==="--incoming"||d==="--in"){a="incoming";continue}if(d==="--outgoing"||d==="--out"){a="outgoing";continue}if(d==="--both"){a="both";continue}o.push(d)}return{cleanedArgs:o,direction:a}}function bzr(c,o){if(c!=="architecture")return o;let a=[];for(let d of o){if(d.startsWith("--maxFiles=")){let p=d.slice(11);a.push("--maxFiles",p);continue}a.push(d)}return a}async function Szr(c,o,a,d,p){if(c==="trace")return Tzr(o,a,d,p);if(c==="check-dependencies"||c==="deps"||c==="dependencies")return Izr(o,a,d,p)}async function Tzr(c,o,a,d){let{cleanedArgs:p,maxDepth:y}=yzr(c),E=p[0]??ysr(a);return E?Ezr(E,y,o,a,d):{command:"trace",output:"Trace needs a file context. Usage: /trace <file#Symbol> or set a file with /file <path>."}}function ysr(c){if(c.lastFile)return c.lastSymbol?`${c.lastFile}#${c.lastSymbol}`:c.lastFile}async function Ezr(c,o,a,d,p){let y=L2e(c,d.workspaceRoot);if(y.symbolName){let B=[`${y.filePath}#${y.symbolName}`];o!==void 0&&B.push("--maxDepth",String(o));let{run:K}=await Promise.resolve().then(()=>(xZt(),EZt));return{...await UVe("trace",B,a,p,K),contextFile:y.filePath,contextSymbol:y.symbolName}}let{run:E}=await Promise.resolve().then(()=>(c7t(),a7t));return{...await UVe("explain",[y.filePath],a,p,E),contextFile:y.filePath}}async function xzr(c,o,a,d,p){if(c==="callers"||c==="impact")return Azr(c,o,a,d,p);if(c==="explain")return wzr(o,a,d,p);if(c==="context")return Czr(o,a,d,p)}async function Azr(c,o,a,d,p){let y=o[0]!==void 0&&!o[0].startsWith("-"),E=y?o[0]:ysr(d),I=E?L2e(E,d.workspaceRoot):void 0;if(!I?.symbolName)return{command:c,output:`/${c} needs a symbol. Usage: /${c} <file#Symbol>, or pick one first with /trace <file#Symbol>.`};let{tool:B,params:K}=Xjr[c],Y=[B,"--args",JSON.stringify({...K,filePath:I.filePath,symbolName:I.symbolName}),...y?o.slice(1):o],{run:ue}=await Promise.resolve().then(()=>(tZt(),eZt));return{...await UVe(c,Y,a,p,ue),contextFile:I.filePath,contextSymbol:I.symbolName}}async function wzr(c,o,a,d){let p=c[0]?L2e(c[0],a.workspaceRoot).filePath:a.lastFile;if(!p)return{command:"explain",output:"Explain needs a file. Usage: /explain <file>, or set a file with /file <path>."};let{run:y}=await Promise.resolve().then(()=>(c7t(),a7t)),E=await UVe("explain",[p],o,d,y),I=a.lastFile!==void 0&&$ce(a.lastFile)===$ce(p);return{...E,contextFile:p,contextSymbol:I?a.lastSymbol:void 0}}async function Czr(c,o,a,d){let p=c;if(c.length===0){if(!a.lastFile||!a.lastSymbol)return{command:"context",output:'Context needs a question or a symbol. Usage: /context "<question>" [--detail compact], or pick a symbol first with /trace <file#Symbol>.'};p=["--seeds",`${a.lastFile}#${a.lastSymbol}`]}let{run:y}=await Promise.resolve().then(()=>(MAn(),RAn));return{...await UVe("context",p,o,d,y),contextFile:a.lastFile,contextSymbol:a.lastSymbol}}async function Izr(c,o,a,d){let{cleanedArgs:p,direction:y}=vzr(c),E=p[0]??a.lastFile;if(!E)return{command:"check-dependencies",output:"check-dependencies needs a file path. Usage: /check-dependencies <file> [--incoming|--outgoing|--both]"};let I=L2e(E,a.workspaceRoot).filePath;return kzr(y,I,o,d)}async function kzr(c,o,a,d){if(c==="outgoing"){let{run:E}=await Promise.resolve().then(()=>(yZt(),gZt));return{...await UVe("path",[o],a,d,E),contextFile:o}}if(c==="incoming"){let{run:E}=await Promise.resolve().then(()=>(bZt(),vZt));return{...await UVe("path-in",[o],a,d,E),contextFile:o}}let{run:p}=await Promise.resolve().then(()=>(TZt(),SZt));return{...await UVe("check-dependencies",[o],a,d,p),contextFile:o}}function Dzr(c,o){return o!=="mermaid"&&o!=="json"&&o!=="toon"?c:c.split(`
47432
47432
  `).filter(d=>{let p=d.trim();return!(p.startsWith("%% output truncated")||/^PARSING ERROR\b/i.test(p))}).join(`
47433
- `)}async function Pzr(c,o){await _sr(o);try{let{run:a}=await Promise.resolve().then(()=>(c7t(),a7t)),d=await Promise.race([a([c],o,"json"),new Promise((B,K)=>{setTimeout(()=>K(new Error("timeout")),5e3)})]),p=JSON.parse(d);if(typeof p!="object"||p===null)return[];let y=new Set,E=p,I=B=>{if(Array.isArray(B)){for(let K of B)if(typeof K=="object"&&K!==null){let Y=K;typeof Y.symbolName=="string"&&y.add(Y.symbolName),typeof Y.name=="string"&&y.add(Y.name)}}};return I(E.nodes),I(E.symbols),[...y].sort((B,K)=>B.localeCompare(K))}catch{return[]}}var BJ,psr,Kjr,FAn,dsr,Jjr,LAn,qjr,msr,Xjr,OAn,tzr,bsr=Zi(()=>{"use strict";BJ=Ec(require("node:path")),psr=require("node:fs");v3e();jH();cN();mle();Pp();YL();r6e();hrr();_rr();vrr();ior();Kjr="1.25.5",FAn=!process.env.NO_COLOR&&process.stdout.isTTY,dsr=FAn?"\x1B[2m":"",Jjr=FAn?"\x1B[1m":"",LAn=FAn?"\x1B[0m":"",qjr=`Interactive mode unavailable (no TTY).
47433
+ `)}async function Pzr(c,o){await _sr(o);try{let{run:a}=await Promise.resolve().then(()=>(c7t(),a7t)),d=await Promise.race([a([c],o,"json"),new Promise((B,K)=>{setTimeout(()=>K(new Error("timeout")),5e3)})]),p=JSON.parse(d);if(typeof p!="object"||p===null)return[];let y=new Set,E=p,I=B=>{if(Array.isArray(B)){for(let K of B)if(typeof K=="object"&&K!==null){let Y=K;typeof Y.symbolName=="string"&&y.add(Y.symbolName),typeof Y.name=="string"&&y.add(Y.name)}}};return I(E.nodes),I(E.symbols),[...y].sort((B,K)=>B.localeCompare(K))}catch{return[]}}var BJ,psr,Kjr,FAn,dsr,Jjr,LAn,qjr,msr,Xjr,OAn,tzr,bsr=Zi(()=>{"use strict";BJ=Ec(require("node:path")),psr=require("node:fs");v3e();jH();cN();mle();Pp();YL();r6e();hrr();_rr();vrr();ior();Kjr="1.25.6",FAn=!process.env.NO_COLOR&&process.stdout.isTTY,dsr=FAn?"\x1B[2m":"",Jjr=FAn?"\x1B[1m":"",LAn=FAn?"\x1B[0m":"",qjr=`Interactive mode unavailable (no TTY).
47434
47434
  Use direct commands: graph-it --help
47435
47435
  `,msr={architecture:()=>Promise.resolve().then(()=>(hZt(),mZt)),summary:()=>Promise.resolve().then(()=>(eAn(),Zxn)),check:()=>Promise.resolve().then(()=>(nAn(),tAn)),path:()=>Promise.resolve().then(()=>(yZt(),gZt)),pathIn:()=>Promise.resolve().then(()=>(bZt(),vZt)),checkDependencies:()=>Promise.resolve().then(()=>(TZt(),SZt)),cycles:()=>Promise.resolve().then(()=>(oAn(),iAn)),trace:()=>Promise.resolve().then(()=>(xZt(),EZt)),scan:()=>Promise.resolve().then(()=>(aAn(),sAn)),query:()=>Promise.resolve().then(()=>(pAn(),fAn)),wiki:()=>Promise.resolve().then(()=>(hAn(),mAn)),"review-pr":()=>Promise.resolve().then(()=>(TAn(),SAn)),"check-architecture":()=>Promise.resolve().then(()=>(DZt(),bAn))},Xjr={callers:{tool:"query_call_graph",params:{direction:"callers"}},impact:{tool:"get_impact_analysis",params:{}}};OAn=new WeakMap;tzr=new Set(["help","quit","scope","path","file","format"])});function WAn(c){if(c===JH)return"root";let o=c.split(/[^\w.-]+/).filter(Boolean).join("-").slice(0,BAn);return o===""||o===Esr?`unit-${o}`.slice(0,BAn).replace(/-$/,""):o}function xsr(c,o,a=BAn){if(!o(c))return c;for(let d=2;;d+=1){let p=`-${d}`,y=`${c.slice(0,a-p.length)}${p}`;if(!o(y))return y}}function Ssr(c,o,a){let d=JSON.stringify(a),p=Object.entries(c).find(([,E])=>JSON.stringify(E)===d);if(p)return p[0];let y=xsr(o,E=>E in c||E===Esr);return c[y]=a,y}function Tsr(c,o){let a=new Set(c.map(d=>d.name));c.push({...o,name:xsr(o.name,d=>a.has(d),128)})}function Ozr(c){let o=(d,p)=>DG(d,p.key)||DG(d,p.name),a=d=>c.filter(p=>o(d,p)).length===1;return new Map(c.map(d=>[d.key,[d.key,d.name].find(a)??d.key]))}function Asr(c,o){let a={$schema:o?.$schema??Nzr,elements:{...o?.elements},rules:[...o?.rules??[]],...o?.roles===void 0?{}:{roles:o.roles}},d=c.units.map(Y=>Y.key).sort(B_),p=Ozr(c.units),y=new Map(d.map(Y=>[Y,Ssr(a.elements,WAn(Y),{unit:p.get(Y)})])),E=new Map;for(let Y of c.unitEdges)E.set(Y.from,(E.get(Y.from)??new Set).add(Y.to));let I=new Set(a.rules.filter(Y=>Y.allowOnly!==void 0).flatMap(Y=>Lzr(Y.from)));for(let Y of d){let ue=y.get(Y);I.has(ue)||Tsr(a.rules,{name:`${ue}-imports`,from:ue,allowOnly:[...E.get(Y)??[]].map(ie=>y.get(ie)).sort(B_),reason:`graph-it init: the units that "${Y}" imported when this rule was generated. Remove an entry once its imports are gone; never add one to pass a check.`})}let B=new Set(c.unitEdges.filter(Y=>Y.kind==="cycle").flatMap(Y=>[Y.from,Y.to])),K=d.filter(Y=>!B.has(Y));if(K.length>=2&&!a.rules.some(Y=>Y.noCycles!==void 0)){let Y=Ssr(a.elements,Rzr,{unit:K.map(ue=>p.get(ue)),each:!0});Tsr(a.rules,{name:Mzr,noCycles:Y,reason:"graph-it init: these units were in no import cycle when this rule was generated; keep it that way."})}return a}function wsr(c,o){let a=B=>new Map(B.map(([K,Y])=>[K,JSON.stringify(Y)])),p=[["element",a(Object.entries(c.config?.elements??{})),a(Object.entries(o.config.elements))],["rule",a((c.config?.rules??[]).map(B=>[B.name,B])),a(o.config.rules.map(B=>[B.name,B]))]].flatMap(([B,K,Y])=>[...[...Y].filter(([ue])=>!K.has(ue)).map(([ue,ie])=>`+ ${B} "${ue}": ${ie}`),...[...Y].filter(([ue,ie])=>K.has(ue)&&K.get(ue)!==ie).map(([ue,ie])=>`~ ${B} "${ue}": ${K.get(ue)} -> ${ie}`),...[...K].filter(([ue])=>!Y.has(ue)).map(([ue,ie])=>`- ${B} "${ue}": ${ie}`)]);for(let B of["$schema","roles"]){let K=JSON.stringify(c.config?.[B]),Y=JSON.stringify(o.config[B]);c.config!==void 0&&K!==Y&&p.push(`~ ${B}: ${K} -> ${Y}`)}let y=B=>`${B.rule}: ${B.source} -> ${B.target}`,E=new Set((c.baseline??[]).map(y)),I=new Set(o.baseline.map(y));return p.push(...[...I].filter(B=>!E.has(B)).map(B=>`+ accepted violation ${B}`),...[...E].filter(B=>!I.has(B)).map(B=>`- accepted violation ${B}`)),p}var Nzr,Rzr,Mzr,BAn,Esr,Lzr,Csr=Zi(()=>{"use strict";qH();y2t();Nzr="https://raw.githubusercontent.com/magic5644/Graph-It-Live/main/schemas/architecture.schema.json",Rzr="acyclic-units",Mzr="no-new-unit-cycles",BAn=64,Esr="units",Lzr=c=>c===void 0?[]:[c].flat()});function eyt(c,o,a){return o>c?[`... ${o-c} more${a}`]:[]}function Nsr(c){let o=new Map(c.unitNames.map(a=>[a.key,a.name]));return a=>o.get(a)??a}function jzr(c,o,a){let d=c.files.slice(0,ekt).map(p=>`${p.relativePath}: ${p.lines===void 0?"lines unknown":mN(p.lines,"line")}, ${mN(p.exports,"export")}, ${p.confidence} ${p.reasons.join(", ")}`+(p.via?` via ${p.via.join(", ")}`:"")+(p.tests?`; delete with ${p.tests.map(y=>y.relativePath).join(", ")}`:""));return{label:`${mN(c.files.length,"file")}, ${mN(c.lines,"line")}`,subject:a(c.unit),details:[...d,...eyt(ekt,c.files.length,o===void 0?Dsr:Psr(o))],next:`graph-it check${c.unit===JH?"":" "+JSON.stringify(c.unit)} --unreferencedFiles`,units:[c.unit]}}function Gzr(c){return{label:`${c.kind}, gain ${c.gain} / effort ${c.effort}`,subject:c.subject,details:[...c.evidence,...eyt(c.evidence.length,c.totalEvidence,c.kind==="cycle-break"?Wzr:Dsr)],next:c.next,units:c.units,fallback:zzr[c.kind]}}function Isr(c,o,a,d){return o.unitCycles+o.mutualImports===0?[]:[{label:c,subject:[...o.units.slice(0,ekt).map(d),...eyt(ekt,o.units.length,"")].join(", "),note:`${mN(o.unitCycles,"unit cycle")} and ${mN(o.mutualImports,"mutual file import")} ${Rsr[c]}, no init-order risk.`,details:[...o.evidence,...eyt(o.evidence.length,o.totalEvidence,Psr(a))],units:o.units,fallback:"units"}]}function ksr(c,o){return{label:c.kind,subject:c.rows.map(o).join(", "),note:c.action,details:c.evidence,next:c.next,units:c.rows,fallback:"matrix"}}function Uzr(c,o,a){if(c.length===0)return[];let d=c.flatMap(E=>E.rows),p=new Set(o.map(E=>E.unit)),y=d.filter(E=>p.has(E)).length;return[{label:"entry-row",subject:[...d.slice(0,ekt).map(a),...eyt(ekt,d.length,"")].join(", "),note:`${mN(d.length,"unit")} no other unit imports, ${y} of them with dead files. ${dEn("entry-row")}`,details:[],next:c.length===1?c[0].next:"graph-it check --unreferencedFiles",units:[]}]}function GAn(c,o){let{deadFiles:a,quickWins:d,matrixFindings:p,typeOnlyCycles:y,lazyCycles:E}=c,I=(...Y)=>d.filter(ue=>Y.includes(ue.kind)).map(Gzr),B=(...Y)=>p.filter(ue=>Y.includes(ue.kind)),K=Nsr(c);return[{title:"Dead files",count:`${mN(a.reduce((Y,ue)=>Y+ue.files.length,0),"file")} in ${mN(a.length,"unit")}`,noun:"unit",intro:"Files no production file imports, by unit, most lines first: the cheapest deletions. An entry point by convention (script, handler) is listed too: check before deleting.",items:a.map(Y=>jzr(Y,o,K))},{title:"Cycles to cut",intro:"Runtime cycles ranked by gain / effort, then the type-only and the lazy ones, one item each (see Glossary).",items:[...I("cycle-break","mutual-import"),...Isr("type-only",y,o,K),...Isr("lazy",E,o,K)]},{title:"Hubs",items:B("hub-at-risk","wide-row").map(Y=>ksr(Y,K))},{title:"Other leads",intro:"Each lead is for the architect, never a verdict.",items:[...I("weak-dependency","dead-code"),...B("cohesion").map(Y=>ksr(Y,K)),...Uzr(B("entry-row"),a,K)]}]}function Msr(c,o,a){return c>=o?"":` (${a===void 0?String(c):mN(c,a)} shown)`}function RZt(c,o=1/0){return GAn(c.assessment,c.page).filter(a=>a.items.length>0).map(({count:a,noun:d,...p})=>{let y=Math.min(o,p.items.length);return{...p,title:`${p.title}: ${a??p.items.length}${Msr(y,p.items.length,d)}`,items:p.items.slice(0,y),more:eyt(y,p.items.length," (--format json lists them all)")}})}function Lsr(c,o){let a=c.assessment.totals,d=a.mutualHotSpot,p=c.assessment.deadFiles.flatMap(Re=>Re.files).filter(Re=>Re.confidence==="medium").length,y=d===void 0?"":` (hot spot: ${d.file} in ${d.pairs})`,E=c.assessment.deadFiles.flatMap(Re=>Re.files).filter(Re=>Re.via!==void 0).length,I=[p===0?"":`${p} only imported by tests`,E===0?"":`${E} only imported by dead files`].filter(Boolean).join(", "),B=I===""?"":` (${I})`,K=Hzr(c.assessment,o),Y=Object.entries(a.unusedExportsMediumByReason).sort(([Re,Ie],[Ne,bt])=>bt-Ie||Re.localeCompare(Ne)).map(([Re,Ie])=>`${Re} ${Ie}`).join(", "),ue=Y===""?"":` (by reason: ${Y})`,{focus:ie}=c;return[...ie===void 0?[]:[`Focus: ${ie} and its direct neighbours only (the files importing it or imported by it); the rules files cover the whole workspace`],ie===void 0?`Size: ${mN(a.files,"file")} in ${mN(a.units,"unit")}, ${mN(a.unitEdges,"unit edge")}`:`Size: ${mN(a.files,"file")} in ${ie}, ${mN(a.units,"unit")} with its neighbours, ${mN(a.unitEdges,"unit edge")} through it`,`Cycles: ${mN(a.unitCycles,"runtime unit cycle")}, ${mN(a.mutualImports,"runtime mutual file import")}${y}; type-only: ${mN(a.typeOnlyUnitCycles,"unit cycle")}, ${mN(a.typeOnlyMutualImports,"mutual file import")}; lazy: ${mN(a.lazyUnitCycles,"unit cycle")}, ${mN(a.lazyMutualImports,"mutual file import")}`,`Dead files: ${mN(a.deadFiles,"file")} no production file imports, ${mN(a.deadFileLines,"line")} with their tests${B}`,...Vzr(c.unresolvedImports),`Unused exports: ${a.unusedExports} high-confidence in ${mN(a.deadCodeFiles,"file")} listed; not listed: ${a.unusedExportsMedium} medium${ue}, graph-it check --minConfidence medium; ${a.unusedExportsLow} low, graph-it check --minConfidence low`,`Top action: ${K}`]}function Osr(c){return`Report: not written (dry run): ${c}; rerun without --dry-run to write index.html, report.md and the diagrams.`}function Vzr(c){let o=c===void 0?null:njt(c);return o===null?[]:[`Unresolved imports: ${o}`]}function Hzr(c,o){let a=c.deadFiles.flatMap(E=>E.files).find(E=>E.exports>0);if(a!==void 0)return`${a.confidence==="low"?"check, then delete":"delete"} ${a.relativePath} (dead file: ${a.lines===void 0?"lines unknown":mN(a.lines,"line")}, ${mN(a.exports,"export")}, ${a.confidence})`;let d=E=>!Object.hasOwn(Rsr,E.label),p=[...o.slice(1),o[0]].find(E=>E.items.some(d)),y=p?.items.find(d);return y===void 0?"none, nothing to clean up":`${y.subject} (${p.title.toLowerCase()}: ${y.label})`}function Fsr(c,o){return`Rules: ${o}: ${Fzr[c.status]}; the proposed baseline accepts ${mN(c.acceptedViolations,"current violation")}.`}function $zr(c,o){return c.find(a=>a.view==="folder"&&o.units.includes(a.unit??""))??c.find(a=>a.view===o.fallback)}function Kzr(c){return[` [${c.label}] ${c.subject}${c.note===void 0?"":": "+c.note}`,...c.details.map(o=>` ${o}`),...c.next===void 0?[]:[` next: ${c.next}`]]}function Bsr(c){let o=GAn(c.assessment),a=[Fsr(c,c.configFile),...c.written.map(p=>` wrote ${p}`),...c.configWarnings?.length?["Config warnings:",...c.configWarnings.map(p=>` ${p}`)]:[],...c.reportFiles.length===0?[]:[`Report: wrote ${c.reportFiles.join(", ")}`],...c.reportNotWritten===void 0?[]:[Osr(c.reportNotWritten)],"","Summary:",...Lsr(c,o).map(p=>` ${p}`)];for(let p of RZt(c,jAn))a.push("",p.title,...p.intro===void 0?[]:[` ${p.intro}`],...p.items.flatMap(Kzr),...p.more);let d=c.assessment.matrixGuide;if(a.push("","How to read the matrix:",...d.reading.map(p=>` ${p}`),...d.patterns.map(({pattern:p,meaning:y,action:E})=>` ${p}: ${y} ${E}`),"","Glossary:",...Object.entries(c.assessment.glossary).map(([p,y])=>` ${p}: ${y}`)),c.diagrams.length>0&&a.push("","Diagrams:",...c.diagrams.map(p=>` ${p.file}`)),c.changes.length>0){let p=Math.min(jAn,c.changes.length);a.push("",`Config changes: ${c.changes.length}${Msr(p,c.changes.length)}`,...c.changes.slice(0,p).map(y=>` ${y}`),...Bzr(c.changes.length))}return a.push("","Guard:",` pre-commit: ${c.guard.preCommit}`,` CI: ${c.guard.ci}`," Code scanning (SARIF):",...c.guard.sarif.split(`
47436
47436
  `).map(p=>` ${p}`)),a.join(`
@@ -47447,7 +47447,7 @@ Run "npm run build:cli" first.`,Au.GENERAL_ERROR);if(!process.stdin.isTTY)throw
47447
47447
  Add ${a} to your PATH if needed.`}function pGr(c,o){let a=$rt.dirname(o);WJ.mkdirSync(a,{recursive:!0});let d=`@echo off
47448
47448
  node "${c}" %*
47449
47449
  `,p=o.endsWith(".cmd")?o:o+".cmd";return WJ.writeFileSync(p,d,"utf-8"),`\u2713 graph-it installed to ${p}
47450
- Ensure ${a} is in your PATH.`}var WJ,$rt,MZt,ear,nar=Zi(()=>{"use strict";WJ=Ec(require("node:fs")),$rt=Ec(require("node:path")),MZt=Ec(require("node:os")),ear=Ec(require("node:readline"));cN()});var rar={};eA(rar,{run:()=>hGr});function mGr(c){let o=["install","--global",`${$An}@${c}`];try{(0,HAn.execFileSync)("npm",o,{stdio:"inherit"});return}catch(a){if(!(a?.code==="ENOENT"||a instanceof Error&&a.message.includes("spawnSync npm ENOENT")))throw a}(0,HAn.execFileSync)("npm.cmd",o,{stdio:"inherit"})}async function hGr(c,o,a){let d="1.25.5";process.stderr.write(`Current version : v${d}
47450
+ Ensure ${a} is in your PATH.`}var WJ,$rt,MZt,ear,nar=Zi(()=>{"use strict";WJ=Ec(require("node:fs")),$rt=Ec(require("node:path")),MZt=Ec(require("node:os")),ear=Ec(require("node:readline"));cN()});var rar={};eA(rar,{run:()=>hGr});function mGr(c){let o=["install","--global",`${$An}@${c}`];try{(0,HAn.execFileSync)("npm",o,{stdio:"inherit"});return}catch(a){if(!(a?.code==="ENOENT"||a instanceof Error&&a.message.includes("spawnSync npm ENOENT")))throw a}(0,HAn.execFileSync)("npm.cmd",o,{stdio:"inherit"})}async function hGr(c,o,a){let d="1.25.6";process.stderr.write(`Current version : v${d}
47451
47451
  `),process.stderr.write(`Checking npm registry for ${$An}\u2026
47452
47452
  `);let p;try{p=await oyn(1e4)}catch(y){let E=y instanceof Error?y.message:String(y);throw new Ku(E,Au.GENERAL_ERROR)}if(p===d)return`\u2713 Already up to date (v${d})`;process.stderr.write(`Latest version : v${p}
47453
47453
  Installing update\u2026
@@ -47456,7 +47456,7 @@ Installing update\u2026
47456
47456
  `),this.open=!1}async phase(o,a){if(!this.enabled||this.interrupted||this.current)return a(()=>{});let d="",p=Date.now(),y=()=>{let I=d||`\u2026 ${Math.floor((Date.now()-p)/1e3)}s`;this.redraw(` ${o}${I}`)},E={label:o,startedAt:p,timer:setInterval(y,1e3).unref()};this.current=E,y();try{let I=await a((B,K)=>{d=` ${B}/${K}`,this.current===E&&y()});return this.endPhase(E,`${d} (${rjt(Date.now()-p)})`),I}catch(I){throw this.endPhase(E,` failed after ${rjt(Date.now()-p)}`),I}}finish(){this.enabled&&!this.interrupted&&this.line(` Done in ${rjt(Date.now()-this.startedAt)}`)}interrupt(){this.interrupted=!0,this.current?this.endPhase(this.current,` interrupted after ${rjt(Date.now()-this.current.startedAt)}`):this.end()}end(){this.open&&(process.stderr.write(`
47457
47457
  `),this.open=!1)}endPhase(o,a){clearInterval(o.timer),this.current===o&&(this.current=void 0,this.line(` ${o.label}${a}`))}};var G3e=Ec(require("node:fs")),PVe=Ec(require("node:path"));var s3n=require("node:crypto"),ajt=Ec(require("node:fs")),Swt=Ec(require("node:path")),a3n=require("node:worker_threads");YL();var rVe=e1("AstWorkerHost"),Ent=class{worker=null;nextId=1;pendingRequests=new Map;workerPath;extensionPath;rootDir;isStopping=!1;isDisposed=!1;stopPromise=null;build;constructor(o,a,d){if(this.extensionPath=a,this.rootDir=d,o)this.workerPath=o;else{let p=[Swt.join(__dirname,"astWorker.js"),Swt.join(__dirname,"../../../dist/astWorker.js"),Swt.join(__dirname,"../../../../dist/astWorker.js"),Swt.join(process.cwd(),"dist/astWorker.js")],y="";for(let E of p)if(ajt.existsSync(E)){y=E;break}this.workerPath=y||Swt.join(process.cwd(),"dist/astWorker.js")}}buildId(){if(this.build===void 0)try{this.build=(0,s3n.createHash)("sha256").update(ajt.readFileSync(this.workerPath)).digest("hex")}catch{this.build="missing"}return this.build}async start(){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||this.isStopping){rVe.warn("AstWorker already started");return}rVe.info(`Starting AstWorker from ${this.workerPath}`);try{this.worker=new a3n.Worker(this.workerPath,{workerData:{extensionPath:this.extensionPath,rootDir:this.rootDir}}),this.worker.on("message",o=>{this.handleResponse(o)}),this.worker.on("error",o=>{rVe.error("AstWorker error:",o);for(let[a,d]of this.pendingRequests)d.reject(new Error(`AstWorker crashed: ${o.message}`)),this.pendingRequests.delete(a)}),this.worker.on("exit",o=>{o!==0&&!this.isStopping&&rVe.error(`AstWorker exited with code ${o}`),this.worker=null,this.stopPromise||(this.isStopping=!1)}),rVe.info("AstWorker started successfully")}catch(o){let a=o instanceof Error?o.message:String(o);throw rVe.error(`Failed to start AstWorker: ${a}`),new Error(`Failed to start AstWorker: ${a}`,{cause:o})}}stop(){if(this.isDisposed=!0,this.stopPromise)return this.stopPromise;let o=this.worker;if(!o)return Promise.resolve();rVe.debug("Stopping AstWorker");for(let[a,d]of this.pendingRequests)d.reject(new Error("AstWorker stopped")),this.pendingRequests.delete(a);return this.isStopping=!0,this.stopPromise=o.terminate().then(()=>{}).finally(()=>{this.worker===o&&(this.worker=null),this.isStopping=!1,this.stopPromise=null,rVe.debug("AstWorker stopped")}),this.stopPromise}async analyzeFile(o,a){return await this.sendRequest({type:"analyzeFile",id:0,filePath:o,content:a})}async getInternalExportDependencyGraph(o,a){let p=await this.sendRequest({type:"getInternalExportDeps",id:0,filePath:o,content:a});return new Map(Object.entries(p).map(([y,E])=>[y,new Set(E)]))}async extractSignatures(o,a){return await this.sendRequest({type:"extractSignatures",id:0,filePath:o,content:a})}async extractInterfaceMembers(o,a){let p=await this.sendRequest({type:"extractInterfaceMembers",id:0,filePath:o,content:a});return new Map(Object.entries(p))}async extractTypeAliases(o,a){return await this.sendRequest({type:"extractTypeAliases",id:0,filePath:o,content:a})}async compareSignatures(o,a){return await this.sendRequest({type:"compareSignatures",id:0,oldSig:o,newSig:a})}async analyzeBreakingChanges(o,a,d,p){return await this.sendRequest({type:"analyzeBreakingChanges",id:0,filePath:o,oldContent:a,newContent:d,symbolName:p})}async reset(){await this.sendRequest({type:"reset",id:0})}async getFileCount(){return await this.sendRequest({type:"getFileCount",id:0})}async sendRequest(o){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||await this.start(),this.isDisposed)throw new Error("AstWorker has been stopped");let a=this.nextId++,d={...o,id:a};return new Promise((p,y)=>{this.pendingRequests.set(a,{resolve:p,reject:y}),this.worker?.postMessage(d)})}handleResponse(o){let a=this.pendingRequests.get(o.id);if(!a){rVe.warn(`Received response for unknown request ${o.id}`);return}if(this.pendingRequests.delete(o.id),o.type==="success")a.resolve(o.result);else{let d=new Error(o.error);o.stack&&(d.stack=o.stack),a.reject(d)}}};Hpn();ngn();v3e();var ort=class{cache=new Map;maxSize;enableLRU;hits=0;misses=0;evictions=0;constructor(o={}){this.maxSize=o.maxSize??0,this.enableLRU=o.enableLRU??!0}get(o){let a=this.cache.get(o);if(a!==void 0)return this.hits++,this.enableLRU&&this.maxSize>0&&(this.cache.delete(o),this.cache.set(o,a)),a;this.misses++}set(o,a){this.cache.has(o)?this.cache.delete(o):this.maxSize>0&&this.cache.size>=this.maxSize&&this.evictOldest(),this.cache.set(o,a)}has(o){return this.cache.has(o)}clear(){this.cache.clear(),this.resetStats()}delete(o){return this.cache.delete(o)}get size(){return this.cache.size}getStats(){let o=this.hits+this.misses;return{hits:this.hits,misses:this.misses,evictions:this.evictions,size:this.cache.size,maxSize:this.maxSize,hitRate:o>0?this.hits/o:0}}resetStats(){this.hits=0,this.misses=0,this.evictions=0}keys(){return this.cache.keys()}entries(){return this.cache.entries()}evictOldest(){let o=this.cache.keys().next().value;o!==void 0&&(this.cache.delete(o),this.evictions++)}};tSe();YL();var sAr=e1("IndexerStatus"),jCt=class{_state="idle";_processed=0;_total=0;_currentFile;_startTime;_completedAt;_errorMessage;_cancelled=!1;_listeners=new Set;_lastNotifyTime=0;_notifyThrottleMs;constructor(o){this._notifyThrottleMs=o?.notifyThrottleMs??250}subscribe(o){return this._listeners.add(o),o(this.getSnapshot()),()=>this._listeners.delete(o)}getSnapshot(){let o=this._total>0?Math.round(this._processed/this._total*100):0,a;if(this._startTime&&this._processed>0&&this._total>0&&this._state==="indexing"){let p=(Date.now()-this._startTime)/this._processed,y=this._total-this._processed;a=Math.round(p*y)}return{state:this._state,processed:this._processed,total:this._total,currentFile:this._currentFile,percentage:o,startTime:this._startTime,estimatedTimeRemaining:a,completedAt:this._completedAt,errorMessage:this._errorMessage,cancelled:this._cancelled}}startCounting(){this._state="counting",this._processed=0,this._total=0,this._currentFile=void 0,this._startTime=Date.now(),this._errorMessage=void 0,this._cancelled=!1,this._notifyListeners(!0)}setTotal(o){this._total=o,this._notifyListeners(!0)}startIndexing(){this._state="indexing",this._startTime=Date.now(),this._notifyListeners(!0)}startValidating(){this._state="validating",this._notifyListeners(!0)}updateProgress(o,a){this._processed=o,this._currentFile=a,this._notifyListeners(!1)}complete(){this._state="complete",this._completedAt=Date.now(),this._currentFile=void 0,this._notifyListeners(!0)}setError(o){this._state="error",this._errorMessage=o,this._currentFile=void 0,this._notifyListeners(!0)}setCancelled(){this._cancelled=!0,this._state="idle",this._currentFile=void 0,this._notifyListeners(!0)}reset(){this._state="idle",this._processed=0,this._total=0,this._currentFile=void 0,this._startTime=void 0,this._completedAt=void 0,this._errorMessage=void 0,this._cancelled=!1,this._notifyListeners(!0)}isActive(){return this._state==="counting"||this._state==="indexing"||this._state==="validating"}isReady(){return this._state==="complete"}_notifyListeners(o){let a=Date.now();if(!o&&a-this._lastNotifyTime<this._notifyThrottleMs)return;this._lastNotifyTime=a;let d=this.getSnapshot();for(let p of this._listeners)try{p(d)}catch(y){sAr.error("Listener error:",y)}}get state(){return this._state}get total(){return this._total}get processed(){return this._processed}};a6t();W3();YL();B3();var WVn=e1("ReferencingFilesFinder"),qCt=class{sourceFileCollector;getRootDir;getConcurrency;findReferencesInFile;constructor(o){this.sourceFileCollector=o.sourceFileCollector,this.getRootDir=o.getRootDir,this.getConcurrency=o.getConcurrency,this.findReferencesInFile=o.findReferencesInFile}async findReferencingFilesFallback(o){return(await this.findReferencingFilesFallbackMany([o])).get(fr(o))??[]}async findReferencingFilesFallbackMany(o){let a=[...new Set(o.map(B=>fr(B)))],d=a.flatMap(B=>{let K=this.extractBasename(B);return K?[{path:B,basename:K}]:[]});if(!d.length)return new Map(a.map(B=>[B,[]]));WVn.debug("findReferencingFilesFallback for",d.map(B=>B.path).join(", "));let p=await this.sourceFileCollector.collectAllSourceFiles(this.getRootDir()),y=this.getConcurrency()??8,I=(await xv(p,y,B=>{let K=d.filter(Y=>Y.path!==fr(B));return K.length?this.findReferencesInFile(B,K):Promise.resolve([])})).flat();return WVn.debug("findReferencingFilesFallback found",I.length,"referencing files"),new Map(a.map(B=>[B,I.filter(({target:K})=>K===B).map(({dependency:K})=>K)]))}extractBasename(o){return o.split(/[/\\]/).pop()?.replace(/\.[^/.]+$/,"")}};var GVn=Ec(require("node:fs/promises")),c6t=Ec(require("node:path"));B3();W3();YL();var sCr=32,aCr=5,cCr=/[/\\.:]+/,jVn=e1("ReverseIndex"),Mgn=9,crt=class c{reverseMap=new Map;forwardMap=new Map;fileHashes=new Map;outOfRootImports=new Map;unresolvedImports=new Map;rootDir;constructor(o){this.rootDir=fr(o)}addDependencies(o,a,d,p,y){let E=fr(o),I=p??this.outOfRootImports.get(E),B=y??this.unresolvedImports.get(E);this.removeDependenciesFromSource(E),I&&I.length>0&&this.outOfRootImports.set(E,I),B&&B.length>0&&this.unresolvedImports.set(E,B);for(let K of a){let Y=fr(K.path);this.addForwardEntry(E,Y);let ue={sourcePath:E,type:K.type,line:K.line,module:K.module,...K.typeOnly?{typeOnly:!0}:{}},ie=this.reverseMap.get(Y);ie||(ie=new Map,this.reverseMap.set(Y,ie)),ie.set(E,ue)}d&&this.fileHashes.set(E,d)}removeDependenciesFromSource(o){let a=fr(o);for(let d of this.forwardMap.get(a)??[])this.reverseMap.get(d)?.delete(a);this.forwardMap.delete(a),this.fileHashes.delete(a),this.outOfRootImports.delete(a),this.unresolvedImports.delete(a)}getReferencingFiles(o){let a=fr(o),d=this.reverseMap.get(a);return d?.size===0?(this.reverseMap.delete(a),[]):d?Array.from(d.values()).map(p=>({path:p.sourcePath,type:p.type,line:p.line,module:p.module,...p.typeOnly?{typeOnly:!0}:{}})):[]}getCallerCount(o){let a=fr(o);return this.reverseMap.get(a)?.size??0}isFileStale(o,a){let d=fr(o),p=this.fileHashes.get(d);return p?p.mtime!==a.mtime||p.size!==a.size:!0}async getFreshDependencies(o){let a=fr(o);if(!this.fileHashes.has(a))return;let d=await c.getFileHashFromDisk(o);if(!d||this.isFileStale(a,d))return;let p=[];for(let y of this.forwardMap.get(a)??[]){let E=this.reverseMap.get(y)?.get(a);E&&p.push({path:y,type:E.type,line:E.line,module:E.module,...E.typeOnly?{typeOnly:!0}:{}})}return p.sort((y,E)=>y.line-E.line),p}getFileHash(o){return this.fileHashes.get(fr(o))}updateFileHash(o,a){this.fileHashes.set(fr(o),a)}hasEntries(){return this.reverseMap.size>0||this.fileHashes.size>0}hasFile(o){return this.fileHashes.has(fr(o))}getIndexedFiles(){return[...this.fileHashes.keys()]}get indexedFileCount(){return this.fileHashes.size}get targetFileCount(){return this.reverseMap.size}clear(){this.reverseMap.clear(),this.forwardMap.clear(),this.fileHashes.clear(),this.outOfRootImports.clear(),this.unresolvedImports.clear()}getEmptyMapCount(){let o=0;for(let a of this.reverseMap.values())a.size===0&&o++;return o}static async getFileHashFromDisk(o){try{let a=await GVn.stat(o);return{mtime:a.mtimeMs,size:a.size}}catch{return null}}serialize(){let o={};for(let[d,p]of this.reverseMap)p.size!==0&&(o[d]=Array.from(p.values()));let a={};for(let[d,p]of this.fileHashes)a[d]=p;return{version:Mgn,timestamp:Date.now(),rootDir:this.rootDir,reverseMap:o,fileHashes:a,outOfRootImports:Object.fromEntries(this.outOfRootImports),unresolvedImports:Object.fromEntries(this.unresolvedImports)}}static deserialize(o,a){let d=fr(a),p=fr(o.rootDir);if(o.version!==Mgn)return jVn.warn("Version mismatch:",o.version,"!==",Mgn),null;if(p!==d)return jVn.warn("Root dir mismatch:",o.rootDir,"!==",a),null;let y=new c(a);for(let[E,I]of Object.entries(o.fileHashes))y.fileHashes.set(fr(E),I);zVn(o.outOfRootImports,y.outOfRootImports),zVn(o.unresolvedImports,y.unresolvedImports);for(let[E,I]of Object.entries(o.reverseMap)){let B=fr(E),K=new Map;for(let Y of I){let ue=fr(Y.sourcePath);K.set(ue,{...Y,sourcePath:ue}),y.addForwardEntry(ue,B)}y.reverseMap.set(B,K)}return y}async validateIndex(o=.2,a,d){let p=[],y=[],E=d?[...new Set(d.map(fr))]:[...this.fileHashes.keys()],I=await xv(E,sCr,ie=>c.getFileHashFromDisk(ie));for(let[ie,Re]of E.entries()){let Ie=I[ie];if(!Ie){this.fileHashes.has(Re)&&y.push(Re);continue}(!this.fileHashes.has(Re)||this.isFileStale(Re,Ie))&&p.push(Re)}let B=a?this.addUnindexedFiles(a,p):0;this.addImportersOfDeleted(y,p);let K=(d?E.length:this.fileHashes.size)+B,Y=p.length+y.length,ue=K>0?Y/K:0;return{isValid:ue<=o,staleFiles:p,stalePercentage:ue,missingFiles:y}}addForwardEntry(o,a){let d=this.forwardMap.get(o);d||(d=new Set,this.forwardMap.set(o,d)),d.add(a)}addImportersOfDeleted(o,a){let d=new Set([...o,...a]);for(let p of o)for(let y of this.reverseMap.get(p)?.keys()??[])d.has(y)||(d.add(y),a.push(y))}addUnindexedFiles(o,a){let d=new Set(a),p=E=>{d.has(E)||(d.add(E),a.push(E))},y=0;for(let E of o){let I=fr(E);if(!this.fileHashes.has(I)&&!d.has(I)){p(I),y++;for(let B of this.getUnresolvedImportersOf(I))p(B)}}return y}getStats(){let o=0;for(let a of this.reverseMap.values())o+=a.size;return{indexedFiles:this.fileHashes.size,targetFiles:this.reverseMap.size,totalReferences:o}}getOutOfRootImports(){let o=0,a=new Set;for(let d of this.outOfRootImports.values()){o+=d.length;for(let p of d)a.add(p)}return{count:o,examples:[...a].sort((d,p)=>d.localeCompare(p)).slice(0,aCr)}}getUnindexedTargets(){let o=[];for(let[a,d]of this.reverseMap)if(!this.fileHashes.has(a))for(let[p,y]of d)o.push({sourcePath:p,specifier:y.module,targetPath:a});return o}getUnresolvedImports(){return[...this.unresolvedImports].flatMap(([o,a])=>a.map(d=>({sourcePath:o,specifier:d})))}getUnresolvedImportersOf(o){let a=fr(o),d=new Set([c6t.basename(a).split(".")[0],c6t.basename(c6t.dirname(a))].filter(y=>y!=="").map(y=>y.toLowerCase())),p=[];for(let[y,E]of this.unresolvedImports)y!==a&&E.some(I=>I.split(cCr).some(B=>d.has(B.toLowerCase())))&&p.push(y);return p}};function zVn(c,o){for(let[a,d]of Object.entries(c??{}))Array.isArray(d)&&o.set(fr(a),d.filter(p=>typeof p=="string"))}var XCt=Ec(require("node:fs/promises")),VVn=Ec(require("node:path"));B3();var UVn=1,KJt=class{reverseMap=new Map;forwardMap=new Map;fileHashes=new Map;rootDir;lastUpdated=0;constructor(o){this.rootDir=fr(o)}addDependencies(o,a,d){let p=fr(o);this.removeDependenciesFromSource(p);for(let y of a){let E={callerSymbolId:y.sourceSymbolId,callerFilePath:p,isTypeOnly:y.isTypeOnly??!1},I=this.reverseMap.get(y.targetSymbolId);I||(I=new Map,this.reverseMap.set(y.targetSymbolId,I)),I.set(y.sourceSymbolId,E),this.addForwardEntry(p,y.targetSymbolId,y.sourceSymbolId)}d&&this.fileHashes.set(p,d),this.lastUpdated=Date.now()}removeDependenciesFromSource(o){let a=fr(o);for(let[d,p]of this.forwardMap.get(a)??[]){let y=this.reverseMap.get(d);y?.get(p)?.callerFilePath===a&&y.delete(p)}this.forwardMap.delete(a),this.fileHashes.delete(a),this.lastUpdated=Date.now()}getCallers(o){let a=this.reverseMap.get(o);return a?.size===0?(this.reverseMap.delete(o),[]):a?Array.from(a.values()):[]}getCallersFiltered(o,a=!0){let d=this.getCallers(o);return a?d:d.filter(p=>!p.isTypeOnly)}getRuntimeCallers(o){return this.getCallersFiltered(o,!1)}getTypeOnlyCallers(o){return this.getCallers(o).filter(a=>a.isTypeOnly)}hasCallers(o){let a=this.reverseMap.get(o);return a!==void 0&&a.size>0}getCallerCount(o){return this.reverseMap.get(o)?.size??0}getCallerFiles(o){let a=this.getCallers(o),d=new Set;for(let p of a)d.add(p.callerFilePath);return Array.from(d)}getStats(){let o=0;for(let a of this.reverseMap.values())o+=a.size;return{targetSymbolCount:this.reverseMap.size,totalCallerCount:o,sourceFileCount:this.fileHashes.size,lastUpdated:this.lastUpdated}}isFileStale(o,a){let d=fr(o),p=this.fileHashes.get(d);return p?p.mtime!==a.mtime||p.size!==a.size:!0}clear(){this.reverseMap.clear(),this.forwardMap.clear(),this.fileHashes.clear(),this.lastUpdated=Date.now()}cleanup(){let o=0,a=[];for(let[d,p]of this.reverseMap)p.size===0&&a.push(d);for(let d of a)this.reverseMap.delete(d),o++;return o}serialize(){let o={};for(let[d,p]of this.reverseMap)o[d]=Array.from(p.values());let a={};for(let[d,p]of this.fileHashes)a[d]=p;return{version:UVn,timestamp:Date.now(),rootDir:this.rootDir,reverseMap:o,fileHashes:a}}deserialize(o){if(o.version!==UVn||fr(o.rootDir)!==this.rootDir)return!1;this.clear();for(let[a,d]of Object.entries(o.reverseMap)){let p=new Map;for(let y of d){let E=fr(y.callerFilePath);p.set(y.callerSymbolId,{...y,callerFilePath:E}),this.addForwardEntry(E,a,y.callerSymbolId)}this.reverseMap.set(a,p)}for(let[a,d]of Object.entries(o.fileHashes))this.fileHashes.set(a,d);return this.lastUpdated=o.timestamp,!0}addForwardEntry(o,a,d){let p=this.forwardMap.get(o);p||(p=[],this.forwardMap.set(o,p)),p.push([a,d])}async saveToFile(o){let a=this.serialize(),d=JSON.stringify(a,null,2);await XCt.mkdir(VVn.dirname(o),{recursive:!0}),await XCt.writeFile(o,d,"utf-8")}async loadFromFile(o){try{let a=await XCt.readFile(o,"utf-8"),d=JSON.parse(a);return this.deserialize(d)}catch{return!1}}};var QCt=class{constructor(o){this.rootDir=o}rootDir;reverseIndex=null;symbolReverseIndex=null;enable(o){let a=!1;if(this.reverseIndex??=new crt(this.rootDir),this.symbolReverseIndex??=new KJt(this.rootDir),o)try{let d=JSON.parse(o),p=crt.deserialize(d,this.rootDir);p&&(this.reverseIndex=p,a=!0)}catch{a=!1}return a}disable(){this.reverseIndex?.clear(),this.reverseIndex=null,this.symbolReverseIndex?.clear(),this.symbolReverseIndex=null}clear(){this.reverseIndex?.clear(),this.symbolReverseIndex?.clear()}isEnabled(){return this.reverseIndex!==null}hasEntries(){return this.reverseIndex?.hasEntries()??!1}ensure(){this.reverseIndex??=new crt(this.rootDir)}addDependencies(o,a,d,p,y){this.reverseIndex?.addDependencies(o,a,d,p,y)}removeDependenciesFromSource(o){this.reverseIndex?.removeDependenciesFromSource(o)}getReferencingFiles(o){return this.reverseIndex?this.reverseIndex.getReferencingFiles(o):[]}async getFreshDependencies(o){return this.reverseIndex?.getFreshDependencies(o)}getUnresolvedImportersOf(o){return this.reverseIndex?.getUnresolvedImportersOf(o)??[]}getUnindexedTargets(){return this.reverseIndex?.getUnindexedTargets()??[]}getUnresolvedImports(){return this.reverseIndex?.getUnresolvedImports()??null}getIndexedFiles(){return this.reverseIndex?.getIndexedFiles()??[]}getCallerCount(o){return this.reverseIndex?this.reverseIndex.getCallerCount(o):0}getSerialized(){return this.reverseIndex?JSON.stringify(this.reverseIndex.serialize()):null}validate(o=.2,a,d){return this.reverseIndex?.validateIndex(o,a,d)??null}getStats(){return this.reverseIndex?.getStats()}getOutOfRootImports(){return this.reverseIndex?.getOutOfRootImports()??null}addSymbolDependencies(o,a,d){this.symbolReverseIndex?.addDependencies(o,a,d)}removeSymbolDependenciesFromSource(o){this.symbolReverseIndex?.removeDependenciesFromSource(o)}getSymbolReferencingFiles(o){return this.symbolReverseIndex?.getCallerFiles(o)??[]}getSymbolStats(){return this.symbolReverseIndex?.getStats()}};v3e();var r$n=Ec(require("node:fs/promises")),i$n=Ec(require("node:path"));zpn();tSe();a6t();v3e();wnt();Wpn();B3();var YCt=class{constructor(o,a,d){this.dependencyCache=o;this.symbolCache=a;this.reverseIndexManager=d}dependencyCache;symbolCache;reverseIndexManager;clearAll(){this.dependencyCache.clear(),this.symbolCache.clear(),this.reverseIndexManager.clear()}invalidateFile(o){let a=fr(o),d=this.dependencyCache.has(a);return this.dependencyCache.delete(a),this.symbolCache.delete(a),this.reverseIndexManager.removeDependenciesFromSource(a),d}invalidateFiles(o){let a=0;for(let d of o)this.invalidateFile(d)&&a++;return a}handleFileDeleted(o){let a=fr(o);this.dependencyCache.delete(a),this.symbolCache.delete(a),this.reverseIndexManager.removeDependenciesFromSource(a)}};n3t();B3();YL();var ZCt=e1("SpiderDependencyAnalyzer"),eIt=class{constructor(o,a,d,p){this.languageService=o;this.resolver=a;this.dependencyCache=d;this.reverseIndexManager=p}languageService;resolver;dependencyCache;reverseIndexManager;async analyze(o){let a=fr(o),d=this.dependencyCache.get(a);if(d)return ZCt.debug(`Returning ${d.length} cached dependencies for ${o}`),await this.updateReverseIndexIfEnabled(o,a,d),d;ZCt.debug(`Analyzing ${o}...`);try{let p=this.languageService.getAnalyzer(o),y=await p.parseImports(o);ZCt.debug(`Parsed ${y.length} imports from ${o}`);let{dependencies:E,outOfRootImports:I,unresolvedImports:B}=await l$t(p,o,y,K=>this.resolver.isWithinWorkspace(K));return ZCt.debug(`Resolved ${E.length} dependencies for ${o}`),this.dependencyCache.set(a,E),await this.updateReverseIndexIfEnabled(o,a,E,I,B),E}catch(p){let y=_E.fromError(p,o);if(y.code==="FILE_TOO_LARGE"||y.code==="TIMEOUT")return ZCt.warn(`Skipping ${o}: ${y.toUserMessage()}`),[];throw ZCt.error("Analysis failed:",y.toUserMessage(),y.code),y}}async analyzeFromIndex(o){return await this.reverseIndexManager.getFreshDependencies(o)??this.analyze(o)}async resolveModuleSpecifier(o,a){try{return await this.resolver.resolve(o,a)}catch{return null}}invalidateDependencyCache(o){this.dependencyCache.delete(fr(o))}async updateReverseIndexIfEnabled(o,a,d,p,y){if(!this.reverseIndexManager.isEnabled())return;let E=await crt.getFileHashFromDisk(o);E&&this.reverseIndexManager.addDependencies(a,d,E,p,y)}};JJt();var nIt=class{cancelled=!1;reset(){this.cancelled=!1}cancel(){this.cancelled=!0}isCancelled(){return this.cancelled}};W3();YL();B3();function rIt(){return new Promise(c=>setTimeout(c,1))}var iIt=50;var lgt=e1("SpiderIndexingService"),oIt=class{constructor(o,a,d,p,y,E,I,B,K,Y){this.dependencyAnalyzer=o;this.dependencyCache=a;this.reverseIndexManager=d;this.sourceFileCollector=p;this.indexerStatus=y;this.workerManager=E;this.cancellation=I;this.getConfig=B;this.yieldToEventLoop=K;this.getSymbolGraph=Y}dependencyAnalyzer;dependencyCache;reverseIndexManager;sourceFileCollector;indexerStatus;workerManager;cancellation;getConfig;yieldToEventLoop;getSymbolGraph;cancel(){this.cancellation.cancel(),this.workerManager.cancel()}async disposeWorker(){await this.workerManager.dispose()}async analyzeFileForIndex(o,a){let d=await this.dependencyAnalyzer.analyze(o).then(()=>!0,()=>!1),p=this.getSymbolGraph;return!d||!p||a>=(this.getConfig().maxSymbolAnalyzerFiles??100)?d:this.addSymbolDependencies(o,p)}async addSymbolDependencies(o,a){try{let d=await a(o);d.dependencies.length>0&&this.reverseIndexManager.addSymbolDependencies(o,d.dependencies)}catch{}return!0}checkCancellation(o){if(this.cancellation.isCancelled())return this.indexerStatus.setCancelled(),{indexedFiles:o,duration:Date.now()-(this.indexerStatus.getSnapshot().startTime??Date.now()),cancelled:!0}}async buildFullIndex(o){this.reverseIndexManager.ensure(),this.cancellation.reset(),this.indexerStatus.startCounting();let a=await this.sourceFileCollector.collectAllSourceFiles(this.getConfig().rootDir),d=this.checkCancellation(0);if(d)return d;let p=a.length;this.indexerStatus.setTotal(p),await this.yieldToEventLoop(),this.indexerStatus.startIndexing();let y=0,E=!1,I=Date.now();try{await xv(a,this.getConfig().indexingConcurrency??8,async(ue,ie)=>{if(E||this.cancellation.isCancelled()){E=!0;return}await this.analyzeFileForIndex(ue,ie),y++,this.indexerStatus.updateProgress(y,ue),o?.(y,p,ue),Date.now()-I>=iIt&&(I=Date.now(),await this.yieldToEventLoop())});let B=E?this.checkCancellation(y):void 0;if(B)return B;this.indexerStatus.complete();let K=this.indexerStatus.getSnapshot(),Y=Date.now()-(K.startTime??Date.now());return{indexedFiles:y,duration:Y,cancelled:!1}}catch(B){let K=_E.fromError(B);throw this.indexerStatus.setError(K.toUserMessage()),lgt.error("Indexing failed:",K.toUserMessage(),K.code),K}}async buildFullIndexInWorker(o,a){this.cancellation.reset();let d=this.getConfig();return this.workerManager.buildFullIndexInWorker({workerPath:o,progressCallback:a,config:{rootDir:d.rootDir,excludeNodeModules:d.excludeNodeModules,tsConfigPath:d.tsConfigPath,progressInterval:d.indexingProgressInterval,extensionPath:d.extensionPath,ignoreTypeImports:d.ignoreTypeImports}})}async reindexStaleFiles(o,a){if(!this.reverseIndexManager.isEnabled())return 0;this.cancellation.reset(),lgt.info(`Re-indexing ${o.length} stale files`),this.indexerStatus.startCounting(),this.indexerStatus.setTotal(o.length),this.indexerStatus.startIndexing();let d=this.getConfig().indexingConcurrency??8,p=0;return await xv(o,d,async y=>{if(this.cancellation.isCancelled())return;let E=fr(y);lgt.debug(`Re-indexing stale file: ${y}`);try{this.reverseIndexManager.removeDependenciesFromSource(E),this.dependencyCache.delete(E),lgt.debug(`Deleted cache for ${y}, re-analyzing...`),await this.dependencyAnalyzer.analyze(y),lgt.debug(`Successfully re-analyzed ${y}`)}catch(I){lgt.error(`Failed to re-index ${y}:`,I),this.reverseIndexManager.removeDependenciesFromSource(E)}p++,this.indexerStatus.updateProgress(p,y),a?.(p,o.length,y),p%d===0&&await this.yieldToEventLoop()}),this.cancellation.isCancelled()?(this.indexerStatus.setCancelled(),p):(this.indexerStatus.complete(),lgt.info(`Completed re-indexing ${p} files`),p)}};B3();var sIt=class{constructor(o,a,d,p=()=>!0,y=()=>!1){this.reverseIndexManager=o;this.dependencyAnalyzer=a;this.fileReader=d;this.isIndexReady=p;this.isIndexingActive=y}reverseIndexManager;dependencyAnalyzer;fileReader;isIndexReady;isIndexingActive;fallbackFinder=null;_fallbackCache=new Map;_fallbackCacheVersion=0;_fallbackCacheEntryVersion=new Map;setFallbackFinder(o){this.fallbackFinder=o}clearFallbackCache(){this._fallbackCacheVersion++}async findReferencingFiles(o){let a=fr(o),d=this.reverseIndexManager.hasEntries();if(d&&this.isIndexReady())return this.reverseIndexManager.getReferencingFiles(a);let p=d?this.reverseIndexManager.getReferencingFiles(a):[];if(d&&!this.isIndexingActive()||!this.fallbackFinder)return p;let y=await this.getFallbackReferencingFiles(a);return p.length===0?y:y.length===0?p:this.mergeDependencies(p,y)}async findReferencingFilesWithFallback(o){return(await this.findManyReferencingFilesWithFallback([o])).get(fr(o))??[]}async findManyReferencingFilesWithFallback(o){this.clearFallbackCache();let a=[...new Set(o.map(p=>fr(p)))],d=await this.fallbackFinder?.findReferencingFilesFallbackMany(a);return new Map(a.map(p=>{let y=this.reverseIndexManager.hasEntries()?this.reverseIndexManager.getReferencingFiles(p):[],E=d?.get(p)??[];return d&&(this._fallbackCache.set(p,E),this._fallbackCacheEntryVersion.set(p,this._fallbackCacheVersion)),[p,this.mergeDependencies(y,E)]}))}async getFallbackReferencingFiles(o){if(!this.fallbackFinder)return[];if(this._fallbackCacheEntryVersion.get(o)===this._fallbackCacheVersion){let p=this._fallbackCache.get(o);if(p!==void 0)return p}let d=await this.fallbackFinder.findReferencingFilesFallback(o);return this._fallbackCache.set(o,d),this._fallbackCacheEntryVersion.set(o,this._fallbackCacheVersion),d}mergeDependencies(o,a){let d=new Map;for(let p of[...o,...a]){let y=fr(p.path);d.has(y)||d.set(y,p)}return[...d.values()]}async findReferencesInFile(o,a){try{let d=await this.fileReader.readFile(o),p=a.filter(E=>d.includes(E.basename));if(p.length===0)return[];this.dependencyAnalyzer.invalidateDependencyCache(o);let y=await this.dependencyAnalyzer.analyze(o);return p.flatMap(({path:E})=>{let I=y.find(B=>fr(B.path)===E);return I?[{target:E,dependency:{path:fr(o),type:I.type,line:I.line,module:I.module}}]:[]})}catch{return[]}}};var QHn=Ec(require("node:fs/promises")),DVe=Ec(require("node:path")),YHn=require("node:timers/promises");W3();Jce();YL();v3e();wnt();B3();UCt();lgn();fVe();igt();xJt();ogt();Pp();urt();eqt();var Ygn=Ec(require("node:fs/promises")),BM=Ec(require("node:path"));W3();Pp();v3e();wnt();n$t();var l6t=Ec(require("node:path")),MHn="convention:framework-route",s7="[cm]?[jt]sx?",tqt=c=>`^(?:${c}/)?`,IVe="^(?:layers/[^/]+/)?",uIr="page|layout|template|loading|error|global-error|global-not-found|not-found|forbidden|unauthorized|default|route|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest",LHn=[{uses:c=>c==="next",files:[new RegExp(String.raw`${tqt("src")}app/(?:.+/)?(?:${uIr})\.${s7}$`),new RegExp(String.raw`${tqt("src")}pages/.+\.${s7}$`),new RegExp(String.raw`${tqt("src")}(?:middleware|proxy|instrumentation|instrumentation-client)\.${s7}$`)]},{uses:c=>c==="@sveltejs/kit",files:[new RegExp(String.raw`^src/routes/(?:.+/)?\+(?:page|layout|server|error)(?:\.server)?(?:@[^/]*)?\.(?:svelte|${s7})$`),new RegExp(String.raw`^src/(?:hooks(?:\.server|\.client)?|service-worker|instrumentation\.server|env)\.${s7}$`),new RegExp(String.raw`^src/params/[^/]+\.${s7}$`)]},{uses:c=>c.startsWith("@remix-run/")||c==="@react-router/dev",files:[new RegExp(String.raw`^app/routes/.+\.${s7}$`),new RegExp(String.raw`^app/(?:root|routes|entry\.client|entry\.server)\.${s7}$`)]},{uses:c=>c==="nuxt",files:[new RegExp(String.raw`${IVe}(?:app/)?(?:pages|layouts|middleware|plugins|components|composables|utils)/.+\.(?:vue|${s7})$`),new RegExp(String.raw`${IVe}(?:app/)?(?:app|error)\.vue$`),new RegExp(String.raw`${IVe}(?:app/)?router\.options\.${s7}$`),new RegExp(String.raw`${IVe}modules/[^/]+(?:/index)?\.${s7}$`),new RegExp(String.raw`${IVe}server/(?:api|routes|middleware|plugins|utils|tasks)/.+\.${s7}$`),new RegExp(String.raw`${IVe}shared/(?:utils|types)/.+\.${s7}$`)]},{uses:c=>c==="@nuxtjs/mcp-toolkit",files:[new RegExp(String.raw`${IVe}server/mcp/.+\.${s7}$`)]},{uses:c=>c==="nuxt-workers",files:[new RegExp(String.raw`${IVe}(?:app/)?workers/[^/]+\.${s7}$`)]},{uses:c=>c==="eve",files:[new RegExp(String.raw`${IVe}agent/.+\.${s7}$`)]},{uses:c=>c==="astro",files:[new RegExp(String.raw`^src/pages/.+\.${s7}$`),new RegExp(String.raw`^src/(?:middleware|content/config|content\.config|actions/index)\.${s7}$`)]},{uses:c=>c==="expo-router",files:[new RegExp(String.raw`${tqt("src")}app/.+\.${s7}$`)]},{uses:c=>c==="gatsby",files:[new RegExp(String.raw`^src/(?:pages|api)/.+\.${s7}$`),new RegExp(String.raw`^gatsby-(?:node|browser|ssr)\.${s7}$`)]},{uses:c=>c==="storybook"||c.startsWith("@storybook/"),files:[new RegExp(String.raw`(?:^|/)[^/]+\.stories\.${s7}$`)]}];function OHn(c){let o;try{o=JSON.parse(c)}catch{return[]}if(typeof o!="object"||o===null)return[];let a=["dependencies","devDependencies","peerDependencies","optionalDependencies"].flatMap(d=>{let p=o[d];return typeof p=="object"&&p!==null?Object.keys(p):[]});return LHn.flatMap((d,p)=>a.some(d.uses)?[p]:[])}function FHn(c,o){for(let a=l6t.default.posix.dirname(c);;a=l6t.default.posix.dirname(a)){let d=l6t.default.posix.relative(a,c);if((o.get(a)??[]).some(y=>LHn[y].files.some(E=>E.test(d))))return!0;if(l6t.default.posix.dirname(a)===a)return!1}}z3e();Jce();YL();urt();eqt();var _Ir=e1("DeadCodeTextIndex"),gIr=16,yIr=/\.rs$/i,vIr=/\.pyi?$/i,$Hn=/\.(?:[cm]?[jt]sx?|vue|svelte)$/i,bIr=/\.ya?ml$/i,UHn=/\.html?$/i,SIr=[/^\.?(?:eslint|prettier|stylelint)(?:rc|\.config)(?:\.\w+)*$/i,/^\.markdownlint(?:-cli2|rc)?(?:\.\w+)*$/i,/^biome\.jsonc?$/i],VHn={loads:[],rustPaths:[],rustTokens:[],readsComputedAttribute:!1,pythonAll:[],rustPubMods:[],rustAttributed:[],deployRefs:[],deepSpecifiers:[],writtenPaths:[],workingDirs:[],globs:[],urls:[],nameTemplates:[]},rqt=class{constructor(o){this.fileReader=o}fileReader;rootDir="";perFile=new Map;async collect(o,a){let d=fr(BM.default.resolve(o));d!==this.rootDir&&(this.rootDir=d,this.perFile=new Map);let p=Ie=>Ugn.has(Ie),y=new kW({excludeNodeModules:a}),E=(await y.collectFiles(o,Ie=>Cwt(Ie)||p(Ie)||Fgn(Ie)||rHn(Ie)||UHn.test(Ie))).map(fr),I=new Set((await Promise.all(iHn.map(Ie=>y.collectFiles(BM.default.join(o,Ie),Ne=>bIr.test(Ne))))).flat().map(fr)),B=new Map;await xv([...E,...I],gIr,async Ie=>{let Ne=await this.factsOf(Ie,p(BM.default.posix.basename(Ie)),I.has(Ie));Ne&&B.set(Ie,Ne)}),this.perFile=B;let K=E.filter(Ie=>Cwt(Ie)),Y=E.filter(Ie=>BM.default.posix.basename(Ie)==="package.json").map(Ie=>BM.default.posix.dirname(Ie)),ue=K.flatMap(Ie=>B.get(Ie)??[]),ie=new Set(K.filter(Ie=>B.get(Ie)?.readsComputedAttribute)),Re=new Map;for(let Ie of ue.flatMap(Ne=>Ne.rustTokens))Re.set(Ie,(Re.get(Ie)??0)+1);return{loads:ue.flatMap(Ie=>Ie.loads),rustPaths:new Set(ue.flatMap(Ie=>Ie.rustPaths)),rustTokenFiles:Re,computedAttributeReaders:ie,entryPoints:await this.entryPoints(d,K,B),packageDeepImport:IIr(B,new Set(ue.flatMap(Ie=>Ie.deepSpecifiers))),namedPaths:xIr(d,B,K,Y,EIr(d,B,new Set(K))),frameworksByPackage:new Map(Y.map(Ie=>[Ie,OHn(B.get(`${Ie}/package.json`)?.manifestText??"")]))}}async entryPoints(o,a,d){let p=await Promise.all([...d].filter(([,B])=>B.manifestText!==void 0).map(async([B,K])=>({file:B,text:K.manifestText??"",...BM.default.posix.basename(B)==="package.json"?{layout:await kIr(BM.default.posix.dirname(B))}:{}}))),y=B=>{let K=new Map;for(let Y of a){let ue=d.get(Y),ie=ue?B(ue):[];ie.length>0&&K.set(Y,ie)}return K},{entryPoints:E,warnings:I}=SHn({rootDir:o,files:new Set(a),manifests:p,pythonAll:y(B=>B.pythonAll),rustPubMods:y(B=>B.rustPubMods),rustAttributed:y(B=>B.rustAttributed),deployRefs:new Map([...d].filter(([,B])=>B.deployRefs.length>0).map(([B,K])=>[B,K.deployRefs]))});for(let B of I)_Ir.warn(`Dead-code scan: ${B}`);return E}async factsOf(o,a,d){try{let{mtimeMs:p,size:y}=await Ygn.default.stat(o),E=this.perFile.get(o);if(E?.mtimeMs===p&&E.size===y)return E;let I=await this.fileReader.readFile(o,{maxSize:Number.POSITIVE_INFINITY});return{mtimeMs:p,size:y,...this.contentFacts(o,I,a,d)}}catch{return null}}contentFacts(o,a,d,p){let y=CVe(BD(o,this.rootDir));if(p)return{...VHn,...HHn(a)};if(UHn.test(o))return{...VHn,writtenPaths:y?[]:lHn(a)};let E=QVn(a)?qVn(o,BD(o,this.rootDir),a,this.rootDir):[],I=yIr.test(o);return{loads:E,rustPaths:I?eHn(a):[],rustTokens:I?[...new Set(a.match(/\b[A-Za-z_]\w*\b/g))]:[],readsComputedAttribute:vIr.test(o)&&nHn(a),...d?{manifestText:a}:{},pythonAll:BM.default.posix.basename(o)==="__init__.py"?PHn(a):[],rustPubMods:I?DHn(a):[],rustAttributed:I?kHn(a):[],deployRefs:Fgn(BM.default.posix.basename(o))?oHn(a):[],deepSpecifiers:$Hn.test(o)?AHn(a):[],...TIr(o,a,y),...y||SIr.some(B=>B.test(BM.default.posix.basename(o)))?{writtenPaths:[],workingDirs:[]}:HHn(a)}}};function TIr(c,o,a){if(a||!$Hn.test(c))return{globs:[],urls:[],nameTemplates:[]};let d=o.includes("import.meta.");return{globs:d?cHn(o):[],urls:d?aHn(o):[],nameTemplates:o.includes("${")?uHn(o):[]}}function HHn(c){let o=Wgn(c);return{writtenPaths:o,workingDirs:o.length>0?fHn(c):[]}}function EIr(c,o,a){let d=new Map;for(let[p,y]of o){let E=[c,BM.default.posix.dirname(p)],I=[...E,...y.workingDirs.flatMap(B=>E.map(K=>BM.default.posix.join(K,B)))];for(let B of y.writtenPaths)for(let K of I){let Y=fr(BM.default.resolve(K,B));Y!==p&&a.has(Y)&&!d.has(Y)&&d.set(Y,BD(p,c))}}return d}function xIr(c,o,a,d,p){let y=new Set(a),E=I=>d.filter(B=>I.startsWith(`${B}/`)).sort((B,K)=>K.length-B.length)[0]??c;for(let[I,B]of o){if(B.globs.length===0&&B.urls.length===0&&B.nameTemplates.length===0)continue;let K=[...B.globs.flatMap(Y=>AIr(Y,I,E(I),a)),...B.urls.flatMap(Y=>CIr(Y,I,y)??[]),...wIr(B.nameTemplates,E(I),a)];for(let Y of K)Y!==I&&!p.has(Y)&&p.set(Y,BD(I,c))}return p}function AIr(c,o,a,d){let p=c.base?BM.default.posix.join(BM.default.posix.dirname(o),c.base):BM.default.posix.dirname(o),y=(B,K="")=>jgn(B).flatMap(Y=>{if(!Y.startsWith(".")&&!Y.startsWith("/"))return[];let ue=Y.startsWith("/")?BM.default.posix.join(a,Y):BM.default.posix.join(p,Y);return[new RegExp(`^${nqt(ue)}${K}$`)]}),E=c.patterns.filter(B=>!B.startsWith("!")).flatMap(B=>y(B)),I=c.patterns.filter(B=>B.startsWith("!")).flatMap(B=>y(B.slice(1).replace(/^(?![./])/,"./"),"(?:/.*)?"));return d.filter(B=>E.some(K=>K.test(B))&&!I.some(K=>K.test(B)))}function wIr(c,o,a){if(c.length===0)return[];let d=c.map(p=>new RegExp(`^${nqt(p)}$`));return a.filter(p=>p.startsWith(`${o}/`)&&d.some(y=>y.test(BM.default.posix.basename(p))))}function CIr(c,o,a){let d=BM.default.posix.join(BM.default.posix.dirname(o),c);return[d,...Awt.flatMap(p=>[d+p,`${d}/index${p}`])].find(p=>a.has(p))}function IIr(c,o){let a=new Map;for(let[d,p]of c){if(p.manifestText===void 0||BM.default.posix.basename(d)!=="package.json")continue;let y=xHn(p.manifestText);a.set(BM.default.posix.dirname(d),y!==void 0&&o.has(y))}return a}async function kIr(c){let o=BM.default.posix.join(c,"tsconfig.json"),a;try{a=await Ygn.default.readFile(o,"utf8")}catch{return{}}let d=T_t(o,a)?.compilerOptions,p={};if(typeof d!="object"||d===null)return p;for(let y of["outDir","rootDir"]){let E=d[y];typeof E=="string"&&(p[y]=fr(BM.default.resolve(c,E)))}return p}urt();function Zgn(c,o,a,d){let p=new Map;for(let[y,E]of c){if(o.has(y)||a.has(y))continue;let I=E.filter(B=>!d(B));I.length>0&&p.set(y,I)}for(let y of DIr(p,o))p.delete(y);return p}function DIr(c,o){let a=new Map;for(let[y,E]of c)for(let I of E){let B=a.get(I);B?B.push(y):a.set(I,[y])}let d=[...c].filter(([,y])=>y.some(E=>!o.has(E)&&!c.has(E))).map(([y])=>y),p=new Set(d);for(let y=d.pop();y!==void 0;y=d.pop())for(let E of a.get(y)??[])p.has(E)||(p.add(E),d.push(E));return p}function KHn(c,o,a){let d=new Map,p=(y,E)=>aIt(E,y)?y:E;for(let y=!0;y;){y=!1;for(let[E,I]of c){let B=I.flatMap(Y=>o.get(Y)??d.get(Y)??[]);if(B.length===0)continue;let K=B.reduce((Y,ue)=>p(Y,ue),a.get(E)??"high");K!==d.get(E)&&(d.set(E,K),y=!0)}}for(let y of c.keys())d.has(y)||d.set(y,"low");return d}var kVe=e1("SpiderSymbolService"),PIr=c=>`${c}:(file)`;function NIr(c,o,a,d){let p=(y,E)=>{if(y===E)return;let I=c.get(y);I||(I=new Set,c.set(y,I)),I.add(E)};for(let y of o)y.parentSymbolId&&p(fr(y.parentSymbolId),fr(y.id));for(let y of a)fr(y.targetFilePath)===d&&p(fr(y.sourceSymbolId),fr(y.targetSymbolId));return c}var JHn="convention:framework-default-export",RIr=/\.[cm]?[jt]sx?$/i,MIr=/\.vue$/i,qHn=/\.svelte$/i,LIr=/(?:\.config|(?:^|\/)(?:vercel|codegen|serverless|\.[\w-]+rc))\.[cm]?[jt]s$/i,OIr="convention:migration",FIr=/\.d\.[cm]?ts$/i,ZHn=/\.pyi?$/i,eyn=/\.rs$/i,BIr=new Set(p4t),iqt=8,lIt=class{constructor(o,a,d,p,y,E,I,B){this.astWorkerHost=o;this.symbolCache=a;this.fileReader=d;this.resolver=p;this.symbolDependencyHelper=y;this.getConfig=E;this.findReferencingFiles=I;this.languageService=B;this.textIndex=new rqt(d)}astWorkerHost;symbolCache;fileReader;resolver;symbolDependencyHelper;getConfig;findReferencingFiles;languageService;textIndex;analysisCache=null;scanResolutions;scanDependencyResolutions;async getSymbolGraph(o){if(!DVe.default.isAbsolute(o))try{let p=await this.resolveModuleSpecifier(this.getConfig().rootDir,o);p&&(o=p)}catch{}let a=fr(o);if(this.isAstUnsupportedFile(a))return{symbols:[],dependencies:[]};let d=this.symbolCache.get(a);if(d)return d;try{let p=await this.fileReader.readFile(o),y=await this.analyzeContent(a,p),E=new Map,I=Y=>{let ue=E.get(Y);return ue||(ue=this.resolveDependencyTarget(a,Y),E.set(Y,ue)),ue},B=await Promise.all(y.dependencies.map(async Y=>{try{let ue=await I(Y.targetFilePath);if(ue){let ie=fr(ue),Re=this.symbolDependencyHelper.extractSymbolName(Y.targetSymbolId);return{...Y,targetFilePath:ie,targetSymbolId:this.symbolDependencyHelper.buildUsedSymbolId(ie,Re)}}}catch{}return Y})),K={symbols:y.symbols,dependencies:B};return this.symbolCache.set(a,K),K}catch(p){let y=_E.fromError(p,o);if(kVe.error("Symbol analysis failed:",y.toUserMessage()),y.isRecoverable())return{symbols:[],dependencies:[]};throw y}}useAnalysisCache(o){this.analysisCache=o}async analyzeContent(o,a){let d=this.analysisCache?.getGraph(o,a);if(d)return d;let p=await this.astWorkerHost.analyzeFile(o,a);return this.analysisCache?.setGraph(o,a,p),p}resolveDependencyTarget(o,a){let d=async()=>{try{return await this.languageService.getAnalyzer(o).resolvePath(o,a)}catch{return null}},p=this.scanDependencyResolutions;if(!p)return d();let y=`${fr(o)}\0${a}`,E=p.get(y);return E||(E=d(),p.set(y,E)),E}async internalExportGraph(o,a){let d=this.analysisCache?.getInternalGraph(o,a);if(d)return d;let p=await this.astWorkerHost.getInternalExportDependencyGraph(o,a);return this.analysisCache?.setInternalGraph(o,a,p),p}async findUnusedSymbols(o,a){let d=a??{reExportMemo:new Map};try{let p=fr(o);if(qHn.test(p))return[];let{symbols:y,dependencies:E}=await this.getSymbolGraph(p),I=y.filter(Jn=>Jn.isExported);if(I.length===0)return[];let B=await this.findReferencingFiles(p),K=await this.fileReader.readFile(p),Y=NIr(await this.internalExportGraph(p,K),y,E,p),ue=this.workspaceTextFacts(d),{entryPoints:ie,packageDeepImport:Re,frameworksByPackage:Ie}=await ue,Ne=Bgn(p,Re),bt=this.conventionReason(p,Ie),Qt=zgn(K),Fn=new Map,Kr={target:p,graph:{symbols:I,dependencies:E},referencingFiles:B,internalGraph:Y,entryReason:Jn=>{let is=Fn.get(Jn.id);return is||(is=bt?Promise.resolve(bt):this.entryReason(p,K,Jn,B,ie,d.reExportMemo),Fn.set(Jn.id,is)),is}},jr=CVe(this.relativeToRoot(p));d.barrelUsage??={production:new Map,all:new Map};let Tn={accept:()=>!0,barrelUsage:d.barrelUsage.all},bn=jr?Tn:{accept:Jn=>!CVe(this.relativeToRoot(Jn)),barrelUsage:d.barrelUsage.production},Cr=await this.unusedExports(Kr,d.reExportMemo,bn);d.excluded?.push(...Cr.excluded.map(({symbol:Jn,reason:is})=>({filePath:p,name:Jn.name,kind:Jn.kind,line:Jn.line,reason:is})));let vi=await this.withoutRustQualifiedUse(p,K,Cr.unused,ue);if(vi.length===0)return[];let eo=jr?new Set(vi.map(Jn=>Jn.id)):new Set((await this.unusedExports(Kr,d.reExportMemo,Tn)).unused.map(Jn=>Jn.id)),Tr=await this.dynamicLoadsReaching(p,B,ue),ta=YVn(p,K),zo=this.expandUsedSymbolsViaInternalGraph(new Set(I.filter(Jn=>Jn.isDecorated).map(Jn=>Jn.id)),Y);return await Promise.all(vi.map(async Jn=>({...Jn,...Ogn({importers:await this.consumersOf(p,Jn,B,d.reExportMemo),testOnlyUse:!eo.has(Jn.id),testFile:jr,decorated:zo.has(Jn.id),nameWrittenElsewhere:await this.rustNameWrittenElsewhere(p,Jn,ue),namedInOwnFile:ZVn(ta,Jn.name),publishedDeepImport:Ne,generated:Qt,dynamicLoads:Tr})})))}catch(p){let y=_E.fromError(p,o);return kVe.error("Find unused symbols failed:",y.toUserMessage()),[]}}async unusedExports(o,a,d){let{target:p,graph:y,internalGraph:E}=o,I=o.referencingFiles.filter(bt=>d.accept(bt.path)),B=await this.collectUsedSymbolIds(I,p);if(B.has(this.symbolDependencyHelper.buildUsedSymbolId(p,"*")))return{unused:[],excluded:[]};for(let bt of E.get(PIr(p))??[])B.add(bt);this.addJsxConsumers(p,y,B);let K=y.symbols.find(bt=>bt.isDefaultExport);K&&B.has(this.symbolDependencyHelper.buildUsedSymbolId(p,"default"))&&B.add(K.id),await this.addSymbolsUsedThroughBarrels(p,y.symbols,I,B,a,d);let Y=this.expandUsedSymbolsViaInternalGraph(B,E),ue=y.symbols.filter(bt=>!Y.has(bt.id)),ie=await Promise.all(ue.map(bt=>o.entryReason(bt))),Re=new Map(ue.flatMap((bt,Qt)=>ie[Qt]?[[bt.id,ie[Qt]]]:[]));if(Re.size===0)return{unused:ue,excluded:[]};let Ie=new Map;for(let[bt,Qt]of Re)for(let Fn of this.expandUsedSymbolsViaInternalGraph(new Set([bt]),E))Ie.has(Fn)||Ie.set(Fn,Qt);let Ne=ue.flatMap(bt=>{let Qt=Ie.get(bt.id);return Qt?[{symbol:bt,reason:Qt}]:[]});return{unused:ue.filter(bt=>!Ie.has(bt.id)),excluded:Ne}}async entryReason(o,a,d,p,y,E){if(XHn(o,d))return JHn;if(y.size===0||eyn.test(o)&&jIr(a,d))return;let I=d.isDefaultExport&&d.name!=="default"?[d.name,"default"]:[d.name],B=I.map(ie=>Hgn(y,o,ie)).find(Boolean);if(B)return B;let K=await Promise.all(p.map(ie=>this.moduleReExports(ie.path,E)));if(K.every(ie=>ie.reExports.length===0&&ie.namespaces.length===0))return;let Y=(await Promise.all(I.map(ie=>this.collectReexportAliases(o,ie,E,!0)))).flat(),ue=await this.collectNamespaceAliases(K,o,E);return[...Y,...ue].map(ie=>Hgn(y,ie.filePath,ie.name)).find(Boolean)}relativeToRoot(o){return BD(o,this.getConfig().rootDir)}async consumersOf(o,a,d,p){let E=(await Promise.all(d.map(ie=>this.moduleReExports(ie.path,p)))).some(ie=>ie.reExports.length>0||ie.namespaces.length>0),I=a.isDefaultExport&&a.name!=="default"?[a.name,"default"]:[a.name],B=E?(await Promise.all(I.map(ie=>this.collectReexportAliases(o,ie,p,!0)))).flat():[],K=new Set([o,...B.map(ie=>ie.filePath)]),Y=await Promise.all([...K].filter(ie=>ie!==o).map(ie=>this.findReferencingFiles(ie))),ue=new Set;for(let ie of[...d,...Y.flat()]){let Re=fr(ie.path);K.has(Re)||ue.add(this.relativeToRoot(Re))}return[...ue].sort((ie,Re)=>ie.localeCompare(Re))}workspaceTextFacts(o){return o.textFacts??=this.textIndex.collect(this.getConfig().rootDir,this.getConfig().excludeNodeModules??!0),o.textFacts}async withoutRustQualifiedUse(o,a,d,p){if(!eyn.test(o)||d.length===0)return d;let{rustPaths:y}=await p;return d.filter(E=>!tHn(o,a,E.name,y))}async rustNameWrittenElsewhere(o,a,d){return eyn.test(o)&&((await d).rustTokenFiles.get(a.name)??0)>=2}async dynamicLoadsReaching(o,a,d){let{loads:p,computedAttributeReaders:y}=await d,E=XVn(o,p);if(!ZHn.test(o))return E;let I=a.filter(B=>y.has(fr(B.path))).map(B=>`${this.relativeToRoot(B.path)}:getattr`);return[...E,...I]}addJsxConsumers(o,a,d){for(let p of a.dependencies)p.relation==="REFERENCES"&&fr(p.targetFilePath)===o&&fr(p.sourceSymbolId)!==fr(p.targetSymbolId)&&d.add(fr(p.targetSymbolId))}async addSymbolsUsedThroughBarrels(o,a,d,p,y,E){let I=await Promise.all(d.map(Re=>this.moduleReExports(Re.path,y)));if(I.every(Re=>Re.reExports.length===0&&Re.namespaces.length===0))return;let B=await this.collectNamespaceAliases(I,o,y),K=await Promise.all(B.map(Re=>this.collectNamespaceUse(Re,E.accept))),Y=async Re=>{let Ie=E.barrelUsage.get(Re.filePath);return Ie||(Ie=this.findReferencingFiles(Re.filePath).then(Ne=>this.collectUsedSymbolIds(Ne.filter(bt=>E.accept(bt.path)),Re.filePath)),E.barrelUsage.set(Re.filePath,Ie)),(await Ie).has(this.symbolDependencyHelper.buildUsedSymbolId(Re.filePath,Re.name))},ue=a.filter(Re=>!p.has(Re.id)),ie=await Promise.all(ue.map(async Re=>{let Ie=Re.isDefaultExport&&Re.name!=="default"?[Re.name,"default"]:[Re.name],Ne=(await Promise.all(Ie.map(Qt=>this.collectReexportAliases(o,Qt,y,!0)))).flat();return(await Promise.all(Ne.filter(Qt=>Qt.filePath!==o).map(Y))).some(Boolean)||K.some(Qt=>Qt.escapes||Qt.members.has(Re.name))}));ue.forEach((Re,Ie)=>{ie[Ie]&&p.add(Re.id)})}async collectNamespaceUse(o,a){let d=(await this.findReferencingFiles(o.filePath)).filter(E=>a(E.path)),p=await Promise.all(d.map(E=>this.namespaceUseInFile(E.path,o))),y={members:new Set,escapes:!1};for(let E of p.flat()){for(let I of E.members)y.members.add(I);y.escapes||=E.escapes}return y}async namespaceUseInFile(o,a){let d;try{d=await this.fileReader.readFile(o)}catch{return[]}return(await Promise.all(vJt(o,d).map(y=>this.namespaceUseOfBinding(y,o,d,a)))).filter(y=>y!==null)}async namespaceUseOfBinding(o,a,d,p){if(o.imported!==p.name&&o.imported!=="*")return null;let y=await this.resolveModuleSpecifier(a,o.specifier);return!y||fr(y)!==p.filePath?null:o.imported==="*"?{members:new Set,escapes:!0}:$Un(a,d,o.local)}async collectNamespaceAliases(o,a,d){let p=o.flatMap(({path:E,namespaces:I})=>I.map(({specifier:B,alias:K})=>({barrelPath:E,specifier:B,alias:K}))),y=await Promise.all(p.map(async({barrelPath:E,specifier:I,alias:B})=>{let K=await this.resolveModuleSpecifier(E,I);return!K||fr(K)!==a||!JUn(I,a)?[]:this.collectReexportAliases(E,B,d,!0)}));return[...new Map(y.flat().map(E=>[`${E.filePath}:${E.name}`,E])).values()]}async getSymbolDependents(o,a){let d=await this.exportNamesOf(o,a),p=(await Promise.all(d.map(B=>this.collectReexportAliases(o,B)))).flat(),y=await Promise.all(p.map(B=>this.findReferencingFiles(B.filePath))),E=await Promise.all(p.map((B,K)=>this.collectSymbolDependents([B.filePath,...y[K].map(Y=>Y.path)],B.filePath,B.name))),I=new Map;for(let B of E.flat())I.set(fr(B.sourceSymbolId),B);return[...I.values()]}async exportNamesOf(o,a){if(a==="default")return[a];let{symbols:d}=await this.getSymbolGraph(o);return d.some(p=>p.name===a&&p.isDefaultExport)?[a,"default"]:[a]}async findReferencingFilesThroughBarrels(o){let a=fr(o),d=await this.findReferencingFiles(a),p=new Map,y=await Promise.all(d.map(Ne=>this.moduleReExports(Ne.path,p))),E=y.flatMap(Ne=>[...Ne.reExports,...Ne.namespaces].map(({specifier:bt})=>({from:Ne.path,specifier:bt})));if(!(await Promise.all(E.map(({from:Ne,specifier:bt})=>this.resolveModuleSpecifier(Ne,bt)))).some(Ne=>!!Ne&&fr(Ne)===a))return d;let{symbols:B}=await this.getSymbolGraph(a),K=await Promise.all(B.filter(Ne=>Ne.isExported).map(Ne=>this.collectReexportAliases(a,Ne.name,p,!0))),Y=await this.collectNamespaceAliases(y,a,p),ue=new Map;for(let Ne of[...K.flat(),...Y]){if(Ne.filePath===a)continue;let bt=ue.get(Ne.filePath)??new Set;ue.set(Ne.filePath,bt.add(Ne.name))}let ie=await Promise.all([...ue].map(([Ne,bt])=>this.barrelConsumers(Ne,bt,ue,p))),Re=new Set([a,...d.map(Ne=>fr(Ne.path))]),Ie=[...d];for(let Ne of ie.flat()){let bt=fr(Ne.path);Re.has(bt)||(Re.add(bt),Ie.push(Ne))}return Ie}async barrelConsumers(o,a,d,p){let y=await this.findReferencingFiles(o),E=await Promise.all(y.map(async I=>d.has(fr(I.path))&&await this.reexportsNameFrom(I.path,o,a,p)||this.importsNameFrom(I.path,o,a,p)));return y.filter((I,B)=>E[B]).map(I=>({...I,via:o}))}async reexportsNameFrom(o,a,d,p){return(await Promise.all([...d].map(E=>this.reexportedAs(o,{filePath:a,name:E},p)))).some(E=>E.length>0)}async importsNameFrom(o,a,d,p){let y;try{y=await this.fileReader.readFile(o)}catch{return!1}let{starNames:E}=await this.moduleReExports(a,p),I=[...d].some(Y=>VCt(Y,E)),B=bJt(o,y).filter(Y=>Y.imported!=="*"?d.has(Y.imported):Y.local!=="*"||DVe.default.extname(o).toLowerCase()!==".py"||I);return(await Promise.all(B.map(Y=>this.resolveModuleSpecifier(o,Y.specifier)))).some(Y=>!!Y&&fr(Y)===a)}async collectReexportAliases(o,a,d=new Map,p=!1){let y={filePath:fr(o),name:a},E=new Map([[`${y.filePath}:${y.name}`,y]]);return await this.expandReexportAliases([y],E,d,p),[...E.values()]}async expandReexportAliases(o,a,d,p){let y=(await Promise.all(o.map(I=>this.directReexports(I,d,p)))).flat(),E=[];for(let I of y){let B=`${I.filePath}:${I.name}`;a.has(B)||(a.set(B,I),E.push(I))}E.length>0&&await this.expandReexportAliases(E,a,d,p)}async directReexports(o,a,d){let p=await this.findReferencingFiles(o.filePath),y=d?p:p.filter(I=>I.type==="export"||Z3t(I.path));return(await Promise.all(y.map(I=>this.reexportedAs(I.path,o,a)))).flat()}async moduleReExports(o,a){let d=fr(o),p=a.get(d);return p||(p=this.fileReader.readFile(d).then(y=>TJt(d,y)).catch(()=>({reExports:[],namespaces:[]})),a.set(d,p)),{...await p,path:d}}async reexportedAs(o,a,d){let{path:p,reExports:y}=await this.moduleReExports(o,d),E=await Promise.all(y.map(({specifier:B})=>this.resolveModuleSpecifier(p,B))),I=await this.starTakes(a,d);return y.flatMap(({names:B},K)=>{let Y=E[K];return!Y||fr(Y)!==a.filePath?[]:B==="all"?I?[{filePath:p,name:a.name}]:[]:B.filter(({imported:ue})=>ue===a.name).map(({exported:ue})=>({filePath:p,name:ue}))})}async starTakes(o,a){return o.name==="default"?!1:DVe.default.extname(o.filePath).toLowerCase()!==".py"?!0:VCt(o.name,(await this.moduleReExports(o.filePath,a)).starNames)}async traceFunctionExecution(o,a,d=10){let p=`${o}:${a}`,y=[],E=new Set,I=new Map,B=new Map,K=ie=>{let Re=fr(ie),Ie=B.get(Re);return Ie||(Ie=this.getSymbolGraph(ie),Ie.catch(()=>B.delete(Re)),B.set(Re,Ie)),Ie},Y=!1,ue=async(ie,Re,Ie)=>{if(Ie>d){Y=!0;return}let Ne=`${ie}:${Re}`;if(!E.has(Ne)){E.add(Ne);try{let{symbols:bt,dependencies:Qt}=await K(ie),Fn=bt.find(Tn=>Tn.name===Re);if(!Fn)return;let vr=Qt.filter(Tn=>Tn.sourceSymbolId===Fn.id&&!Tn.isTypeOnly),Kr=await Promise.all(vr.map(Tn=>this.resolveTraceTarget(ie,Tn,I,K))),jr=new Set;for(let[Tn,bn]of vr.entries()){let{resolvedFilePath:Cr,name:vi}=Kr[Tn],eo=Cr?`${Cr}:${vi}`:bn.targetSymbolId,Tr=`${eo}|${bn.relation??""}`;jr.has(Tr)||(jr.add(Tr),y.push({depth:Ie,callerSymbolId:Ne,calledSymbolId:eo,calledFilePath:bn.targetFilePath,resolvedFilePath:Cr,...bn.line!==void 0&&{line:bn.line},...bn.relation&&{relation:bn.relation}}),Cr&&!rle(Cr)&&await ue(Cr,vi,Ie+1))}}catch(bt){let Qt=_E.fromError(bt,ie);kVe.error("Trace execution failed:",Ne,Qt.toUserMessage())}}};return await ue(o,a,1),{rootSymbol:{id:p,filePath:o,symbolName:a},callChain:y,visitedSymbols:Array.from(E),maxDepthReached:Y}}async resolveTraceTarget(o,a,d,p){let y=this.symbolDependencyHelper.extractSymbolName(a.targetSymbolId),E;try{let bt=DVe.default.isAbsolute(a.targetFilePath)?a.targetFilePath:await this.resolver.resolve(o,a.targetFilePath);E=bt&&fr(bt)}catch{return{resolvedFilePath:null,name:y}}let I=E===fr(o);if(!E||I||y==="*"||!RIr.test(E)||rle(E))return{resolvedFilePath:E,name:y};let{symbols:B}=await p(E),K=B.filter(bt=>bt.isExported),Y=y==="default"?K.find(bt=>bt.isDefaultExport):K.find(bt=>bt.name===y&&!bt.isDefaultExport);if(Y)return{resolvedFilePath:E,name:Y.name};let ue=await w2e(E,y,this.resolver,d);if(ue&&ue!==Wme&&(ue.filePath!==E||ue.name!==y))return{resolvedFilePath:ue.filePath,name:ue.name};let Re=await d.get(E),Ie=K.length>0||!!Re&&r6t(Re);return{resolvedFilePath:ue===Wme||Ie&&!K.some(bt=>bt.name===y)?null:E,name:y}}async resolveModuleSpecifier(o,a){let d=this.scanResolutions;if(!d)return this.resolveModuleSpecifierNow(o,a);let p=`${o}\0${a}`,y=d.get(p);return y||(y=this.resolveModuleSpecifierNow(o,a),d.set(p,y)),y}async resolveModuleSpecifierNow(o,a){try{return Z3t(C2(o))?await this.languageService.getAnalyzer(o).resolvePath(o,a):await this.resolver.resolve(o,a)}catch{return null}}expandUsedSymbolsViaInternalGraph(o,a){let d=new Set(o),p=Array.from(d);for(;p.length>0;){let y=p.pop();if(y===void 0)continue;let E=a.get(y);if(E)for(let I of E)d.has(I)||(d.add(I),p.push(I))}return d}async collectUsedSymbolIds(o,a){let d=await Promise.all(o.map(y=>this.edgesToFile(y.path,a))),p=new Set;for(let y of d.flat()){let E=this.symbolDependencyHelper.extractSymbolName(y.targetSymbolId);p.add(this.symbolDependencyHelper.buildUsedSymbolId(a,E))}return p}async edgesToFile(o,a,d=()=>!0){let{dependencies:p}=await this.getSymbolGraph(o),y=p.filter(d),E=fr(a),I=await Promise.all(y.map(async B=>{if(fr(B.targetFilePath)===E)return!0;if(DVe.default.isAbsolute(B.targetFilePath))return!1;let K=await this.resolveDependencyTarget(o,B.targetFilePath);return K!==null&&fr(K)===E}));return y.filter((B,K)=>I[K])}async collectSymbolDependents(o,a,d){let p=fr(a),y=this.symbolDependencyHelper.buildUsedSymbolId(p,d),E=K=>fr(K.sourceSymbolId)!==y&&this.symbolDependencyHelper.extractSymbolName(K.targetSymbolId)===d,I=await Promise.all(o.map(K=>this.edgesToFile(K,p,E))),B=new Map;for(let K of I.flat()){let Y=fr(K.sourceSymbolId);B.has(Y)||B.set(Y,K)}return[...B.values()]}async verifyDependencyUsage(o,a){try{let d=fr(o),p=fr(a);if(rle(p))return!0;if(this.isUsageUnverifiable(d))return kVe.debug(`Skipping symbol analysis for unsupported file type: ${d}`),!0;if((await this.sideEffectTargets(d)).has(p))return!0;let{dependencies:y}=await this.getSymbolGraph(d);if(y.length===0)return!1;let E=p.split("/").pop()||"",I=y.filter(K=>K.targetFilePath===p||K.targetFilePath.includes(E)||!K.targetFilePath.startsWith("/"));return!!(await Promise.all(I.map(K=>this.symbolDependencyHelper.doesDependencyTargetFile(K,d,p)))).some(Boolean)}catch(d){let p=_E.fromError(d,o);return kVe.warn("Usage verification failed, assuming used:",p.message),!0}}async verifyDependencyUsageBatch(o,a){try{let d=fr(o);if(this.isUsageUnverifiable(d))return kVe.debug(`Skipping symbol analysis for unsupported file type: ${d}`),this.markAllAsUsed(a);let{dependencies:p}=await this.getSymbolGraph(d),y=await this.sideEffectTargets(d);if(p.length===0&&y.size===0)return this.markAllAsUnused(a);let E=await this.buildResolvedTargetsSet(p,d);for(let I of y)E.add(I);return this.checkTargetsAgainstResolved(a,E)}catch(d){let p=_E.fromError(d,o);return kVe.warn("Batch usage verification failed, assuming all used:",p.message),this.markAllAsUsed(a)}}async sideEffectTargets(o){return new Set(await this.resolvedImports(o,a=>a.type==="side-effect"))}async resolvedImports(o,a=()=>!0){let d=this.languageService.getAnalyzer(o),p=await d.parseImports(o);return(await Promise.all(p.filter(a).map(E=>d.resolvePath(o,E.module)))).filter(E=>E!==null).map(fr)}markAllAsUsed(o){let a=new Map;for(let d of o)a.set(fr(d),!0);return a}markAllAsUnused(o){let a=new Map;for(let d of o)a.set(fr(d),!1);return a}async buildResolvedTargetsSet(o,a){let d=await Promise.all(o.map(p=>this.symbolDependencyHelper.resolveTargetPath(p,a).catch(()=>null)));return new Set(d.filter(p=>!!p).map(fr))}checkTargetsAgainstResolved(o,a){let d=new Map;for(let p of o){let y=fr(p);if(rle(y)){d.set(y,!0);continue}d.set(y,a.has(y))}return d}isAstUnsupportedFile(o){return!BIr.has(DVe.default.extname(o).toLowerCase())}isUsageUnverifiable(o){return this.isAstUnsupportedFile(o)||qHn.test(o)}async scanDeadCode(o,a){let{filesToScan:d,filesBeyondLimit:p}=await this.collectScanFiles(o,a),y={reExportMemo:new Map,excluded:[]};this.scanResolutions=new Map,this.scanDependencyResolutions=new Map;try{let{results:E,skippedFiles:I}=await this.scanEachFile(d,"scanDeadCode",a,async B=>({filePath:B,unusedSymbols:await this.findUnusedSymbols(B,y)}));return{entries:E.flatMap(B=>B&&B.unusedSymbols.length>0?[B]:[]),excluded:y.excluded??[],scannedFiles:d.length,skippedFiles:I,filesBeyondLimit:p}}finally{this.scanResolutions=void 0,this.scanDependencyResolutions=void 0}}async scanUnreferencedFiles(o,a){let{filesToScan:d,filesBeyondLimit:p}=await this.collectScanFiles(o,a),y=this.workspaceTextFacts({reExportMemo:new Map}),E=k3n(this.getConfig().rootDir),I=[],B=new Map,{results:K,skippedFiles:Y}=await this.scanEachFile(d,"scanUnreferencedFiles",a,async Re=>{let Ie=fr(Re),Ne=(await this.findReferencingFiles(Ie)).map(Qt=>fr(Qt.path));B.set(Ie,Ne);let bt=await this.unreferencedFile(Ie,Ne,y,E);if(!bt||!("reason"in bt))return bt;I.push(bt)}),ue=K.filter(Re=>Re!==void 0),ie=[...ue,...await this.cascadeFiles(ue,B,y,E,I)];return await this.addDeletableTests(ie,B),{files:ie,excluded:I,scannedFiles:d.length,skippedFiles:Y,filesBeyondLimit:p}}async scanEachFile(o,a,{signal:d,onProgress:p},y){let E=0,I=0;return{results:await xv(o,iqt,async K=>{d&&(await(0,YHn.setImmediate)(),d.throwIfAborted());try{return await y(K)}catch(Y){kVe.warn(`${a}: skipping file due to error:`,K,_E.fromError(Y,K).message),E++;return}finally{p?.(++I,o.length)}}).finally(()=>this.analysisCache?.save()),skippedFiles:E}}async cascadeFiles(o,a,d,p,y){let E=bt=>CVe(this.relativeToRoot(bt)),I=bt=>bt.exports>0&&bt.reasons.every(Qt=>Qt==="no-importer"||Qt==="test-only-use"),B=new Set;await xv(o.filter(I),iqt,async({filePath:bt})=>{pHn(await this.fileReader.readFile(bt))||B.add(bt)});let K=new Set,Y=new Map,ue=Zgn(a,B,K,E);for(;;){let bt=[...ue.keys()].filter(Fn=>!Y.has(Fn));await xv(bt,iqt,async Fn=>{Y.set(Fn,await this.unreferencedFile(Fn,(a.get(Fn)??[]).filter(E),d,p))});let Qt=[...ue.keys()].filter(Fn=>{let vr=Y.get(Fn);return!vr||"reason"in vr});if(Qt.length===0)break;for(let Fn of Qt)K.add(Fn);ue=Zgn(a,B,K,E)}for(let bt of K){let Qt=Y.get(bt);Qt&&"reason"in Qt&&y.push(Qt)}let ie=bt=>Y.get(bt),Re=new Map([...ue.keys()].map(bt=>[bt,ie(bt).reasons.some(Qt=>Qt!=="no-importer")?"medium":"high"])),Ie=KHn(ue,new Map(o.map(bt=>[bt.filePath,bt.confidence])),Re),Ne=bt=>bt.map(Qt=>this.relativeToRoot(Qt)).sort((Qt,Fn)=>Qt.localeCompare(Fn));return[...ue].map(([bt,Qt])=>{let Fn=ie(bt),vr=Ne(a.get(bt)??[]);return{...Fn,confidence:Ie.get(bt)??Fn.confidence,reasons:["cascade",...Fn.reasons.filter(Kr=>Kr!=="no-importer")],evidence:{...Fn.evidence,importers:vr.length,firstImporters:vr.slice(0,qJt)},via:Ne(Qt)}})}async addDeletableTests(o,a){let d=new Set(o.map(I=>I.filePath)),p=new Map(o.map(I=>[I,(a.get(I.filePath)??[]).filter(B=>CVe(this.relativeToRoot(B)))])),y=[...new Set([...p.values()].flat())],E=new Set;await xv(y,iqt,async I=>{try{(await this.resolvedImports(I)).every(B=>d.has(B))&&E.add(I)}catch(B){kVe.debug("Dead-code scan: cannot read the imports of",I,_E.fromError(B,I).message)}});for(let[I,B]of p){let K=B.filter(Y=>E.has(Y)).map(Y=>this.relativeToRoot(Y)).sort((Y,ue)=>Y.localeCompare(ue));K.length>0&&(I.tests=K)}}conventionReason(o,a){return FHn(o,a)?MHn:dHn(this.relativeToRoot(o))?OIr:void 0}async unreferencedFile(o,a,d,p){let y=a.map(vr=>this.relativeToRoot(vr)),E=y.length>0;if(E&&!y.every(vr=>CVe(vr)))return;let I=this.relativeToRoot(o);if(CVe(I))return{filePath:o,reason:"convention:test-file"};if(p(I,!1))return{filePath:o,reason:"gitignored"};if(FIr.test(o))return{filePath:o,reason:"convention:type-declaration"};if(LIr.test(o))return{filePath:o,reason:"convention:config-file"};let{entryPoints:B,packageDeepImport:K,namedPaths:Y,frameworksByPackage:ue}=await d,ie=this.conventionReason(o,ue);if(ie)return{filePath:o,reason:ie};if(DVe.default.posix.basename(o)==="__init__.py"&&await WIr(DVe.default.posix.dirname(o)))return{filePath:o,reason:"convention:package-init"};let Re=async()=>(await this.getSymbolGraph(o)).symbols.filter(vr=>vr.isExported),Ie=[...B.get(o)??[]],Ne=Ie.some(([,vr])=>Vgn(vr))?new Set((await Re()).map(vr=>vr.name)):void 0,bt=Ie.find(([vr,Kr])=>!Vgn(Kr)||Ne?.has(vr))?.[1];if(bt)return{filePath:o,reason:bt};let Qt=Y.get(o);if(Qt)return{filePath:o,reason:`named-in:${Qt}`};let Fn=await Re();return Fn.some(vr=>XHn(o,vr))?{filePath:o,reason:JHn}:(y.sort((vr,Kr)=>vr.localeCompare(Kr)),{filePath:o,exports:Fn.length,...E?{testImporters:y}:{},...Ogn({importers:y,testOnlyUse:E,testFile:!1,dynamicLoads:await this.dynamicLoadsReaching(o,[],d),publishedDeepImport:Bgn(o,K),generated:zgn(await this.fileReader.readFile(o))})})}async collectScanFiles(o,a){if(!a.hasReverseIndex)throw new _E("Dead code scan requires the reverse index. Wait for indexing to complete or call rebuild_index first.","INDEX_NOT_READY");let p=(await new kW({excludeNodeModules:this.getConfig().excludeNodeModules??!0}).collectAllSourceFiles(o)).filter(E=>!this.isUsageUnverifiable(E)),y=p.slice(0,a.maxFiles??Number.POSITIVE_INFINITY);return{filesToScan:y,filesBeyondLimit:p.length-y.length}}};async function WIr(c){return(await QHn.default.readdir(c,{withFileTypes:!0})).some(a=>a.isDirectory()||ZHn.test(a.name)&&a.name!=="__init__.py")}function XHn(c,o){return o.isDefaultExport?MIr.test(c)||/\.[jt]sx$/i.test(c)&&(o.category==="function"||o.category==="class"):!1}function jIr(c,o){let a=c.split(`
47458
47458
  `)[o.line-1]??"";return/\bpub\s*\(/.test(a)}var e$n=require("node:worker_threads"),t$n=Ec(require("node:path")),oqt=class{worker=null;statusCallbacks=new Set;currentState="idle";currentProgress=0;currentTotal=0;currentFile="";startTime=void 0;cancelled=!1;stopActiveRequest=null;workerTermination=null;workerPath;constructor(o){this.workerPath=o??t$n.join(__dirname,"indexerWorker.js")}subscribeToStatus(o){return this.statusCallbacks.add(o),o(this.getSnapshot()),()=>this.statusCallbacks.delete(o)}getSnapshot(){let o=this.currentTotal>0?Math.round(this.currentProgress/this.currentTotal*100):0;return{state:this.currentState,processed:this.currentProgress,total:this.currentTotal,currentFile:this.currentFile,percentage:o,startTime:this.startTime,cancelled:this.cancelled}}notifySubscribers(){let o=this.getSnapshot();for(let a of this.statusCallbacks)try{a(o)}catch{}}updateState(o,a=0,d=0,p=""){this.currentState=o,this.currentProgress=a,this.currentTotal=d,this.currentFile=p,this.notifySubscribers()}getPendingCount(){return this.worker||this.workerTermination?1:0}async startIndexing(o){if(this.worker||this.workerTermination)throw new Error("Indexing already in progress");this.cancelled=!1,this.startTime=Date.now(),this.updateState("counting");let a=o.timeoutMs??600*1e3;return new Promise((d,p)=>{let y=!1,E=K=>{y||(y=!0,clearTimeout(B),this.stopActiveRequest=null,d(K))},I=K=>{y||(y=!0,clearTimeout(B),this.stopActiveRequest=null,p(K))},B=setTimeout(()=>{this.cancel(),this.updateState("error"),this.cleanupWorker().then(()=>{I(new Error(`Indexing timed out after ${Math.round(a/6e4)} minute(s)`))})},a);this.stopActiveRequest=()=>{this.cancelled=!0,this.updateState("complete",this.currentProgress,this.currentTotal),E({indexedFiles:this.currentProgress,duration:Date.now()-(this.startTime??Date.now()),cancelled:!0,data:[]})};try{this.worker=new e$n.Worker(this.workerPath,{workerData:o});let K={indexedFiles:0,duration:0,cancelled:!1,data:[]};this.worker.on("message",Y=>{switch(Y.type){case"counting":this.updateState("counting");break;case"progress":Y.data&&this.updateState("indexing",Y.data.processed??0,Y.data.total??0,Y.data.currentFile??"");break;case"complete":Y.data&&(K={indexedFiles:Y.data.processed??0,duration:Y.data.duration??0,cancelled:this.cancelled,data:Y.data.indexData??[]}),this.updateState("complete"),this.cleanupWorker().then(()=>E(K));break;case"error":this.updateState("error"),this.cleanupWorker().then(()=>I(new Error(Y.error??"Unknown worker error")));break}}),this.worker.on("error",Y=>{this.updateState("error"),this.cleanupWorker().then(()=>I(Y))}),this.worker.on("exit",Y=>{Y!==0&&this.currentState!=="complete"&&this.currentState!=="error"&&(this.updateState("error"),this.cleanupWorker().then(()=>I(new Error(`Worker stopped with exit code ${Y}`))))}),this.worker.postMessage({type:"start"})}catch(K){this.updateState("error"),this.cleanupWorker().then(()=>I(K))}})}cancel(){if(this.cancelled=!0,this.worker)try{this.worker.postMessage({type:"cancel"})}catch{}}isIndexing(){return this.currentState==="indexing"||this.currentState==="counting"}cleanupWorker(){if(this.worker){let o=this.worker;this.worker=null,o.removeAllListeners(),o.on("error",()=>{});let a=o.terminate().then(()=>{},()=>{}).then(()=>{this.workerTermination===a&&(this.workerTermination=null)});return this.workerTermination=a,a}return this.workerTermination??Promise.resolve()}async dispose(){this.cancel(),this.stopActiveRequest?.(),await this.cleanupWorker(),this.statusCallbacks.clear()}};B3();var uIt=class{constructor(o,a,d){this.indexerStatus=o;this.reverseIndexManager=a;this.dependencyCache=d}indexerStatus;reverseIndexManager;dependencyCache;workerHost=null;async buildFullIndexInWorker(o){let{workerPath:a,config:d,progressCallback:p}=o;this.workerHost??=new oqt(a),this.reverseIndexManager.ensure();let y=this.workerHost.subscribeToStatus(E=>{switch(E.state){case"counting":this.indexerStatus.startCounting();break;case"indexing":E.total>0&&(this.indexerStatus.setTotal(E.total),this.indexerStatus.startIndexing()),this.indexerStatus.updateProgress(E.processed,E.currentFile);break;case"complete":this.indexerStatus.complete();break;case"error":this.indexerStatus.setError(E.errorMessage??"Unknown error");break}p&&E.state==="indexing"&&p(E.processed,E.total,E.currentFile)});try{let E=await this.workerHost.startIndexing({rootDir:d.rootDir,excludeNodeModules:d.excludeNodeModules,tsConfigPath:d.tsConfigPath,extensionPath:d.extensionPath,ignoreTypeImports:d.ignoreTypeImports});return this.importWorkerResult(E),{indexedFiles:E.indexedFiles,duration:E.duration,cancelled:E.cancelled}}finally{y()}}cancel(){this.workerHost?.cancel()}async dispose(){let o=this.workerHost;this.workerHost=null,await o?.dispose()}importWorkerResult(o){for(let a of o.data){let d=fr(a.filePath);this.dependencyCache.set(d,a.dependencies),this.reverseIndexManager.addDependencies(d,a.dependencies,{mtime:a.mtime,size:a.size},a.outOfRootImports??[],a.unresolvedImports??[])}}};var n$n=Ec(require("node:path"));B3();YL();var dIt=e1("SymbolDependencyHelper"),fIt=class{resolveFn;constructor(o){this.resolveFn=o.resolve}async doesDependencyTargetFile(o,a,d){let p=fr(o.targetFilePath),y=fr(d);if(dIt.debug(`Comparing: dep.targetFilePath='${p}' vs targetFilePath='${y}'`),p===y)return dIt.debug("\u2713 Direct match"),!0;if(n$n.default.isAbsolute(o.targetFilePath))return!1;dIt.debug(`Attempting fallback resolution for '${o.targetFilePath}' from '${a}'`);let E=await this.resolveFn(a,o.targetFilePath);if(E){let I=fr(E);dIt.debug(`Resolved to: '${I}'`);let B=I===y;return dIt.debug(B?"\u2713 Fallback match":"\u2717 No match after resolution"),B}return dIt.debug("\u2717 Resolution failed, no match"),!1}extractSymbolName(o){return o.split(":").pop()||""}extractBasename(o){return o.split(/[/\\]/).pop()?.replace(/\.[^/.]+$/,"")}buildUsedSymbolId(o,a){return`${fr(o)}:${a}`}async resolveTargetPath(o,a){let d=fr(o.targetFilePath);if(d.startsWith("/")||/^[a-zA-Z]:\//.test(d))return d;try{let p=await this.resolveFn(a,o.targetFilePath);return p?fr(p):null}catch{return null}}};Jce();Pp();pVe();o4t();Zht();var zIr=2e3,sqt=class{activeIndexingOperations=new Set;disposed=!1;disposePromise=null;workerShutdownPromise=null;config;languageService;resolver;resolverInputs=Promise.resolve(new Map);extendsConfigs=new Set;pendingResolverConfigs=new Map;resolverReindex=Promise.resolve();queuedResolverReindex=null;cache;symbolCache;fileReader;astWorkerHost;reverseIndexManager;indexerStatus;workerManager;cancellation;sourceFileCollector;referencingFilesFinder;symbolDependencyHelper;dependencyAnalyzer;referenceLookup;symbolService;graphCrawler;indexingService;cacheCoordinator;constructor(o){if("dependencyAnalyzer"in o){let a=o;this.config=a.config,this.languageService=a.languageService,this.resolver=a.resolver,this.cache=a.cache,this.symbolCache=a.symbolCache,this.fileReader=a.fileReader,this.astWorkerHost=a.astWorkerHost,this.reverseIndexManager=a.reverseIndexManager,this.indexerStatus=a.indexerStatus,this.workerManager=a.workerManager,this.cancellation=a.cancellation,this.sourceFileCollector=a.sourceFileCollector,this.referencingFilesFinder=a.referencingFilesFinder,this.symbolDependencyHelper=a.symbolDependencyHelper,this.dependencyAnalyzer=a.dependencyAnalyzer,this.referenceLookup=a.referenceLookup,this.symbolService=a.symbolService,this.graphCrawler=a.graphCrawler,this.indexingService=a.indexingService,this.cacheCoordinator=a.cacheCoordinator}else{let a=o;this.config={maxDepth:50,excludeNodeModules:!0,enableReverseIndex:!1,indexingConcurrency:4,maxCacheSize:500,maxSymbolCacheSize:200,maxSymbolAnalyzerFiles:100,...a},this.languageService=new ole(a.rootDir,a.tsConfigPath,a.extensionPath),this.resolver=new UH(a.tsConfigPath,this.config.excludeNodeModules,a.rootDir),this.cache=new ort({maxSize:this.config.maxCacheSize,enableLRU:!0}),this.symbolCache=new ort({maxSize:this.config.maxSymbolCacheSize,enableLRU:!0}),this.astWorkerHost=new Ent(void 0,a.extensionPath,a.rootDir),this.reverseIndexManager=new QCt(this.config.rootDir),this.fileReader=new s4,this.indexerStatus=new jCt,this.cancellation=new nIt,this.workerManager=new uIt(this.indexerStatus,this.reverseIndexManager,this.cache),this.dependencyAnalyzer=new eIt(this.languageService,this.resolver,this.cache,this.reverseIndexManager),this.sourceFileCollector=new kW({excludeNodeModules:this.config.excludeNodeModules??!0,yieldIntervalMs:iIt,yieldCallback:()=>rIt(),isCancelled:()=>this.cancellation.isCancelled()}),this.referenceLookup=new sIt(this.reverseIndexManager,this.dependencyAnalyzer,this.fileReader,()=>this.indexerStatus.isReady(),()=>this.indexerStatus.isActive()),this.referencingFilesFinder=new qCt({sourceFileCollector:this.sourceFileCollector,getRootDir:()=>this.config.rootDir,getConcurrency:()=>this.config.indexingConcurrency,findReferencesInFile:(d,p)=>this.referenceLookup.findReferencesInFile(d,p)}),this.referenceLookup.setFallbackFinder(this.referencingFilesFinder),this.symbolDependencyHelper=new fIt({resolve:async(d,p)=>{try{return await this.resolver.resolve(d,p)}catch{return null}}}),this.symbolService=new lIt(this.astWorkerHost,this.symbolCache,this.fileReader,this.resolver,this.symbolDependencyHelper,()=>this.config,d=>this.findReferencingFiles(d),this.languageService),this.graphCrawler=new tIt(this.dependencyAnalyzer,()=>this.config),this.indexingService=new oIt(this.dependencyAnalyzer,this.cache,this.reverseIndexManager,this.sourceFileCollector,this.indexerStatus,this.workerManager,this.cancellation,()=>this.config,()=>rIt(),d=>this.symbolService.getSymbolGraph(d)),this.cacheCoordinator=new YCt(this.cache,this.symbolCache,this.reverseIndexManager),a.enableReverseIndex&&this.enableReverseIndex()}}get workspaceRoot(){return this.config.rootDir}dispose(){return this.disposed=!0,this.disposePromise??=this.disposeResources(),this.disposePromise}async disposeResources(){let o;try{await this.beginShutdown()}catch(a){o=a}if(await this.drainIndexingOperations(),o!==void 0)throw o}async drainIndexingOperations(){if(this.activeIndexingOperations.size!==0)return await Promise.allSettled([...this.activeIndexingOperations]),this.drainIndexingOperations()}beginShutdown(){return this.disposed=!0,this.cancelIndexing(),this.workerShutdownPromise??=this.stopWorkers(),this.workerShutdownPromise}async stopWorkers(){let a=(await Promise.allSettled([this.disposeWorker(),this.astWorkerHost.stop()])).find(d=>d.status==="rejected");if(a)throw a.reason}updateConfig(o){this.config.excludeNodeModules=o.excludeNodeModules??this.config.excludeNodeModules,this.config.maxDepth=o.maxDepth??this.config.maxDepth,o.excludeNodeModules!==void 0&&(this.resolver.updateConfig(o.excludeNodeModules),this.sourceFileCollector.updateOptions({excludeNodeModules:o.excludeNodeModules})),o.enableReverseIndex!==void 0&&(this.config.enableReverseIndex=o.enableReverseIndex,o.enableReverseIndex?this.reverseIndexManager.enable():this.reverseIndexManager.disable()),o.indexingConcurrency!==void 0&&(this.config.indexingConcurrency=o.indexingConcurrency),this.clearCache()}async analyze(o){return this.dependencyAnalyzer.analyze(o)}async analyzeFromIndex(o){return this.dependencyAnalyzer.analyzeFromIndex(o)}clearCache(){this.cacheCoordinator.clearAll(),this.referenceLookup.clearFallbackCache()}invalidateFile(o){return this.referenceLookup.clearFallbackCache(),this.cacheCoordinator.invalidateFile(o)}invalidateFiles(o){return this.referenceLookup.clearFallbackCache(),this.cacheCoordinator.invalidateFiles(o)}async reanalyzeFile(o){this.invalidateFile(o);try{return await this.analyze(o)}catch{return null}}getUnresolvedImportersOf(o){return this.reverseIndexManager.getUnresolvedImportersOf(o)}async reanalyzeUnresolvedImporters(o){let a=this.reverseIndexManager.getUnresolvedImportersOf(o);return await Promise.all(a.map(d=>this.reanalyzeFile(d))),a}handleResolverConfigChange(o){if(this.pendingResolverConfigs.set(fr(o),o),!this.queuedResolverReindex){let a=this.resolverReindex.then(()=>(this.queuedResolverReindex=null,this.reindexForResolverConfigs()));this.queuedResolverReindex=a,this.resolverReindex=a.catch(()=>null)}return this.queuedResolverReindex}isResolverConfig(o){return hjt.test(o)||this.extendsConfigs.has(fr(o))}async reindexForResolverConfigs(){let o=[...this.pendingResolverConfigs];this.pendingResolverConfigs.clear();let a=await this.resolverInputs,d=await Promise.all(o.map(([,I])=>this.resolver.readResolverInputs(I)));if(o.every(([I],B)=>a.has(I)&&a.get(I)===d[B]))return this.extendsConfigs=this.readExtendsConfigs(),null;this.resolver.clearCaches(),ole.releaseWorkspace(this.config.rootDir),this.referenceLookup.clearFallbackCache(),this.cache.clear(),this.symbolCache.clear();let p=Date.now(),y=await this.reindexStaleFiles(this.reverseIndexManager.getIndexedFiles());this.snapshotResolverInputs(p);let E=await this.resolverInputs;for(let[I,B]of a)E.has(I)||E.set(I,B);return o.forEach(([I],B)=>E.set(I,d[B])),y}snapshotResolverInputs(o){this.resolverInputs=this.readResolverInputs(o)}async readResolverInputs(o){let a=new Map;try{let d=Fpn(this.config.rootDir,this.reverseIndexManager.getIndexedFiles());this.extendsConfigs=new Set(Bpn(this.config.rootDir,d)),await Promise.all(d.map(async p=>{let y=await this.resolver.readResolverInputs(p);(await r$n.stat(p)).mtimeMs<o-zIr&&a.set(p,y)}))}catch{a.clear(),this.extendsConfigs.clear()}return a}readExtendsConfigs(){try{let o=Fpn(this.config.rootDir,this.reverseIndexManager.getIndexedFiles());return new Set(Bpn(this.config.rootDir,o))}catch{return new Set}}handleFileDeleted(o){this.referenceLookup.clearFallbackCache(),this.cacheCoordinator.handleFileDeleted(o)}enableReverseIndex(o){let a=this.reverseIndexManager.enable(o);return this.config.enableReverseIndex=!0,this.snapshotResolverInputs(Date.now()),a}disableReverseIndex(){this.config.enableReverseIndex=!1,this.reverseIndexManager.disable()}getSerializedReverseIndex(){return this.reverseIndexManager.getSerialized()}async validateReverseIndex(o=.2,a,d){return this.reverseIndexManager.validate(o,a,d)}async getUnresolvedImports(){let o=this.reverseIndexManager.getUnresolvedImports();if(!o)return null;let a=this.reverseIndexManager.getUnindexedTargets(),d=this.reverseIndexManager.getIndexedFiles(),p=JSON.stringify([o,a,d]);if(this.unresolvedReport?.key!==p){let y=this.collectUnresolvedImports(o,a,d);this.unresolvedReport={key:p,report:y},y.catch(()=>{this.unresolvedReport?.report===y&&(this.unresolvedReport=null)})}return this.unresolvedReport.report}unresolvedReport=null;async collectUnresolvedImports(o,a,d){let p=new bme,y=new Map,E=await Promise.all(o.map(async({sourcePath:ue,specifier:ie})=>{let Re=y.get(ue);Re||(Re=this.languageService.getAnalyzer(ue),y.set(ue,Re));let Ie=await(Re.localTargetOf?Re.localTargetOf(ue,ie,p):this.resolver.localTargetOf(ue,ie));if(!Ie)return[];let Ne=$ln(Ie,p),bt=Ne?null:Kln(Ie,p);return[{importer:ue,specifier:ie,target:Ie,...Ne?{notAnalyzed:Ne}:{},...bt?{caseOf:bt}:{}}]})),I=D3n(this.config.rootDir),B=a.flatMap(({sourcePath:ue,specifier:ie,targetPath:Re})=>{if(I(Re))return[{importer:ue,specifier:ie,target:Re,excluded:!0}];let Ie=Kln(Re,p);return Ie?[{importer:ue,specifier:ie,target:Re,caseOf:Ie}]:[]}),K=fr(i$n.resolve(this.config.rootDir)),Y=z4n(K);return G4n([...E.flat(),...B],K,d,Y,p)}getOutOfRootImports(){return this.reverseIndexManager.getOutOfRootImports()}getIndexStatus(){return this.indexerStatus.getSnapshot()}subscribeToIndexStatus(o){return this.indexerStatus.subscribe(o)}isReverseIndexEnabled(){return this.reverseIndexManager.isEnabled()}hasReverseIndex(){return this.reverseIndexManager.hasEntries()}getCallerCount(o){return this.reverseIndexManager.hasEntries()?this.reverseIndexManager.getCallerCount(o):0}cancelIndexing(){this.indexingService.cancel()}async buildFullIndex(o){if(this.disposed)return{indexedFiles:0,duration:0,cancelled:!0};let a=Date.now(),d=await this.trackIndexingOperation(this.indexingService.buildFullIndex(o));return this.snapshotResolverInputs(a),d}async buildFullIndexInWorker(o,a){if(this.disposed)return{indexedFiles:0,duration:0,cancelled:!0};let d=Date.now(),p=await this.trackIndexingOperation(this.indexingService.buildFullIndexInWorker(o,a));return this.snapshotResolverInputs(d),p}async disposeWorker(){await this.indexingService.disposeWorker()}async reindexStaleFiles(o,a){return this.disposed?0:this.trackIndexingOperation(this.indexingService.reindexStaleFiles(o,a))}trackIndexingOperation(o){return this.activeIndexingOperations.add(o),o.finally(()=>this.activeIndexingOperations.delete(o)).catch(()=>{}),o}async crawl(o,a){return this.graphCrawler.crawl(o,a)}async getReadOnlyDependencyGraph(o){let a=fr(o),d=new Set([a]),p=[],y={};try{let E=this.languageService.getAnalyzer(o),I=await E.parseImports(o),B=new Map,K=await Promise.all(I.map(Y=>E.resolvePath(o,Y.module)));for(let[Y,ue]of I.entries()){let ie=K[Y];if(!ie||!this.resolver.isWithinWorkspace(ie))continue;let Re=fr(ie),Ie=B.get(Re);if(Ie){ue.typeOnly||delete Ie.typeOnly;continue}d.add(Re);let Ne={...cgt(a,Re,ue),...ue.line>0?{sourceLine:ue.line}:{}};B.set(Re,Ne),p.push(Ne),ue.module.startsWith("@")&&ue.module.includes("/")&&!ue.module.startsWith("@/")&&(y[Re]=ue.module)}}catch{}return{nodes:[...d],edges:p,nodeLabels:Object.keys(y).length>0?y:void 0}}async crawlFrom(o,a,d=10,p){return this.graphCrawler.crawlFrom(o,a,d,p)}async findReferencingFiles(o){return this.referenceLookup.findReferencingFiles(o)}getIndexedReferencingFiles(o){return this.reverseIndexManager.getReferencingFiles(fr(o))}getExternalTemplateOwners(o){return/\.html?$/i.test(o)?this.getIndexedReferencingFiles(o).map(a=>a.path).filter(a=>/\.vue$/i.test(a)):[]}async findReferencingFilesThroughBarrels(o){return this.symbolService.findReferencingFilesThroughBarrels(o)}async findReferencingFilesWithFallback(o){return this.referenceLookup.findReferencingFilesWithFallback(o)}findManyReferencingFilesWithFallback(o){return this.referenceLookup.findManyReferencingFilesWithFallback(o)}getSymbolReferencingFiles(o){if(!this.reverseIndexManager.hasEntries())return new Set;let a=this.reverseIndexManager.getSymbolReferencingFiles(o);return new Set(a)}async getSymbolGraph(o){return this.symbolService.getSymbolGraph(o)}useSymbolAnalysisCache(o){this.symbolService.useAnalysisCache(o===null?null:new o$t(o,this.astWorkerHost.buildId()))}async resolveModuleSpecifier(o,a){return this.dependencyAnalyzer.resolveModuleSpecifier(o,a)}async findUnusedSymbols(o){return this.symbolService.findUnusedSymbols(o)}async scanDeadCode(o,a){let d=o??this.config.rootDir;return this.symbolService.scanDeadCode(d,{maxFiles:a?.maxFiles,hasReverseIndex:this.hasReverseIndex(),signal:a?.signal,onProgress:a?.onProgress})}async scanUnreferencedFiles(o,a){return this.symbolService.scanUnreferencedFiles(o??this.config.rootDir,{maxFiles:a?.maxFiles,hasReverseIndex:this.hasReverseIndex(),signal:a?.signal,onProgress:a?.onProgress})}async verifyDependencyUsage(o,a){return this.symbolService.verifyDependencyUsage(o,a)}async verifyDependencyUsageBatch(o,a){return this.symbolService.verifyDependencyUsageBatch(o,a)}async getSymbolDependents(o,a){return this.symbolService.getSymbolDependents(o,a)}async traceFunctionExecution(o,a,d=10){return this.symbolService.traceFunctionExecution(o,a,d)}getCacheStats(){return{dependencyCache:this.cache.getStats(),symbolCache:this.symbolCache.getStats(),symbolAnalyzerFileCount:0,reverseIndexStats:this.reverseIndexManager.getStats()}}async getCacheStatsAsync(){let o=0;try{o=await this.astWorkerHost.getFileCount()}catch{}return{dependencyCache:this.cache.getStats(),symbolCache:this.symbolCache.getStats(),symbolAnalyzerFileCount:o,reverseIndexStats:this.reverseIndexManager.getStats()}}};JJt();pVe();var aqt=class{rootDir;tsConfigPath;extensionPath;maxDepth=50;excludeNodeModules=!0;enableReverseIndex=!1;indexingConcurrency=4;maxCacheSize=500;maxSymbolCacheSize=200;maxSymbolAnalyzerFiles=100;indexingProgressInterval;ignoreTypeImports=!1;customCache;customSymbolCache;customLanguageService;customPathResolver;customAstWorkerHost;customReverseIndexManager;withRootDir(o){return this.rootDir=o,this}withTsConfigPath(o){return this.tsConfigPath=o,this}withExtensionPath(o){return this.extensionPath=o,this}withMaxDepth(o){return this.maxDepth=o,this}withExcludeNodeModules(o){return this.excludeNodeModules=o,this}withIgnoreTypeImports(o){return this.ignoreTypeImports=o,this}withReverseIndex(o){return this.enableReverseIndex=o,this}withIndexingConcurrency(o){return this.indexingConcurrency=o,this}withCacheConfig(o){return o.maxCacheSize!==void 0&&(this.maxCacheSize=o.maxCacheSize),o.maxSymbolCacheSize!==void 0&&(this.maxSymbolCacheSize=o.maxSymbolCacheSize),o.maxSymbolAnalyzerFiles!==void 0&&(this.maxSymbolAnalyzerFiles=o.maxSymbolAnalyzerFiles),this}withIndexingProgressInterval(o){return this.indexingProgressInterval=o,this}withConfig(o){return this.rootDir=o.rootDir,o.tsConfigPath!==void 0&&(this.tsConfigPath=o.tsConfigPath),o.extensionPath!==void 0&&(this.extensionPath=o.extensionPath),o.maxDepth!==void 0&&(this.maxDepth=o.maxDepth),o.excludeNodeModules!==void 0&&(this.excludeNodeModules=o.excludeNodeModules),o.ignoreTypeImports!==void 0&&(this.ignoreTypeImports=o.ignoreTypeImports),o.enableReverseIndex!==void 0&&(this.enableReverseIndex=o.enableReverseIndex),o.indexingConcurrency!==void 0&&(this.indexingConcurrency=o.indexingConcurrency),o.maxCacheSize!==void 0&&(this.maxCacheSize=o.maxCacheSize),o.maxSymbolCacheSize!==void 0&&(this.maxSymbolCacheSize=o.maxSymbolCacheSize),o.maxSymbolAnalyzerFiles!==void 0&&(this.maxSymbolAnalyzerFiles=o.maxSymbolAnalyzerFiles),o.indexingProgressInterval!==void 0&&(this.indexingProgressInterval=o.indexingProgressInterval),this}withCache(o){return this.customCache=o,this}withSymbolCache(o){return this.customSymbolCache=o,this}withLanguageService(o){return this.customLanguageService=o,this}withPathResolver(o){return this.customPathResolver=o,this}withAstWorkerHost(o){return this.customAstWorkerHost=o,this}withReverseIndexManager(o){return this.customReverseIndexManager=o,this}build(){this.validate();let o=this.initializeServices();return new sqt(o)}initializeServices(){let o=this.buildConfig(),a=this.customLanguageService??new ole(this.rootDir,this.tsConfigPath,this.extensionPath,this.ignoreTypeImports),d=this.customPathResolver??new UH(this.tsConfigPath,this.excludeNodeModules,this.rootDir),p=this.customCache??new ort({maxSize:this.maxCacheSize,enableLRU:!0}),y=this.customSymbolCache??new ort({maxSize:this.maxSymbolCacheSize,enableLRU:!0}),E=this.customAstWorkerHost??new Ent(void 0,this.extensionPath,this.rootDir),I=this.customReverseIndexManager??new QCt(this.rootDir),B=new s4,K=new jCt,Y=new nIt,ue=new uIt(K,I,p),ie=new eIt(a,d,p,I),Re=new kW({excludeNodeModules:this.excludeNodeModules,yieldIntervalMs:iIt,yieldCallback:()=>rIt(),isCancelled:()=>Y.isCancelled()}),Ie=new sIt(I,ie,B,()=>K.isReady(),()=>K.isActive()),Ne=new qCt({sourceFileCollector:Re,getRootDir:()=>this.rootDir,getConcurrency:()=>this.indexingConcurrency,findReferencesInFile:(jr,Tn)=>Ie.findReferencesInFile(jr,Tn)});Ie.setFallbackFinder(Ne);let bt=new fIt({resolve:async(jr,Tn)=>{try{return await d.resolve(jr,Tn)}catch{return null}}}),Qt=new lIt(E,y,B,d,bt,()=>o,jr=>Ie.findReferencingFiles(jr),a),Fn=new tIt(ie,()=>o),vr=new oIt(ie,p,I,Re,K,ue,Y,()=>o,()=>rIt(),jr=>Qt.getSymbolGraph(jr)),Kr=new YCt(p,y,I);return this.enableReverseIndex&&I.enable(),{config:o,languageService:a,resolver:d,cache:p,symbolCache:y,fileReader:B,astWorkerHost:E,reverseIndexManager:I,indexerStatus:K,workerManager:ue,cancellation:Y,sourceFileCollector:Re,referencingFilesFinder:Ne,symbolDependencyHelper:bt,dependencyAnalyzer:ie,referenceLookup:Ie,symbolService:Qt,graphCrawler:Fn,indexingService:vr,cacheCoordinator:Kr}}validate(){if(!this.rootDir)throw new Error("rootDir is required");if(this.maxDepth<0)throw new Error("maxDepth must be non-negative");if(this.indexingConcurrency<1)throw new Error("indexingConcurrency must be at least 1");if(this.maxCacheSize<0)throw new Error("maxCacheSize must be non-negative");if(this.maxSymbolCacheSize<0)throw new Error("maxSymbolCacheSize must be non-negative");if(this.maxSymbolAnalyzerFiles<0)throw new Error("maxSymbolAnalyzerFiles must be non-negative")}buildConfig(){return{rootDir:this.rootDir,tsConfigPath:this.tsConfigPath,extensionPath:this.extensionPath,maxDepth:this.maxDepth,excludeNodeModules:this.excludeNodeModules,ignoreTypeImports:this.ignoreTypeImports,enableReverseIndex:this.enableReverseIndex,indexingConcurrency:this.indexingConcurrency,maxCacheSize:this.maxCacheSize,maxSymbolCacheSize:this.maxSymbolCacheSize,maxSymbolAnalyzerFiles:this.maxSymbolAnalyzerFiles,indexingProgressInterval:this.indexingProgressInterval}}};pVe();Qht();nO();YL();cN();var nyn=class{constructor(o,a="info",d=[]){this.source=o;this.entries=d;this.level=a}source;entries;level;setLevel(o){this.level=o}debug(o){this.record("debug",o)}info(o){this.record("info",o)}warn(o){this.record("warn",o)}error(o){this.record("error",o)}record(o,a){this.entries.length>=1e3&&this.entries.shift(),this.entries.push({level:o,source:this.source,message:a,timestamp:Date.now()})}getEntries(){return[...this.entries]}clear(){this.entries.length=0}},cqt=class{sharedEntries=[];createLogger(o,a){return new nyn(o,a??"info",this.sharedEntries)}getCollectedEntries(){return[...this.sharedEntries]}clear(){this.sharedEntries.length=0}getErrorCount(){let o=0,a=0;for(let d of this.sharedEntries)d.level==="error"?o+=1:d.level==="warn"&&(a+=1);return{errors:o,warnings:a,total:this.sharedEntries.length}}};sjt({createLogger(c,o){return new l4t(c,o)}});Tnt.setDefaultLevel(o3n("LOG_LEVEL"));var ryn=e1("CliRuntime");function iyn(c,o=process.cwd()){if(c===void 0)return F4n(o);if(c.trim()==="")throw new Ku("--workspace needs a directory.",Au.WORKSPACE_NOT_FOUND);let a=PVe.resolve(o,c);if(!G3e.statSync(a,{throwIfNoEntry:!1})?.isDirectory())throw new Ku(`Workspace directory not found: ${c}`,Au.WORKSPACE_NOT_FOUND);return a}function GIr(c){let o=PVe.join(c,"tsconfig.json");return G3e.existsSync(o)?o:void 0}var lqt=class{workspaceRoot;stateDir;cacheEnabled;requireProject;_initialized=!1;_indexReady=!1;_sourceFiles=null;indexCache=null;errorCollectorBackend=null;progress=new bwt(!1);constructor(o,a){this.workspaceRoot=PVe.resolve(o),this.stateDir=PVe.join(this.workspaceRoot,".graph-it"),this.cacheEnabled=(a?.cache??!0)&&!process.env.GRAPH_IT_NO_CACHE,this.requireProject=a?.requireProject??!1}get isProjectRoot(){return!this.requireProject||bnt(this.workspaceRoot)}assertProjectRoot(){if(!this.isProjectRoot)throw new Ku(`No project found in ${this.workspaceRoot} or above it: no marker of a supported language (package.json, tsconfig.json, pyproject.toml, Cargo.toml, go.mod, pom.xml, build.gradle, *.csproj, ...). Run graph-it inside a project, or pass --workspace <dir> to analyze this directory anyway.`,Au.WORKSPACE_NOT_FOUND)}clearCache(){new A_t(this.workspaceRoot,[]).clear()}get initialized(){return this._initialized}enableErrorCollection(){this.errorCollectorBackend||(this.errorCollectorBackend=new cqt,sjt(this.errorCollectorBackend))}disableErrorCollection(){if(!this.errorCollectorBackend)return[];let o=this.errorCollectorBackend.getCollectedEntries();return sjt({createLogger(a,d){return new l4t(a,d)}}),this.errorCollectorBackend=null,o}getCollectedErrors(){return this.errorCollectorBackend?.getCollectedEntries()??[]}clearCollectedErrors(){this.errorCollectorBackend?.clear()}async init(){if(this._initialized)return;this.assertProjectRoot(),G3e.mkdirSync(this.stateDir,{recursive:!0});let o=GIr(this.workspaceRoot);gu.parser=new WCt,gu.resolver=new UH(o,!0,this.workspaceRoot);let a=PVe.resolve(__dirname,"..");gu.astWorkerHost=new Ent(void 0,a,this.workspaceRoot),await gu.astWorkerHost.start();let d=new aqt().withRootDir(this.workspaceRoot).withMaxDepth(50).withExcludeNodeModules(!0).withReverseIndex(!0).withExtensionPath(a);o&&d.withTsConfigPath(o),gu.spider=d.build(),this.cacheEnabled&&(this.indexCache=new A_t(this.workspaceRoot,await this.collectSourceFiles()),gu.indexCache=this.indexCache),gu.config={rootDir:this.workspaceRoot,tsConfigPath:o,excludeNodeModules:!0,maxDepth:50,extensionPath:a},gu.isReady=!0,this._initialized=!0,ryn.info("Runtime initialized for",this.workspaceRoot)}async ensureIndexed(o){if(!this._initialized||!gu.spider)throw new Ku("Runtime not initialized. Call init() first.",Au.WORKSPACE_NOT_FOUND);if(this._indexReady){let B=gu.warmupInfo;return{filesIndexed:B?.filesIndexed??0,filesFound:B?.filesFound??B?.filesIndexed??0,filesAnalyzed:B?.filesAnalyzed??0,fromCache:B?.fromCache??!1,durationMs:B?.durationMs??0}}let a=gu.spider,d=Date.now(),p=o?.silent??!1,y=!p&&process.stderr.isTTY===!0,E="Indexing",I=a.subscribeToIndexStatus(B=>{y&&B.state==="indexing"&&B.total>0&&this.progress.redraw(` ${E}: ${B.processed}/${B.total} files...`)});try{let B=await OBn(a,{cache:this.indexCache,reverseIndexOptions:{excludeNodeModules:!0,ignoreTypeImports:!1},buildFullIndex:()=>(y&&this.progress.redraw(" Indexing workspace..."),a.buildFullIndex()),onWait:ie=>{p||this.progress.line(` Waiting for the index being built by process ${ie??"?"}...`)},onReindexStart:()=>{E="Re-indexing changed"}}),K=Date.now()-d;if(!p&&!B.cancelled){this.progress.line(this.describeOutcome(B));let ie=this.describeOutOfRootImports();ie&&process.stderr.write(` Warning: ${ie}
47459
- `)}ryn.info(`${B.fromCache?"Cache":"Index"}: ${B.filesIndexed} files,`,`${B.filesAnalyzed} analyzed in ${K}ms`),this.saveState({lastScanTimestamp:new Date().toISOString(),filesIndexed:B.filesIndexed,workspaceRoot:this.workspaceRoot});let{cancelled:Y,...ue}=B;return gu.warmupInfo={completed:!0,durationMs:K,...ue},this._indexReady=!0,{...ue,durationMs:K}}finally{I()}}describeOutOfRootImports(){let o=gu.getSpider().getOutOfRootImports();if(!o||o.count===0)return null;let a=Uln(this.workspaceRoot),d=a?Vln(process.cwd(),a):null;return`${Hln(o,d)} Rerun with --workspace ${d??"<directory containing them>"} to include them.`}describeOutcome(o){return o.fromCache?o.filesAnalyzed===0?` Loaded ${o.filesIndexed} files from cache (nothing changed)`:` Loaded ${o.filesIndexed} files from cache, re-indexed ${o.filesAnalyzed} changed`:` Indexed ${o.filesIndexed}/${o.filesFound} files`}async collectSourceFiles(){return this._sourceFiles??=await new kW({excludeNodeModules:!0,yieldIntervalMs:30,isCancelled:()=>!1}).collectAllSourceFiles(this.workspaceRoot),this._sourceFiles}async dispose(){gu.astWorkerHost&&await gu.astWorkerHost.stop(),gu.spider&&await gu.spider.dispose(),gu.reset(),this._initialized=!1,this._indexReady=!1}saveState(o){try{G3e.writeFileSync(PVe.join(this.stateDir,"state.json"),JSON.stringify(o,null,2))}catch(a){ryn.warn("Could not save state:",a instanceof Error?a.message:String(a))}}loadState(){try{let o=G3e.readFileSync(PVe.join(this.stateDir,"state.json"),"utf-8");return JSON.parse(o)}catch{return null}}};ayn();var KAn="1.25.5",d7t={workspace:{type:"string",short:"w"},format:{type:"string",short:"f"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"},reindex:{type:"boolean"},"no-cache":{type:"boolean"}};X1e.setSource("cli");var u7t,f7t,vGr=new Set(["init","check","check-architecture","architecture","export","review-pr","wiki","scan"]),mar=!1;function _ar(){if(!mar){mar=!0;try{sFn(X1e.snapshot())}catch{}}}process.on("exit",()=>{_ar()});process.stdout.on("error",c=>{if(c.code!=="EPIPE")throw c;process.exit(Au.SUCCESS)});for(let c of["SIGINT","SIGTERM"])process.on(c,()=>{_ar(),u7t?.progress.interrupt(),f7t??=c==="SIGINT"?130:143,process.exitCode=f7t,u7t&&u7t.dispose().catch(()=>{})});var gar=`
47459
+ `)}ryn.info(`${B.fromCache?"Cache":"Index"}: ${B.filesIndexed} files,`,`${B.filesAnalyzed} analyzed in ${K}ms`),this.saveState({lastScanTimestamp:new Date().toISOString(),filesIndexed:B.filesIndexed,workspaceRoot:this.workspaceRoot});let{cancelled:Y,...ue}=B;return gu.warmupInfo={completed:!0,durationMs:K,...ue},this._indexReady=!0,{...ue,durationMs:K}}finally{I()}}describeOutOfRootImports(){let o=gu.getSpider().getOutOfRootImports();if(!o||o.count===0)return null;let a=Uln(this.workspaceRoot),d=a?Vln(process.cwd(),a):null;return`${Hln(o,d)} Rerun with --workspace ${d??"<directory containing them>"} to include them.`}describeOutcome(o){return o.fromCache?o.filesAnalyzed===0?` Loaded ${o.filesIndexed} files from cache (nothing changed)`:` Loaded ${o.filesIndexed} files from cache, re-indexed ${o.filesAnalyzed} changed`:` Indexed ${o.filesIndexed}/${o.filesFound} files`}async collectSourceFiles(){return this._sourceFiles??=await new kW({excludeNodeModules:!0,yieldIntervalMs:30,isCancelled:()=>!1}).collectAllSourceFiles(this.workspaceRoot),this._sourceFiles}async dispose(){gu.astWorkerHost&&await gu.astWorkerHost.stop(),gu.spider&&await gu.spider.dispose(),gu.reset(),this._initialized=!1,this._indexReady=!1}saveState(o){try{G3e.writeFileSync(PVe.join(this.stateDir,"state.json"),JSON.stringify(o,null,2))}catch(a){ryn.warn("Could not save state:",a instanceof Error?a.message:String(a))}}loadState(){try{let o=G3e.readFileSync(PVe.join(this.stateDir,"state.json"),"utf-8");return JSON.parse(o)}catch{return null}}};ayn();var KAn="1.25.6",d7t={workspace:{type:"string",short:"w"},format:{type:"string",short:"f"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"},reindex:{type:"boolean"},"no-cache":{type:"boolean"}};X1e.setSource("cli");var u7t,f7t,vGr=new Set(["init","check","check-architecture","architecture","export","review-pr","wiki","scan"]),mar=!1;function _ar(){if(!mar){mar=!0;try{sFn(X1e.snapshot())}catch{}}}process.on("exit",()=>{_ar()});process.stdout.on("error",c=>{if(c.code!=="EPIPE")throw c;process.exit(Au.SUCCESS)});for(let c of["SIGINT","SIGTERM"])process.on(c,()=>{_ar(),u7t?.progress.interrupt(),f7t??=c==="SIGINT"?130:143,process.exitCode=f7t,u7t&&u7t.dispose().catch(()=>{})});var gar=`
47460
47460
  graph-it \u2014 Graph-It-Live standalone CLI
47461
47461
 
47462
47462
  Usage: graph-it <command> [options]
@@ -3349,7 +3349,7 @@ ${e.toon}`,a=zp(JSON.stringify(e,null,2),r);return Dn.record({toolName:"graphitl
3349
3349
 
3350
3350
  ${n.join(`
3351
3351
  `)}`}function js(e,t=[]){let r=tz(e,"mcp");return t.length===0?r:`${r}
3352
- PARAMETERS: ${t.join(", ")}.`}var _k=["toon","json","markdown"],Sk="Output format: 'toon' (default, compact Token-Oriented Object Notation), 'json' (the raw object, for code that parses it), or 'markdown' (a readable report of this tool's result)";function Ek(e,t,r=3){let a=t.toLowerCase(),n=Math.max(2,Math.floor(a.length/3));return e.map(i=>({name:i,distance:nz(i.toLowerCase(),a)})).filter(i=>i.distance<=n).sort((i,o)=>i.distance-o.distance||i.name.localeCompare(o.name)).slice(0,r).map(i=>i.name)}function nz(e,t){let r=Array.from({length:t.length+1},(a,n)=>n);for(let a=1;a<=e.length;a++){let n=r[0];r[0]=a;for(let i=1;i<=t.length;i++){let o=r[i];r[i]=Math.min(r[i]+1,r[i-1]+1,n+(e[a-1]===t[i-1]?0:1)),n=o}}return r[t.length]}function Ck(e){return e.map((t,r)=>typeof t=="number"?`[${t}]`:r===0?String(t):`.${String(t)}`).join("")}function e_(e){if(typeof e=="string"){let t=e.length>60?`${e.slice(0,57)}...`:e;return JSON.stringify(t)}return Array.isArray(e)?"an array":e===null?"null":typeof e=="object"?"an object":String(e)}var Ak={string:"a string",number:"a number",int:"an integer",boolean:"true or false",array:"an array",object:"an object"};function rz(e){let t=Number(e.code==="too_small"?e.minimum:e.maximum),r={string:" characters",array:" items"}[e.origin]??"";return r?e.code==="too_small"?`at least ${t}${r}`:`at most ${t}${r}`:`${e.code==="too_small"?">":"<"}${e.inclusive?"=":""} ${t}`}function wk(e){switch(e.code){case"invalid_type":return Ak[e.expected]??e.expected;case"invalid_value":return e.values.length===1?e_(e.values[0]):`one of ${e.values.map(t=>typeof t=="string"?t:e_(t)).join(", ")}`;case"too_small":case"too_big":return rz(e);case"invalid_format":return e.format==="regex"&&"pattern"in e?`a string matching ${String(e.pattern)}`:`a valid ${e.format}`;case"not_multiple_of":return`a multiple of ${String(e.divisor)}`;case"invalid_union":{let t=e.errors.flatMap(r=>r.map(wk)).filter(r=>r!==void 0);return t.length>0?[...new Set(t)].join(" or "):void 0}default:return}}var Qv=5;function iz(e,t,r){let a=t.length>0?` in "${Ck(t)}"`:"",n=e.slice(0,Qv).map(s=>{let[l]=t.length===0?Ek([...r],s,1):[],c=l?` Did you mean "${l}"?`:"";return`Unknown parameter "${s}"${a}.${c}`}),i=e.length>Qv?[`And ${e.length-Qv} more unknown parameters.`]:[],o=t.length===0?[`Parameters: ${r.join(", ")}.`]:[];return[...n,...i,...o].join(" ")}function az(e,t){if(e.code==="unrecognized_keys")return iz(e.keys,e.path,t);let r=Ck(e.path),a=e.input;if(e.code==="invalid_type"&&a===void 0&&r!=="")return`Missing required parameter "${r}" (${Ak[e.expected]??e.expected}).`;let n=wk(e);if(n===void 0)return r===""?e.message:`"${r}": ${e.message}`;let o=Array.isArray(a)&&(e.code==="too_big"||e.code==="too_small")?`${a.length} items`:e_(a),s=a===void 0?"":`; got ${o}`;return`${r===""?"Parameters":JSON.stringify(r)} must be ${n}${s}.`}function Us(e){let t=U.toJSONSchema(e,{io:"input",unrepresentable:"any"});return Object.keys(t.properties??{})}function oz(e,t){let r=t.some(a=>a.code==="unrecognized_keys")?Us(e):[];return[...new Set(t.map(a=>az(a,r)))].join(" ")}function kk(e,t){let r=e.safeParse(t,{reportInput:!0});return r.success?{success:!0,data:r.data}:{success:!1,error:oz(e,r.error.issues),issues:r.error.issues}}function qs(e){return{"~standard":{...e["~standard"],validate:r=>{let a=kk(e,r);return a.success?{value:a.data}:{issues:[{message:a.error}]}}}}}import*as cn from"node:path";var t_=["path","louvain"];var Rk=["units","folder","matrix"],Tk=["svg","html","diagram-spec"],Ik=e=>e==="diagram-spec"?"architecture.diagram-spec.json":`architecture.${e}`,Pk=["light","dark"];function Dk(e,t){let r=t?.replaceAll("\\","/");return{view:e??(r===void 0?"units":"folder"),folder:r}}var sz={down:{colour:"line",text:"dependency"},upward:{colour:"accent",text:"upward"},cycle:{colour:"cycle",text:"runtime cycle"},"type-only":{colour:"cycle",dash:"2 3",text:"type-only cycle"},lazy:{colour:"cycle",dash:"8 4",text:"lazy cycle (import())"},cut:{colour:"cycle",text:"cell to cut"},error:{colour:"error",text:"breaks a rule"},accepted:{colour:"error",dash:"4 3",text:"accepted in baseline"},dead:{colour:"muted",dash:"4 3",text:"dead file"},"inferred-role":{colour:"line",dash:"3 3",text:"dashed border: role inferred"}},T6=Object.keys(sz);var P6=new Set("(,=:[!&|?{};~+-*%<>^");var xk=["high","medium","low"];var Vs="1.1.0",Ok="1.25.5",H6=U.enum(["json","toon"]).default("json").describe("Output format: 'json' (default) or 'toon' (Token-Oriented Object Notation for reduced token usage)"),ur={FILE_PATH:1024,SYMBOL_NAME:500,FILE_CONTENT:1024*1024,GENERIC_STRING:10*1024},et=U.string().max(ur.FILE_PATH,`File path exceeds maximum length of ${ur.FILE_PATH} bytes`).refine(e=>!e.includes("\0"),"File path contains null bytes"),ba=U.string().max(ur.SYMBOL_NAME,`Symbol name exceeds maximum length of ${ur.SYMBOL_NAME} bytes`).refine(e=>!e.includes("\0"),"Symbol name contains null bytes"),$k=U.string().max(ur.FILE_CONTENT,`File content exceeds maximum size of ${ur.FILE_CONTENT} bytes (~1 MB)`).refine(e=>!e.includes("\0"),"File content contains null bytes"),va=U.string().max(ur.GENERIC_STRING,`String exceeds maximum length of ${ur.GENERIC_STRING} bytes`).refine(e=>!e.includes("\0"),"String contains null bytes"),ya={MAX_LIMIT:1e4,MAX_OFFSET:1e5,DEFAULT_LIMIT:1e3},lz=U.object({hubScore:U.number().min(0,"hubScore must be >= 0").max(1,"hubScore must be <= 1"),loc:U.number().int().positive().optional(),fileExtension:U.string().optional(),communityId:U.number().int().min(0).optional(),communityKey:U.string().optional()}),cz=U.object({source:U.string(),target:U.string(),relationType:U.enum(["dependency","call","reference","containment"]).optional()}),W6=U.object({nodes:U.array(U.string()),edges:U.array(cz),nodeLabels:U.record(U.string(),U.string()).optional(),parentCounts:U.record(U.string(),U.number()).optional(),unusedEdges:U.array(U.string()).optional(),nodeMetadata:U.record(U.string(),lz).optional()}),zk=U.object({workspacePath:et.describe("Absolute path to the project/workspace directory to analyze"),tsConfigPath:et.optional().describe("Optional path to tsconfig.json for path alias resolution. Omitted: kept when the same workspace is selected again, otherwise each file uses its nearest tsconfig.json"),excludeNodeModules:U.boolean().optional().describe("Whether to exclude node_modules (default: true)"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum crawl depth (default: 50, min: 1, max: 100)")}).strict(),Mk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze")}).strict(),Lk=U.union([U.literal(0),U.number().int().min(500).max(16e3)]).default(4e3).optional().describe("Maximum output size in tokens (default: 4000, 500-16000, or 0 for no limit). A larger result is cut and reports truncated=true, omitted counts and nextOffset; pass nextOffset as offset to read the rest."),i_=U.number().int().min(0).max(ya.MAX_OFFSET).optional().describe("Items to skip, usually the nextOffset of the previous response (default: 0)"),Fk=U.object({entryFile:et.describe("Workspace-relative or absolute path to the entry file"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to crawl (default: from config, min: 1, max: 100)"),limit:U.number().min(1).max(ya.MAX_LIMIT).optional().describe(`Maximum number of nodes to return (for pagination, max: ${ya.MAX_LIMIT})`),offset:U.number().min(0).max(ya.MAX_OFFSET).optional().describe(`Number of nodes to skip (for pagination, max: ${ya.MAX_OFFSET})`),onlyUsed:U.boolean().optional().describe("If true, only returns edges where symbols are actually used (requires AST analysis, slower)"),communityMode:U.enum(t_).optional().describe("How nodes are grouped into communityId/communityKey: 'path' (default) by folder, 'louvain' by import structure (deterministic Louvain over the crawled graph)"),tokenBudget:Lk}).strict(),Bk=U.object({targetPath:et.describe("Workspace-relative or absolute path to the file to find references for")}).strict(),jk=U.object({sourceFile:et.describe("Workspace-relative or absolute path to the source file (the one importing using symbols)"),targetFile:et.describe("Workspace-relative or absolute path to the target file (the one providing symbols)")}).strict(),Uk=U.object({fromFile:et.describe("Workspace-relative or absolute path of the file containing the import"),moduleSpecifier:va.describe('The module specifier to resolve (e.g., "./utils", "@/components/Button")')}).strict(),qk=U.object({}).strict(),Nk=1e4,Gk=U.object({filePaths:U.array(et).max(Nk).describe(`Array of file paths, workspace-relative or absolute, to invalidate from the cache (max: ${Nk} per call; use rebuild_index for the whole workspace). Needed only for edits the file watcher missed: it invalidates changed files on its own.`)}).strict(),Vk=U.object({}).strict(),Hk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze for symbols")}).strict(),Wk=U.enum(xk).optional().describe("Lowest confidence listed (default: high). high: the file is imported, no importer uses the export and no other evidence of use was found: a deletion candidate. medium: only tests use it, a computed import may reach it, a decorator may register it, its name is written again in its file (or, in Rust, in another file), or it sits in a test file. low: nothing imports the file (entry point by convention, script, config), review only. Unlisted items are counted in byConfidence."),Kk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to check for unused exported symbols"),minConfidence:Wk}).strict(),Jk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file containing the root symbol"),symbolName:ba.describe("Name of the root symbol to trace from"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to trace the call chain (default: 10, min: 1, max: 100)")}).strict(),Zk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze"),symbolName:ba.optional().describe("Optional: Only analyze changes to this specific symbol"),oldContent:$k.describe("The old version of the file content"),newContent:$k.optional().describe("The new version of the file content (if not provided, reads current file)")}).strict(),Yk=U.object({baseRef:va.describe("Git base ref to compare against, for example origin/main"),headRef:va.optional().describe("Optional Git head ref; defaults to the checked-out worktree"),maxFiles:U.number().int().min(1).optional().describe("Optional cap on changed files analysed (default: 200, no upper bound)"),maxDepth:U.number().int().min(1).max(10).optional()}).strict(),Xk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file being modified"),symbolName:ba.describe("Name of the symbol being modified"),includeTransitive:U.boolean().optional().describe("Include transitive dependents (default: false)"),maxDepth:U.number().min(1).max(20).optional().describe("Maximum depth for transitive analysis (default: 3, min: 1, max: 20)")}).strict(),K6=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze"),includeExternal:U.boolean().optional().describe("Include calls to external modules (default: false)")}).strict(),Qk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to generate a codemap for")}).strict(),e1=U.object({filePath:et.describe("Workspace-relative or absolute path to the file containing the target symbol."),symbolName:ba.describe("Name of the symbol to query (function, class, method). A bare name shared by several symbols in the file returns reason='ambiguous' with candidates; qualified names such as 'Class.method' are not supported."),symbolId:ba.optional().describe("Exact node id taken from a previous result or candidate (valid for the current index only, since ids embed the line). Narrows symbolName to that node; a stale id returns reason='stale_selector'."),startLine:U.number().int().min(0).optional().describe("Declaration line of the symbol, 0-based like 'startLine' in results and candidates (editor line 3 is 2). Selects one of several same-name symbols."),direction:U.enum(["callers","callees","both"]).optional().describe("Direction of traversal: 'callers', 'callees', or 'both' (default: 'both')"),depth:U.number().min(1).max(10).optional().describe("Maximum BFS traversal depth (default: 2, min: 1, max: 10)"),relationTypes:U.array(U.enum(["CALLS","INHERITS","IMPLEMENTS","USES","REFERENCES"])).optional().describe("Filter by relation types (default: CALLS, INHERITS, IMPLEMENTS and REFERENCES; USES is added with includeTypeOnly)"),includeTypeOnly:U.boolean().optional().describe("Also include USES edges (type-only references such as interfaces and type aliases). Default is false. Ignored when relationTypes is set."),offset:i_,tokenBudget:Lk}).strict(),a_=U.object({question:U.string().max(1024).describe("Natural language question about the codebase"),depth:U.number().int().min(1).max(5).default(2).optional().describe("BFS traversal depth from seed nodes (default: 2, min: 1, max: 5)"),tokenBudget:U.number().int().min(500).max(16e3).default(4e3).optional().describe("Maximum token budget for the output subgraph (default: 4000)"),fileFilter:U.string().max(256).optional().describe("Workspace-relative glob restricting the search (e.g. 'src/analyzer/**'); a glob matching no indexed file is an error")}).strict(),J6=a_.extend({outputFormat:U.enum(["toon","json"]).optional()}),n_=U.object({id:va.refine(e=>e.trim().length>0,"Seed ID must not be empty").optional(),filePath:et.refine(e=>e.trim().length>0,"Seed file path must not be empty").optional(),symbolName:ba.refine(e=>e.trim().length>0,"Seed symbol name must not be empty").optional(),label:va.refine(e=>e.trim().length>0,"Seed label must not be empty").optional()}).refine(e=>e.id!==void 0||e.filePath!==void 0||e.symbolName!==void 0||e.label!==void 0,"A seed must contain an id, filePath, symbolName, or label"),uz=U.enum(["CONTAINS","IMPORTS","CALLS","INHERITS","IMPLEMENTS","USES","TESTED_BY","IMPACTED_BY","BELONGS_TO","REFERENCES","EXPLAINS","DOCUMENTS"]),o_=U.object({question:U.string().max(1024).optional(),seeds:U.array(n_).max(500).optional(),mode:U.enum(["search","neighbors","path","impact","refactor","overview"]).optional(),from:n_.optional(),to:n_.optional(),relations:U.array(uz).max(12).refine(e=>new Set(e).size===e.length,"Relations must be unique").optional(),scope:U.string().max(256).optional(),depth:U.number().int().min(1).max(5).optional(),maxNodes:U.number().int().min(1).max(500).optional(),tokenBudget:U.number().int().min(500).max(16e3).optional(),directed:U.boolean().optional(),cursor:U.string().min(1).max(4096).optional(),detail:U.enum(["compact","standard","full"]).optional()}).strict().superRefine((e,t)=>{let r=e.question!==void 0&&e.question.trim().length>0,a=(e.seeds?.length??0)>0,n=e.from!==void 0,i=e.to!==void 0;n!==i&&t.addIssue({code:"custom",message:"Both from and to are required for a path request"}),e.mode==="path"&&!(n&&i)&&t.addIssue({code:"custom",message:"Path mode requires both from and to"}),e.mode!==void 0&&e.mode!=="path"&&(n||i)&&t.addIssue({code:"custom",message:"from and to are only valid in path mode"}),e.mode===void 0&&n&&i&&(r||a)&&t.addIssue({code:"custom",message:"Set mode to path when combining endpoints with a question or seeds"}),!r&&!a&&!(n&&i)&&t.addIssue({code:"custom",message:"Provide a question, at least one seed, or both from and to"})}),Z6=o_.transform(e=>{let t=e.question!==void 0&&e.question.trim().length>0,r=(e.seeds?.length??0)>0,a=e.from!==void 0&&e.to!==void 0;return e.mode===void 0&&!t&&!r&&a?{...e,mode:"path"}:e}),t1=U.object({outputDir:et.optional().refine(e=>e===void 0||!cn.isAbsolute(e),"Output directory must be relative to the workspace").describe("Workspace-relative output directory for wiki files (default: wiki)"),topHubsLimit:U.number().int().min(1).max(50).optional().describe("Number of top hub files to list (max: 50, default: 10)"),scope:et.optional().refine(e=>e===void 0||!cn.isAbsolute(e),"Scope must be relative to the workspace").describe("Relative path within workspace to restrict wiki to (e.g. 'src/'; default: the whole workspace)"),exclude:U.array(va).max(100).optional().describe("Relative glob-like patterns to exclude (e.g. ['tests/**', '**/*.test.ts']); omitted: tests/, dist/, *.test.ts and the other default exclusions")}).strict(),r_=U.union([U.number().int().min(0),U.string().min(1).max(256)]).describe("Numeric group id from a previous response, or a group key (e.g. 'analyzer') or label as a string; 0 or 'unassigned' for files without a group"),n1=U.object({communityMode:U.enum(t_).optional().describe("How files are grouped: 'path' (default) by folder domain, 'louvain' by import structure"),maxFiles:U.number().int().min(1).max(ya.MAX_OFFSET).optional().describe("Analyse only the first maxFiles source files, like graph-it architecture --maxFiles (default: all)"),level:U.enum(["groups","units"]).optional().describe("groups (default): folder or Louvain groups; units: the declared elements of graphit.architecture.json, else the detected projects (a top-level folder for files outside every project), with their layers, roles and role evidence, unit edges (down, upward, cycle) with their rules, and cycles, like graph-it architecture --level units"),folder:U.string().min(1).max(1024).optional().describe("communityMode 'path' only: walk down one level, below this unit key (from level units) or group key; groups are then its sub-folders plus its own files (key = folder), nestedGroups those holding sub-folders; group, from and to then name groups of this level"),view:U.enum(["matrix"]).optional().describe("matrix: the dependency structure matrix of the level (units with level units, a folder's groups with folder, else the groups): rows ordered by layer with each cycle's rows together, non-zero cells (row imports column, diagonal = pairs inside) paged by offset/limit, per-row Ce/Ca/instability with their formula, cycles and totals of every cell, like graph-it architecture --matrix"),group:r_.optional().describe("Return this group's files and its incoming / outgoing group edges"),from:r_.optional().describe("Source group of the edge whose file pairs to return (requires to); with level units, a unit key such as 'apps/web', 'scripts' or a declared element name"),to:r_.optional().describe("Target group of the edge whose file pairs to return (requires from); with level units, a unit key"),limit:U.number().int().min(1).max(500).optional().describe("Items per page: groups and group edges, a group's files and its incoming and outgoing edges, or file pairs (default: 50)"),offset:i_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the group ids or offset come from; the call fails if the architecture has changed since")}).strict().superRefine((e,t)=>{e.from===void 0!=(e.to===void 0)&&t.addIssue({code:"custom",message:"Both from and to are required for edge evidence"}),e.group!==void 0&&e.from!==void 0&&t.addIssue({code:"custom",message:"Pass either group or from and to, not both"}),e.level==="units"&&e.group!==void 0&&t.addIssue({code:"custom",message:"level units lists units and unit edges, or with from and to a unit edge's file pairs: drop group"}),e.folder!==void 0&&(e.level==="units"||e.communityMode==="louvain")&&t.addIssue({code:"custom",message:"folder walks the path-mode folders: drop level units and communityMode louvain"}),e.view==="matrix"&&(e.group!==void 0||e.from!==void 0)&&t.addIssue({code:"custom",message:"view matrix returns the whole level: drop group, from and to (call them afterwards for a row or a cell)"})}),Gs=U.string().min(1).max(1024).refine(e=>!cn.isAbsolute(e)&&!cn.win32.isAbsolute(e),"Must be relative to the workspace"),r1=U.object({config:Gs.optional().describe("Rules file, relative to the workspace (default: graphit.architecture.json)"),baseline:Gs.optional().describe("Accepted violations, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),rule:U.string().min(1).max(128).optional().describe("Return only the violations of this rule"),limit:U.number().int().min(1).max(500).optional().describe("Violations per page; also caps unmatchedFiles and resolved (default: 50)"),offset:i_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the offset comes from; the call fails if the code, rules or baseline changed since")}).strict(),i1=U.object({view:U.enum(Rk).optional().describe("'units' (default): every unit; 'folder': the groups of the unit or folder named by folder (default when folder is set); 'matrix': the dependency structure matrix of that level"),folder:U.string().min(1).max(1024).optional().describe("Unit or folder key, '/'-separated as explore_architecture returns it (e.g. 'src/analyzer')"),diagramFormat:U.enum(Tk).optional().describe("'svg' (default): a bare SVG; 'html': one self-contained page following the reader's light or dark scheme; 'diagram-spec': the level's data as JSON (schemas/diagram-spec.schema.json) for a diagram skill"),theme:U.enum(Pk).optional().describe("Colours of the SVG (default: light); svg only"),rules:U.boolean().optional().describe("Draw the violations of graphit.architecture.json in the error colour, and the baseline's accepted ones dashed"),config:Gs.optional().describe("Rules file with rules, relative to the workspace (default: graphit.architecture.json)"),baseline:Gs.optional().describe("Accepted violations with rules, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),output:Gs.optional().describe("File to write, relative to the workspace and inside it; without it, a diagram over the inline cap goes to architecture.<diagramFormat> (architecture.diagram-spec.json for a spec)")}).strict().superRefine((e,t)=>{let{view:r}=Dk(e.view,e.folder);r==="folder"&&e.folder===void 0&&t.addIssue({code:"custom",message:"view folder draws the groups of one unit or folder: pass folder"}),r==="units"&&e.folder!==void 0&&t.addIssue({code:"custom",message:"view units draws every unit: drop folder, or use view folder"}),e.theme!==void 0&&(e.diagramFormat??"svg")!=="svg"&&t.addIssue({code:"custom",message:"theme sets the colours of diagramFormat svg; the HTML page follows the reader's scheme and a spec has none"}),!e.rules&&(e.config!==void 0||e.baseline!==void 0)&&t.addIssue({code:"custom",message:"config and baseline apply to the rules overlay: add rules: true"});let a=e.diagramFormat??"svg",n=cn.extname(Ik(a));e.output!==void 0&&cn.extname(e.output).toLowerCase()!==n&&t.addIssue({code:"custom",message:`output must end with ${n} for diagramFormat ${a}; got ${e.output}`})}),a1=U.object({scopePath:et.optional().describe("Folder to scope the scan, workspace-relative or absolute (default: workspace root). Must be inside the workspace."),maxFiles:U.number().int().min(1).optional().describe("Optional cap on analysed files (default: every analysable file in scope, no upper bound). When the cap stops the scan, truncated=true and filesBeyondLimit > 0: the result is partial."),minConfidence:Wk,verbose:U.boolean().optional().describe('Also list the unused exports left out as excluded, each with its reason: the manifest field that declares it (declared:package.json#exports["./x"]), a Rust attribute, or convention:framework-default-export (default: false)'),unreferencedFiles:U.boolean().optional().describe("List whole files no production file imports instead of unused exports (default: false): low (no-importer) when nothing imports the file, medium (test-only-use) when only tests do. minConfidence then defaults to low. medium items list testImporters, the tests to delete or clean up with the file. Left out (excluded with verbose): test files, manifest entry points, files a non-test file names by path (bundler entry, package.json script, CI workflow, Makefile, shell script), JSX/Vue default exports, framework route files (Next.js, SvelteKit, Remix, Nuxt, Astro...), files a bundler loads (import.meta.glob, new URL, HTML entry), migrations, .d.ts files, *.config.* files, files a folder's .gitignore ignores, Python package __init__.py. Then the files only dead files and tests import (reason cascade, via = their dead importers); tests = the tests that import nothing but dead files.")}).strict();function o1(e,t){return Yv(e,t)}function s_(e,t,r,a,n){return{success:!0,data:e,metadata:{executionTimeMs:t,toolVersion:Vs,timestamp:new Date().toISOString(),workspaceRoot:r,...n&&{indexedAt:n.indexedAt,stale:n.stale}},...a&&{pagination:a}}}function Hs(e,t,r){return{success:!1,data:null,error:e,metadata:{executionTimeMs:t,toolVersion:Vs,timestamp:new Date().toISOString(),workspaceRoot:r}}}import*as bt from"node:fs";import*as l1 from"node:os";import*as Jr from"node:path";var s1=50,l_="cumulative.totals",dz=500,pz=3e4;function Fp(){return Jr.join(l1.homedir(),".graph-it","stats")}function mz(){return process.env.GRAPH_IT_NO_STATS==="1"}function gz(e){bt.mkdirSync(e,{recursive:!0,mode:448})}function c1(e){return`${e.source}-${e.sessionId}.json`}function hz(e){return e.totals.calls>0||e.llmUsage.calls>0}function fz(e,t){if(mz()||!hz(e))return;let r=t??Fp();gz(r);let a=c1(e);u1(r,a,JSON.stringify(e,null,2)),bz(r),Ez(r,e.startedAt)}function u1(e,t,r){let a=Jr.join(e,`.${t}.${process.pid}.tmp`);bt.writeFileSync(a,r,"utf8"),bt.renameSync(a,Jr.join(e,t))}var yz=Date.parse("2026-08-28T14:13:27Z");function c_(e,t=!1){let r=e??Fp(),a=o=>{t||console.warn(o)},n;try{n=bt.readdirSync(r)}catch{return[]}let i=[];for(let o of n){if(!o.endsWith(".json"))continue;let s=Jr.join(r,o);try{let l=bt.readFileSync(s,"utf8"),c=JSON.parse(l);if(c&&typeof c=="object"&&c.schemaVersion===1&&typeof c.startedAt=="number"){if(c.startedAt<yz)continue;i.push({...c,estimationMethod:"cl100k_base"})}else a(`graph-it stats: skipping invalid stats file: ${o}`)}catch{a(`graph-it stats: skipping corrupted stats file: ${o}`)}}return i}function bz(e){let t=e??Fp(),r;try{r=bt.readdirSync(t)}catch{return}let a=new Map;for(let n of r){if(!n.endsWith(".json"))continue;let i=n.indexOf("-");if(i<=0)continue;let o=n.slice(0,i),s=Jr.join(t,n);try{let l=bt.statSync(s),c=a.get(o);c||(c=[],a.set(o,c)),c.push({filePath:s,mtimeMs:l.mtimeMs})}catch{}}for(let n of a.values()){if(n.length<=s1)continue;n.sort((o,s)=>o.mtimeMs-s.mtimeMs);let i=n.length-s1;for(let o=0;o<i;o++)try{bt.unlinkSync(n[o].filePath)}catch{}}}function u_(){return{sessions:0,calls:0,jsonTokens:0,toonTokens:0,savings:0,truncations:0,llmCalls:0,llmTokensUsed:0}}function d_(e,t){let r=e[t.source]??=u_();r.sessions+=1,r.calls+=t.totals.calls,r.jsonTokens+=t.totals.jsonTokens,r.toonTokens+=t.totals.toonTokens,r.savings+=t.totals.savings,r.truncations+=t.totals.truncations,r.llmCalls+=t.llmUsage.calls,r.llmTokensUsed+=t.llmUsage.tokensUsed}function vz(e,t){for(let r of Object.keys(e))e[r]+=t[r]}function d1(e){let t=u_();for(let r of Object.values(e))vz(t,r);return t}function p_(e){let t={};for(let r of e)d_(t,r);return{persistedSessions:e.length,bySource:t,total:d1(t)}}function _z(e){let{source:t,startedAt:r,totals:a,llmUsage:n}=e;return{source:t,startedAt:r,totals:a,llmUsage:n}}function Sz(e){let t=e;return typeof t=="object"&&t!==null&&t.schemaVersion===1&&typeof t.since=="number"&&typeof t.retired=="object"&&t.retired!==null&&typeof t.sessions=="object"&&t.sessions!==null&&(t.evicted===void 0||typeof t.evicted=="object"&&t.evicted!==null)}function p1(e){let t;try{t=bt.readFileSync(Jr.join(e,l_),"utf8")}catch{return}try{let r=JSON.parse(t);if(Sz(r))return r}catch{}console.warn(`graph-it stats: ignoring invalid cumulative totals file: ${l_}`)}function Ez(e,t){let r=p1(e),a={},n=r?.since??t;for(let c of c_(e,!0))a[c1(c)]=_z(c),n=Math.min(n,c.startedAt);let i={...r?.evicted};for(let[c,u]of Object.entries(r?.sessions??{}))c in a||(i[c]=u);for(let c of Object.keys(a))delete i[c];let o=r?.retired??{},s=Object.entries(i).sort(([,c],[,u])=>c.startedAt-u.startedAt);for(let[c,u]of s.slice(0,Math.max(0,s.length-dz)))d_(o,u),delete i[c];u1(e,l_,JSON.stringify({schemaVersion:1,since:n,retired:o,evicted:i,sessions:a}))}function m1(e){let t=p1(e??Fp());if(!t)return;let r={};for(let[a,n]of Object.entries(t.retired))r[a]={...u_(),...n};for(let a of[...Object.values(t.evicted??{}),...Object.values(t.sessions)])d_(r,a);return{since:new Date(t.since).toISOString(),bySource:r,total:d1(r)}}function g1(e,{delayMs:t=pz,baseDir:r,onError:a}={}){let n,i=()=>{clearTimeout(n),n=void 0;try{fz(e.snapshot(),r)}catch(s){a?.(s)}},o=e.onRecord(()=>{n||(n=setTimeout(i,t),n.unref())});return{dispose(){o(),n&&i()}}}var h1=U.object({}).strict();function f1(e){let t=Dn.snapshot(),r=p_([]),a;try{r=p_(c_(e)),a=m1(e)}catch{}let n=t.source==="mcp"&&t.llmUsage.calls===0?"llmUsage is tracked for CLI `graph-it query` only \u2014 the MCP server delegates LLM synthesis to the calling client and makes no LLM API calls itself":"llmUsage is real provider-reported token consumption; it is never summed into the estimated encoding totals";return{description:"TOON encoding size vs JSON equivalent",estimationNote:Qw,llmUsageNote:n,currentSession:t,history:r,...a&&{cumulative:a}}}import*as Bp from"node:fs";import*as Zr from"node:path";var m_={typescript:["package.json","tsconfig.json","jsconfig.json","deno.json","deno.jsonc"],python:["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile"],rust:["Cargo.toml"],csharp:["*.csproj","*.sln","*.slnx","Directory.Build.props"],go:["go.mod","go.work"],java:["pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts"]},Cz=new Set(Object.values(m_).flat().filter(e=>!e.startsWith("*"))),Az=Object.values(m_).flat().filter(e=>e.startsWith("*")).map(e=>e.slice(1));function wz(e){return Cz.has(e)||Az.some(t=>e.endsWith(t))}var i3=`**/{${Object.values(m_).flat().join(",")}}`;function kz(e){let t;try{t=Bp.readdirSync(e)}catch{return!1}return t.some(wz)}function y1(e){let t=Zr.resolve(e);for(;!kz(t);){let r=Zr.dirname(t);if(r===t)return null;t=r}return t}w_({createLogger(e,t){return new pl(e,t)}});var y_=process.env.DEBUG_MCP==="true",qp=`${C1.homedir()}/mcp-debug.log`,Rz=5*1024*1024,g_=`${qp}.1`;function Tz(){if(y_)try{Tt.statSync(qp).size>=Rz&&(Tt.existsSync(g_)&&Tt.unlinkSync(g_),Tt.renameSync(qp,g_))}catch{}}function we(...e){let t=e.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(" ");if(process.stderr.write(t.endsWith(`
3352
+ PARAMETERS: ${t.join(", ")}.`}var _k=["toon","json","markdown"],Sk="Output format: 'toon' (default, compact Token-Oriented Object Notation), 'json' (the raw object, for code that parses it), or 'markdown' (a readable report of this tool's result)";function Ek(e,t,r=3){let a=t.toLowerCase(),n=Math.max(2,Math.floor(a.length/3));return e.map(i=>({name:i,distance:nz(i.toLowerCase(),a)})).filter(i=>i.distance<=n).sort((i,o)=>i.distance-o.distance||i.name.localeCompare(o.name)).slice(0,r).map(i=>i.name)}function nz(e,t){let r=Array.from({length:t.length+1},(a,n)=>n);for(let a=1;a<=e.length;a++){let n=r[0];r[0]=a;for(let i=1;i<=t.length;i++){let o=r[i];r[i]=Math.min(r[i]+1,r[i-1]+1,n+(e[a-1]===t[i-1]?0:1)),n=o}}return r[t.length]}function Ck(e){return e.map((t,r)=>typeof t=="number"?`[${t}]`:r===0?String(t):`.${String(t)}`).join("")}function e_(e){if(typeof e=="string"){let t=e.length>60?`${e.slice(0,57)}...`:e;return JSON.stringify(t)}return Array.isArray(e)?"an array":e===null?"null":typeof e=="object"?"an object":String(e)}var Ak={string:"a string",number:"a number",int:"an integer",boolean:"true or false",array:"an array",object:"an object"};function rz(e){let t=Number(e.code==="too_small"?e.minimum:e.maximum),r={string:" characters",array:" items"}[e.origin]??"";return r?e.code==="too_small"?`at least ${t}${r}`:`at most ${t}${r}`:`${e.code==="too_small"?">":"<"}${e.inclusive?"=":""} ${t}`}function wk(e){switch(e.code){case"invalid_type":return Ak[e.expected]??e.expected;case"invalid_value":return e.values.length===1?e_(e.values[0]):`one of ${e.values.map(t=>typeof t=="string"?t:e_(t)).join(", ")}`;case"too_small":case"too_big":return rz(e);case"invalid_format":return e.format==="regex"&&"pattern"in e?`a string matching ${String(e.pattern)}`:`a valid ${e.format}`;case"not_multiple_of":return`a multiple of ${String(e.divisor)}`;case"invalid_union":{let t=e.errors.flatMap(r=>r.map(wk)).filter(r=>r!==void 0);return t.length>0?[...new Set(t)].join(" or "):void 0}default:return}}var Qv=5;function iz(e,t,r){let a=t.length>0?` in "${Ck(t)}"`:"",n=e.slice(0,Qv).map(s=>{let[l]=t.length===0?Ek([...r],s,1):[],c=l?` Did you mean "${l}"?`:"";return`Unknown parameter "${s}"${a}.${c}`}),i=e.length>Qv?[`And ${e.length-Qv} more unknown parameters.`]:[],o=t.length===0?[`Parameters: ${r.join(", ")}.`]:[];return[...n,...i,...o].join(" ")}function az(e,t){if(e.code==="unrecognized_keys")return iz(e.keys,e.path,t);let r=Ck(e.path),a=e.input;if(e.code==="invalid_type"&&a===void 0&&r!=="")return`Missing required parameter "${r}" (${Ak[e.expected]??e.expected}).`;let n=wk(e);if(n===void 0)return r===""?e.message:`"${r}": ${e.message}`;let o=Array.isArray(a)&&(e.code==="too_big"||e.code==="too_small")?`${a.length} items`:e_(a),s=a===void 0?"":`; got ${o}`;return`${r===""?"Parameters":JSON.stringify(r)} must be ${n}${s}.`}function Us(e){let t=U.toJSONSchema(e,{io:"input",unrepresentable:"any"});return Object.keys(t.properties??{})}function oz(e,t){let r=t.some(a=>a.code==="unrecognized_keys")?Us(e):[];return[...new Set(t.map(a=>az(a,r)))].join(" ")}function kk(e,t){let r=e.safeParse(t,{reportInput:!0});return r.success?{success:!0,data:r.data}:{success:!1,error:oz(e,r.error.issues),issues:r.error.issues}}function qs(e){return{"~standard":{...e["~standard"],validate:r=>{let a=kk(e,r);return a.success?{value:a.data}:{issues:[{message:a.error}]}}}}}import*as cn from"node:path";var t_=["path","louvain"];var Rk=["units","folder","matrix"],Tk=["svg","html","diagram-spec"],Ik=e=>e==="diagram-spec"?"architecture.diagram-spec.json":`architecture.${e}`,Pk=["light","dark"];function Dk(e,t){let r=t?.replaceAll("\\","/");return{view:e??(r===void 0?"units":"folder"),folder:r}}var sz={down:{colour:"line",text:"dependency"},upward:{colour:"accent",text:"upward"},cycle:{colour:"cycle",text:"runtime cycle"},"type-only":{colour:"cycle",dash:"2 3",text:"type-only cycle"},lazy:{colour:"cycle",dash:"8 4",text:"lazy cycle (import())"},cut:{colour:"cycle",text:"cell to cut"},error:{colour:"error",text:"breaks a rule"},accepted:{colour:"error",dash:"4 3",text:"accepted in baseline"},dead:{colour:"muted",dash:"4 3",text:"dead file"},"inferred-role":{colour:"line",dash:"3 3",text:"dashed border: role inferred"}},T6=Object.keys(sz);var P6=new Set("(,=:[!&|?{};~+-*%<>^");var xk=["high","medium","low"];var Vs="1.1.0",Ok="1.25.6",H6=U.enum(["json","toon"]).default("json").describe("Output format: 'json' (default) or 'toon' (Token-Oriented Object Notation for reduced token usage)"),ur={FILE_PATH:1024,SYMBOL_NAME:500,FILE_CONTENT:1024*1024,GENERIC_STRING:10*1024},et=U.string().max(ur.FILE_PATH,`File path exceeds maximum length of ${ur.FILE_PATH} bytes`).refine(e=>!e.includes("\0"),"File path contains null bytes"),ba=U.string().max(ur.SYMBOL_NAME,`Symbol name exceeds maximum length of ${ur.SYMBOL_NAME} bytes`).refine(e=>!e.includes("\0"),"Symbol name contains null bytes"),$k=U.string().max(ur.FILE_CONTENT,`File content exceeds maximum size of ${ur.FILE_CONTENT} bytes (~1 MB)`).refine(e=>!e.includes("\0"),"File content contains null bytes"),va=U.string().max(ur.GENERIC_STRING,`String exceeds maximum length of ${ur.GENERIC_STRING} bytes`).refine(e=>!e.includes("\0"),"String contains null bytes"),ya={MAX_LIMIT:1e4,MAX_OFFSET:1e5,DEFAULT_LIMIT:1e3},lz=U.object({hubScore:U.number().min(0,"hubScore must be >= 0").max(1,"hubScore must be <= 1"),loc:U.number().int().positive().optional(),fileExtension:U.string().optional(),communityId:U.number().int().min(0).optional(),communityKey:U.string().optional()}),cz=U.object({source:U.string(),target:U.string(),relationType:U.enum(["dependency","call","reference","containment"]).optional()}),W6=U.object({nodes:U.array(U.string()),edges:U.array(cz),nodeLabels:U.record(U.string(),U.string()).optional(),parentCounts:U.record(U.string(),U.number()).optional(),unusedEdges:U.array(U.string()).optional(),nodeMetadata:U.record(U.string(),lz).optional()}),zk=U.object({workspacePath:et.describe("Absolute path to the project/workspace directory to analyze"),tsConfigPath:et.optional().describe("Optional path to tsconfig.json for path alias resolution. Omitted: kept when the same workspace is selected again, otherwise each file uses its nearest tsconfig.json"),excludeNodeModules:U.boolean().optional().describe("Whether to exclude node_modules (default: true)"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum crawl depth (default: 50, min: 1, max: 100)")}).strict(),Mk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze")}).strict(),Lk=U.union([U.literal(0),U.number().int().min(500).max(16e3)]).default(4e3).optional().describe("Maximum output size in tokens (default: 4000, 500-16000, or 0 for no limit). A larger result is cut and reports truncated=true, omitted counts and nextOffset; pass nextOffset as offset to read the rest."),i_=U.number().int().min(0).max(ya.MAX_OFFSET).optional().describe("Items to skip, usually the nextOffset of the previous response (default: 0)"),Fk=U.object({entryFile:et.describe("Workspace-relative or absolute path to the entry file"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to crawl (default: from config, min: 1, max: 100)"),limit:U.number().min(1).max(ya.MAX_LIMIT).optional().describe(`Maximum number of nodes to return (for pagination, max: ${ya.MAX_LIMIT})`),offset:U.number().min(0).max(ya.MAX_OFFSET).optional().describe(`Number of nodes to skip (for pagination, max: ${ya.MAX_OFFSET})`),onlyUsed:U.boolean().optional().describe("If true, only returns edges where symbols are actually used (requires AST analysis, slower)"),communityMode:U.enum(t_).optional().describe("How nodes are grouped into communityId/communityKey: 'path' (default) by folder, 'louvain' by import structure (deterministic Louvain over the crawled graph)"),tokenBudget:Lk}).strict(),Bk=U.object({targetPath:et.describe("Workspace-relative or absolute path to the file to find references for")}).strict(),jk=U.object({sourceFile:et.describe("Workspace-relative or absolute path to the source file (the one importing using symbols)"),targetFile:et.describe("Workspace-relative or absolute path to the target file (the one providing symbols)")}).strict(),Uk=U.object({fromFile:et.describe("Workspace-relative or absolute path of the file containing the import"),moduleSpecifier:va.describe('The module specifier to resolve (e.g., "./utils", "@/components/Button")')}).strict(),qk=U.object({}).strict(),Nk=1e4,Gk=U.object({filePaths:U.array(et).max(Nk).describe(`Array of file paths, workspace-relative or absolute, to invalidate from the cache (max: ${Nk} per call; use rebuild_index for the whole workspace). Needed only for edits the file watcher missed: it invalidates changed files on its own.`)}).strict(),Vk=U.object({}).strict(),Hk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze for symbols")}).strict(),Wk=U.enum(xk).optional().describe("Lowest confidence listed (default: high). high: the file is imported, no importer uses the export and no other evidence of use was found: a deletion candidate. medium: only tests use it, a computed import may reach it, a decorator may register it, its name is written again in its file (or, in Rust, in another file), or it sits in a test file. low: nothing imports the file (entry point by convention, script, config), review only. Unlisted items are counted in byConfidence."),Kk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to check for unused exported symbols"),minConfidence:Wk}).strict(),Jk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file containing the root symbol"),symbolName:ba.describe("Name of the root symbol to trace from"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to trace the call chain (default: 10, min: 1, max: 100)")}).strict(),Zk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze"),symbolName:ba.optional().describe("Optional: Only analyze changes to this specific symbol"),oldContent:$k.describe("The old version of the file content"),newContent:$k.optional().describe("The new version of the file content (if not provided, reads current file)")}).strict(),Yk=U.object({baseRef:va.describe("Git base ref to compare against, for example origin/main"),headRef:va.optional().describe("Optional Git head ref; defaults to the checked-out worktree"),maxFiles:U.number().int().min(1).optional().describe("Optional cap on changed files analysed (default: 200, no upper bound)"),maxDepth:U.number().int().min(1).max(10).optional()}).strict(),Xk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file being modified"),symbolName:ba.describe("Name of the symbol being modified"),includeTransitive:U.boolean().optional().describe("Include transitive dependents (default: false)"),maxDepth:U.number().min(1).max(20).optional().describe("Maximum depth for transitive analysis (default: 3, min: 1, max: 20)")}).strict(),K6=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to analyze"),includeExternal:U.boolean().optional().describe("Include calls to external modules (default: false)")}).strict(),Qk=U.object({filePath:et.describe("Workspace-relative or absolute path to the file to generate a codemap for")}).strict(),e1=U.object({filePath:et.describe("Workspace-relative or absolute path to the file containing the target symbol."),symbolName:ba.describe("Name of the symbol to query (function, class, method). A bare name shared by several symbols in the file returns reason='ambiguous' with candidates; qualified names such as 'Class.method' are not supported."),symbolId:ba.optional().describe("Exact node id taken from a previous result or candidate (valid for the current index only, since ids embed the line). Narrows symbolName to that node; a stale id returns reason='stale_selector'."),startLine:U.number().int().min(0).optional().describe("Declaration line of the symbol, 0-based like 'startLine' in results and candidates (editor line 3 is 2). Selects one of several same-name symbols."),direction:U.enum(["callers","callees","both"]).optional().describe("Direction of traversal: 'callers', 'callees', or 'both' (default: 'both')"),depth:U.number().min(1).max(10).optional().describe("Maximum BFS traversal depth (default: 2, min: 1, max: 10)"),relationTypes:U.array(U.enum(["CALLS","INHERITS","IMPLEMENTS","USES","REFERENCES"])).optional().describe("Filter by relation types (default: CALLS, INHERITS, IMPLEMENTS and REFERENCES; USES is added with includeTypeOnly)"),includeTypeOnly:U.boolean().optional().describe("Also include USES edges (type-only references such as interfaces and type aliases). Default is false. Ignored when relationTypes is set."),offset:i_,tokenBudget:Lk}).strict(),a_=U.object({question:U.string().max(1024).describe("Natural language question about the codebase"),depth:U.number().int().min(1).max(5).default(2).optional().describe("BFS traversal depth from seed nodes (default: 2, min: 1, max: 5)"),tokenBudget:U.number().int().min(500).max(16e3).default(4e3).optional().describe("Maximum token budget for the output subgraph (default: 4000)"),fileFilter:U.string().max(256).optional().describe("Workspace-relative glob restricting the search (e.g. 'src/analyzer/**'); a glob matching no indexed file is an error")}).strict(),J6=a_.extend({outputFormat:U.enum(["toon","json"]).optional()}),n_=U.object({id:va.refine(e=>e.trim().length>0,"Seed ID must not be empty").optional(),filePath:et.refine(e=>e.trim().length>0,"Seed file path must not be empty").optional(),symbolName:ba.refine(e=>e.trim().length>0,"Seed symbol name must not be empty").optional(),label:va.refine(e=>e.trim().length>0,"Seed label must not be empty").optional()}).refine(e=>e.id!==void 0||e.filePath!==void 0||e.symbolName!==void 0||e.label!==void 0,"A seed must contain an id, filePath, symbolName, or label"),uz=U.enum(["CONTAINS","IMPORTS","CALLS","INHERITS","IMPLEMENTS","USES","TESTED_BY","IMPACTED_BY","BELONGS_TO","REFERENCES","EXPLAINS","DOCUMENTS"]),o_=U.object({question:U.string().max(1024).optional(),seeds:U.array(n_).max(500).optional(),mode:U.enum(["search","neighbors","path","impact","refactor","overview"]).optional(),from:n_.optional(),to:n_.optional(),relations:U.array(uz).max(12).refine(e=>new Set(e).size===e.length,"Relations must be unique").optional(),scope:U.string().max(256).optional(),depth:U.number().int().min(1).max(5).optional(),maxNodes:U.number().int().min(1).max(500).optional(),tokenBudget:U.number().int().min(500).max(16e3).optional(),directed:U.boolean().optional(),cursor:U.string().min(1).max(4096).optional(),detail:U.enum(["compact","standard","full"]).optional()}).strict().superRefine((e,t)=>{let r=e.question!==void 0&&e.question.trim().length>0,a=(e.seeds?.length??0)>0,n=e.from!==void 0,i=e.to!==void 0;n!==i&&t.addIssue({code:"custom",message:"Both from and to are required for a path request"}),e.mode==="path"&&!(n&&i)&&t.addIssue({code:"custom",message:"Path mode requires both from and to"}),e.mode!==void 0&&e.mode!=="path"&&(n||i)&&t.addIssue({code:"custom",message:"from and to are only valid in path mode"}),e.mode===void 0&&n&&i&&(r||a)&&t.addIssue({code:"custom",message:"Set mode to path when combining endpoints with a question or seeds"}),!r&&!a&&!(n&&i)&&t.addIssue({code:"custom",message:"Provide a question, at least one seed, or both from and to"})}),Z6=o_.transform(e=>{let t=e.question!==void 0&&e.question.trim().length>0,r=(e.seeds?.length??0)>0,a=e.from!==void 0&&e.to!==void 0;return e.mode===void 0&&!t&&!r&&a?{...e,mode:"path"}:e}),t1=U.object({outputDir:et.optional().refine(e=>e===void 0||!cn.isAbsolute(e),"Output directory must be relative to the workspace").describe("Workspace-relative output directory for wiki files (default: wiki)"),topHubsLimit:U.number().int().min(1).max(50).optional().describe("Number of top hub files to list (max: 50, default: 10)"),scope:et.optional().refine(e=>e===void 0||!cn.isAbsolute(e),"Scope must be relative to the workspace").describe("Relative path within workspace to restrict wiki to (e.g. 'src/'; default: the whole workspace)"),exclude:U.array(va).max(100).optional().describe("Relative glob-like patterns to exclude (e.g. ['tests/**', '**/*.test.ts']); omitted: tests/, dist/, *.test.ts and the other default exclusions")}).strict(),r_=U.union([U.number().int().min(0),U.string().min(1).max(256)]).describe("Numeric group id from a previous response, or a group key (e.g. 'analyzer') or label as a string; 0 or 'unassigned' for files without a group"),n1=U.object({communityMode:U.enum(t_).optional().describe("How files are grouped: 'path' (default) by folder domain, 'louvain' by import structure"),maxFiles:U.number().int().min(1).max(ya.MAX_OFFSET).optional().describe("Analyse only the first maxFiles source files, like graph-it architecture --maxFiles (default: all)"),level:U.enum(["groups","units"]).optional().describe("groups (default): folder or Louvain groups; units: the declared elements of graphit.architecture.json, else the detected projects (a top-level folder for files outside every project), with their layers, roles and role evidence, unit edges (down, upward, cycle) with their rules, and cycles, like graph-it architecture --level units"),folder:U.string().min(1).max(1024).optional().describe("communityMode 'path' only: walk down one level, below this unit key (from level units) or group key; groups are then its sub-folders plus its own files (key = folder), nestedGroups those holding sub-folders; group, from and to then name groups of this level"),view:U.enum(["matrix"]).optional().describe("matrix: the dependency structure matrix of the level (units with level units, a folder's groups with folder, else the groups): rows ordered by layer with each cycle's rows together, non-zero cells (row imports column, diagonal = pairs inside) paged by offset/limit, per-row Ce/Ca/instability with their formula, cycles and totals of every cell, like graph-it architecture --matrix"),group:r_.optional().describe("Return this group's files and its incoming / outgoing group edges"),from:r_.optional().describe("Source group of the edge whose file pairs to return (requires to); with level units, a unit key such as 'apps/web', 'scripts' or a declared element name"),to:r_.optional().describe("Target group of the edge whose file pairs to return (requires from); with level units, a unit key"),limit:U.number().int().min(1).max(500).optional().describe("Items per page: groups and group edges, a group's files and its incoming and outgoing edges, or file pairs (default: 50)"),offset:i_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the group ids or offset come from; the call fails if the architecture has changed since")}).strict().superRefine((e,t)=>{e.from===void 0!=(e.to===void 0)&&t.addIssue({code:"custom",message:"Both from and to are required for edge evidence"}),e.group!==void 0&&e.from!==void 0&&t.addIssue({code:"custom",message:"Pass either group or from and to, not both"}),e.level==="units"&&e.group!==void 0&&t.addIssue({code:"custom",message:"level units lists units and unit edges, or with from and to a unit edge's file pairs: drop group"}),e.folder!==void 0&&(e.level==="units"||e.communityMode==="louvain")&&t.addIssue({code:"custom",message:"folder walks the path-mode folders: drop level units and communityMode louvain"}),e.view==="matrix"&&(e.group!==void 0||e.from!==void 0)&&t.addIssue({code:"custom",message:"view matrix returns the whole level: drop group, from and to (call them afterwards for a row or a cell)"})}),Gs=U.string().min(1).max(1024).refine(e=>!cn.isAbsolute(e)&&!cn.win32.isAbsolute(e),"Must be relative to the workspace"),r1=U.object({config:Gs.optional().describe("Rules file, relative to the workspace (default: graphit.architecture.json)"),baseline:Gs.optional().describe("Accepted violations, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),rule:U.string().min(1).max(128).optional().describe("Return only the violations of this rule"),limit:U.number().int().min(1).max(500).optional().describe("Violations per page; also caps unmatchedFiles and resolved (default: 50)"),offset:i_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the offset comes from; the call fails if the code, rules or baseline changed since")}).strict(),i1=U.object({view:U.enum(Rk).optional().describe("'units' (default): every unit; 'folder': the groups of the unit or folder named by folder (default when folder is set); 'matrix': the dependency structure matrix of that level"),folder:U.string().min(1).max(1024).optional().describe("Unit or folder key, '/'-separated as explore_architecture returns it (e.g. 'src/analyzer')"),diagramFormat:U.enum(Tk).optional().describe("'svg' (default): a bare SVG; 'html': one self-contained page following the reader's light or dark scheme; 'diagram-spec': the level's data as JSON (schemas/diagram-spec.schema.json) for a diagram skill"),theme:U.enum(Pk).optional().describe("Colours of the SVG (default: light); svg only"),rules:U.boolean().optional().describe("Draw the violations of graphit.architecture.json in the error colour, and the baseline's accepted ones dashed"),config:Gs.optional().describe("Rules file with rules, relative to the workspace (default: graphit.architecture.json)"),baseline:Gs.optional().describe("Accepted violations with rules, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),output:Gs.optional().describe("File to write, relative to the workspace and inside it; without it, a diagram over the inline cap goes to architecture.<diagramFormat> (architecture.diagram-spec.json for a spec)")}).strict().superRefine((e,t)=>{let{view:r}=Dk(e.view,e.folder);r==="folder"&&e.folder===void 0&&t.addIssue({code:"custom",message:"view folder draws the groups of one unit or folder: pass folder"}),r==="units"&&e.folder!==void 0&&t.addIssue({code:"custom",message:"view units draws every unit: drop folder, or use view folder"}),e.theme!==void 0&&(e.diagramFormat??"svg")!=="svg"&&t.addIssue({code:"custom",message:"theme sets the colours of diagramFormat svg; the HTML page follows the reader's scheme and a spec has none"}),!e.rules&&(e.config!==void 0||e.baseline!==void 0)&&t.addIssue({code:"custom",message:"config and baseline apply to the rules overlay: add rules: true"});let a=e.diagramFormat??"svg",n=cn.extname(Ik(a));e.output!==void 0&&cn.extname(e.output).toLowerCase()!==n&&t.addIssue({code:"custom",message:`output must end with ${n} for diagramFormat ${a}; got ${e.output}`})}),a1=U.object({scopePath:et.optional().describe("Folder to scope the scan, workspace-relative or absolute (default: workspace root). Must be inside the workspace."),maxFiles:U.number().int().min(1).optional().describe("Optional cap on analysed files (default: every analysable file in scope, no upper bound). When the cap stops the scan, truncated=true and filesBeyondLimit > 0: the result is partial."),minConfidence:Wk,verbose:U.boolean().optional().describe('Also list the unused exports left out as excluded, each with its reason: the manifest field that declares it (declared:package.json#exports["./x"]), a Rust attribute, or convention:framework-default-export (default: false)'),unreferencedFiles:U.boolean().optional().describe("List whole files no production file imports instead of unused exports (default: false): low (no-importer) when nothing imports the file, medium (test-only-use) when only tests do. minConfidence then defaults to low. medium items list testImporters, the tests to delete or clean up with the file. Left out (excluded with verbose): test files, manifest entry points, files a non-test file names by path (bundler entry, package.json script, CI workflow, Makefile, shell script), JSX/Vue default exports, framework route files (Next.js, SvelteKit, Remix, Nuxt, Astro...), files a bundler loads (import.meta.glob, new URL, HTML entry), migrations, .d.ts files, *.config.* files, files a folder's .gitignore ignores, Python package __init__.py. Then the files only dead files and tests import (reason cascade, via = their dead importers); tests = the tests that import nothing but dead files.")}).strict();function o1(e,t){return Yv(e,t)}function s_(e,t,r,a,n){return{success:!0,data:e,metadata:{executionTimeMs:t,toolVersion:Vs,timestamp:new Date().toISOString(),workspaceRoot:r,...n&&{indexedAt:n.indexedAt,stale:n.stale}},...a&&{pagination:a}}}function Hs(e,t,r){return{success:!1,data:null,error:e,metadata:{executionTimeMs:t,toolVersion:Vs,timestamp:new Date().toISOString(),workspaceRoot:r}}}import*as bt from"node:fs";import*as l1 from"node:os";import*as Jr from"node:path";var s1=50,l_="cumulative.totals",dz=500,pz=3e4;function Fp(){return Jr.join(l1.homedir(),".graph-it","stats")}function mz(){return process.env.GRAPH_IT_NO_STATS==="1"}function gz(e){bt.mkdirSync(e,{recursive:!0,mode:448})}function c1(e){return`${e.source}-${e.sessionId}.json`}function hz(e){return e.totals.calls>0||e.llmUsage.calls>0}function fz(e,t){if(mz()||!hz(e))return;let r=t??Fp();gz(r);let a=c1(e);u1(r,a,JSON.stringify(e,null,2)),bz(r),Ez(r,e.startedAt)}function u1(e,t,r){let a=Jr.join(e,`.${t}.${process.pid}.tmp`);bt.writeFileSync(a,r,"utf8"),bt.renameSync(a,Jr.join(e,t))}var yz=Date.parse("2026-08-28T14:13:27Z");function c_(e,t=!1){let r=e??Fp(),a=o=>{t||console.warn(o)},n;try{n=bt.readdirSync(r)}catch{return[]}let i=[];for(let o of n){if(!o.endsWith(".json"))continue;let s=Jr.join(r,o);try{let l=bt.readFileSync(s,"utf8"),c=JSON.parse(l);if(c&&typeof c=="object"&&c.schemaVersion===1&&typeof c.startedAt=="number"){if(c.startedAt<yz)continue;i.push({...c,estimationMethod:"cl100k_base"})}else a(`graph-it stats: skipping invalid stats file: ${o}`)}catch{a(`graph-it stats: skipping corrupted stats file: ${o}`)}}return i}function bz(e){let t=e??Fp(),r;try{r=bt.readdirSync(t)}catch{return}let a=new Map;for(let n of r){if(!n.endsWith(".json"))continue;let i=n.indexOf("-");if(i<=0)continue;let o=n.slice(0,i),s=Jr.join(t,n);try{let l=bt.statSync(s),c=a.get(o);c||(c=[],a.set(o,c)),c.push({filePath:s,mtimeMs:l.mtimeMs})}catch{}}for(let n of a.values()){if(n.length<=s1)continue;n.sort((o,s)=>o.mtimeMs-s.mtimeMs);let i=n.length-s1;for(let o=0;o<i;o++)try{bt.unlinkSync(n[o].filePath)}catch{}}}function u_(){return{sessions:0,calls:0,jsonTokens:0,toonTokens:0,savings:0,truncations:0,llmCalls:0,llmTokensUsed:0}}function d_(e,t){let r=e[t.source]??=u_();r.sessions+=1,r.calls+=t.totals.calls,r.jsonTokens+=t.totals.jsonTokens,r.toonTokens+=t.totals.toonTokens,r.savings+=t.totals.savings,r.truncations+=t.totals.truncations,r.llmCalls+=t.llmUsage.calls,r.llmTokensUsed+=t.llmUsage.tokensUsed}function vz(e,t){for(let r of Object.keys(e))e[r]+=t[r]}function d1(e){let t=u_();for(let r of Object.values(e))vz(t,r);return t}function p_(e){let t={};for(let r of e)d_(t,r);return{persistedSessions:e.length,bySource:t,total:d1(t)}}function _z(e){let{source:t,startedAt:r,totals:a,llmUsage:n}=e;return{source:t,startedAt:r,totals:a,llmUsage:n}}function Sz(e){let t=e;return typeof t=="object"&&t!==null&&t.schemaVersion===1&&typeof t.since=="number"&&typeof t.retired=="object"&&t.retired!==null&&typeof t.sessions=="object"&&t.sessions!==null&&(t.evicted===void 0||typeof t.evicted=="object"&&t.evicted!==null)}function p1(e){let t;try{t=bt.readFileSync(Jr.join(e,l_),"utf8")}catch{return}try{let r=JSON.parse(t);if(Sz(r))return r}catch{}console.warn(`graph-it stats: ignoring invalid cumulative totals file: ${l_}`)}function Ez(e,t){let r=p1(e),a={},n=r?.since??t;for(let c of c_(e,!0))a[c1(c)]=_z(c),n=Math.min(n,c.startedAt);let i={...r?.evicted};for(let[c,u]of Object.entries(r?.sessions??{}))c in a||(i[c]=u);for(let c of Object.keys(a))delete i[c];let o=r?.retired??{},s=Object.entries(i).sort(([,c],[,u])=>c.startedAt-u.startedAt);for(let[c,u]of s.slice(0,Math.max(0,s.length-dz)))d_(o,u),delete i[c];u1(e,l_,JSON.stringify({schemaVersion:1,since:n,retired:o,evicted:i,sessions:a}))}function m1(e){let t=p1(e??Fp());if(!t)return;let r={};for(let[a,n]of Object.entries(t.retired))r[a]={...u_(),...n};for(let a of[...Object.values(t.evicted??{}),...Object.values(t.sessions)])d_(r,a);return{since:new Date(t.since).toISOString(),bySource:r,total:d1(r)}}function g1(e,{delayMs:t=pz,baseDir:r,onError:a}={}){let n,i=()=>{clearTimeout(n),n=void 0;try{fz(e.snapshot(),r)}catch(s){a?.(s)}},o=e.onRecord(()=>{n||(n=setTimeout(i,t),n.unref())});return{dispose(){o(),n&&i()}}}var h1=U.object({}).strict();function f1(e){let t=Dn.snapshot(),r=p_([]),a;try{r=p_(c_(e)),a=m1(e)}catch{}let n=t.source==="mcp"&&t.llmUsage.calls===0?"llmUsage is tracked for CLI `graph-it query` only \u2014 the MCP server delegates LLM synthesis to the calling client and makes no LLM API calls itself":"llmUsage is real provider-reported token consumption; it is never summed into the estimated encoding totals";return{description:"TOON encoding size vs JSON equivalent",estimationNote:Qw,llmUsageNote:n,currentSession:t,history:r,...a&&{cumulative:a}}}import*as Bp from"node:fs";import*as Zr from"node:path";var m_={typescript:["package.json","tsconfig.json","jsconfig.json","deno.json","deno.jsonc"],python:["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile"],rust:["Cargo.toml"],csharp:["*.csproj","*.sln","*.slnx","Directory.Build.props"],go:["go.mod","go.work"],java:["pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts"]},Cz=new Set(Object.values(m_).flat().filter(e=>!e.startsWith("*"))),Az=Object.values(m_).flat().filter(e=>e.startsWith("*")).map(e=>e.slice(1));function wz(e){return Cz.has(e)||Az.some(t=>e.endsWith(t))}var i3=`**/{${Object.values(m_).flat().join(",")}}`;function kz(e){let t;try{t=Bp.readdirSync(e)}catch{return!1}return t.some(wz)}function y1(e){let t=Zr.resolve(e);for(;!kz(t);){let r=Zr.dirname(t);if(r===t)return null;t=r}return t}w_({createLogger(e,t){return new pl(e,t)}});var y_=process.env.DEBUG_MCP==="true",qp=`${C1.homedir()}/mcp-debug.log`,Rz=5*1024*1024,g_=`${qp}.1`;function Tz(){if(y_)try{Tt.statSync(qp).size>=Rz&&(Tt.existsSync(g_)&&Tt.unlinkSync(g_),Tt.renameSync(qp,g_))}catch{}}function we(...e){let t=e.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(" ");if(process.stderr.write(t.endsWith(`
3353
3353
  `)?t:`${t}
3354
3354
  `),!!y_)try{Tz();let a=`[${new Date().toISOString()}] ${t}
3355
3355
  `;Tt.appendFileSync(qp,a)}catch{}}y_?(we("[McpServer] ===== PROCESS STARTING (DEBUG MODE) ====="),we("[McpServer] Node version:",process.version),we("[McpServer] PID:",process.pid),we("[McpServer] cwd:",process.cwd()),we("[McpServer] argv:",JSON.stringify(process.argv)),we("[McpServer] Environment vars:"),we(" WORKSPACE_ROOT:",process.env.WORKSPACE_ROOT??"(not set)"),we(" TSCONFIG_PATH:",process.env.TSCONFIG_PATH??"(not set)"),we(" EXCLUDE_NODE_MODULES:",process.env.EXCLUDE_NODE_MODULES??"(not set)"),we(" MAX_DEPTH:",process.env.MAX_DEPTH??"(not set)")):process.stderr.write(`[McpServer] Starting (debug logging disabled - set DEBUG_MCP=true to enable)
package/dist/mcpWorker.js CHANGED
@@ -46078,7 +46078,7 @@ Additional information: BADCLIENT: Bad error code, ${U} not found in range ${v}.
46078
46078
  JOIN nodes n_tgt ON e.target_id = n_tgt.id
46079
46079
  WHERE n_src.path = ?
46080
46080
  ORDER BY e.source_line ASC
46081
- `);for(f.bind([o]);f.step();){let _=f.getAsObject();a.push({name:_.callee_name,filePath:Ir(_.callee_path),callSiteLine:_.source_line})}f.free()}catch{}return a}}});var DDr={};module.exports=tXn(DDr);var d1n=require("node:worker_threads");var EPn=require("node:crypto"),n9t=Yl(require("node:fs")),Vxt=Yl(require("node:path")),xPn=require("node:worker_threads");LF();var cUe=V0("AstWorkerHost"),Ctt=class{worker=null;nextId=1;pendingRequests=new Map;workerPath;extensionPath;rootDir;isStopping=!1;isDisposed=!1;stopPromise=null;build;constructor(o,a,f){if(this.extensionPath=a,this.rootDir=f,o)this.workerPath=o;else{let _=[Vxt.join(__dirname,"astWorker.js"),Vxt.join(__dirname,"../../../dist/astWorker.js"),Vxt.join(__dirname,"../../../../dist/astWorker.js"),Vxt.join(process.cwd(),"dist/astWorker.js")],b="";for(let C of _)if(n9t.existsSync(C)){b=C;break}this.workerPath=b||Vxt.join(process.cwd(),"dist/astWorker.js")}}buildId(){if(this.build===void 0)try{this.build=(0,EPn.createHash)("sha256").update(n9t.readFileSync(this.workerPath)).digest("hex")}catch{this.build="missing"}return this.build}async start(){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||this.isStopping){cUe.warn("AstWorker already started");return}cUe.info(`Starting AstWorker from ${this.workerPath}`);try{this.worker=new xPn.Worker(this.workerPath,{workerData:{extensionPath:this.extensionPath,rootDir:this.rootDir}}),this.worker.on("message",o=>{this.handleResponse(o)}),this.worker.on("error",o=>{cUe.error("AstWorker error:",o);for(let[a,f]of this.pendingRequests)f.reject(new Error(`AstWorker crashed: ${o.message}`)),this.pendingRequests.delete(a)}),this.worker.on("exit",o=>{o!==0&&!this.isStopping&&cUe.error(`AstWorker exited with code ${o}`),this.worker=null,this.stopPromise||(this.isStopping=!1)}),cUe.info("AstWorker started successfully")}catch(o){let a=o instanceof Error?o.message:String(o);throw cUe.error(`Failed to start AstWorker: ${a}`),new Error(`Failed to start AstWorker: ${a}`,{cause:o})}}stop(){if(this.isDisposed=!0,this.stopPromise)return this.stopPromise;let o=this.worker;if(!o)return Promise.resolve();cUe.debug("Stopping AstWorker");for(let[a,f]of this.pendingRequests)f.reject(new Error("AstWorker stopped")),this.pendingRequests.delete(a);return this.isStopping=!0,this.stopPromise=o.terminate().then(()=>{}).finally(()=>{this.worker===o&&(this.worker=null),this.isStopping=!1,this.stopPromise=null,cUe.debug("AstWorker stopped")}),this.stopPromise}async analyzeFile(o,a){return await this.sendRequest({type:"analyzeFile",id:0,filePath:o,content:a})}async getInternalExportDependencyGraph(o,a){let _=await this.sendRequest({type:"getInternalExportDeps",id:0,filePath:o,content:a});return new Map(Object.entries(_).map(([b,C])=>[b,new Set(C)]))}async extractSignatures(o,a){return await this.sendRequest({type:"extractSignatures",id:0,filePath:o,content:a})}async extractInterfaceMembers(o,a){let _=await this.sendRequest({type:"extractInterfaceMembers",id:0,filePath:o,content:a});return new Map(Object.entries(_))}async extractTypeAliases(o,a){return await this.sendRequest({type:"extractTypeAliases",id:0,filePath:o,content:a})}async compareSignatures(o,a){return await this.sendRequest({type:"compareSignatures",id:0,oldSig:o,newSig:a})}async analyzeBreakingChanges(o,a,f,_){return await this.sendRequest({type:"analyzeBreakingChanges",id:0,filePath:o,oldContent:a,newContent:f,symbolName:_})}async reset(){await this.sendRequest({type:"reset",id:0})}async getFileCount(){return await this.sendRequest({type:"getFileCount",id:0})}async sendRequest(o){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||await this.start(),this.isDisposed)throw new Error("AstWorker has been stopped");let a=this.nextId++,f={...o,id:a};return new Promise((_,b)=>{this.pendingRequests.set(a,{resolve:_,reject:b}),this.worker?.postMessage(f)})}handleResponse(o){let a=this.pendingRequests.get(o.id);if(!a){cUe.warn(`Received response for unknown request ${o.id}`);return}if(this.pendingRequests.delete(o.id),o.type==="success")a.resolve(o.result);else{let f=new Error(o.error);o.stack&&(f.stack=o.stack),a.reject(f)}}};var h3=Yl(require("node:fs")),cH=Yl(require("node:path"));ktt();LF();Hm();var WFn=require("node:crypto"),ZGt=Yl(require("node:fs")),EAt=Yl(require("node:path"));dce();LF();Hm();OF();YGt();var air=V0("configFingerprint");function yln(l,o){try{let a=zFn(jFn(l,o));return(0,WFn.createHash)("sha256").update(JSON.stringify([...a].sort(([f],[_])=>f.localeCompare(_)))).digest("hex")}catch(a){air.info(`Index cache disabled: ${a instanceof Error?a.message:String(a)}`);return}}function vln(l,o){return[...zFn(jFn(l,o)).keys()]}function bln(l,o){return o.filter(a=>!u9t.test(a)&&Jte(a,l))}function jFn(l,o){let a=new Set([Ir(l)]);for(let f of o){let _=Ir(EAt.dirname(f));for(;!a.has(_);){if(!Jte(_,l))throw new Error(`source file outside the workspace: ${Ir(f)}`);a.add(_),_=Ir(EAt.dirname(_))}}return a}function zFn(l){let o=[...l].flatMap(_=>[EAt.join(_,"tsconfig.json"),EAt.join(_,"package.json")]),a=new Set,f=new Map;for(let _=o.shift();_;_=o.shift()){let b=Ir(_);if(a.has(b)||!ZGt.existsSync(_))continue;a.add(b);let C=cir(_);f.set(b,C),o.push(...QGt(_,i_t(_,C)?.extends))}return f}function cir(l){try{return ZGt.readFileSync(l,"utf-8")}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`cannot read resolver config ${Ir(l)}: ${a}`,{cause:o})}}var $Fn=require("node:crypto"),tW=Yl(require("node:fs")),o_t=Yl(require("node:path"));LF();Hm();var GFn=V0("SymbolAnalysisCache"),WOt="1.25.5",s_t="symbols.cache",UFn=2;function Sln(l){try{tW.writeFileSync(o_t.join(o_t.dirname(l),".gitignore"),`*
46081
+ `);for(f.bind([o]);f.step();){let _=f.getAsObject();a.push({name:_.callee_name,filePath:Ir(_.callee_path),callSiteLine:_.source_line})}f.free()}catch{}return a}}});var DDr={};module.exports=tXn(DDr);var d1n=require("node:worker_threads");var EPn=require("node:crypto"),n9t=Yl(require("node:fs")),Vxt=Yl(require("node:path")),xPn=require("node:worker_threads");LF();var cUe=V0("AstWorkerHost"),Ctt=class{worker=null;nextId=1;pendingRequests=new Map;workerPath;extensionPath;rootDir;isStopping=!1;isDisposed=!1;stopPromise=null;build;constructor(o,a,f){if(this.extensionPath=a,this.rootDir=f,o)this.workerPath=o;else{let _=[Vxt.join(__dirname,"astWorker.js"),Vxt.join(__dirname,"../../../dist/astWorker.js"),Vxt.join(__dirname,"../../../../dist/astWorker.js"),Vxt.join(process.cwd(),"dist/astWorker.js")],b="";for(let C of _)if(n9t.existsSync(C)){b=C;break}this.workerPath=b||Vxt.join(process.cwd(),"dist/astWorker.js")}}buildId(){if(this.build===void 0)try{this.build=(0,EPn.createHash)("sha256").update(n9t.readFileSync(this.workerPath)).digest("hex")}catch{this.build="missing"}return this.build}async start(){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||this.isStopping){cUe.warn("AstWorker already started");return}cUe.info(`Starting AstWorker from ${this.workerPath}`);try{this.worker=new xPn.Worker(this.workerPath,{workerData:{extensionPath:this.extensionPath,rootDir:this.rootDir}}),this.worker.on("message",o=>{this.handleResponse(o)}),this.worker.on("error",o=>{cUe.error("AstWorker error:",o);for(let[a,f]of this.pendingRequests)f.reject(new Error(`AstWorker crashed: ${o.message}`)),this.pendingRequests.delete(a)}),this.worker.on("exit",o=>{o!==0&&!this.isStopping&&cUe.error(`AstWorker exited with code ${o}`),this.worker=null,this.stopPromise||(this.isStopping=!1)}),cUe.info("AstWorker started successfully")}catch(o){let a=o instanceof Error?o.message:String(o);throw cUe.error(`Failed to start AstWorker: ${a}`),new Error(`Failed to start AstWorker: ${a}`,{cause:o})}}stop(){if(this.isDisposed=!0,this.stopPromise)return this.stopPromise;let o=this.worker;if(!o)return Promise.resolve();cUe.debug("Stopping AstWorker");for(let[a,f]of this.pendingRequests)f.reject(new Error("AstWorker stopped")),this.pendingRequests.delete(a);return this.isStopping=!0,this.stopPromise=o.terminate().then(()=>{}).finally(()=>{this.worker===o&&(this.worker=null),this.isStopping=!1,this.stopPromise=null,cUe.debug("AstWorker stopped")}),this.stopPromise}async analyzeFile(o,a){return await this.sendRequest({type:"analyzeFile",id:0,filePath:o,content:a})}async getInternalExportDependencyGraph(o,a){let _=await this.sendRequest({type:"getInternalExportDeps",id:0,filePath:o,content:a});return new Map(Object.entries(_).map(([b,C])=>[b,new Set(C)]))}async extractSignatures(o,a){return await this.sendRequest({type:"extractSignatures",id:0,filePath:o,content:a})}async extractInterfaceMembers(o,a){let _=await this.sendRequest({type:"extractInterfaceMembers",id:0,filePath:o,content:a});return new Map(Object.entries(_))}async extractTypeAliases(o,a){return await this.sendRequest({type:"extractTypeAliases",id:0,filePath:o,content:a})}async compareSignatures(o,a){return await this.sendRequest({type:"compareSignatures",id:0,oldSig:o,newSig:a})}async analyzeBreakingChanges(o,a,f,_){return await this.sendRequest({type:"analyzeBreakingChanges",id:0,filePath:o,oldContent:a,newContent:f,symbolName:_})}async reset(){await this.sendRequest({type:"reset",id:0})}async getFileCount(){return await this.sendRequest({type:"getFileCount",id:0})}async sendRequest(o){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||await this.start(),this.isDisposed)throw new Error("AstWorker has been stopped");let a=this.nextId++,f={...o,id:a};return new Promise((_,b)=>{this.pendingRequests.set(a,{resolve:_,reject:b}),this.worker?.postMessage(f)})}handleResponse(o){let a=this.pendingRequests.get(o.id);if(!a){cUe.warn(`Received response for unknown request ${o.id}`);return}if(this.pendingRequests.delete(o.id),o.type==="success")a.resolve(o.result);else{let f=new Error(o.error);o.stack&&(f.stack=o.stack),a.reject(f)}}};var h3=Yl(require("node:fs")),cH=Yl(require("node:path"));ktt();LF();Hm();var WFn=require("node:crypto"),ZGt=Yl(require("node:fs")),EAt=Yl(require("node:path"));dce();LF();Hm();OF();YGt();var air=V0("configFingerprint");function yln(l,o){try{let a=zFn(jFn(l,o));return(0,WFn.createHash)("sha256").update(JSON.stringify([...a].sort(([f],[_])=>f.localeCompare(_)))).digest("hex")}catch(a){air.info(`Index cache disabled: ${a instanceof Error?a.message:String(a)}`);return}}function vln(l,o){return[...zFn(jFn(l,o)).keys()]}function bln(l,o){return o.filter(a=>!u9t.test(a)&&Jte(a,l))}function jFn(l,o){let a=new Set([Ir(l)]);for(let f of o){let _=Ir(EAt.dirname(f));for(;!a.has(_);){if(!Jte(_,l))throw new Error(`source file outside the workspace: ${Ir(f)}`);a.add(_),_=Ir(EAt.dirname(_))}}return a}function zFn(l){let o=[...l].flatMap(_=>[EAt.join(_,"tsconfig.json"),EAt.join(_,"package.json")]),a=new Set,f=new Map;for(let _=o.shift();_;_=o.shift()){let b=Ir(_);if(a.has(b)||!ZGt.existsSync(_))continue;a.add(b);let C=cir(_);f.set(b,C),o.push(...QGt(_,i_t(_,C)?.extends))}return f}function cir(l){try{return ZGt.readFileSync(l,"utf-8")}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`cannot read resolver config ${Ir(l)}: ${a}`,{cause:o})}}var $Fn=require("node:crypto"),tW=Yl(require("node:fs")),o_t=Yl(require("node:path"));LF();Hm();var GFn=V0("SymbolAnalysisCache"),WOt="1.25.6",s_t="symbols.cache",UFn=2;function Sln(l){try{tW.writeFileSync(o_t.join(o_t.dirname(l),".gitignore"),`*
46082
46082
  `,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o}}var KFn="",eUt=" ",lir=1<<20,uir=/<template\b[^>]*\ssrc\s*=/i,VFn=l=>(0,$Fn.createHash)("sha256").update(l).digest("hex"),JFn=l=>JSON.stringify(l).slice(1,-1),HFn=(l,o)=>JSON.stringify(o).replaceAll(JFn(l),KFn),dir=(l,o)=>JSON.parse(o.replaceAll(KFn,JFn(l))),fir=l=>Array.isArray(l)&&l.every(o=>typeof o=="string"),pir=l=>typeof l=="object"&&l!==null&&Array.isArray(l.symbols)&&Array.isArray(l.dependencies),mir=l=>Array.isArray(l)&&l.every(o=>Array.isArray(o)&&typeof o[0]=="string"&&fir(o[1])),tUt=class{constructor(o,a){this.dir=o;this.build=a}dir;build;entries;dirty=!1;getGraph(o,a){let f=this.read(o,a,"graph");return pir(f)?f:this.drop(o,"graph",f)}setGraph(o,a,f){let _=Ir(o);this.update(_,a,{graph:HFn(_,f)})}getInternalGraph(o,a){let f=this.read(o,a,"internal");return mir(f)?new Map(f.map(([_,b])=>[_,new Set(b)])):this.drop(o,"internal",f)}setInternalGraph(o,a,f){let _=Ir(o);this.update(_,a,{internal:HFn(_,[...f].map(([b,C])=>[b,[...C]]))})}save(){if(!this.dirty||!this.entries)return;let o=o_t.join(this.dir,s_t),a=o_t.join(this.dir,`.${s_t}.${process.pid}.tmp`),f,_=!1;try{tW.mkdirSync(this.dir,{recursive:!0}),Sln(this.dir),f=tW.openSync(a,"w"),_=!0;let b={schema:UFn,version:WOt,build:this.build},C=JSON.stringify(b);for(let[k,G]of this.entries){if(!tW.existsSync(k)){this.entries.delete(k);continue}C+=`
46083
46083
  ${JSON.stringify(k)}${eUt}${G.hash}${eUt}${G.graph??""}${eUt}${G.internal??""}`,C.length>=lir&&(tW.writeSync(f,C),C="")}tW.writeSync(f,C),tW.closeSync(f),f=void 0,tW.renameSync(a,o),this.dirty=!1}catch(b){f!==void 0&&tW.closeSync(f),_&&tW.rmSync(a,{force:!0}),GFn.warn("Could not save symbol cache:",b instanceof Error?b.message:String(b))}}read(o,a,f){let _=Ir(o),b=this.load().get(_),C=b?.hash===VFn(a)?b[f]:void 0;if(C!==void 0)try{return dir(_,C)}catch{return null}}drop(o,a,f){let _=f===void 0?void 0:this.load().get(Ir(o));_&&(GFn.warn("Damaged symbol cache entry, analyzing again:",o),_[a]=void 0,this.dirty=!0)}update(o,a,f){if(o.toLowerCase().endsWith(".vue")&&uir.test(a))return;let _=VFn(a),b=this.load().get(o);this.load().set(o,{...b?.hash===_?b:{},...f,hash:_}),this.dirty=!0}load(){if(this.entries)return this.entries;this.entries=new Map;let o;try{o=tW.readFileSync(o_t.join(this.dir,s_t),"utf-8").split(/\r?\n/);let a=JSON.parse(o[0]);if(a.schema!==UFn||a.version!==WOt||a.build!==this.build)return this.entries}catch{return this.entries}for(let a of o.slice(1))this.loadLine(a);return this.entries}loadLine(o){let[a,f,_,b]=o.split(eUt);if(b!==void 0)try{let C=JSON.parse(a);typeof C=="string"&&this.entries?.set(C,{hash:f,graph:_||void 0,internal:b||void 0})}catch{}}};var AAt=V0("IndexCache"),qFn=2,_ir=.2,XFn=10*6e4,hir=250,Tln="meta.json",jOt="reverse-index.json",nUt="callgraph.db",QFn="index.lock";function YFn(){return""}var xAt=new Map,xln=()=>{};function Eln(l,o){let a=cH.join(cH.dirname(l),`.${cH.basename(l)}.${process.pid}.tmp`);h3.writeFileSync(a,o),h3.renameSync(a,l)}function gir(l){try{return process.kill(l,0),!0}catch(o){return o.code==="EPERM"}}function yir(l,o){return l?.excludeNodeModules===o.excludeNodeModules&&l?.ignoreTypeImports===o.ignoreTypeImports}var CAt=class l{dir;sourceFiles;workspaceRoot;fingerprint;constructor(o,a){this.workspaceRoot=cH.resolve(o),this.dir=l.dirFor(this.workspaceRoot),this.sourceFiles=a,this.fingerprint=yln(this.workspaceRoot,a)}static dirFor(o){return cH.join(o,".graph-it","cache")}static async open(o){let a=await new KQ({excludeNodeModules:!0,yieldIntervalMs:30,isCancelled:()=>!1}).collectAllSourceFiles(o);return new l(o,a)}get enabled(){return this.fingerprint!==void 0}get callGraphPath(){return cH.join(this.dir,nUt)}isValid(){return this.matches(this.readMeta())}readReverseIndex(o){let a=this.readMeta();if(!this.matches(a)||!yir(a?.reverseIndexOptions,o))return null;try{return h3.readFileSync(cH.join(this.dir,jOt),"utf-8")}catch{return null}}save(o){let a=this.currentFingerprint();if(!a)return!1;try{h3.mkdirSync(this.dir,{recursive:!0}),Sln(this.dir);let f=this.readMeta(),_=this.matches(f,a),b=cH.join(this.dir,jOt);o.reverseIndex?Eln(b,o.reverseIndex.data):_||h3.rmSync(b,{force:!0}),o.callGraph?Eln(this.callGraphPath,o.callGraph):_||h3.rmSync(this.callGraphPath,{force:!0});let C={schema:qFn,version:WOt,build:YFn(),savedAt:new Date().toISOString(),workspaceRoot:this.workspaceRoot,configFingerprint:a,reverseIndexOptions:o.reverseIndex?.options??(_?f?.reverseIndexOptions:void 0)};Eln(cH.join(this.dir,Tln),JSON.stringify(C,null,2));let k=l.fileSizes(this.dir);return AAt.info(`Saved index cache: ${jOt} ${k.reverseIndexBytes} B, ${nUt} ${k.callGraphBytes} B, ${s_t} ${k.symbolsBytes} B`),!0}catch(f){return AAt.warn("Could not save index cache:",f instanceof Error?f.message:String(f)),!1}}static fileSizes(o){let a=f=>{try{return h3.statSync(cH.join(o,f)).size}catch{return 0}};return{reverseIndexBytes:a(jOt),callGraphBytes:a(nUt),symbolsBytes:a(s_t)}}clear(){for(let o of[Tln,jOt,nUt,s_t])h3.rmSync(cH.join(this.dir,o),{force:!0});try{h3.rmdirSync(this.dir)}catch{}}tryLock(){if(!this.enabled)return xln;let o=cH.join(this.dir,QFn),a=xAt.get(Ir(o));if(a)return xAt.set(Ir(o),a+1),this.releaser(o);try{if(h3.mkdirSync(this.dir,{recursive:!0}),!this.createLockFile(o)&&(!this.isLockStale(o)||(h3.rmSync(o,{force:!0}),!this.createLockFile(o))))return null}catch(f){return AAt.warn("Could not lock index cache:",f instanceof Error?f.message:String(f)),xln}return xAt.set(Ir(o),1),this.releaser(o)}async lock(o){let a=!1;for(;;){let f=this.tryLock();if(f)return f;a||(a=!0,o?.(this.readLockHolder(cH.join(this.dir,QFn))?.pid)),await new Promise(_=>setTimeout(_,hir))}}releaser(o){let a=!1;return()=>{if(a)return;a=!0;let f=Ir(o),_=(xAt.get(f)??1)-1;if(_>0){xAt.set(f,_);return}xAt.delete(f),this.readLockHolder(o)?.pid===process.pid&&h3.rmSync(o,{force:!0})}}createLockFile(o){let a={pid:process.pid,acquiredAt:Date.now()};try{return h3.writeFileSync(o,JSON.stringify(a),{flag:"wx"}),!0}catch(f){if(f.code==="EEXIST")return!1;throw f}}readLockHolder(o){try{let a=JSON.parse(h3.readFileSync(o,"utf-8"));return typeof a.pid=="number"?a:void 0}catch{return}}isLockStale(o){let a=this.readLockHolder(o);if(!a)try{return Date.now()-h3.statSync(o).mtimeMs>XFn}catch{return!0}return a.pid===process.pid?!0:Date.now()-a.acquiredAt>XFn||!gir(a.pid)}readMeta(){try{return JSON.parse(h3.readFileSync(cH.join(this.dir,Tln),"utf-8"))}catch{return}}currentFingerprint(){return this.fingerprint&&yln(this.workspaceRoot,this.sourceFiles)}matches(o,a=this.currentFingerprint()){return a!==void 0&&o?.schema===qFn&&o.version===WOt&&(o.build??"")===YFn()&&o.configFingerprint===a&&typeof o.workspaceRoot=="string"&&Ir(o.workspaceRoot)===Ir(this.workspaceRoot)}};async function ZFn(l,o){let{cache:a}=o,f=a?await a.lock(o.onWait):xln;try{l.useSymbolAnalysisCache(a?.enabled?a.dir:null);let _=a?.readReverseIndex(o.reverseIndexOptions),b=_?l.enableReverseIndex(_):!1;b&&AAt.info("Restored reverse index from cache");let C=a&&b?await vir(l,a,o):null,{deleted:k,...G}=C??await bir(l,o),X=!G.fromCache||G.filesAnalyzed>0||k>0;if(a&&X&&!G.cancelled){let te=l.getSerializedReverseIndex();te&&a.save({reverseIndex:{data:te,options:o.reverseIndexOptions}})}return G}finally{f()}}async function vir(l,o,a){let f=await l.validateReverseIndex(_ir,o.sourceFiles);if(!f?.isValid)return AAt.info("Cached index too stale, rebuilding from scratch"),null;for(let C of f.missingFiles)l.handleFileDeleted(C);f.staleFiles.length>0&&a.onReindexStart?.(f.staleFiles.length);let _=await l.reindexStaleFiles(f.staleFiles);return AAt.info(`Incremental index: ${_} changed, ${f.missingFiles.length} deleted`),{filesIndexed:l.getCacheStats().reverseIndexStats?.indexedFiles??0,filesFound:o.sourceFiles.length,filesAnalyzed:_,fromCache:!0,cancelled:!1,deleted:f.missingFiles.length}}async function bir(l,o){l.clearCache();let a=await o.buildFullIndex();return{filesIndexed:l.getCacheStats().reverseIndexStats?.indexedFiles??a.indexedFiles,filesFound:a.indexedFiles,filesAnalyzed:a.indexedFiles,fromCache:!1,cancelled:a.cancelled,deleted:0}}var a_t=Yl(require("node:fs/promises")),rUt=Yl(require("node:fs"));g3();LF();var Sir=V0("FileReader"),Tir=5*1024*1024,Eir=64*1024,xir=3e4,BF=class{maxSize;chunkSize;timeout;constructor(o={}){this.maxSize=o.maxSize??Tir,this.chunkSize=o.chunkSize??Eir,this.timeout=o.timeout??xir}async getFileSize(o){try{let a=await a_t.stat(o);return{size:a.size,isLarge:a.size>this.maxSize,path:o}}catch(a){throw oE.fromError(a,o)}}async readFile(o,a){let f=a?.maxSize??this.maxSize,_=a?.timeout??this.timeout,b=a?.streaming??!1,C;try{C=await a_t.stat(o)}catch(X){throw oE.fromError(X,o)}if(C.size>f)throw new oE(`File too large: ${o} (${this.formatSize(C.size)} > ${this.formatSize(f)})`,"FILE_TOO_LARGE",{filePath:o});let k,G=new Promise((X,te)=>{k=setTimeout(()=>{te(new oE(`File read timed out after ${_}ms: ${o}`,"TIMEOUT",{filePath:o}))},_)});try{let X;return b||C.size>1024*1024?(Sir.debug(`Streaming read for large file: ${o} (${this.formatSize(C.size)})`),X=await Promise.race([this.readFileStreaming(o),G])):X=await Promise.race([a_t.readFile(o,"utf-8"),G]),clearTimeout(k),X}catch(X){throw clearTimeout(k),X instanceof oE?X:oE.fromError(X,o)}}async readFileStreaming(o){return new Promise((a,f)=>{let _=[],b=rUt.createReadStream(o,{highWaterMark:this.chunkSize});b.on("data",C=>{_.push(Buffer.isBuffer(C)?C:Buffer.from(C))}),b.on("end",()=>{let C=Buffer.concat(_).toString("utf-8");a(C)}),b.on("error",C=>{f(oE.fromError(C,o))})})}async readFileIfExists(o){try{return await this.readFile(o)}catch(a){if(a instanceof oE&&a.code==="FILE_NOT_FOUND")return null;throw a}}async canRead(o){try{return await a_t.access(o,rUt.constants.R_OK),!0}catch{return!1}}formatSize(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}};var Air=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]),Cir=new Set("(,=:[!&|?{};~+-*%<>^");function t4n(l){return l===void 0?!1:l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||l===95||l===36}function wir(l){return l===32||l===9||l===10||l===13}function Aln(l,o,a){a<=o||(l.parts.push(l.src.slice(l.copied,o),l.src.slice(o,a).replaceAll(/[^\n\r]/g," ")),l.copied=a)}function Iir(l){let{src:o}=l,a=l.i-1;for(;a>=0;)if(a<l.commentEnd&&a>=l.commentStart)a=l.commentStart-1;else if(wir(o.codePointAt(a)))a--;else break;if(a<0)return"";if(!t4n(o.codePointAt(a)))return o[a];let f=a;for(;f>0&&t4n(o.codePointAt(f-1));)f--;return o.slice(f,a+1)}function kir(l){return l===""||Cir.has(l)||Air.has(l)}function Dir(l,o){let a=l[o],f=o+1;for(;f<l.length&&l[f]!==a&&l[f]!==`
46084
46084
  `;)f+=l[f]==="\\"?2:1;return l[f]===a?f+1:Math.min(f,l.length)}function Pir(l,o){let a=!1;for(let f=o+1;f<l.length;f++){let _=l[f];if(_===`
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@magic5644/graph-it-live",
3
3
  "displayName": "Graph-It-Live",
4
4
  "description": "AI-first dependency graph & code intelligence for VS Code. Visualize file imports, symbol call hierarchies, and cross-file call graphs. Detect circular dependencies, dead code, and breaking changes. Built-in MCP Server with 25 tools for GitHub Copilot, Cursor, Claude, Windsurf, and Antigravity. Generate AI-friendly codemaps. TypeScript, JavaScript, C#, Go, Java, Python, Rust, Vue, Svelte, GraphQL.",
5
- "version": "1.25.5",
5
+ "version": "1.25.6",
6
6
  "publisher": "magic5644",
7
7
  "author": {
8
8
  "name": "magic56"