pando-ai 0.2.0 → 0.2.2

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.
@@ -0,0 +1,518 @@
1
+ import{c as un,d as re,e as F,f as at}from"./chunk-ODST7O2H.mjs";import{a as cn}from"./chunk-AYCBSZ56.mjs";var G={getAbbrev(r,e="ts"){return r},getKindFromAbbrev(r,e="ts"){return r}};function Se(r){let e=`${r.sourceFile}#${r.sourceStart}-${r.sourceEnd}`,t=r.refKind??"",n=r.refName??"",i=r.targetFile??"",s=r.targetStart!=null&&r.targetEnd!=null?`#${r.targetStart}-${r.targetEnd}`:"",o=r.targetNodeId??"",a=`${e}:REF:${t}:${n}|${i}${s}|${o}`;return at(a)}function lt(r){let e=[],t=new Set,n=i=>{!i?.name||t.has(i.name)||(t.add(i.name),e.push(i))};for(let i of r.exports??[])n(i);for(let i of r.explicitExports??[])n({name:i});for(let i of r.modulePublic??[])n({name:i});return e}function de(r,e,t){let n=new Date().toISOString();return{payload:{lang:r,fileRel:e,preDeleted:!1,exportRows:[],nodeRows:[],referenceRows:[],symbolMentionRows:[],importRows:[],importBindingRows:[],fileRow:[e,t?.mtime??null,t?.size??null,"failed",n],fts:null},fileSize:t?.size,mtime:t?.mtime}}function pe(r){let{lang:e,fileRel:t,content:n,meta:i,preDeleted:s,parsed:o,resolveNodeId:a,exportKind:c}=r,d=[];for(let l of o.nodes??[]){let C=l.rawKind??l.kind,v=l.rawKindSource??"cli",N=l.containerRawKind??l.containerKind??null,T=l.containerRawKindSource??(N?"cli":null),f=l.scopeChain??null,h=Array.isArray(f)?JSON.stringify(f):typeof f=="string"?f:null,x=`${t}#${l.start}-${l.end}:${G.getAbbrev(l.kind,e)}`,b=(e==="c"||e==="cpp"||e==="java"||e==="clojure")&&l.name?`${x}:${l.name}`:x,R=l.metadata&&Object.keys(l.metadata).length?JSON.stringify(l.metadata):null;d.push([b,l.name,l.kind,C,v,l.semanticKind??null,l.start,l.end,typeof l.isExported=="number"?l.isExported:0,l.containerKind??null,N,T,typeof l.paramCount=="number"?l.paramCount:null,l.qualifiedName??null,h,l.symbolKey??null,R])}let g=[],p=new Set;for(let l of lt(o)){if(!l.name||p.has(l.name))continue;p.add(l.name);let C=l.nodeId??(a?a(l.name):null);g.push([t,l.name,C??null,l.isReexport?1:0,l.reexportFrom??null,l.reexportName??null,l.exportKind??c??"cli",l.targetSymbolKey??null])}let S=[],k=[],D=new Map,E=new Map;for(let l of d){let C=l[0]!=null?String(l[0]):null,v=l[13]!=null?String(l[13]):null,N=l[15]!=null?String(l[15]):null;C&&(v&&!D.has(v)&&D.set(v,C),N&&!E.has(N)&&E.set(N,C))}if(re()&&e==="clojure"&&(o.references??[]).length>0){let l=Array.from(D.keys()).slice(0,10),C=Array.from(E.keys()).slice(0,10),v=(o.references??[]).slice(0,10).map(T=>T.containerQualifiedName),N={file:t,nodeCount:d.length,refCount:(o.references??[]).length,nodeQualifiedNames:l,nodeSymbolKeys:C,refContainers:v,qualifiedNameMapSize:D.size,symbolKeyMapSize:E.size};try{console.error("[CliPayload][CLOJURE-DEBUG] source_node_id lookup context",N)}catch{}}for(let l of o.references??[]){let C=l.targetNodeId??(a&&l.refName?a(l.refName):null),v=l.targetFile??(C?t:null),N=l.sourceNodeId??(l.containerQualifiedName?D.get(l.containerQualifiedName)??null:null)??(l.containerQualifiedName?E.get(l.containerQualifiedName)??null:null),T=Se({sourceFile:t,sourceStart:l.sourceStart,sourceEnd:l.sourceEnd,refKind:l.refKind,refName:l.refName,targetFile:v??null,targetStart:l.targetStart??null,targetEnd:l.targetEnd??null,targetNodeId:C??l.targetNodeId??null}),f=l.metadata&&Object.keys(l.metadata).length?JSON.stringify(l.metadata):null;S.push([T,t,N,l.refName??null,l.refKind,l.sourceStart,l.sourceEnd,C??l.targetNodeId??null,v??null,C||l.targetNodeId||l.targetFile?"resolved":"unresolved",l.receiverName??null,typeof l.arity=="number"?l.arity:null,l.containerQualifiedName??null,l.targetSymbolKey??null,l.confidence??null,f])}for(let l of o.symbolMentions??[]){let C=typeof l?.name=="string"?l.name.trim():"";if(!C)continue;let v=typeof l?.mentionKind=="string"&&l.mentionKind.trim().length>0?l.mentionKind.trim():"reference",N=typeof l?.count=="number"&&Number.isFinite(l.count)&&l.count>0?Math.floor(l.count):1;k.push([C,v,l.targetSymbolKey??null,l.containerQualifiedName??null,N])}if(re()&&e==="clojure"&&S.length>0){let l=S.reduce((v,N)=>v+(N?.[2]!=null?1:0),0),C=S.reduce((v,N)=>v+(N?.[12]!=null?1:0),0);try{console.error("[CliPayload] clojure source-node summary",{file:t,refs:S.length,sourceNodeCount:l,containerCount:C,sample:S.slice(0,5).map(v=>({sourceNodeId:v[2]==null?null:String(v[2]),refName:v[3],refKind:v[4],containerQualifiedName:v[12]}))})}catch{}}let M=[];for(let l of o.imports??[])M.push([t,l.module??null,l.isTypeOnly??0]);let Q=[];for(let l of o.importBindings??[])Q.push([t,l.module??null,l.kind,l.localName,l.importedName,l.isTypeOnly??0]);let u=new Date().toISOString(),w=[t,i?.mtime??null,i?.size??null,"completed",u];return{payload:{lang:e,fileRel:t,preDeleted:!!s,exportRows:g,nodeRows:d,referenceRows:S,symbolMentionRows:k,importRows:M,importBindingRows:Q,fileRow:w,fts:typeof n=="string"?{blobOid:t,content:n}:null},fileSize:i?.size,mtime:i?.mtime}}var fe=["ts","js","python","c","cpp","csharp","dart","java","clojure"];function je(r){return typeof r=="string"&&fe.includes(r)}un();function ct(){let r=process.env.PANDO_ENABLED_LANGUAGES;if(r&&r.trim().length>0){let t=r.split(",").map(n=>n.trim()).filter(n=>n.length>0).filter(je);if(t.length>0)return ut(t)}return[...fe]}function ut(r){let e=new Set;for(let t of r)je(t)&&e.add(t);return fe.filter(t=>e.has(t))}function dt(r){let e=new Set(ut(r)),t={};for(let n of fe){if(e.has(n)){t[n]={enabled:!0,source:"embedded"};continue}t[n]={enabled:!1,source:"none",reason:"disabled by language support config"}}return{byLanguage:t}}import Be from"path";import bn from"fs";import{Project as xn,Node as J}from"ts-morph";import{Node as m,SyntaxKind as ie}from"ts-morph";import*as q from"typescript";import{SyntaxKind as me}from"ts-morph";var Fe={LINE_COMMENT:{kind:9001,name:"LineComment",triviaKind:me.SingleLineCommentTrivia},BLOCK_COMMENT:{kind:9002,name:"BlockComment",triviaKind:me.MultiLineCommentTrivia},JSDOC_COMMENT:{kind:9003,name:"JSDocComment",triviaKind:me.MultiLineCommentTrivia}};function pt(r,e){return r===me.SingleLineCommentTrivia?Fe.LINE_COMMENT:r===me.MultiLineCommentTrivia&&e.startsWith("/**")?Fe.JSDOC_COMMENT:Fe.BLOCK_COMMENT}import{Node as I}from"ts-morph";var ft={TS_MORPH:"ts-morph",PYTHON_AST:"python-ast",CLANG:"clang",ROSLYN:"roslyn",JAVA_AST:"java-ast",CLI:"cli",UNKNOWN:"unknown"},mt=(r,e)=>I.isFunctionDeclaration(r)||I.isFunctionExpression(r)||I.isArrowFunction(r)?{kind:"Function",semanticKind:"function"}:I.isGetAccessorDeclaration(r)||I.isSetAccessorDeclaration(r)?{kind:"Method",semanticKind:"property"}:I.isMethodDeclaration(r)||I.isMethodSignature(r)||I.isConstructorDeclaration(r)?{kind:"Method",semanticKind:"method"}:I.isClassDeclaration(r)||I.isClassExpression(r)?{kind:"Class",semanticKind:"class"}:I.isInterfaceDeclaration(r)?{kind:"Interface",semanticKind:"interface"}:I.isEnumDeclaration(r)?{kind:"Enum",semanticKind:"enum"}:I.isEnumMember(r)?{kind:"EnumMember",semanticKind:"enum"}:I.isTypeAliasDeclaration(r)?{kind:"TypeAlias",semanticKind:"type"}:I.isModuleDeclaration(r)?{kind:"Namespace",semanticKind:"namespace"}:I.isPropertyDeclaration(r)||I.isPropertySignature(r)?{kind:"Field",semanticKind:"property"}:I.isVariableDeclaration(r)?{kind:"Variable",semanticKind:"variable"}:{kind:e,semanticKind:null};function gt(r){try{let e=r.getKindName?.();if(typeof e=="string"&&e.trim())return e}catch{}return"Unknown"}function Ce(r){let e=gt(r),t=mt(r,e);return{kind:t.kind,semanticKind:t.semanticKind,rawKind:e,rawKindSource:ft.TS_MORPH}}function ht(r){let e=gt(r);return{kind:mt(r,e).kind,rawKind:e,rawKindSource:ft.TS_MORPH}}function ve(r,e){if(!r.kind||!r.kind.trim())throw new Error(`Invalid normalized kind: missing kind ${e?JSON.stringify(e):""}`);if(!r.rawKind||!r.rawKind.trim())throw new Error(`Invalid normalized kind: missing rawKind ${e?JSON.stringify(e):""}`);if(!r.rawKindSource||!String(r.rawKindSource).trim())throw new Error(`Invalid normalized kind: missing rawKindSource ${e?JSON.stringify(e):""}`)}function dn(r){if(r.kind==="local"){let n=r.isDefault?"default":r.name;return n?{name:n,priority:r.isDefault?4:3}:null}if(r.kind==="alias")return r.exported?{name:r.exported,priority:2}:null;let e=r.isNamespace??!1,t=r.alias||r.name||(e?"*":null);return t?{name:t,priority:e?0:1}:null}function pn(r){if(r.length<2)return r;let e=new Map;for(let t of r){let n=dn(t);if(!n)continue;let i=e.get(n.name);(!i||n.priority>i.priority)&&e.set(n.name,{record:t,priority:n.priority})}return Array.from(e.values()).map(t=>t.record)}function Ne(r){try{if(r&&typeof r.getName=="function"){let e=r.getName();if(typeof e=="string"&&e.length>0)return e}}catch{}return null}function yt(r){let e;try{let n=r.getStart?.(!1);typeof n=="number"&&Number.isFinite(n)&&(e=n)}catch{}if(e===void 0)try{let n=r.getStart?.();typeof n=="number"&&Number.isFinite(n)&&(e=n)}catch{}if(e===void 0)try{let n=r.getFullStart?.();typeof n=="number"&&Number.isFinite(n)&&(e=n)}catch{}e===void 0&&(e=0);let t;try{let n=r.getEnd?.();typeof n=="number"&&Number.isFinite(n)&&(t=n)}catch{}if(t===void 0)try{let n=r.getStart?.();typeof n=="number"&&Number.isFinite(n)&&(t=n)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}function fn(r){try{if(m.isFunctionDeclaration(r)||m.isMethodDeclaration(r)||m.isConstructorDeclaration(r)||m.isFunctionExpression(r)||m.isArrowFunction(r)){let e=r.getParameters?.();if(Array.isArray(e))return e.length}}catch{}return null}function mn(r){try{return m.isIdentifier(r)?r.getSymbol():m.isPropertyAccessExpression(r)?r.getNameNode().getSymbol()??r.getSymbol():r.getSymbol?.()}catch{return}}function we(r,e){try{return typeof r?.hasModifier=="function"&&r.hasModifier(e)}catch{return!1}}function bt(r){try{return r.getModuleSpecifierValue?.()??null}catch{try{return r.getModuleSpecifier?.()?.getLiteralText?.()??null}catch{return null}}}function gn(r,e,t){if(!m.isImportDeclaration(r))return;let i={moduleSpecifier:bt(r),isTypeOnly:r.isTypeOnly(),namedImports:[]};try{let s=r.getDefaultImport();if(s){let o=s.getText();i.defaultImport=o,t(o,s)}}catch{}try{let s=r.getNamespaceImport();if(s){let o=s.getText();i.namespaceImport=o,t(o,s)}}catch{}try{r.getNamedImports().forEach(s=>{try{let o=s.getName(),a=s.getAliasNode(),c=a?a.getText():void 0;o&&(i.namedImports.push({name:o,alias:c||void 0}),t(c||o,s.getNameNode()))}catch{}})}catch{}e.push(i)}function hn(r,e){if(m.isExportDeclaration(r)){let t=bt(r);if(t){if(r.getNamedExports().length>0)try{r.getNamedExports().forEach(n=>{try{let i=n.getName(),s=n.getAliasNode(),o=s?s.getText():void 0;e.push({kind:"reexport",moduleSpecifier:t,name:i||void 0,alias:o||void 0,isNamespace:!1})}catch{}})}catch{}else if(r.isNamespaceExport())try{let i=r.getNamespaceExport()?.getName();e.push({kind:"reexport",moduleSpecifier:t,name:i||"*",alias:i||void 0,isNamespace:!0})}catch{e.push({kind:"reexport",moduleSpecifier:t,name:"*",isNamespace:!0})}else e.push({kind:"reexport",moduleSpecifier:t,name:"*",isNamespace:!0});return}try{r.getNamedExports().forEach(n=>{try{let i=n.getName();if(!i)return;let s=n.getAliasNode(),o=s?s.getText():i;e.push({kind:"alias",local:i,exported:o})}catch{}})}catch{}return}if(m.isExportAssignment(r))try{let t=r.getExpression();if(t&&m.isIdentifier(t)){let n=t.getText();e.push({kind:"alias",local:n,exported:"default"})}}catch{}}function yn(r,e,t,n){if(!we(r,ie.ExportKeyword))return;let i=we(r,ie.DefaultKeyword);if(m.isVariableStatement(r)){try{let s=r.getDeclarationList().getDeclarations();for(let o of s){let a=Ne(o)??o.getName?.()??null;if(a){t(a,o);let c=n(o);c&&e.push({kind:"local",name:a,isDefault:i,nodeId:c})}}}catch{}return}if(m.isFunctionDeclaration(r)||m.isClassDeclaration(r)||m.isInterfaceDeclaration(r)||m.isEnumDeclaration(r)||m.isTypeAliasDeclaration(r)||m.isModuleDeclaration(r)){let s=Ne(r)||(i?"default":null),o=n(r);o&&e.push({kind:"local",name:s??"default",isDefault:i,nodeId:o})}}function xt(r,e,t,n){let i=[],s=[],o=[],a=new Set,c=new Map,d=[],g=[],p=[{node:r,id:null,kind:"module",rawKind:"SourceFile",rawKindSource:"ts-morph",name:null,isExported:!1}],S=u=>{if(!u)return null;try{return e(u)}catch{return null}},k=(u,w)=>{if(u&&(a.has(u)||a.add(u),w&&!c.has(u))){let P=S(w);P&&c.set(u,P)}},D=u=>m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u)||m.isClassDeclaration(u)||m.isClassExpression(u)||m.isInterfaceDeclaration(u)||m.isEnumDeclaration(u)||m.isEnumMember(u)||m.isTypeAliasDeclaration(u)||m.isModuleDeclaration(u)||m.isMethodDeclaration(u)||m.isMethodSignature(u)||m.isPropertyDeclaration(u)||m.isPropertySignature(u)||m.isGetAccessorDeclaration(u)||m.isSetAccessorDeclaration(u)||m.isConstructorDeclaration(u)||m.isVariableDeclaration(u),E=u=>m.isSourceFile(u)||m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u)||m.isMethodDeclaration(u)||m.isConstructorDeclaration(u)||m.isClassDeclaration(u)||m.isClassExpression(u)||m.isModuleDeclaration(u),M=u=>{let w=Ne(u);if(w)return w;if(m.isConstructorDeclaration(u))return"constructor";if(m.isArrowFunction(u)||m.isFunctionExpression(u)){let P=u.getParent();try{if(m.isVariableDeclaration(P))return P.getName();if(m.isPropertyAssignment(P)||m.isPropertyDeclaration(P)||m.isPropertySignature(P))return P.getName?.()??null;if(m.isShorthandPropertyAssignment(P))return P.getNameNode()?.getText()??null;if(m.isExportAssignment(P))return"default"}catch{}}if(m.isEnumMember(u))try{return u.getName()}catch{return null}if(m.isVariableDeclaration(u))try{return u.getName()}catch{return null}return null},Q=u=>{let w=p[p.length-1],P=w?.id??null,l=w?.kind??"module",C=w?.name??null;if(m.isImportDeclaration(u))gn(u,d,k);else if(m.isImportEqualsDeclaration(u))try{let f=u.getModuleReference();if(f&&m.isExternalModuleReference(f)){let h=f.getExpression(),x;if(h&&m.isStringLiteral(h))x=h.getLiteralText();else if(h){let b=h.getText();x=typeof b=="string"?b.replace(/^['"]|['"]$/g,""):void 0}if(x){let R=u.getNameNode()?.getText(),K={moduleSpecifier:x,isTypeOnly:!1,namedImports:[]};R&&(K.defaultImport=R,k(R,u)),d.push(K)}}}catch{}(m.isExportDeclaration(u)||m.isExportAssignment(u))&&hn(u,g),yn(u,g,k,S);let v=D(u),N=v?M(u):null;if(v){let f=e(u);s.push({nodeId:f,node:u});let h=we(u,ie.ExportKeyword)||w?.isExported||!1,x=v?u.getNameNode?.()?.getText?.()??null:null,b=N??(v?Ne(u)??x:null);N?k(N,u):b&&k(b,u);let R=yt(u),K=fn(u),A=Ce(u);ve(A,{source:"ts-node-collector",file:r.getFilePath(),name:b??null}),i.push({nodeId:f,nodeName:b??null,containerId:P,containerKind:l,containerRawKind:w?.rawKind??null,containerRawKindSource:w?.rawKindSource??null,containerName:C,isExported:h,kind:A.kind,rawKind:A.rawKind,rawKindSource:A.rawKindSource,semanticKind:A.semanticKind??null,start:R.start,end:R.end,paramCount:K,metadata:null})}if(m.isCallExpression(u)||m.isNewExpression(u)){let f=u.getExpression(),h=null,x,b;try{if(b=mn(f),m.isIdentifier(f))h=f.getText();else if(m.isPropertyAccessExpression(f)){h=f.getName();let A=f.getExpression();m.isIdentifier(A)&&(x=A.getText())}}catch{}let R="";try{R=f.getText()}catch{}let K=yt(u);if(o.push({name:h,kind:m.isNewExpression(u)?"new":"call",containerId:P,containerKind:l,containerName:C,expression:R,objectName:x,symbol:b,start:K.start,end:K.end}),m.isCallExpression(u))try{if(m.isIdentifier(f)&&f.getText()==="require"){let _=u.getArguments()[0],j;if(_&&(m.isStringLiteral(_)||m.isNoSubstitutionTemplateLiteral(_)))try{j=_.getLiteralText()}catch{let O=_.getText();j=typeof O=="string"?O.replace(/^['"]|['"]$/g,""):void 0}if(j){let O={moduleSpecifier:j,isTypeOnly:!1,namedImports:[]},z=u.getParent();if(z&&m.isVariableDeclaration(z)){let V=z.getNameNode();try{if(m.isIdentifier(V)){let U=V.getText();U&&(O.defaultImport=U,k(U,z))}}catch{}}d.push(O)}}else if(f?.getKind?.()===ie.ImportKeyword){let _=u.getArguments()[0],j;if(_&&(m.isStringLiteral(_)||m.isNoSubstitutionTemplateLiteral(_)))try{j=_.getLiteralText()}catch{let O=_.getText();j=typeof O=="string"?O.replace(/^['"]|['"]$/g,""):void 0}j&&d.push({moduleSpecifier:j,isTypeOnly:!1,namedImports:[]})}}catch{}}if(m.isCallExpression(u)){let f=u.getExpression();try{if(m.isIdentifier(f)&&f.getText()==="require"){let h=u.getParent();if(!(h&&m.isExternalModuleReference(h))){let b=u.getArguments()[0],R;if(b&&(m.isStringLiteral(b)||m.isNoSubstitutionTemplateLiteral(b)))try{R=b.getLiteralText()}catch{R=b.getText().replace(/^['"]|['"]$/g,"")}if(R){let K={moduleSpecifier:R,isTypeOnly:!1,namedImports:[]};if(h&&m.isVariableDeclaration(h)){let A=h.getNameNode();try{if(m.isIdentifier(A)){let _=A.getText();_&&(K.defaultImport=_,k(_,h))}}catch{}}d.push(K)}}}else if(f?.getKind?.()===ie.ImportKeyword){let x=u.getArguments()[0],b;if(x&&(m.isStringLiteral(x)||m.isNoSubstitutionTemplateLiteral(x)))try{b=x.getLiteralText()}catch{b=x.getText().replace(/^['"]|['"]$/g,"")}b&&d.push({moduleSpecifier:b,isTypeOnly:!1,namedImports:[]})}}catch{}}let T=!1;if(E(u)){let f=S(u)??e(u),h=ht(u);p.push({node:u,id:f,kind:h.kind,rawKind:h.rawKind,rawKindSource:h.rawKindSource,name:N??C,isExported:we(u,ie.ExportKeyword)||w?.isExported||!1}),T=!0}u.forEachChild(Q),T&&p.pop()};if(r.forEachChild(Q),n?.includeComments===!0||process.env.AST_INDEX_COMMENTS==="1")try{let u=r.getFullText(),w=q.createScanner(q.ScriptTarget.Latest,!1,q.LanguageVariant.Standard,u),P=new Set;for(let l=w.scan();l!==q.SyntaxKind.EndOfFileToken;l=w.scan()){if(l!==q.SyntaxKind.SingleLineCommentTrivia&&l!==q.SyntaxKind.MultiLineCommentTrivia)continue;let C=w.getTokenPos(),v=w.getTextPos(),N=`${C}-${v}`;if(P.has(N)||(P.add(N),t.has(N)))continue;t.add(N);let T=u.substring(C,v),f=pt(l,T),x=e({getKindName:()=>f.name,getKind:()=>f.kind,getPos:()=>C,getEnd:()=>v,getStart:()=>C,getFullStart:()=>C,getText:()=>T,getSourceFile:()=>r,getParent:()=>r,__isComment:!0,__commentPosition:"standalone",__attachedTo:null},"COM");i.push({nodeId:x,nodeName:T.substring(0,100),containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:f.name,rawKind:f.name,rawKindSource:"ts-morph",semanticKind:null,start:C,end:v,paramCount:null,metadata:null})}}catch{}return{nodes:i,symbolCandidateNodes:s,references:o,declaredNames:a,localDeclarations:c,imports:d,exports:pn(g)}}function St(r){let e;try{let n=r.getStart?.(!1);typeof n=="number"&&Number.isFinite(n)&&(e=n)}catch{}if(e===void 0)try{let n=r.getStart?.();typeof n=="number"&&Number.isFinite(n)&&(e=n)}catch{}if(e===void 0)try{let n=r.getFullStart?.();typeof n=="number"&&Number.isFinite(n)&&(e=n)}catch{}e===void 0&&(e=0);let t;try{let n=r.getEnd?.();typeof n=="number"&&Number.isFinite(n)&&(t=n)}catch{}if(t===void 0)try{let n=r.getStart?.();typeof n=="number"&&Number.isFinite(n)&&(t=n)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}var Sn=100;function Cn(r,e,t,n){let{start:i,end:s}=St(e),o=Ce(e);ve(o,{source:"ts-node-id",file:r,kind:o.kind});let a=n||G.getAbbrev(o.kind,t);return`${r}#${i}-${s}:${a}`}function vn(r,e){return Be.relative(r,e).replace(/\\/g,"/")}function Ct(r,e){if(!r)return null;let t=r;try{let g=r.getAliasedSymbol();g&&(t=g)}catch{}let n=[];try{n=t.getDeclarations()??[]}catch{n=[]}if(!n.length)return null;let s=n.slice().sort((g,p)=>{let S=g.getSourceFile().getFilePath(),k=p.getSourceFile().getFilePath();if(S!==k)return S.localeCompare(k);let D=g.getStart(!1),E=p.getStart(!1);return D!==E?D-E:g.getEnd()-p.getEnd()})[0],o=vn(e,s.getSourceFile().getFilePath()),a=s.getStart(!1),c=s.getEnd(),d="";try{d=t.getEscapedName()}catch{try{d=t.getName()}catch{d=""}}return`${o}#${a}-${c}:${d}`}function Nn(r){try{return J.isVariableDeclaration(r)||J.isEnumMember(r)?r.getNameNode().getSymbol()??r.getSymbol():r.getSymbol()}catch{return}}function wn(r,e){let t=r.getDescendantAtPos(e);if(!t)return;let n=t;if(!J.isCallExpression(n)&&!J.isNewExpression(n)&&(n=t.getFirstAncestor(s=>J.isCallExpression(s)||J.isNewExpression(s))??void 0),!n||!J.isCallExpression(n)&&!J.isNewExpression(n))return;let i=n.getExpression();try{return J.isIdentifier(i)?i.getSymbol():J.isPropertyAccessExpression(i)?i.getNameNode().getSymbol()??i.getSymbol():i.getSymbol()}catch{return}}async function En(r){let{sf:e,fileRel:t,content:n,preDeleted:i,meta:s,projectRoot:o,lang:a}=r,d=xt(e,(f,h)=>Cn(t,f,a,h),new Set,{includeComments:!1}),g=new Map;for(let{nodeId:f,node:h}of d.symbolCandidateNodes){let x=Ct(Nn(h),o);x&&(g.has(f)||g.set(f,x))}let p=[],S=new Map,k=d.exports.filter(f=>f.kind!=="reexport"),D=d.exports.filter(f=>f.kind==="reexport");for(let f of k)if(f.kind==="local"){let h=f.isDefault?"default":f.name;if(!h||S.has(h))continue;let x=f.nodeId;p.push([t,h,x,0,null,null,f.isDefault?"default":"named"]),S.set(h,x)}else if(f.kind==="alias"){let h=f.exported;if(!h||S.has(h))continue;p.push([t,h,null,0,null,f.local,"alias"]),S.set(h,"alias")}for(let f of D){let h=f.moduleSpecifier;if(!h)continue;let x=h;if(f.isNamespace){let b=f.alias||"*";if(S.has(b))continue;p.push([t,b,null,1,x,f.name||b,"reexport_star"]),S.set(b,"reexport")}else{let b=f.alias||f.name;if(!b||S.has(b))continue;p.push([t,b,null,1,x,f.name||b,"reexport_named"]),S.set(b,"reexport")}}let E=[],M=typeof n=="string"?n:null;if(M==null)try{let f=e.getFullText();M=typeof f=="string"?f:null}catch{M=null}for(let f of d.nodes){let{nodeId:h,nodeName:x,containerKind:b,containerRawKind:R,containerRawKindSource:K,isExported:A,kind:_,rawKind:j,rawKindSource:O,semanticKind:z,start:V,end:U,paramCount:Oe,metadata:X}=f,Me=X&&Object.keys(X).length?JSON.stringify(X):null,ln=g.get(h)??null;E.push([h,x??null,_,j??_,O??null,z??null,V,U,A?1:0,b??"module",R??b??"module",K??null,Oe,null,null,ln,Me])}let Q=[];for(let f of d.references){let{name:h,kind:x,containerId:b,containerName:R,expression:K,objectName:A,start:_,end:j}=f,O=null,z=null,V=Ct(f.symbol??wn(e,_),o),U=h?d.localDeclarations.get(h):void 0;U&&(O=U,z=t,V||(V=g.get(U)??null));let Oe=Se({sourceFile:t,sourceStart:_,sourceEnd:j,refKind:x,refName:h,targetFile:z,targetNodeId:O}),X={};K&&(X.expression=K),A&&(X.objectName=A),R&&(X.containerName=R);let Me=Object.keys(X).length?JSON.stringify(X):null;Q.push([Oe,t,b,h,x,_,j,O,z,O?"resolved":"unresolved",A??null,null,null,V,Me])}let u=[],w=[];for(let f of d.imports){let h=f.moduleSpecifier??null;u.push([t,h,f.isTypeOnly?1:0]),f.defaultImport&&w.push([t,h,"default",f.defaultImport,"default",f.isTypeOnly?1:0]),f.namespaceImport&&w.push([t,h,"namespace",f.namespaceImport,"*",f.isTypeOnly?1:0]);for(let x of f.namedImports){let b=x.alias||x.name;w.push([t,h,"named",b,x.name,f.isTypeOnly?1:0])}}let P=Be.join(o,t),l=s?.size,C=s?.mtime;if(l===void 0||C===void 0)try{let f=bn.statSync(P);l=f.size,C=Math.floor(f.mtimeMs)}catch{}let v=new Date().toISOString(),N=[t,C??null,l??null,"completed",v],T=null;if(typeof M=="string")T={blobOid:t,content:M};else try{let f=e.getFullText?.();typeof f=="string"&&(T={blobOid:t,content:f})}catch(f){console.log(`[TypescriptIndexer] Failed to compute FTS payload for ${t}:`,f?.message??f)}return{payload:{lang:a,fileRel:t,preDeleted:i,exportRows:p,nodeRows:E,referenceRows:Q,importRows:u,importBindingRows:w,fileRow:N,fts:T},fileSize:l,mtime:C}}var Le=class{constructor(e,t){this.project=null;this.filesProcessed=0;this.projectRoot=e,this.lang=t}getProject(){return this.project||(this.project=new xn({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0})),this.project}disposeProject(){if(this.project){try{let e=this.project.getLanguageService().compilerObject;typeof e?.dispose=="function"&&e.dispose()}catch{}this.project=null}}async process(e){let t=this.getProject(),n;try{let i=t.createSourceFile(Be.join(this.projectRoot,e.relPath),e.content,{overwrite:!0});n=await En({sf:i,fileRel:e.relPath,content:e.content,preDeleted:!!e.preDeleted,meta:e.meta,projectRoot:this.projectRoot,lang:e.lang})}catch(i){this.disposeProject(),this.filesProcessed=0;let s=i?.message||String(i);throw new Error(`TypeScript parser failed for ${e.relPath}: ${s}`)}return this.filesProcessed++,this.filesProcessed>=Sn&&(this.disposeProject(),this.filesProcessed=0),{payload:n.payload,fileSize:n.fileSize,mtime:n.mtime}}};function _n(r){return r==="ts"?[".ts",".tsx",".mts",".cts"]:r==="js"?[".js",".jsx",".mjs",".cjs"]:[]}function $e(r){return{id:r,extensions:_n(r),indexingMode:"worker",createIndexer:e=>new Le(e,r)}}import _e from"fs";import H from"path";import{spawn as An,spawnSync as Et}from"child_process";import Pn from"fs";var se=class{constructor(e=5e3){this.maxEntries=e;this.cache=new Map}get(e,t){let n=this.cache.get(e);if(!n)return null;let i=t?.mtime??null,s=t?.size??null;return i!=null&&s!=null&&n.mtime===i&&n.size===s?n.result:null}set(e,t,n){let i=t?.mtime??null,s=t?.size??null;this.cache.set(e,{mtime:i,size:s,result:n}),this.cache.size>this.maxEntries&&this.cache.clear()}};var ze=class{constructor(e,t,n,i){this.projectRoot=e;this.lang=t;this.parse=n;this.exportKind=i;this.cache=new se}async process(e){let t=e.meta?.mtime,n=e.meta?.size;if(t==null||n==null)try{let o=Pn.statSync(e.absPath);t=Math.floor(o.mtimeMs),n=o.size}catch{}let i=this.cache.get(e.absPath,{mtime:t,size:n});if(i)return pe({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:n},preDeleted:e.preDeleted,parsed:i,resolveNodeId:vt(e.relPath,i,this.lang),exportKind:this.exportKind??"cli"});let s=null;try{s=await this.parse({absPath:e.absPath,relPath:e.relPath,content:e.content,meta:{mtime:t,size:n},projectRoot:this.projectRoot,lang:this.lang})}catch(o){try{console.log(`[CliContract:${this.lang}] parse threw for ${e.relPath}: ${o?.message||String(o)}`)}catch{}return de(this.lang,e.relPath,{mtime:t,size:n})}return!s||s.error?de(this.lang,e.relPath,{mtime:t,size:n}):(this.cache.set(e.absPath,{mtime:t,size:n},s),pe({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:n},preDeleted:e.preDeleted,parsed:s,resolveNodeId:vt(e.relPath,s,this.lang),exportKind:this.exportKind??"cli"}))}};function vt(r,e,t){let n=new Map;for(let i of e.nodes??[]){if(!i.name||n.has(i.name))continue;let s=`${r}#${i.start}-${i.end}:${G.getAbbrev(i.kind,t)}`;n.set(i.name,s)}return i=>n.get(i)??null}function W(r){return{id:r.id,extensions:r.extensions,indexingMode:"worker",createIndexer:e=>new ze(e,r.id,r.parse,r.exportKind),resolveSpan:r.resolve?async(e,t,n)=>r.resolve({projectRoot:e,absPath:t,nodePath:n,lang:r.id}):void 0}}import Rn from"fs";import Ee from"path";var qe=null;function kn(r){for(let e of r)if(Rn.existsSync(e))return e;return null}function B(r){let e=qe?.toolsRoot??process.env.PANDO_TOOLS_ROOT,t=qe?.runtimeRoot??process.env.PANDO_RUNTIME_ROOT,n=qe?.resourcesRoot??process.env.PANDO_RESOURCES_ROOT,i=[e?Ee.join(e,r):null,t?Ee.join(t,"tools",r):null,n?Ee.join(n,"tools",r):null,Ee.resolve(process.cwd(),"tools",r)].filter(s=>!!s);return kn(i)}function $(...r){try{let e=r.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
2
+ `)}catch{}}var In=Number(process.env.PANDO_PYTHON_WORKER_PARSE_TIMEOUT_MS||18e4),Dn=Number(process.env.PANDO_PYTHON_WORKER_RESOLVE_TIMEOUT_MS||6e4),le=class extends Error{constructor(t,n){super(t);this.fatal=n;this.name="PythonWorkerRequestError"}},Pe=class{constructor(e,t){this.interpreter=e;this.scriptPath=t;this.buffer=Buffer.alloc(0);this.pending=new Map;this.requestQueue=Promise.resolve();this.seq=1;this.closed=!1;if(this.proc=An(this.interpreter,["-u",this.scriptPath],{stdio:["pipe","pipe","pipe"]}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw new Error("python worker stdio unavailable");this.proc.stdout.on("data",n=>this.onData(n)),this.proc.stderr.on("data",n=>{$(`[PythonWorker] ${n.toString("utf8").trim()}`)}),this.proc.stdin.on("error",n=>this.handleError(n)),this.proc.on("error",n=>this.handleError(n)),this.proc.on("exit",n=>this.handleError(new Error(`python worker exited with code ${n}`))),this.ready=this.ping()}handleError(e){if(!this.closed){this.closed=!0;for(let[,t]of this.pending)t.timeout&&clearTimeout(t.timeout),t.summary&&$("[PythonCliAdapter] worker error",{interpreter:this.interpreter,error:e.message,...t.summary}),t.reject(e);this.pending.clear();try{this.proc.stdin?.end()}catch{}try{this.proc.kill()}catch{}}}onData(e){for(this.buffer=Buffer.concat([this.buffer,e]);this.buffer.length>=4;){let t=this.buffer.readUInt32BE(0);if(this.buffer.length<4+t)return;let n=this.buffer.slice(4,4+t);this.buffer=this.buffer.slice(4+t);let i=null;try{i=JSON.parse(n.toString("utf8"))}catch{continue}let s=this.pending.get(i.id);s&&(this.pending.delete(i.id),s.timeout&&clearTimeout(s.timeout),i.ok?s.resolve(i):s.reject(new le(i.error||"python worker error",!1)))}}sendMessage(e){if(this.closed)throw new Error("python worker is closed");let t=Buffer.from(JSON.stringify(e),"utf8"),n=Buffer.alloc(4);n.writeUInt32BE(t.length,0),this.proc.stdin.write(n),this.proc.stdin.write(t)}async requestRaw(e,t,n=1e4){let i=this.seq++,s={id:i,op:e,...t},o={op:e,id:i};return typeof t?.path=="string"&&(o.path=t.path),typeof t?.nodePath=="string"&&(o.nodePath=t.nodePath),typeof t?.content_b64=="string"&&(o.contentBytes=t.content_b64.length),new Promise((a,c)=>{let d=setTimeout(()=>{this.pending.delete(i);let g=new le(`python worker timeout (${e})`,!0);$("[PythonCliAdapter] worker timeout",{op:e,id:i,timeoutMs:n,pending:this.pending.size,interpreter:this.interpreter,...o}),c(g),this.handleError(g)},n);this.pending.set(i,{resolve:a,reject:c,timeout:d,summary:o}),this.pending.size%200===0&&$("[PythonCliAdapter] worker pending",{op:e,pending:this.pending.size,interpreter:this.interpreter});try{this.sendMessage(s)}catch(g){clearTimeout(d),this.pending.delete(i),c(g)}})}async enqueueRequest(e){let t=this.requestQueue.catch(()=>{}),n,i=new Promise(s=>{n=s});this.requestQueue=t.then(()=>i),await t;try{return await e()}finally{n()}}async request(e,t,n=1e4){await this.ready;let i=Date.now();return this.enqueueRequest(async()=>{let s=Date.now()-i,o=Date.now();s>2e3&&$("[PythonCliAdapter] worker queued",{op:e,queueMs:s,interpreter:this.interpreter,path:t?.path});let a=await this.requestRaw(e,t,n),c=Date.now()-o;return c>2e3&&$("[PythonCliAdapter] worker slow",{op:e,ms:c,queueMs:s,pending:this.pending.size,interpreter:this.interpreter,path:t?.path}),a})}async ping(){await this.requestRaw("ping",{},5e3)}async parse(e){let t=Buffer.from(e.content,"utf8").toString("base64"),n=await this.request("parse",{path:e.path,content_b64:t,encoding:e.encoding},In);return n.nodes?n:null}async resolve(e){let t=Buffer.from(e.content,"utf8").toString("base64"),n=await this.request("resolve",{path:e.path,nodePath:e.nodePath,content_b64:t,encoding:e.encoding},Dn);return typeof n.start=="number"&&typeof n.end=="number"?n:null}close(){if(this.closed)return;this.closed=!0;for(let[,t]of this.pending)t.timeout&&clearTimeout(t.timeout),t.reject(new Error("python worker client closed"));this.pending.clear();let e=this.proc;try{e.stdin?.end()}catch{}try{e.kill()}catch{}}},Tn=`
3
+ import ast, json, sys, os
4
+
5
+ path = sys.argv[1]
6
+ with open(path, 'r', encoding='utf-8', errors='ignore') as f:
7
+ src = f.read()
8
+
9
+ # line start offsets
10
+ line_starts = [0]
11
+ for line in src.splitlines(True):
12
+ line_starts.append(line_starts[-1] + len(line))
13
+
14
+ def offset(lineno, col):
15
+ if lineno is None:
16
+ return 0
17
+ if lineno < 1:
18
+ lineno = 1
19
+ if lineno >= len(line_starts):
20
+ return line_starts[-1]
21
+ return line_starts[lineno - 1] + (col or 0)
22
+
23
+ def node_span(n):
24
+ start = offset(getattr(n, 'lineno', None), getattr(n, 'col_offset', 0))
25
+ end = offset(getattr(n, 'end_lineno', getattr(n, 'lineno', None)), getattr(n, 'end_col_offset', 0))
26
+ if end < start:
27
+ end = start
28
+ return start, end
29
+
30
+ nodes = []
31
+ imports = []
32
+ bindings = []
33
+ references = []
34
+ class_names = set()
35
+ module_public = set()
36
+ all_exports = None
37
+
38
+ module_name = os.path.splitext(os.path.basename(path))[0] if path else "__main__"
39
+ scope_stack = [module_name]
40
+ nodes.append({
41
+ 'name': module_name,
42
+ 'kind': 'Namespace',
43
+ 'rawKind': 'Module',
44
+ 'rawKindSource': 'python-ast',
45
+ 'semanticKind': 'namespace',
46
+ 'start': 0,
47
+ 'end': len(src),
48
+ 'isExported': 1,
49
+ 'containerKind': None,
50
+ 'containerRawKind': None,
51
+ 'containerRawKindSource': None,
52
+ 'paramCount': None,
53
+ 'qualifiedName': module_name,
54
+ 'scopeChain': [module_name],
55
+ 'metadata': { 'path': path },
56
+ })
57
+
58
+ def decorator_names(node_list):
59
+ out = []
60
+ for d in node_list or []:
61
+ try:
62
+ if isinstance(d, ast.Name):
63
+ out.append(d.id)
64
+ elif isinstance(d, ast.Attribute):
65
+ out.append(d.attr)
66
+ elif hasattr(ast, 'Call') and isinstance(d, ast.Call):
67
+ if isinstance(d.func, ast.Name):
68
+ out.append(d.func.id)
69
+ elif isinstance(d.func, ast.Attribute):
70
+ out.append(d.func.attr)
71
+ except Exception:
72
+ pass
73
+ return out
74
+
75
+ def annotation_text(n):
76
+ try:
77
+ return ast.get_source_segment(src, n)
78
+ except Exception:
79
+ return None
80
+
81
+ def raw_kind(n):
82
+ try:
83
+ return n.__class__.__name__
84
+ except Exception:
85
+ return None
86
+
87
+ def base_name(txt):
88
+ try:
89
+ return txt.split('.')[-1]
90
+ except Exception:
91
+ return txt
92
+
93
+ ENUM_BASES = set(['Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag'])
94
+ META_BASES = set(['type', 'ABCMeta', 'EnumMeta'])
95
+
96
+ def is_enum_base(txt):
97
+ if not txt:
98
+ return False
99
+ name = base_name(txt)
100
+ return name in ENUM_BASES
101
+
102
+ def is_metaclass_base(txt):
103
+ if not txt:
104
+ return False
105
+ name = base_name(txt)
106
+ return name in META_BASES
107
+
108
+ class Visitor(ast.NodeVisitor):
109
+ def __init__(self):
110
+ self.class_name = None
111
+ self.class_is_enum = False
112
+ self.class_stack = []
113
+ self.func_name = None
114
+ self.func_stack = []
115
+ self.scope_stack = list(scope_stack)
116
+
117
+ def visit_ClassDef(self, n):
118
+ start, end = node_span(n)
119
+ name = n.name
120
+ class_names.add(name)
121
+ deco = decorator_names(getattr(n, 'decorator_list', None))
122
+ bases = []
123
+ is_enum = False
124
+ is_meta = False
125
+ meta_value = None
126
+ try:
127
+ for kw in getattr(n, 'keywords', []) or []:
128
+ if getattr(kw, 'arg', None) == 'metaclass':
129
+ meta_value = annotation_text(kw.value)
130
+ except Exception:
131
+ meta_value = None
132
+ try:
133
+ for b in getattr(n, 'bases', []) or []:
134
+ txt = annotation_text(b)
135
+ if txt:
136
+ bases.append(txt)
137
+ if is_enum_base(txt):
138
+ is_enum = True
139
+ if is_metaclass_base(txt):
140
+ is_meta = True
141
+ except Exception:
142
+ pass
143
+ is_exported = 0 if name.startswith('_') else 1
144
+ if is_exported:
145
+ module_public.add(name)
146
+ metadata = {
147
+ 'decorators': deco,
148
+ 'extends': bases if bases else None,
149
+ 'visibility': 'private' if name.startswith('_') else 'public'
150
+ }
151
+ if meta_value:
152
+ metadata['metaclass'] = meta_value
153
+ if is_meta:
154
+ metadata['isMetaclass'] = True
155
+ if is_enum:
156
+ metadata['isEnum'] = True
157
+ scope_chain = self.scope_stack + [name]
158
+ nodes.append({
159
+ 'name': name,
160
+ 'kind': 'Enum' if is_enum else 'Class',
161
+ 'rawKind': raw_kind(n),
162
+ 'rawKindSource': 'python-ast',
163
+ 'semanticKind': 'enum' if is_enum else 'class',
164
+ 'start': start,
165
+ 'end': end,
166
+ 'isExported': is_exported,
167
+ 'containerKind': None,
168
+ 'containerRawKind': None,
169
+ 'containerRawKindSource': None,
170
+ 'paramCount': None,
171
+ 'qualifiedName': '.'.join(scope_chain),
172
+ 'scopeChain': scope_chain,
173
+ 'metadata': metadata,
174
+ })
175
+ prev = self.class_name
176
+ prev_enum = self.class_is_enum
177
+ self.class_stack.append({ 'name': name, 'is_enum': is_enum })
178
+ self.class_name = name
179
+ self.class_is_enum = is_enum
180
+ self.scope_stack.append(name)
181
+ self.generic_visit(n)
182
+ self.scope_stack.pop()
183
+ self.class_stack.pop()
184
+ self.class_name = prev
185
+ self.class_is_enum = prev_enum
186
+
187
+ def visit_FunctionDef(self, n):
188
+ start, end = node_span(n)
189
+ name = n.name
190
+ param_count = len(getattr(n, 'args', {}).args) if hasattr(n, 'args') else None
191
+ is_async = isinstance(n, ast.AsyncFunctionDef)
192
+ deco = decorator_names(getattr(n, 'decorator_list', None))
193
+ ret = annotation_text(getattr(n, 'returns', None)) if hasattr(n, 'returns') else None
194
+ is_static = 'staticmethod' in deco
195
+ is_abstract = 'abstractmethod' in deco
196
+ is_readonly = 'property' in deco
197
+ visibility = 'private' if name.startswith('_') else 'public'
198
+ scope_chain = self.scope_stack + [name]
199
+ if self.class_name:
200
+ sem_kind = 'property' if is_readonly else 'method'
201
+ nodes.append({
202
+ 'name': name,
203
+ 'kind': 'Method',
204
+ 'rawKind': raw_kind(n),
205
+ 'rawKindSource': 'python-ast',
206
+ 'semanticKind': sem_kind,
207
+ 'start': start,
208
+ 'end': end,
209
+ 'isExported': 0,
210
+ 'containerKind': 'Class',
211
+ 'containerRawKind': 'ClassDef',
212
+ 'containerRawKindSource': 'python-ast',
213
+ 'paramCount': param_count,
214
+ 'qualifiedName': '.'.join(scope_chain),
215
+ 'scopeChain': scope_chain,
216
+ 'metadata': { 'isAsync': is_async, 'containerName': self.class_name, 'decorators': deco, 'returnType': ret, 'isStatic': is_static, 'isAbstract': is_abstract, 'isReadonly': is_readonly, 'visibility': visibility },
217
+ })
218
+ else:
219
+ is_exported = 0 if name.startswith('_') else 1
220
+ if is_exported:
221
+ module_public.add(name)
222
+ nodes.append({
223
+ 'name': name,
224
+ 'kind': 'Function',
225
+ 'rawKind': raw_kind(n),
226
+ 'rawKindSource': 'python-ast',
227
+ 'semanticKind': 'function',
228
+ 'start': start,
229
+ 'end': end,
230
+ 'isExported': is_exported,
231
+ 'containerKind': None,
232
+ 'containerRawKind': None,
233
+ 'containerRawKindSource': None,
234
+ 'paramCount': param_count,
235
+ 'qualifiedName': '.'.join(scope_chain),
236
+ 'scopeChain': scope_chain,
237
+ 'metadata': { 'isAsync': is_async, 'decorators': deco, 'returnType': ret, 'isAbstract': is_abstract, 'visibility': visibility },
238
+ })
239
+ prev = self.func_name
240
+ self.func_name = name
241
+ self.func_stack.append(name)
242
+ self.scope_stack.append(name)
243
+ self.generic_visit(n)
244
+ self.scope_stack.pop()
245
+ self.func_stack.pop()
246
+ self.func_name = prev
247
+
248
+ def visit_AsyncFunctionDef(self, n):
249
+ self.visit_FunctionDef(n)
250
+
251
+ def visit_Import(self, n):
252
+ for alias in n.names:
253
+ module = alias.name
254
+ imports.append({ 'module': module, 'isTypeOnly': 0 })
255
+ local = alias.asname or alias.name
256
+ if local and not local.startswith('_'):
257
+ module_public.add(local)
258
+ bindings.append({
259
+ 'module': module,
260
+ 'localName': local,
261
+ 'importedName': alias.name,
262
+ 'kind': 'named',
263
+ 'isTypeOnly': 0,
264
+ })
265
+
266
+ def visit_ImportFrom(self, n):
267
+ module = n.module
268
+ imports.append({ 'module': module, 'isTypeOnly': 0 })
269
+ for alias in n.names:
270
+ if alias.name == '*':
271
+ bindings.append({
272
+ 'module': module,
273
+ 'localName': alias.asname or '*',
274
+ 'importedName': '*',
275
+ 'kind': 'namespace',
276
+ 'isTypeOnly': 0,
277
+ })
278
+ else:
279
+ bindings.append({
280
+ 'module': module,
281
+ 'localName': alias.asname or alias.name,
282
+ 'importedName': alias.name,
283
+ 'kind': 'named',
284
+ 'isTypeOnly': 0,
285
+ })
286
+ local_name = alias.asname or alias.name
287
+ if local_name and not local_name.startswith('_'):
288
+ module_public.add(local_name)
289
+
290
+ def visit_Assign(self, n):
291
+ # module-level or class-level names
292
+ global all_exports
293
+ targets = getattr(n, 'targets', [])
294
+ for t in targets:
295
+ if isinstance(t, ast.Name):
296
+ start, end = node_span(t)
297
+ name = t.id
298
+ is_exported = 0 if name.startswith('_') else 1
299
+ scope_chain = self.scope_stack + [name]
300
+ if self.class_name:
301
+ if self.class_is_enum:
302
+ nodes.append({
303
+ 'name': name,
304
+ 'kind': 'EnumMember',
305
+ 'rawKind': raw_kind(t),
306
+ 'rawKindSource': 'python-ast',
307
+ 'semanticKind': 'enum',
308
+ 'start': start,
309
+ 'end': end,
310
+ 'isExported': 0,
311
+ 'containerKind': 'Enum',
312
+ 'containerRawKind': 'ClassDef',
313
+ 'containerRawKindSource': 'python-ast',
314
+ 'paramCount': None,
315
+ 'qualifiedName': '.'.join(scope_chain),
316
+ 'scopeChain': scope_chain,
317
+ 'metadata': { 'containerName': self.class_name, 'visibility': 'private' if name.startswith('_') else 'public' },
318
+ })
319
+ continue
320
+ nodes.append({
321
+ 'name': name,
322
+ 'kind': 'Field',
323
+ 'rawKind': raw_kind(t),
324
+ 'rawKindSource': 'python-ast',
325
+ 'semanticKind': 'field',
326
+ 'start': start,
327
+ 'end': end,
328
+ 'isExported': 0,
329
+ 'containerKind': 'Class',
330
+ 'containerRawKind': 'ClassDef',
331
+ 'containerRawKindSource': 'python-ast',
332
+ 'paramCount': None,
333
+ 'qualifiedName': '.'.join(scope_chain),
334
+ 'scopeChain': scope_chain,
335
+ 'metadata': { 'containerName': self.class_name, 'visibility': 'private' if name.startswith('_') else 'public' },
336
+ })
337
+ else:
338
+ if is_exported:
339
+ module_public.add(name)
340
+ nodes.append({
341
+ 'name': name,
342
+ 'kind': 'Variable',
343
+ 'rawKind': raw_kind(t),
344
+ 'rawKindSource': 'python-ast',
345
+ 'semanticKind': 'variable',
346
+ 'start': start,
347
+ 'end': end,
348
+ 'isExported': is_exported,
349
+ 'containerKind': None,
350
+ 'containerRawKind': None,
351
+ 'containerRawKindSource': None,
352
+ 'paramCount': None,
353
+ 'qualifiedName': '.'.join(scope_chain),
354
+ 'scopeChain': scope_chain,
355
+ 'metadata': { 'visibility': 'private' if name.startswith('_') else 'public' },
356
+ })
357
+ if (not self.class_name) and name == '__all__':
358
+ try:
359
+ if isinstance(n.value, (ast.List, ast.Tuple)):
360
+ all_list = []
361
+ for elt in n.value.elts:
362
+ if isinstance(elt, ast.Str):
363
+ all_list.append(elt.s)
364
+ elif hasattr(ast, 'Constant') and isinstance(elt, ast.Constant) and isinstance(elt.value, str):
365
+ all_list.append(elt.value)
366
+ if all_list:
367
+ all_exports = all_list
368
+ except Exception:
369
+ pass
370
+ self.generic_visit(n)
371
+
372
+ def visit_Call(self, n):
373
+ try:
374
+ func = n.func
375
+ call_name = None
376
+ object_name = None
377
+ expr_text = None
378
+ if isinstance(func, ast.Name):
379
+ call_name = func.id
380
+ elif isinstance(func, ast.Attribute):
381
+ call_name = func.attr
382
+ if isinstance(func.value, ast.Name):
383
+ object_name = func.value.id
384
+ try:
385
+ expr_text = ast.get_source_segment(src, func)
386
+ except Exception:
387
+ expr_text = None
388
+ start, end = node_span(n)
389
+ kind = 'new' if call_name in class_names else 'call'
390
+ container_name = self.class_name or self.func_name
391
+ container_kind = 'Class' if self.class_name else ('Function' if self.func_name else None)
392
+ try:
393
+ arity = len(getattr(n, 'args', []) or []) + len(getattr(n, 'keywords', []) or [])
394
+ except Exception:
395
+ arity = 0
396
+ container_qualified_name = '.'.join(self.scope_stack) if self.scope_stack else None
397
+ references.append({
398
+ 'name': call_name,
399
+ 'kind': kind,
400
+ 'start': start,
401
+ 'end': end,
402
+ 'expression': expr_text,
403
+ 'objectName': object_name,
404
+ 'containerName': container_name,
405
+ 'containerKind': container_kind,
406
+ 'receiverName': object_name,
407
+ 'arity': arity,
408
+ 'containerQualifiedName': container_qualified_name,
409
+ })
410
+ except Exception:
411
+ pass
412
+ self.generic_visit(n)
413
+
414
+ try:
415
+ tree = ast.parse(src, filename=path)
416
+ Visitor().visit(tree)
417
+ out = { 'nodes': nodes, 'imports': imports, 'importBindings': bindings, 'references': references, 'modulePublic': sorted(list(module_public)), 'explicitExports': all_exports }
418
+ print(json.dumps(out))
419
+ except Exception as e:
420
+ print(json.dumps({ 'error': str(e) }))
421
+ sys.exit(2)
422
+ `,Kn=`
423
+ import ast, json, sys
424
+
425
+ path = sys.argv[1]
426
+ node_path = sys.argv[2]
427
+ with open(path, 'r', encoding='utf-8', errors='ignore') as f:
428
+ src = f.read()
429
+
430
+ # line start offsets
431
+ line_starts = [0]
432
+ for line in src.splitlines(True):
433
+ line_starts.append(line_starts[-1] + len(line))
434
+
435
+ def offset(lineno, col):
436
+ if lineno is None:
437
+ return 0
438
+ if lineno < 1:
439
+ lineno = 1
440
+ if lineno >= len(line_starts):
441
+ return line_starts[-1]
442
+ return line_starts[lineno - 1] + (col or 0)
443
+
444
+ def node_span(n):
445
+ start = offset(getattr(n, 'lineno', None), getattr(n, 'col_offset', 0))
446
+ end = offset(getattr(n, 'end_lineno', getattr(n, 'lineno', None)), getattr(n, 'end_col_offset', 0))
447
+ if end < start:
448
+ end = start
449
+ return start, end
450
+
451
+ def parse_range(node_path):
452
+ clean = node_path
453
+ if clean.startswith('SyntaxError:') or clean.startswith('CompileError:'):
454
+ clean = clean.split(':', 1)[1]
455
+ if '#' in clean:
456
+ clean = clean.split('#', 1)[1]
457
+ if ':' in clean:
458
+ clean = clean.rsplit(':', 1)[0]
459
+ if '-' not in clean:
460
+ return None
461
+ parts = clean.split('-', 1)
462
+ try:
463
+ return int(parts[0]), int(parts[1])
464
+ except Exception:
465
+ return None
466
+
467
+ target = parse_range(node_path)
468
+ if target is None:
469
+ print(json.dumps({ 'error': 'invalid nodePath' }))
470
+ sys.exit(2)
471
+
472
+ target_start, target_end = target
473
+ resolved = None
474
+
475
+ try:
476
+ tree = ast.parse(src, filename=path)
477
+ for n in ast.walk(tree):
478
+ s, e = node_span(n)
479
+ if s == target_start and e == target_end:
480
+ body_start = None
481
+ body_end = None
482
+ if hasattr(n, 'body') and isinstance(n.body, list) and len(n.body) > 0:
483
+ try:
484
+ bs, _ = node_span(n.body[0])
485
+ _, be = node_span(n.body[-1])
486
+ body_start = bs
487
+ body_end = be
488
+ except Exception:
489
+ body_start = None
490
+ body_end = None
491
+ try:
492
+ text = src[s:e]
493
+ except Exception:
494
+ text = None
495
+ resolved = { 'start': s, 'end': e, 'bodyStart': body_start, 'bodyEnd': body_end, 'text': text }
496
+ break
497
+ if not resolved:
498
+ print(json.dumps({ 'error': 'node not found' }))
499
+ sys.exit(2)
500
+ print(json.dumps(resolved))
501
+ except Exception as e:
502
+ print(json.dumps({ 'error': str(e) }))
503
+ sys.exit(2)
504
+ `;function _t(r){let e=H.resolve(r,"tools/python-indexer/pando_python_worker.py");if(_e.existsSync(e))return e;let t=B("python-indexer/pando_python_worker.py");if(t)return t;let n=H.resolve(__dirname,"../../../../../tools/python-indexer/pando_python_worker.py");return _e.existsSync(n)?n:null}var ae=new Map;function oe(r){try{return _e.readFileSync(r,"utf8")}catch{return null}}function ge(r){if(!r)return null;let e=r.match(/(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2])}:null}function On(r){let e=oe(H.join(r,"pyproject.toml"));if(e){let a=e.match(/requires-python\s*=\s*"([^"]+)"/i),c=ge(a?.[1]??null);if(c)return c}let t=oe(H.join(r,"setup.cfg"));if(t){let a=t.match(/python_requires\s*=\s*([\w\d\.<>~=\s]+)/i),c=ge(a?.[1]??null);if(c)return c}let n=oe(H.join(r,"setup.py"));if(n){let a=n.match(/python_requires\s*=\s*['\"]([^'\"]+)['\"]/i),c=ge(a?.[1]??null);if(c)return c}let i=oe(H.join(r,"tox.ini"));if(i){let a=i.match(/envlist\s*=\s*([^\n]+)/i);if(a&&a[1]){let c=a[1].split(/[,\s]+/).filter(Boolean);for(let d of c){let g=d.match(/py(\d)(\d)/i);if(g)return{major:Number(g[1]),minor:Number(g[2])}}}}let s=oe(H.join(r,".python-version"));if(s){let a=ge(s.trim());if(a)return a}let o=oe(H.join(r,"runtime.txt"));if(o){let a=o.match(/python-(\d+\.\d+)/i),c=ge(a?.[1]??null);if(c)return c}return null}function Re(r){return On(r)?.major===2?["python2","python","python3"]:["python3","python","python2"]}async function Mn(r,e,t){let n=_t(r);if(!n)return null;let i=Re(r);for(let s of i){let o=`${s}::${n}`,a=ae.get(o);if(!a)try{a=new Pe(s,n),ae.set(o,a)}catch{continue}try{let c=await a.parse({path:e,content:t,encoding:"utf-8"});if(c)return c}catch(c){let d=c?.message||String(c),g=c instanceof le?c.fatal:/timeout|closed|exited|EPIPE|ENOENT|spawn/i.test(d);$("[PythonCliAdapter] worker parse error",{file:e,interpreter:s,script:n,fatal:g,error:d}),g&&ae.delete(o)}}return null}async function jn(r,e,t,n){let i=_t(r);if(!i)return null;let s=Re(r);for(let o of s){let a=`${o}::${i}`,c=ae.get(a);if(!c)try{c=new Pe(o,i),ae.set(a,c)}catch{continue}try{let d=await c.resolve({path:e,nodePath:n,content:t,encoding:"utf-8"});if(d)return d}catch(d){let g=d?.message||String(d),p=d instanceof le?d.fatal:/timeout|closed|exited|EPIPE|ENOENT|spawn/i.test(g);$("[PythonCliAdapter] worker resolve error",{file:e,interpreter:o,nodePath:n,script:i,fatal:p,error:g}),p&&ae.delete(a)}}return null}function Nt(r,e){let t=Et(r,["-c",Tn,e],{encoding:"utf8"});if(t.error||typeof t.stdout!="string")return null;try{let n=JSON.parse(t.stdout.trim()||"{}");return n&&n.error?null:n}catch{return null}}function wt(r,e,t){let n=Et(r,["-c",Kn,e,t],{encoding:"utf8"});if(n.error||typeof n.stdout!="string")return null;try{let i=JSON.parse(n.stdout.trim()||"{}");return i&&i.error||typeof i.start!="number"||typeof i.end!="number"?null:i}catch{return null}}async function Fn(r){let e=Date.now(),t=!1,n=null;try{n=await Mn(r.projectRoot,r.absPath,r.content),t=!!n}catch{}if(!n){let o=Re(r.projectRoot),a=null;for(let c of o)if(n=Nt(c,r.absPath),n){a=c;break}if(!n&&o.length>1){for(let c of o.slice().reverse())if(n=Nt(c,r.absPath),n){a=c;break}}if(!n){$(`[PythonCliAdapter] parse failed for ${r.relPath} (interpreters tried: ${o.join(", ")})`);let c=Date.now()-e;return c>2e3&&$("[PythonCliAdapter] parse slow (failed)",{file:r.relPath,ms:c}),null}a&&$(`[PythonCliAdapter] parse ok for ${r.relPath} via ${a}`)}let i=[];for(let o of n.references||[]){let a={};o.expression&&(a.expression=o.expression),o.objectName&&(a.objectName=o.objectName),o.containerName&&(a.containerName=o.containerName),o.containerKind&&(a.containerKind=o.containerKind),i.push({sourceStart:o.start,sourceEnd:o.end,refKind:o.kind,refName:o.name,receiverName:o.receiverName??o.objectName??null,arity:typeof o.arity=="number"?o.arity:null,containerQualifiedName:o.containerQualifiedName??null,targetSymbolKey:o.targetSymbolKey??null,metadata:Object.keys(a).length?a:null})}let s=Date.now()-e;return s>2e3&&$("[PythonCliAdapter] parse slow",{file:r.relPath,ms:s,usedWorker:t}),{nodes:n.nodes,imports:n.imports,importBindings:n.importBindings,references:i,modulePublic:n.modulePublic??void 0,explicitExports:n.explicitExports??void 0}}function Pt(){return W({id:"python",extensions:[".py",".pyw",".pyi"],exportKind:"named",parse:({absPath:r,relPath:e,projectRoot:t,content:n})=>Fn({absPath:r,relPath:e,projectRoot:t,content:n}),resolve:async({absPath:r,nodePath:e,projectRoot:t})=>{try{let i=_e.readFileSync(r,"utf8"),s=await jn(t,r,i,e);if(s)return s}catch{}let n=Re(t);for(let i of n){let s=wt(i,r,e);if(s)return s}for(let i of n.slice().reverse()){let s=wt(i,r,e);if(s)return s}return null}})}import Rt from"fs";import kt from"path";import{spawn as Ln,spawnSync as zi}from"child_process";var Bn=256e3,$n=32;function Z(...r){try{let e=r.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
505
+ `)}catch{}}var Je=class{constructor(e){this.cmd=e;this.proc=null;this.buffer="";this.pending=new Map;this.seq=1;this.closed=!1;this.ensureProcess()}ensureProcess(){if(!(this.proc&&!this.closed)){if(this.closed=!1,this.proc=Ln(this.cmd,["--server"],{stdio:["pipe","pipe","pipe"]}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw this.closed=!0,new Error("csharp indexer stdio unavailable");this.proc.stdout.on("data",e=>this.onData(e)),this.proc.stderr.on("data",e=>{Z(`[CSharpIndexer] ${e.toString("utf8").trim()}`)}),this.proc.stdin.on("error",e=>this.handleExit(e)),this.proc.on("error",e=>this.handleExit(e)),this.proc.on("exit",e=>this.handleExit(new Error(`csharp indexer exited with code ${e}`)))}}handleExit(e){if(!this.closed){this.closed=!0;for(let[,t]of this.pending)t.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let t=this.buffer.indexOf(`
506
+ `);if(t<0)break;let n=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!n)continue;let i=null;try{i=JSON.parse(n)}catch{continue}let s=this.pending.get(i.id);s&&(this.pending.delete(i.id),i.ok?s.resolve(i):s.reject(new Error(i.error||"csharp server error")))}}async request(e,t=1){this.ensureProcess();let n=this.seq++;return new Promise((i,s)=>{let o={id:n,...e};this.pending.set(n,{resolve:i,reject:s});try{this.proc.stdin.write(`${JSON.stringify(o)}
507
+ `)}catch(a){if(this.pending.delete(n),t>0){try{this.handleExit(a)}catch{}return this.request(e,t-1).then(i,s)}s(a)}})}async parseBatch(e){let t=await this.request({op:"parse",files:e});return"results"in t?t.results.map(n=>n.ok&&n.result?n.result:null):"result"in t?[t.result]:e.map(()=>null)}async resolve(e){let t=await this.request({op:"resolve",...e});return"result"in t&&t.result&&typeof t.result.start=="number"?t.result:null}async resolveReferences(e){let t=await this.request({op:"resolve-references",...e});return"result"in t&&t.result?t.result:null}close(){if(this.closed)return;this.closed=!0;for(let[,t]of this.pending)t.reject(new Error("csharp indexer client closed"));this.pending.clear();let e=this.proc;if(this.proc=null,!!e){try{e.stdin?.end()}catch{}try{e.kill()}catch{}}}},We=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((t,n)=>{this.queue.push({input:e,resolve:t,reject:n,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],t=0;for(;this.queue.length&&e.length<$n;){let n=this.queue[0];if(e.length>0&&t+n.input.size>Bn)break;e.push(this.queue.shift()),t+=n.input.size}try{let n=await this.client.parseBatch(e.map(i=>({file:i.input.file,root:i.input.root,lang:i.input.lang})));for(let i=0;i<e.length;i+=1){let s=e[i],o=n[i]??null,a=Date.now()-s.startedAt;a>2e3&&Z(`[${new Date().toISOString()}] [CSharpCliAdapter] parse slow`,{file:s.input.file,ms:a,path:"custom",ok:!!o}),o||Z(`[${new Date().toISOString()}] [CSharpCliAdapter] parse failed`,{file:s.input.file,ms:a,path:"custom"}),s.resolve(o)}}catch(n){for(let i of e)i.reject(n)}}}},At=new Map,It=new Map;function zn(r){let e=process.platform==="win32"?".cmd":"",t=B(`csharp-indexer/bin/pando-csharp-indexer${e}`);if(t)return t;if(r){let i=kt.resolve(r,"tools/csharp-indexer/bin/pando-csharp-indexer"+e);if(Rt.existsSync(i))return i}let n=kt.resolve(__dirname,"../../../../../tools/csharp-indexer/bin/pando-csharp-indexer"+e);return Rt.existsSync(n)?n:null}function Dt(r){let e=process.env.PANDO_CSHARP_INDEXER_CMD||zn(r);if(!e)return null;let t=At.get(e);t||(t=new Je(e),At.set(e,t));let n=It.get(e);return n||(n=new We(t),It.set(e,n)),{client:t,batcher:n}}async function qn(r,e,t){let n=Dt(e);if(!n)return null;try{return await n.batcher.enqueue({file:r,root:e,lang:"csharp",size:t})}catch(i){return Z(`[${new Date().toISOString()}] [CSharpCliAdapter] parse error`,{file:r,error:i?.message||i,path:"custom"}),null}}async function Jn(r,e,t){let n=await qn(r,e,t);return n||null}function Tt(){return W({id:"csharp",extensions:[".cs",".csx",".cshtml",".razor"],parse:({absPath:r,projectRoot:e,content:t,meta:n})=>{let i=n?.size??Buffer.byteLength(t,"utf8");return Jn(r,e,i)},resolve:({absPath:r,nodePath:e,projectRoot:t})=>{let n=Date.now(),i=Dt(t);return i?i.client.resolve({file:r,root:t,lang:"csharp",nodePath:e}).then(s=>{let o=Date.now()-n;return o>2e3&&Z(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve slow`,{file:r,ms:o}),s||Z(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve failed`,{file:r,ms:o,nodePath:e}),s}).catch(s=>{let o=Date.now()-n;return Z(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve error`,{file:r,ms:o,nodePath:e,error:s?.message||s}),null}):null}})}import{spawnSync as tr}from"child_process";import nr from"fs";import Qe from"path";import L from"fs";import y from"path";var he=new Map,Wn=["include","src","lib","libs","third_party","third-party","deps","vendor","build","build/src","build_pando","build_pando/src"],Ue=["build","out","build-debug","build-release","cmake-build-debug","cmake-build-release","build_pando"],Mt=new Set([".c",".cc",".cpp",".cxx",".c++",".cp",".m",".mm"]),jt=new Set([".h",".hh",".hpp",".hxx",".h++",".inl",".ipp",".tcc"]);function ue(r){let e=[],t="",n=null,i=!1;for(let s=0;s<r.length;s+=1){let o=r[s];if(i){t+=o,i=!1;continue}if(o==="\\"){i=!0;continue}if(n){o===n?n=null:t+=o;continue}if(o==='"'||o==="'"){n=o;continue}if(o===" "||o===`
508
+ `||o===" "||o==="\r"){t&&(e.push(t),t="");continue}t+=o}return t&&e.push(t),e}function Un(r,e){let t=[];for(let n=0;n<r.length;n+=1){let i=r[n];if(i==="-c")continue;if(i==="-o"){n+=1;continue}if(i===e)continue;let s=y.extname(i).toLowerCase();Mt.has(s)||t.push(i)}return t}function Ft(r,e){return y.isAbsolute(r)?y.resolve(r):e?y.resolve(e,r):y.resolve(r)}function Xn(r){try{let e=L.readFileSync(r,"utf8"),t=JSON.parse(e),n=new Map,i=[];for(let s of t){let o=s.directory?y.resolve(s.directory):void 0,a=s.file?Ft(s.file,o):null;if(!a)continue;let c=o??y.dirname(a),d=Array.isArray(s.arguments)?s.arguments:s.command?ue(s.command):[];if(d.length===0)continue;let p={args:Un(d.slice(1),a),cwd:c,file:a};n.set(a,p),i.push(p)}return{map:n,entries:i}}catch{return null}}function Qn(r){try{let e=L.readFileSync(r,"utf8");return ue(e.replace(/\r/g,`
509
+ `))}catch{return null}}function Lt(r){let e=y.join(r,"compile_commands.json");if(L.existsSync(e))return e;for(let o of Ue){let a=y.join(r,o,"compile_commands.json");if(L.existsSync(a))return a}let t=Ue.map(o=>y.join(r,o)).filter(o=>L.existsSync(o));t.push(r);let n=10,i=new Set,s=(o,a)=>{if(a>n)return null;let c=y.resolve(o);if(i.has(c))return null;i.add(c);try{let d=L.readdirSync(o,{withFileTypes:!0});for(let g of d)if(g.isFile()&&g.name==="compile_commands.json")return y.join(o,g.name);for(let g of d){if(!g.isDirectory()||g.name==="node_modules"||g.name.startsWith("."))continue;let p=s(y.join(o,g.name),a+1);if(p)return p}}catch{}return null};for(let o of t){let a=s(o,0);if(a)return a}return null}function Vn(r,e){let t=y.resolve(r),n=y.resolve(e);for(;;){let i=Lt(t);if(i)return i;if(t===n)break;let s=y.dirname(t);if(s===t)break;t=s}return null}function Bt(r){let e=y.join(r,"compile_flags.txt");if(L.existsSync(e))return e;for(let t of Ue){let n=y.join(r,t,"compile_flags.txt");if(L.existsSync(n))return n}return null}function Gn(r,e){let t=y.resolve(r),n=y.resolve(e);for(;;){let i=Bt(t);if(i)return i;if(t===n)break;let s=y.dirname(t);if(s===t)break;t=s}return null}function ye(r){if(r)try{return L.statSync(r).mtimeMs}catch{return}}function Hn(r){let e=[],t=new Set([".clangd","CMakeLists.txt","meson.build","meson_options.txt","Makefile","makefile","GNUmakefile","configure.ac","configure.in"]),n=5,i=200,s=(o,a)=>{if(a>n||e.length>=i)return;let c;try{c=L.readdirSync(o,{withFileTypes:!0})}catch{return}for(let d of c){if(e.length>=i)break;let g=y.join(o,d.name);d.isFile()&&(t.has(d.name)||d.name.endsWith(".cmake"))&&e.push(g)}for(let d of c){if(e.length>=i)break;d.isDirectory()&&(d.name==="node_modules"||d.name===".git"||d.name===".pando"||d.name.startsWith(".cache")||s(y.join(o,d.name),a+1))}};return s(r,0),e}function Y(r,e,t){if(!t)return;let n=t.trim();!n||e.has(n)||(e.add(n),r.push(n))}function ce(r,e,t,n){let i=n.trim().replace(/^["']|["']$/g,"");if(!i||i.startsWith("$")||i.includes("${")||i.includes("<"))return;let s=y.isAbsolute(i)?i:y.resolve(t,i);L.existsSync(s)&&Y(r,e,`-I${s}`)}function Kt(r){let e=[],t=new Set,n;for(let i of Hn(r)){let s=ye(i);s&&(!n||s>n)&&(n=s);let o="";try{o=L.readFileSync(i,"utf8")}catch{continue}let a=y.dirname(i),c=o.replace(/#[^\n]*/g," "),d=ue(c.replace(/[()[\]{},;]/g," "));for(let g=0;g<d.length;g+=1){let p=d[g];(p==="-I"||p==="-isystem"||p==="/I")&&d[g+1]?(ce(e,t,a,d[g+1]),g+=1):p.startsWith("-I")&&p.length>2||p.startsWith("/I")&&p.length>2?ce(e,t,a,p.slice(2)):p.startsWith("-isystem")&&p.length>8?ce(e,t,a,p.slice(8)):p.startsWith("-D")||p.startsWith("/D")?Y(e,t,p.startsWith("/D")?`-D${p.slice(2)}`:p):p.startsWith("-std=")&&Y(e,t,p)}for(let g of o.matchAll(/\b(?:target_)?include_directories\s*\(([^)]*)\)/gims))for(let p of ue(g[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE|SYSTEM|BEFORE|AFTER)$/i.test(p)||ce(e,t,a,p);for(let g of o.matchAll(/\b(?:add_compile_definitions|target_compile_definitions)\s*\(([^)]*)\)/gims))for(let p of ue(g[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE)$/i.test(p)||p.includes("$")||Y(e,t,p.startsWith("-D")?p:`-D${p}`);for(let g of o.matchAll(/\binclude_directories\s*:\s*\[([^\]]*)\]/gims))for(let p of ue(g[1].replace(/,/g," ")))ce(e,t,a,p)}return{args:e,mtime:n}}function Yn(r,e){let t=y.resolve(r).split(y.sep),n=y.resolve(e).split(y.sep),i=0;for(;i<t.length&&i<n.length&&t[i]===n[i];)i+=1;return i}function Zn(r,e){if(!r||r.length===0)return null;let t=y.dirname(e),n=y.extname(e).toLowerCase(),i=y.basename(e,n),s=null;for(let o of r){let a=y.extname(o.file).toLowerCase();if(!Mt.has(a))continue;let c=y.dirname(o.file),d=y.basename(o.file,a),g=Yn(e,o.file);c===t&&(g+=100),d===i&&(g+=50),jt.has(n)&&(g+=20),(!s||g>s.score)&&(s={entry:o,score:g})}return s?.entry??null}function Ot(r,e){let t=e?`${y.resolve(r)}::${y.resolve(e)}`:y.resolve(r),n=he.get(t);if(n){let D=ye(n.commandsPath);if(n.commandsPath&&D&&n.commandsMtime&&D!==n.commandsMtime)he.delete(t);else if(n.flagsPath){let E=ye(n.flagsPath);if(E&&n.flagsMtime&&E!==n.flagsMtime)he.delete(t);else return n}else if(n.projectConfigFlags){let E=Kt(e??r);if(n.projectConfigMtime&&E.mtime&&n.projectConfigMtime!==E.mtime)he.delete(t);else return n}else return n}let i=e?Vn(e,r):Lt(r),s=i?Xn(i)??void 0:void 0,o=s?.map,a=s?.entries,c=ye(i),d=o?null:e?Gn(e,r):Bt(r),g=d?Qn(d)??void 0:void 0,p=ye(d),S=!o&&!g?Kt(e??r):void 0,k={commands:o,commandEntries:a,flags:g,projectConfigFlags:S?.args,commandsPath:i,commandsMtime:c,flagsPath:d,flagsMtime:p,projectConfigMtime:S?.mtime};return he.set(t,k),k}function $t(r,e,t){let n=y.dirname(e),i=Ot(r);!i.commands&&!i.flags&&(!i.projectConfigFlags||i.projectConfigFlags.length===0)&&(i=Ot(r,n));let s=Ft(e);if(i.commands){let o=i.commands.get(s);if(o)return{args:o.args,cwd:o.cwd,source:"compile_commands"};let a=Zn(i.commandEntries,s);if(a)return{args:a.args,cwd:a.cwd,source:"compile_commands"}}return i.flags?{args:i.flags,cwd:r,source:"compile_flags"}:i.projectConfigFlags&&i.projectConfigFlags.length>0?{args:zt(i.projectConfigFlags,r,t),cwd:r,source:"project_config"}:Xe(r,t)}function er(r){let e=[],t=new Set,n=a=>{let c=y.resolve(a);!t.has(c)&&L.existsSync(c)&&(t.add(c),e.push(c))};n(r);for(let a of Wn)n(y.join(r,a));let i=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_DEPTH||"5"),s=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_MAX_DIRS||"300"),o=(a,c)=>{if(c>i||e.length>=s)return;let d;try{d=L.readdirSync(a,{withFileTypes:!0})}catch{return}d.some(p=>p.isFile()&&jt.has(y.extname(p.name).toLowerCase()))&&n(a);for(let p of d){if(e.length>=s)break;p.isDirectory()&&(p.name==="node_modules"||p.name===".git"||p.name===".pando"||p.name.startsWith(".cache")||o(y.join(a,p.name),c+1))}};return o(r,0),e}function zt(r,e,t){let n=[...r],i=new Set(n);n.some(s=>s.startsWith("-std="))||Y(n,i,"-std="+(t==="cpp"?"c++20":"c17"));for(let s of er(e))Y(n,i,`-I${s}`);for(let s of["-ferror-limit=0","-Wno-everything","-fparse-all-comments","-fms-extensions"])Y(n,i,s);return t==="cpp"&&Y(n,i,"-fdelayed-template-parsing"),n}function Xe(r,e){return{args:zt([],r,e),cwd:r,source:"fallback"}}var ns=(()=>{let r=Number(process.env.PANDO_CLANG_AST_MAX_BUFFER_BYTES||"");if(Number.isFinite(r)&&r>0)return Math.floor(r);let e=Number(process.env.PANDO_CLANG_AST_MAX_BUFFER_MB||"");return Number.isFinite(e)&&e>0?Math.floor(e*1024*1024):1536*1024*1024})();function rr(){let r=process.env.PANDO_CLANG_INDEXER_CMD;if(r&&r.trim())return r.trim();let e=B("clang-indexer/bin/pando-clang-indexer");if(e)return e;let t=[process.env.PANDO_TOOLS_ROOT?Qe.join(process.env.PANDO_TOOLS_ROOT,"clang-indexer","bin","pando-clang-indexer"):null,process.env.PANDO_RUNTIME_ROOT?Qe.join(process.env.PANDO_RUNTIME_ROOT,"tools","clang-indexer","bin","pando-clang-indexer"):null,typeof __dirname=="string"?Qe.resolve(__dirname,"..","..","..","..","..","tools","clang-indexer","bin","pando-clang-indexer"):null].filter(n=>!!n);for(let n of t)try{if(nr.existsSync(n))return n}catch{}return"pando-clang-indexer"}function ir(r){if(!r)return null;let e=r;(e.startsWith("SyntaxError:")||e.startsWith("CompileError:"))&&(e=e.substring(e.indexOf(":")+1)),e.includes("#")&&(e=e.split("#")[1]);let t=e.lastIndexOf(":"),n=t>=0?e.slice(0,t):e,[i,s]=n.split("-"),o=Number(i),a=Number(s);return!Number.isFinite(o)||!Number.isFinite(a)||a<o?null:{start:o,end:a}}function Ve(r){return W({id:r,extensions:[],parse:({absPath:e,relPath:t,content:n,projectRoot:i})=>{let s=$t(i,e,r),o=d=>["--file",e,"--project-root",i,"--lang",r,"--cwd",d.cwd,"--",...d.args,"-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...d.source==="fallback"?["-x",r==="cpp"?"c++":"c"]:[]],a=d=>{let g=rr(),p=tr(g,o(d),{encoding:"utf8",cwd:d.cwd,maxBuffer:32*1024*1024});if(p.error){try{console.error(`[ClangAdapter] pando-clang-indexer spawn failed ${JSON.stringify({file:e,command:g,error:p.error.message})}`)}catch{}return null}if(p.status!==0){try{console.error(`[ClangAdapter] pando-clang-indexer failed ${JSON.stringify({file:e,status:p.status,stderr:(p.stderr||"").trim().slice(0,4e3)})}`)}catch{}return null}try{return JSON.parse(p.stdout||"{}")}catch(S){try{console.error(`[ClangAdapter] pando-clang-indexer emitted invalid JSON ${JSON.stringify({file:e,stdoutBytes:(p.stdout||"").length,stderr:(p.stderr||"").trim().slice(0,4e3),error:S instanceof Error?S.message:String(S)})}`)}catch{}return null}},c=a(s);return!c&&s.source!=="fallback"&&(c=a(Xe(i,r))),!c||c.error?null:c},resolve:({absPath:e,nodePath:t,projectRoot:n})=>{try{let i=cn("fs").readFileSync(e,"utf8"),s=ir(t);return s?{start:s.start,end:s.end,bodyStart:null,bodyEnd:null,text:i.slice(s.start,s.end)}:null}catch{return null}}})}import Ge from"fs";import He from"path";import{spawn as sr,spawnSync as as}from"child_process";var or=256e3,ar=32;function ee(...r){try{let e=r.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
510
+ `)}catch{}}var Ye=class{constructor(e){this.cmd=e;this.proc=null;this.buffer="";this.pending=new Map;this.seq=1;this.closed=!1;this.ensureProcess()}ensureProcess(){if(!(this.proc&&!this.closed)){if(this.closed=!1,this.proc=sr(this.cmd,["--server"],{stdio:["pipe","pipe","pipe"]}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw this.closed=!0,new Error("dart indexer stdio unavailable");this.proc.stdout.on("data",e=>this.onData(e)),this.proc.stderr.on("data",e=>{ee(`[DartIndexer] ${e.toString("utf8").trim()}`)}),this.proc.stdin.on("error",e=>this.handleExit(e)),this.proc.on("error",e=>this.handleExit(e)),this.proc.on("exit",e=>this.handleExit(new Error(`dart indexer exited with code ${e}`)))}}handleExit(e){if(!this.closed){this.closed=!0;for(let[,t]of this.pending)t.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let t=this.buffer.indexOf(`
511
+ `);if(t<0)break;let n=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!n)continue;let i=null;try{i=JSON.parse(n)}catch{continue}let s=this.pending.get(i.id);s&&(this.pending.delete(i.id),i.ok?s.resolve(i):s.reject(new Error(i.error||"dart server error")))}}async request(e,t=1){this.ensureProcess();let n=this.seq++;return new Promise((i,s)=>{let o={id:n,...e};this.pending.set(n,{resolve:i,reject:s});try{this.proc.stdin.write(`${JSON.stringify(o)}
512
+ `)}catch(a){if(this.pending.delete(n),t>0){try{this.handleExit(a)}catch{}return this.request(e,t-1).then(i,s)}s(a)}})}async parseBatch(e){let t=await this.request({op:"parse",files:e});return"results"in t&&Array.isArray(t.results)?t.results.map(n=>n.ok&&n.result?n.result:null):"result"in t&&t.result?[t.result]:e.map(()=>null)}async resolve(e){let t=await this.request({op:"resolve",...e});return"result"in t&&t.result&&typeof t.result.start=="number"?t.result:null}close(){if(this.closed)return;this.closed=!0;for(let[,t]of this.pending)t.reject(new Error("dart indexer client closed"));this.pending.clear();let e=this.proc;if(this.proc=null,!!e){try{e.stdin?.end()}catch{}try{e.kill()}catch{}}}},Ze=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((t,n)=>{this.queue.push({input:e,resolve:t,reject:n,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],t=0;for(;this.queue.length&&e.length<ar;){let n=this.queue[0];if(e.length>0&&t+n.input.size>or)break;e.push(this.queue.shift()),t+=n.input.size}try{let n=await this.client.parseBatch(e.map(i=>({file:i.input.file,root:i.input.root,lang:i.input.lang})));for(let i=0;i<e.length;i+=1){let s=e[i],o=n[i]??null,a=Date.now()-s.startedAt;a>2e3&&ee(`[${new Date().toISOString()}] [DartCliAdapter] parse slow`,{file:s.input.file,ms:a,ok:!!o}),o||ee(`[${new Date().toISOString()}] [DartCliAdapter] parse failed`,{file:s.input.file,ms:a}),s.resolve(o)}}catch(n){for(let i of e)i.reject(n)}}}},qt=new Map,Jt=new Map;function lr(r){let e=process.platform==="win32"?".cmd":"",t=B(`dart-indexer/bin/pando-dart-indexer${e}`);if(t)return t;if(r){let s=He.resolve(r,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(Ge.existsSync(s))return s}let n=process.env.PANDO_EXTENSION_ROOT;if(n){let s=He.resolve(n,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(Ge.existsSync(s))return s}let i=He.resolve(process.cwd(),"tools/dart-indexer/bin/pando-dart-indexer"+e);return Ge.existsSync(i)?i:null}function Wt(r){let e=process.env.PANDO_DART_INDEXER_CMD||lr(r);if(!e)return null;let t=qt.get(e);t||(t=new Ye(e),qt.set(e,t));let n=Jt.get(e);return n||(n=new Ze(t),Jt.set(e,n)),{client:t,batcher:n}}async function cr(r,e,t){let n=Wt(e);if(!n)return null;try{return await n.batcher.enqueue({file:r,root:e,lang:"dart",size:t})}catch(i){return ee(`[${new Date().toISOString()}] [DartCliAdapter] parse error`,{file:r,error:i?.message||i}),null}}function Ut(){return W({id:"dart",extensions:[".dart"],parse:async({absPath:r,projectRoot:e,content:t,meta:n})=>{let i=n?.size??Buffer.byteLength(t,"utf8");return cr(r,e,i)},resolve:({absPath:r,nodePath:e,projectRoot:t})=>{let n=Date.now(),i=Wt(t);return i?i.client.resolve({file:r,root:t,lang:"dart",nodePath:e}).then(s=>{let o=Date.now()-n;return o>2e3&&ee(`[${new Date().toISOString()}] [DartCliAdapter] resolve slow`,{file:r,ms:o}),s||ee(`[${new Date().toISOString()}] [DartCliAdapter] resolve failed`,{file:r,ms:o,nodePath:e}),s}).catch(s=>{let o=Date.now()-n;return ee(`[${new Date().toISOString()}] [DartCliAdapter] resolve error`,{file:r,ms:o,nodePath:e,error:s?.message||s}),null}):null},exportKind:"dart"})}import et from"fs";import be from"path";import{spawn as ur,spawnSync as ms}from"child_process";var dr=256e3,pr=32;function ne(...r){try{let e=r.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
513
+ `)}catch{}}var tt=class{constructor(e){this.cmd=e;this.proc=null;this.buffer="";this.pending=new Map;this.seq=1;this.closed=!1;this.ensureProcess()}ensureProcess(){if(!(this.proc&&!this.closed)){if(this.closed=!1,this.proc=ur(this.cmd,["--server"],{stdio:["pipe","pipe","pipe"]}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw this.closed=!0,new Error("java indexer stdio unavailable");this.proc.stdout.on("data",e=>this.onData(e)),this.proc.stderr.on("data",e=>{ne(`[JavaCliAdapter] ${e.toString("utf8").trim()}`)}),this.proc.stdin.on("error",e=>this.handleExit(e)),this.proc.on("error",e=>this.handleExit(e)),this.proc.on("exit",e=>this.handleExit(new Error(`java indexer exited with code ${e}`)))}}handleExit(e){if(!this.closed){this.closed=!0;for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let t=this.buffer.indexOf(`
514
+ `);if(t<0)break;let n=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!n)continue;let i=null;try{i=JSON.parse(n)}catch{continue}let s=this.pending.get(i.id);s&&(clearTimeout(s.timer),this.pending.delete(i.id),i.ok?s.resolve(i):s.reject(new Error(i.error||"java server error")))}}async request(e,t=1){this.ensureProcess();let n=this.seq++;return new Promise((i,s)=>{let o={id:n,...e},a=setTimeout(()=>{this.pending.delete(n),s(new Error("java indexer request timed out after 30s"))},3e4);this.pending.set(n,{resolve:i,reject:s,timer:a});try{this.proc.stdin.write(`${JSON.stringify(o)}
515
+ `)}catch(c){if(clearTimeout(a),this.pending.delete(n),t>0){try{this.handleExit(c)}catch{}return this.request(e,t-1).then(i,s)}s(c)}})}async parseBatch(e){let t=await this.request({op:"parse",files:e});return"results"in t?t.results.map(n=>n.ok&&n.result?n.result:null):"result"in t?[t.result]:e.map(()=>null)}async resolve(e){let t=await this.request({op:"resolve",...e});return"result"in t&&t.result&&typeof t.result.start=="number"?t.result:null}close(){if(this.closed)return;this.closed=!0;for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("java indexer client closed"));this.pending.clear();let e=this.proc;if(this.proc=null,!!e){try{e.stdin?.end()}catch{}try{e.kill()}catch{}}}},nt=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((t,n)=>{this.queue.push({input:e,resolve:t,reject:n,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],t=0;for(;this.queue.length&&e.length<pr;){let n=this.queue[0];if(e.length>0&&t+n.input.size>dr)break;e.push(this.queue.shift()),t+=n.input.size}try{let n=await this.client.parseBatch(e.map(i=>({file:i.input.file,root:i.input.root,lang:i.input.lang})));for(let i=0;i<e.length;i+=1){let s=e[i],o=n[i]??null,a=Date.now()-s.startedAt;a>2e3&&ne(`[${new Date().toISOString()}] [JavaCliAdapter] parse slow`,{file:s.input.file,ms:a,path:"custom",ok:!!o}),o||ne(`[${new Date().toISOString()}] [JavaCliAdapter] parse failed`,{file:s.input.file,ms:a,path:"custom"}),s.resolve(o)}}catch(n){for(let i of e)i.reject(n)}}}},Xt=new Map,Qt=new Map;function fr(){return typeof __dirname=="string"?__dirname:process.cwd()}var te,mr;function gr(r){if(te!==void 0&&mr===r)return te;let e=process.platform==="win32"?".cmd":"",t="tools/java-indexer/bin/pando-java-indexer"+e,n=B(`java-indexer/bin/pando-java-indexer${e}`);if(n)return te=n,n;if(r){let s=be.resolve(r,t);if(et.existsSync(s))return te=s,s}let i=fr();for(let s=0;s<8;s++){let o=be.join(i,t);if(et.existsSync(o))return te=o,o;let a=be.dirname(i);if(a===i)break;i=a}i=process.cwd();for(let s=0;s<8;s++){let o=be.join(i,t);if(et.existsSync(o))return te=o,o;let a=be.dirname(i);if(a===i)break;i=a}return te=null,null}function Vt(r){let e=process.env.PANDO_JAVA_INDEXER_CMD||gr(r);if(!e)return null;let t=Xt.get(e);t||(t=new tt(e),Xt.set(e,t));let n=Qt.get(e);return n||(n=new nt(t),Qt.set(e,n)),{client:t,batcher:n}}async function hr(r,e,t){let n=Vt(e);if(!n)return null;try{return await n.batcher.enqueue({file:r,root:e,lang:"java",size:t})}catch(i){return ne(`[${new Date().toISOString()}] [JavaCliAdapter] parse error`,{file:r,error:i?.message||i,path:"custom"}),null}}async function yr(r,e,t){let n=await hr(r,e,t);return n||null}function Gt(){return W({id:"java",extensions:[".java"],exportKind:"named",parse:({absPath:r,projectRoot:e,content:t,meta:n})=>{let i=n?.size??Buffer.byteLength(t,"utf8");return yr(r,e,i)},resolve:({absPath:r,nodePath:e,projectRoot:t})=>{let n=Date.now(),i=Vt(t);return i?i.client.resolve({file:r,root:t,lang:"java",nodePath:e}).then(s=>{let o=Date.now()-n;return o>2e3&&ne(`[${new Date().toISOString()}] [JavaCliAdapter] resolve slow`,{file:r,ms:o}),s||ne(`[${new Date().toISOString()}] [JavaCliAdapter] resolve failed`,{file:r,ms:o,nodePath:e}),s}).catch(s=>{let o=Date.now()-n;return ne(`[${new Date().toISOString()}] [JavaCliAdapter] resolve error`,{file:r,ms:o,nodePath:e,error:s?.message||s}),null}):null}})}import _r from"fs";import Nr from"os";import{spawn as br}from"child_process";import rt from"fs";import it from"path";function Ht(r,e){let t=process.platform==="win32"?".cmd":"",n=r==="clojure-editor"?"pando-clojure-editor":"pando-clojure-indexer",i=B(`${r}/bin/${n}${t}`);if(i)return i;if(e){let a=it.resolve(e,`tools/${r}/bin/${n}${t}`);if(rt.existsSync(a))return a}let s=process.env.PANDO_EXTENSION_ROOT;if(s){let a=it.resolve(s,`tools/${r}/bin/${n}${t}`);if(rt.existsSync(a))return a}let o=it.resolve(process.cwd(),`tools/${r}/bin/${n}${t}`);return rt.existsSync(o)?o:null}var Ae=3e4,xr=Math.max(Ae,Number(process.env.PANDO_CLOJURE_PARSE_TIMEOUT_MS||`${300*1e3}`)),Sr=Math.max(Ae,Number(process.env.PANDO_CLOJURE_CHANGE_SIGNATURE_TIMEOUT_MS||`${300*1e3}`)),Yt="__PANDO_CLOJURE_INDEX__";function Cr(...r){if(!re())return;let e=r.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");F("ClojureIndexer",e)}function xe(r,e){re()&&F("ClojureIndex",r,e)}function vr(r,e=0){let t=Math.max(1,r.length),n=Math.ceil(Math.max(0,e)/(32*1024))*500,i=15e3+t*2500+n;return Math.max(Ae,Math.min(xr,i))}var ke=class{constructor(e,t){this.cmd=e;this.projectRoot=t;this.proc=null;this.buffer="";this.stderrBuffer="";this.pending=new Map;this.seq=1;this.closed=!1;this.ensureProcess()}ensureProcess(){if(!(this.proc&&!this.closed)){if(this.closed=!1,xe("node.server.spawn",{projectRoot:this.projectRoot,cmd:this.cmd}),this.proc=br(this.cmd,["--server"],{cwd:this.projectRoot,stdio:["pipe","pipe","pipe"],env:{...process.env,PANDO_PROJECT_ROOT:this.projectRoot}}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw this.closed=!0,new Error("clojure indexer stdio unavailable");this.proc.stdout.on("data",e=>this.onData(e)),this.proc.stderr.on("data",e=>this.onStderr(e)),this.proc.on("error",e=>this.handleExit(e)),this.proc.on("exit",e=>this.handleExit(new Error(`clojure indexer exited with code ${e}`)))}}handleExit(e){if(!this.closed){xe("node.server.exit",{projectRoot:this.projectRoot,error:e?.message||String(e),pendingRequestCount:this.pending.size}),this.closed=!0;for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.proc=null}}onData(e){for(this.buffer+=e.toString("utf8");;){let t=this.buffer.indexOf(`
516
+ `);if(t<0)break;let n=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!n)continue;let i=null;try{i=JSON.parse(n)}catch{continue}let s=this.pending.get(i.id);s&&(clearTimeout(s.timer),this.pending.delete(i.id),i.ok?s.resolve(i):s.reject(new Error(i.error||"clojure server error")))}}onStderr(e){for(this.stderrBuffer+=e.toString("utf8");;){let t=this.stderrBuffer.indexOf(`
517
+ `);if(t<0)break;let n=this.stderrBuffer.slice(0,t).trim();if(this.stderrBuffer=this.stderrBuffer.slice(t+1),!!n){if(n.startsWith(Yt)){let i=n.slice(Yt.length);try{let s=JSON.parse(i);xe(s.event||"jvm.trace",s)}catch(s){F("ClojureIndexer","stderr trace parse failed",{error:s?.message||String(s),line:n})}continue}Cr(n)}}}close(){if(this.closed)return;this.closed=!0;for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("clojure indexer client closed"));this.pending.clear();let e=this.proc;if(this.proc=null,!!e){try{e.stdin?.end()}catch{}try{e.kill()}catch{}}}async request(e,t){this.ensureProcess();let n=this.seq++,i=t?.retry??1,s=t?.timeoutMs??Ae,o=Date.now();return new Promise((a,c)=>{let d={id:n,...e},g=setTimeout(()=>{this.pending.delete(n),c(new Error(`clojure indexer request timed out after ${s}ms`))},s);this.pending.set(n,{resolve:p=>{xe("node.client.request.complete",{projectRoot:this.projectRoot,id:n,op:e.op,durationMs:Date.now()-o}),a(p)},reject:c,timer:g});try{xe("node.client.request.start",{projectRoot:this.projectRoot,id:n,op:e.op,timeoutMs:s}),this.proc.stdin.write(`${JSON.stringify(d)}
518
+ `)}catch(p){if(clearTimeout(g),this.pending.delete(n),i>0){try{this.handleExit(p)}catch{}return this.request(e,{retry:i-1,timeoutMs:s}).then(a,c)}c(p)}})}async parseBatch(e,t){let n=vr(e,t?.batchBytes??0),i=await this.request({op:"parse",files:e,analysisMode:t.purpose==="query"?"full":"index",traceBatchId:t?.batchId,traceBatchBytes:t?.batchBytes},{timeoutMs:n});return"results"in i?i.results.map(s=>s.ok&&s.result?s.result:null):[]}async resolve(e){let t=await this.request({op:"resolve",...e});if("result"in t){let n=t.result;if(n&&typeof n.start=="number"&&typeof n.end=="number")return n}return null}async changeSignature(e){let t=await this.request({op:"change-signature",...e},{timeoutMs:Sr});return"result"in t&&t.result||null}},Zt=new Map;function en(r){return process.env.PANDO_CLOJURE_INDEXER_CMD||Ht("clojure-indexer",r)}function tn(r){let e=en(r);return e?new ke(e,r):null}function nn(r){let e=en(r);if(!e)return null;let t=`${e}::${r}`,n=Zt.get(t);return n||(n=new ke(e,r),Zt.set(t,n)),n}function wr(){let r=Number(process.env.PANDO_CLOJURE_ANALYZER_POOL_SIZE||"");if(Number.isFinite(r)&&r>=1)return Math.max(1,Math.floor(r));let e=Math.max(1,Nr.cpus()?.length||4);return Math.max(3,Math.min(8,Math.ceil(e/2)))}var Er=wr();function Ie(r,e){F("ClojureIndex",r,e)}function De(r,e){F("IndexTiming",r,e)}var Te=class{constructor(e,t,n=Er){this.projectRoot=e;this.purpose=t;this.clients=[];this.idleClients=[];this.queue=[];this.inFlight=new Set;this.drainWaiters=[];this.batchSeq=1;this.closed=!1;let i=Math.max(1,n);for(let s=0;s<i;s+=1){let o=tn(e);if(!o)break;this.clients.push(o),this.idleClients.push(o)}if(!this.clients.length)throw new Error("clojure indexer command unavailable");Ie("node.pool.init",{projectRoot:e,purpose:t,configuredPoolSize:i,actualClientCount:this.clients.length})}submit(e,t){return this.closed?Promise.reject(new Error("clojure analyzer pool is closed")):new Promise((n,i)=>{this.queue.push({batchId:this.batchSeq++,batchKey:e,files:t,enqueuedAt:Date.now(),resolve:n,reject:i}),this.pump()})}async flush(){for(;this.queue.length||this.inFlight.size;)await new Promise(e=>this.drainWaiters.push(e))}async close(){if(!this.closed){await this.flush(),this.closed=!0;for(let e of this.clients)try{e.close()}catch{}this.clients.length=0,this.idleClients.length=0}}pump(){for(;!this.closed&&this.queue.length&&this.idleClients.length;){let e=this.queue.shift(),t=this.idleClients.shift(),n=this.runJob(t,e).finally(()=>{this.inFlight.delete(n),this.closed||this.idleClients.push(t),this.pump(),this.notifyIfIdle()});this.inFlight.add(n)}this.notifyIfIdle()}async runJob(e,t){let n=t.files.reduce((o,a)=>o+Math.max(0,a.size||0),0),i=Date.now(),s=Math.max(0,i-t.enqueuedAt);Ie("node.pool-batch.start",{batchId:t.batchId,batchKey:t.batchKey,purpose:this.purpose,fileCount:t.files.length,batchBytes:n,queueWaitMs:s,queuedBatchCount:this.queue.length,inFlightCount:this.inFlight.size});try{let o=await this.parseFiles(e,t.files,t.batchId,n);De("clojure-pool.job.complete",{projectRoot:this.projectRoot,batchId:t.batchId,batchKey:t.batchKey,purpose:this.purpose,fileCount:t.files.length,batchBytes:n,queueWaitMs:s,durationMs:Date.now()-i}),Ie("node.pool-batch.complete",{batchId:t.batchId,batchKey:t.batchKey,purpose:this.purpose,fileCount:t.files.length,batchBytes:n,durationMs:Date.now()-i,successCount:Array.from(o.values()).filter(a=>!("error"in a)).length,errorCount:Array.from(o.values()).filter(a=>"error"in a).length}),t.resolve(o)}catch(o){let a=o instanceof Error?o:new Error(String(o));Ie("node.pool-batch.error",{batchId:t.batchId,batchKey:t.batchKey,fileCount:t.files.length,batchBytes:n,durationMs:Date.now()-i,error:a.message}),t.reject(a)}}async parseFiles(e,t,n,i){let s=Date.now();try{let o=await e.parseBatch(t.map(c=>({file:c.absPath,root:this.projectRoot,lang:c.lang})),{batchId:n,batchBytes:i,purpose:this.purpose});De("clojure-parse-batch.complete",{projectRoot:this.projectRoot,batchId:n,fileCount:t.length,batchBytes:i,purpose:this.purpose,durationMs:Date.now()-s,split:!1});let a=new Map;for(let c=0;c<t.length;c+=1){let d=t[c],g=o[c]??null;g?a.set(d.fileKey,g):(F("IndexingAudit","clojure analysis returned no result",{projectRoot:this.projectRoot,batchId:n,file:d.absPath}),a.set(d.fileKey,{error:`clojure analysis returned no result for ${d.absPath}`}))}return a}catch(o){if(t.length>1){let d=Date.now(),g=Math.ceil(t.length/2),p=t.slice(0,g),S=t.slice(g),k=await this.parseFiles(e,p,n,p.reduce((E,M)=>E+Math.max(0,M.size||0),0)),D=await this.parseFiles(e,S,n,S.reduce((E,M)=>E+Math.max(0,M.size||0),0));return De("clojure-parse-batch.split",{projectRoot:this.projectRoot,batchId:n,fileCount:t.length,batchBytes:i,purpose:this.purpose,durationMs:Date.now()-d,leftCount:p.length,rightCount:S.length,error:o instanceof Error?o.message:String(o)}),new Map([...k,...D])}let a=o instanceof Error?o:new Error(String(o));De("clojure-parse-batch.error",{projectRoot:this.projectRoot,batchId:n,fileCount:t.length,batchBytes:i,purpose:this.purpose,durationMs:Date.now()-s,error:a.message});let c=new Map;for(let d of t)F("IndexingAudit","clojure analysis request failed",{projectRoot:this.projectRoot,batchId:n,file:d.absPath,error:a.message}),c.set(d.fileKey,{error:a.message});return c}}notifyIfIdle(){if(this.queue.length||this.inFlight.size)return;let e=this.drainWaiters.splice(0,this.drainWaiters.length);for(let t of e)try{t()}catch{}}};function Pr(r,e){if(typeof e?.size=="number"&&typeof e?.mtime=="number")return{size:e.size,mtime:e.mtime};try{let t=_r.statSync(r);return{size:typeof e?.size=="number"?e.size:t.size,mtime:typeof e?.mtime=="number"?e.mtime:Math.floor(t.mtimeMs)}}catch{return{size:e?.size,mtime:e?.mtime}}}function Rr(r,e){let t=new Map;for(let n of e.nodes??[]){if(!n.name||n.containerKind||t.has(n.name))continue;let i=`${r}#${n.start}-${n.end}:${G.getAbbrev(n.kind,"clojure")}:${n.name}`;t.set(n.name,i)}return n=>t.get(n)??null}function kr(r){let e=r?.error;return typeof e=="string"&&e.trim().length>0?e.trim():null}var Ke=class{constructor(e,t){this.projectRoot=e;this.purpose=t;this.cache=new se;this.pool=new Te(e,t)}prepare(e){let t=Pr(e.absPath,e.meta),n=this.cache.get(e.absPath,t);return{fileKey:e.relPath,absPath:e.absPath,relPath:e.relPath,meta:t,preDeleted:e.preDeleted,lang:e.lang,cachedParsed:n??void 0}}batchKey(e){return`${this.projectRoot}::clojure::${this.purpose}`}async analyzeBatch(e){let t=new Map,n=e.filter(s=>!s.cachedParsed);for(let s of e)s.cachedParsed&&t.set(s.fileKey,s.cachedParsed);if(!n.length)return t;let i=await this.pool.submit(this.batchKey(n[0]),n.map(s=>({fileKey:s.fileKey,absPath:s.absPath,lang:s.lang,size:s.meta?.size??0})));for(let s of n){let o=i.get(s.fileKey)??{error:`missing clojure analysis result for ${s.relPath}`};"error"in o||this.cache.set(s.absPath,s.meta??{},o),t.set(s.fileKey,o)}return t}buildProcessedFile(e,t,n){let i=kr(n);return i?(F("IndexingAudit","clojure batch analysis failed",{projectRoot:this.projectRoot,relPath:e.relPath,error:i}),de("clojure",e.relPath,t.meta)):pe({lang:"clojure",fileRel:e.relPath,content:e.content,meta:t.meta,preDeleted:e.preDeleted,parsed:n,resolveNodeId:Rr(e.relPath,n),exportKind:"cli"})}async flush(){await this.pool.flush()}async close(){await this.pool.close()}};function Ar(){return{maxFilesPerBatch:Math.max(1,Number(process.env.PANDO_CLOJURE_BATCH_MAX_FILES||"24")),maxBatchBytes:Math.max(1,Number(process.env.PANDO_CLOJURE_BATCH_MAX_BYTES||`${4*1024*1024}`)),maxWaitMs:Math.max(1,Number(process.env.PANDO_CLOJURE_BATCH_MAX_WAIT_MS||"10")),maxPendingFiles:Math.max(1,Number(process.env.PANDO_CLOJURE_BATCH_MAX_PENDING_FILES||"512")),maxPendingBytes:Math.max(1,Number(process.env.PANDO_CLOJURE_BATCH_MAX_PENDING_BYTES||`${16*1024*1024}`))}}function Ir(...r){let e=r.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");F("ClojureCliAdapter",e)}function rn(){return{id:"clojure",extensions:[".clj",".cljc",".cljs"],indexingMode:"batch",createBatchIndexer:(r,e)=>new Ke(r,e),getBatchSchedulerOptions:Ar,resolveSpan:(r,e,t)=>{let n=nn(r);return n?n.resolve({file:e,root:r,lang:"clojure",nodePath:t}).catch(i=>(Ir(`[${new Date().toISOString()}] [ClojureCliAdapter] resolve error`,{file:e,nodePath:t,error:i?.message||i}),null)):null}}}function no(r){return r.indexingMode==="worker"&&typeof r.createIndexer=="function"}var st={ts:$e("ts"),js:$e("js"),python:Pt(),c:{...Ve("c"),extensions:[".c",".i",".inc"]},cpp:{...Ve("cpp"),extensions:[".cc",".cpp",".cxx",".c++",".cp",".ccm",".cppm",".cxxm",".ixx",".hpp",".h",".hh",".hxx",".h++",".ii",".inl",".ipp",".tcc",".tpp",".txx"]},csharp:Tt(),dart:Ut(),java:Gt(),clojure:rn()},sn=new Map;for(let r of Object.values(st))for(let e of r.extensions)sn.set(e,r.id);function Dr(){return dt(ct())}function ro(r){let e=r.toLowerCase().match(/\.[a-z0-9+]+$/);return e?sn.get(e[0])??null:null}function io(r){return st[r]}function so(r){let e=r??Dr(),t=new Set;for(let[i,s]of Object.entries(e.byLanguage))s.enabled&&t.add(i);let n=new Set;for(let i of Object.values(st))if(t.has(i.id))for(let s of i.extensions)n.add(s);return n}import Tr from"fs";import on from"path";import{promises as Kr}from"fs";import{execFileSync as Or}from"child_process";import fo from"ignore";function ot(r){return r.replace(/\\/g,"/")}function an(r,e){let t=r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(!t.length)return[];let n=e?`${e}/`:"";return t.map(s=>s.startsWith("\\#")||s.startsWith("\\!")?s.slice(1):s).filter(s=>!s.startsWith("#")).map(s=>{let o=s.startsWith("!"),a=o?s.slice(1):s;if(!a)return s;if((a.endsWith("/")?a.slice(0,-1):a).includes("/")){if(!n&&a.startsWith("/"))return o?`!${a}`:a;let p=a.startsWith("/")?a.slice(1):a,S=n?`${n}${p}`:p;return o?`!${S}`:S}let g=n?`${n}**/${a}`:a;return o?`!${g}`:g})}function mo(r,e){let t=on.join(r,".gitignore");try{let n=Tr.readFileSync(t,"utf8");return an(n,e)}catch{return[]}}async function go(r,e){let t=on.join(r,".gitignore");try{let n=await Kr.readFile(t,"utf8");return an(n,e)}catch{return[]}}function Mr(r){let e=new Set,t=new Set;for(let n of r){let i=ot(n).replace(/^\/+/,"");if(!i)continue;e.add(i);let s=i.split("/");s.pop();let o="";for(let a of s)o=o?`${o}/${a}`:a,t.add(o)}return{files:e,dirs:t,hasFile(n){return e.has(ot(n))},hasDescendant(n){return t.has(ot(n).replace(/\/+$/,""))}}}function ho(r){try{let t=Or("git",["-C",r,"ls-files","-z"],{encoding:"buffer",stdio:["ignore","pipe","ignore"],maxBuffer:67108864}).toString("utf8").split("\0").filter(Boolean);return t.length?Mr(t):null}catch{return null}}function jr(r,e="Operation cancelled"){let t=typeof r=="string"&&r.trim()?r.trim():r instanceof Error&&r.message.trim()?r.message.trim():e,n=new Error(t);return n.name="AbortError",n.code="ABORT_ERR",n}function bo(r,e){if(r?.aborted)throw jr(r.reason,e)}export{de as a,no as b,Dr as c,ro as d,io as e,so as f,bo as g,mo as h,go as i,ho as j};