pando-ai 0.3.0 → 0.3.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.
- package/dist/cli.js +445 -669
- package/dist/watcher-process.js +664 -888
- package/dist/workers/chunk-5T4KKWJC.mjs +16 -0
- package/dist/workers/indexer-worker.mjs +1 -1
- package/dist/workers/snapshot-worker.mjs +1 -1
- package/dist/workers/sqlite-writer-worker.mjs +16 -6
- package/package.json +1 -1
- package/resources/tools/generated_pando-tools.json +38 -12
- package/tools/clang-indexer/bin/pando-clang-indexer +0 -0
- package/tools/clojure-editor/lib/pando-clojure-editor-standalone.jar +0 -0
- package/tools/clojure-indexer/lib/pando-clojure-indexer-standalone.jar +0 -0
- package/tools/csharp-indexer/CSharpIndexer.csproj +4 -0
- package/tools/csharp-indexer/src/Program.cs +159 -19
- package/dist/workers/chunk-A6FOFRZ6.mjs +0 -518
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{c as gn,d as oe,e as B,f as dt}from"./chunk-ODST7O2H.mjs";import{a as fn}from"./chunk-AYCBSZ56.mjs";var Z={getAbbrev(n,e="ts"){return n},getKindFromAbbrev(n,e="ts"){return n}};function Re(n){let e=`${n.sourceFile}#${n.sourceStart}-${n.sourceEnd}`,t=n.refKind??"",r=n.refName??"",i=n.targetFile??"",s=n.targetStart!=null&&n.targetEnd!=null?`#${n.targetStart}-${n.targetEnd}`:"",o=n.targetNodeId??"",l=`${e}:REF:${t}:${r}|${i}${s}|${o}`;return dt(l)}function pt(n){let e=[],t=new Set,r=i=>{!i?.name||t.has(i.name)||(t.add(i.name),e.push(i))};for(let i of n.exports??[])r(i);for(let i of n.explicitExports??[])r({name:i});for(let i of n.modulePublic??[])r({name:i});return e}function he(n,e,t){let r=new Date().toISOString();return{payload:{lang:n,fileRel:e,preDeleted:!1,exportRows:[],nodeRows:[],referenceRows:[],symbolMentionRows:[],importRows:[],importBindingRows:[],fileRow:[e,t?.mtime??null,t?.size??null,"failed",r],fts:null,fullyIndexed:!1},fileSize:t?.size,mtime:t?.mtime}}function ye(n){let{lang:e,fileRel:t,content:r,meta:i,preDeleted:s,parsed:o,resolveNodeId:l,exportKind:c,fullyIndexed:u}=n,m=[],p=o.nodes??[],C=p.map(a=>{let f=`${t}#${a.start}-${a.end}:${Z.getAbbrev(a.kind,e)}`;return(e==="c"||e==="cpp"||e==="java"||e==="clojure")&&a.name?`${f}:${a.name}`:f});for(let a=0;a<p.length;a+=1){let f=p[a],h=f.rawKind??f.kind,N=f.rawKindSource??"cli",g=f.containerRawKind??f.containerKind??null,y=f.containerRawKindSource??(g?"cli":null),E=f.scopeChain??null,P=Array.isArray(E)?JSON.stringify(E):typeof E=="string"?E:null,j=C[a],S=typeof f.parentIndex=="number"?C[f.parentIndex]??null:f.parentNodeId??null,x=f.metadata&&Object.keys(f.metadata).length?JSON.stringify(f.metadata):null;m.push([j,f.name,f.kind,h,N,f.semanticKind??null,f.start,f.end,typeof f.isExported=="number"?f.isExported:0,f.containerKind??null,g,y,typeof f.paramCount=="number"?f.paramCount:null,f.qualifiedName??null,P,f.symbolKey??null,x,S,f.role??null,typeof f.indexInParent=="number"?f.indexInParent:null,typeof f.depth=="number"?f.depth:0,typeof f.bodyStart=="number"?f.bodyStart:null,typeof f.bodyEnd=="number"?f.bodyEnd:null])}let I=[],K=new Set;for(let a of pt(o)){if(!a.name||K.has(a.name))continue;K.add(a.name);let f=a.nodeId??(l?l(a.name):null);I.push([t,a.name,f??null,a.isReexport?1:0,a.reexportFrom??null,a.reexportName??null,a.exportKind??c??"cli",a.targetSymbolKey??null])}let R=[],F=[],O=new Map,U=new Map;for(let a of m){let f=a[0]!=null?String(a[0]):null,h=a[13]!=null?String(a[13]):null,N=a[15]!=null?String(a[15]):null;f&&(h&&!O.has(h)&&O.set(h,f),N&&!U.has(N)&&U.set(N,f))}if(oe()&&e==="clojure"&&(o.references??[]).length>0){let a=Array.from(O.keys()).slice(0,10),f=Array.from(U.keys()).slice(0,10),h=(o.references??[]).slice(0,10).map(g=>g.containerQualifiedName),N={file:t,nodeCount:m.length,refCount:(o.references??[]).length,nodeQualifiedNames:a,nodeSymbolKeys:f,refContainers:h,qualifiedNameMapSize:O.size,symbolKeyMapSize:U.size};try{console.error("[CliPayload][CLOJURE-DEBUG] source_node_id lookup context",N)}catch{}}for(let a of o.references??[]){let f=a.targetNodeId??(l&&a.refName?l(a.refName):null),h=a.targetFile??(f?t:null),N=a.sourceNodeId??(a.containerQualifiedName?O.get(a.containerQualifiedName)??null:null)??(a.containerQualifiedName?U.get(a.containerQualifiedName)??null:null),g=Re({sourceFile:t,sourceStart:a.sourceStart,sourceEnd:a.sourceEnd,refKind:a.refKind,refName:a.refName,targetFile:h??null,targetStart:a.targetStart??null,targetEnd:a.targetEnd??null,targetNodeId:f??a.targetNodeId??null}),y=a.metadata&&Object.keys(a.metadata).length?JSON.stringify(a.metadata):null;R.push([g,t,N,a.refName??null,a.refKind,a.sourceStart,a.sourceEnd,f??a.targetNodeId??null,h??null,f||a.targetNodeId||a.targetFile?"resolved":"unresolved",a.receiverName??null,typeof a.arity=="number"?a.arity:null,a.containerQualifiedName??null,a.targetSymbolKey??null,a.confidence??null,y])}for(let a of o.symbolMentions??[]){let f=typeof a?.name=="string"?a.name.trim():"";if(!f)continue;let h=typeof a?.mentionKind=="string"&&a.mentionKind.trim().length>0?a.mentionKind.trim():"reference",N=typeof a?.count=="number"&&Number.isFinite(a.count)&&a.count>0?Math.floor(a.count):1;F.push([f,h,a.targetSymbolKey??null,a.containerQualifiedName??null,N])}if(oe()&&e==="clojure"&&R.length>0){let a=R.reduce((h,N)=>h+(N?.[2]!=null?1:0),0),f=R.reduce((h,N)=>h+(N?.[12]!=null?1:0),0);try{console.error("[CliPayload] clojure source-node summary",{file:t,refs:R.length,sourceNodeCount:a,containerCount:f,sample:R.slice(0,5).map(h=>({sourceNodeId:h[2]==null?null:String(h[2]),refName:h[3],refKind:h[4],containerQualifiedName:h[12]}))})}catch{}}let z=[];for(let a of o.imports??[])z.push([t,a.module??null,a.isTypeOnly??0]);let V=[];for(let a of o.importBindings??[])V.push([t,a.module??null,a.kind,a.localName,a.importedName,a.isTypeOnly??0]);let fe=new Date().toISOString(),H=[t,i?.mtime??null,i?.size??null,"completed",fe,u?1:0];return{payload:{lang:e,fileRel:t,preDeleted:!!s,exportRows:I,nodeRows:m,referenceRows:R,symbolMentionRows:F,importRows:z,importBindingRows:V,fileRow:H,fts:typeof r=="string"?{blobOid:t,content:r}:null,fullyIndexed:!!u},fileSize:i?.size,mtime:i?.mtime}}var be=["ts","js","python","c","cpp","csharp","dart","java","clojure"];function Be(n){return typeof n=="string"&&be.includes(n)}gn();function mt(){let n=process.env.PANDO_ENABLED_LANGUAGES;if(n&&n.trim().length>0){let t=n.split(",").map(r=>r.trim()).filter(r=>r.length>0).filter(Be);if(t.length>0)return ft(t)}return[...be]}function ft(n){let e=new Set;for(let t of n)Be(t)&&e.add(t);return be.filter(t=>e.has(t))}function gt(n){let e=new Set(ft(n)),t={};for(let r of be){if(e.has(r)){t[r]={enabled:!0,source:"embedded"};continue}t[r]={enabled:!1,source:"none",reason:"disabled by language support config"}}return{byLanguage:t}}import Je from"path";import Nn from"fs";import{Project as Pn,Node as Q}from"ts-morph";import{Node as d,SyntaxKind as ae}from"ts-morph";import*as X from"typescript";import{SyntaxKind as xe}from"ts-morph";var $e={LINE_COMMENT:{kind:9001,name:"LineComment",triviaKind:xe.SingleLineCommentTrivia},BLOCK_COMMENT:{kind:9002,name:"BlockComment",triviaKind:xe.MultiLineCommentTrivia},JSDOC_COMMENT:{kind:9003,name:"JSDocComment",triviaKind:xe.MultiLineCommentTrivia}};function ht(n,e){return n===xe.SingleLineCommentTrivia?$e.LINE_COMMENT:n===xe.MultiLineCommentTrivia&&e.startsWith("/**")?$e.JSDOC_COMMENT:$e.BLOCK_COMMENT}import{Node as T}from"ts-morph";var yt={TS_MORPH:"ts-morph",PYTHON_AST:"python-ast",CLANG:"clang",ROSLYN:"roslyn",JAVA_AST:"java-ast",CLI:"cli",UNKNOWN:"unknown"},bt=(n,e)=>T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n)?{kind:"Function",semanticKind:"function"}:T.isGetAccessorDeclaration(n)||T.isSetAccessorDeclaration(n)?{kind:"Method",semanticKind:"property"}:T.isMethodDeclaration(n)||T.isMethodSignature(n)||T.isConstructorDeclaration(n)?{kind:"Method",semanticKind:"method"}:T.isClassDeclaration(n)||T.isClassExpression(n)?{kind:"Class",semanticKind:"class"}:T.isInterfaceDeclaration(n)?{kind:"Interface",semanticKind:"interface"}:T.isEnumDeclaration(n)?{kind:"Enum",semanticKind:"enum"}:T.isEnumMember(n)?{kind:"EnumMember",semanticKind:"enum"}:T.isTypeAliasDeclaration(n)?{kind:"TypeAlias",semanticKind:"type"}:T.isModuleDeclaration(n)?{kind:"Namespace",semanticKind:"namespace"}:T.isPropertyDeclaration(n)||T.isPropertySignature(n)?{kind:"Field",semanticKind:"property"}:T.isVariableDeclaration(n)?{kind:"Variable",semanticKind:"variable"}:{kind:e,semanticKind:null};function xt(n){try{let e=n.getKindName?.();if(typeof e=="string"&&e.trim())return e}catch{}return"Unknown"}function Ie(n){let e=xt(n),t=bt(n,e);return{kind:t.kind,semanticKind:t.semanticKind,rawKind:e,rawKindSource:yt.TS_MORPH}}function St(n){let e=xt(n);return{kind:bt(n,e).kind,rawKind:e,rawKindSource:yt.TS_MORPH}}function Ae(n,e){if(!n.kind||!n.kind.trim())throw new Error(`Invalid normalized kind: missing kind ${e?JSON.stringify(e):""}`);if(!n.rawKind||!n.rawKind.trim())throw new Error(`Invalid normalized kind: missing rawKind ${e?JSON.stringify(e):""}`);if(!n.rawKindSource||!String(n.rawKindSource).trim())throw new Error(`Invalid normalized kind: missing rawKindSource ${e?JSON.stringify(e):""}`)}function hn(n){if(n.kind==="local"){let r=n.isDefault?"default":n.name;return r?{name:r,priority:n.isDefault?4:3}:null}if(n.kind==="alias")return n.exported?{name:n.exported,priority:2}:null;let e=n.isNamespace??!1,t=n.alias||n.name||(e?"*":null);return t?{name:t,priority:e?0:1}:null}function yn(n){if(n.length<2)return n;let e=new Map;for(let t of n){let r=hn(t);if(!r)continue;let i=e.get(r.name);(!i||r.priority>i.priority)&&e.set(r.name,{record:t,priority:r.priority})}return Array.from(e.values()).map(t=>t.record)}function Se(n){try{if(n&&typeof n.getName=="function"){let e=n.getName();if(typeof e=="string"&&e.length>0)return e}}catch{}return null}function bn(n){try{let e=n?.getBody?.();if(!e||typeof e.getStart!="function"||typeof e.getEnd!="function")return null;let t=typeof e.getKindName=="function"?String(e.getKindName()):"",r=t==="Block"||t==="ModuleBlock",i=e.getStart(),s=e.getEnd(),o=r?i+1:i,l=r?s-1:s;return!Number.isFinite(o)||!Number.isFinite(l)||l<o?null:{start:o,end:l}}catch{return null}}function xn(n){let e=n.getParent?.();if(!e)return null;try{if(d.isIfStatement(e)){if(e.getExpression()===n)return"condition";if(e.getThenStatement()===n)return"then";if(e.getElseStatement()===n)return"else"}if(d.isReturnStatement(e)&&e.getExpression?.()===n)return"value";if(d.isVariableDeclaration(e)){if(e.getNameNode?.()===n)return"name";if(e.getInitializer?.()===n)return"initializer"}if(d.isCallExpression(e)||d.isNewExpression(e)){if(e.getExpression?.()===n)return"callee";if((e.getArguments?.()??[]).indexOf(n)>=0)return"argument"}if(d.isPropertyAccessExpression(e)){if(e.getExpression()===n)return"object";if(e.getNameNode()===n)return"property"}}catch{return null}return null}function ze(n){let e;try{let r=n.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let t;try{let r=n.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}if(t===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}function Sn(n){try{if(d.isFunctionDeclaration(n)||d.isMethodDeclaration(n)||d.isConstructorDeclaration(n)||d.isFunctionExpression(n)||d.isArrowFunction(n)){let e=n.getParameters?.();if(Array.isArray(e))return e.length}}catch{}return null}function Cn(n){try{return d.isIdentifier(n)?n.getSymbol():d.isPropertyAccessExpression(n)?n.getNameNode().getSymbol()??n.getSymbol():n.getSymbol?.()}catch{return}}function ke(n,e){try{return typeof n?.hasModifier=="function"&&n.hasModifier(e)}catch{return!1}}function Ct(n){try{return n.getModuleSpecifierValue?.()??null}catch{try{return n.getModuleSpecifier?.()?.getLiteralText?.()??null}catch{return null}}}function vn(n,e,t){if(!d.isImportDeclaration(n))return;let i={moduleSpecifier:Ct(n),isTypeOnly:n.isTypeOnly(),namedImports:[]};try{let s=n.getDefaultImport();if(s){let o=s.getText();i.defaultImport=o,t(o,s)}}catch{}try{let s=n.getNamespaceImport();if(s){let o=s.getText();i.namespaceImport=o,t(o,s)}}catch{}try{n.getNamedImports().forEach(s=>{try{let o=s.getName(),l=s.getAliasNode(),c=l?l.getText():void 0;o&&(i.namedImports.push({name:o,alias:c||void 0}),t(c||o,s.getNameNode()))}catch{}})}catch{}e.push(i)}function En(n,e){if(d.isExportDeclaration(n)){let t=Ct(n);if(t){if(n.getNamedExports().length>0)try{n.getNamedExports().forEach(r=>{try{let i=r.getName(),s=r.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(n.isNamespaceExport())try{let i=n.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{n.getNamedExports().forEach(r=>{try{let i=r.getName();if(!i)return;let s=r.getAliasNode(),o=s?s.getText():i;e.push({kind:"alias",local:i,exported:o})}catch{}})}catch{}return}if(d.isExportAssignment(n))try{let t=n.getExpression();if(t&&d.isIdentifier(t)){let r=t.getText();e.push({kind:"alias",local:r,exported:"default"})}}catch{}}function wn(n,e,t,r){if(!ke(n,ae.ExportKeyword))return;let i=ke(n,ae.DefaultKeyword);if(d.isVariableStatement(n)){try{let s=n.getDeclarationList().getDeclarations();for(let o of s){let l=Se(o)??o.getName?.()??null;if(l){t(l,o);let c=r(o);c&&e.push({kind:"local",name:l,isDefault:i,nodeId:c})}}}catch{}return}if(d.isFunctionDeclaration(n)||d.isClassDeclaration(n)||d.isInterfaceDeclaration(n)||d.isEnumDeclaration(n)||d.isTypeAliasDeclaration(n)||d.isModuleDeclaration(n)){let s=Se(n)||(i?"default":null),o=r(n);o&&e.push({kind:"local",name:s??"default",isDefault:i,nodeId:o})}}function vt(n,e,t,r){let i=[],s=[],o=[],l=new Set,c=new Map,u=[],m=[],C=(r?.emitMode??"light")==="full",I=new Map,K=new Map,R=new Map,F=[{node:n,id:null,kind:"module",rawKind:"SourceFile",rawKindSource:"ts-morph",name:null,isExported:!1}],O=a=>{if(!a)return null;try{return e(a)}catch{return null}},U=a=>{let f=a.getParent?.();for(;f;){let h=I.get(f);if(h)return h;f=f.getParent?.()}return null},z=(a,f)=>{if(a&&(l.has(a)||l.add(a),f&&!c.has(a))){let h=O(f);h&&c.set(a,h)}},V=a=>d.isFunctionDeclaration(a)||d.isFunctionExpression(a)||d.isArrowFunction(a)||d.isClassDeclaration(a)||d.isClassExpression(a)||d.isInterfaceDeclaration(a)||d.isEnumDeclaration(a)||d.isEnumMember(a)||d.isTypeAliasDeclaration(a)||d.isModuleDeclaration(a)||d.isMethodDeclaration(a)||d.isMethodSignature(a)||d.isPropertyDeclaration(a)||d.isPropertySignature(a)||d.isGetAccessorDeclaration(a)||d.isSetAccessorDeclaration(a)||d.isConstructorDeclaration(a)||d.isVariableDeclaration(a),fe=a=>d.isSourceFile(a)||d.isFunctionDeclaration(a)||d.isFunctionExpression(a)||d.isArrowFunction(a)||d.isMethodDeclaration(a)||d.isConstructorDeclaration(a)||d.isClassDeclaration(a)||d.isClassExpression(a)||d.isModuleDeclaration(a),H=a=>{let f=Se(a);if(f)return f;if(d.isConstructorDeclaration(a))return"constructor";if(d.isArrowFunction(a)||d.isFunctionExpression(a)){let h=a.getParent();try{if(d.isVariableDeclaration(h))return h.getName();if(d.isPropertyAssignment(h)||d.isPropertyDeclaration(h)||d.isPropertySignature(h))return h.getName?.()??null;if(d.isShorthandPropertyAssignment(h))return h.getNameNode()?.getText()??null;if(d.isExportAssignment(h))return"default"}catch{}}if(d.isEnumMember(a))try{return a.getName()}catch{return null}if(d.isVariableDeclaration(a))try{return a.getName()}catch{return null}return null},Y=a=>{let f=F[F.length-1],h=f?.id??null,N=f?.kind??"module",g=f?.name??null;if(d.isImportDeclaration(a))vn(a,u,z);else if(d.isImportEqualsDeclaration(a))try{let S=a.getModuleReference();if(S&&d.isExternalModuleReference(S)){let x=S.getExpression(),v;if(x&&d.isStringLiteral(x))v=x.getLiteralText();else if(x){let w=x.getText();v=typeof w=="string"?w.replace(/^['"]|['"]$/g,""):void 0}if(v){let M=a.getNameNode()?.getText(),_={moduleSpecifier:v,isTypeOnly:!1,namedImports:[]};M&&(_.defaultImport=M,z(M,a)),u.push(_)}}}catch{}(d.isExportDeclaration(a)||d.isExportAssignment(a))&&En(a,m),wn(a,m,z,O);let y=V(a),E=C||y,P=y?H(a):null;if(E){let S=e(a);y&&s.push({nodeId:S,node:a});let x=U(a),v=x==null?null:K.get(x)??0;x!=null&&v!=null&&K.set(x,v+1),I.set(a,S);let w=x?(R.get(x)??-1)+1:0;R.set(S,w);let M=ke(a,ae.ExportKeyword)||f?.isExported||!1,_=y?a.getNameNode?.()?.getText?.()??null:null,D=P??(y?Se(a)??_:Se(a));P?z(P,a):D&&z(D,a);let A=ze(a),L=Sn(a),k=Ie(a);Ae(k,{source:"ts-node-collector",file:n.getFilePath(),name:D??null});let J=bn(a);i.push({nodeId:S,nodeName:D??null,containerId:h,containerKind:N,containerRawKind:f?.rawKind??null,containerRawKindSource:f?.rawKindSource??null,containerName:g,isExported:M,kind:k.kind,rawKind:k.rawKind,rawKindSource:k.rawKindSource,semanticKind:k.semanticKind??null,start:A.start,end:A.end,paramCount:L,metadata:null,parentNodeId:x,role:xn(a),indexInParent:v,depth:w,bodyStart:J?.start??null,bodyEnd:J?.end??null})}if(d.isCallExpression(a)||d.isNewExpression(a)){let S=a.getExpression(),x=null,v,w;try{if(w=Cn(S),d.isIdentifier(S))x=S.getText();else if(d.isPropertyAccessExpression(S)){x=S.getName();let D=S.getExpression();d.isIdentifier(D)&&(v=D.getText())}}catch{}let M="";try{M=S.getText()}catch{}let _=ze(a);if(o.push({name:x,kind:d.isNewExpression(a)?"new":"call",containerId:h,containerKind:N,containerName:g,expression:M,objectName:v,symbol:w,start:_.start,end:_.end}),d.isCallExpression(a))try{if(d.isIdentifier(S)&&S.getText()==="require"){let A=a.getArguments()[0],L;if(A&&(d.isStringLiteral(A)||d.isNoSubstitutionTemplateLiteral(A)))try{L=A.getLiteralText()}catch{let k=A.getText();L=typeof k=="string"?k.replace(/^['"]|['"]$/g,""):void 0}if(L){let k={moduleSpecifier:L,isTypeOnly:!1,namedImports:[]},J=a.getParent();if(J&&d.isVariableDeclaration(J)){let Pe=J.getNameNode();try{if(d.isIdentifier(Pe)){let ge=Pe.getText();ge&&(k.defaultImport=ge,z(ge,J))}}catch{}}u.push(k)}}else if(S?.getKind?.()===ae.ImportKeyword){let A=a.getArguments()[0],L;if(A&&(d.isStringLiteral(A)||d.isNoSubstitutionTemplateLiteral(A)))try{L=A.getLiteralText()}catch{let k=A.getText();L=typeof k=="string"?k.replace(/^['"]|['"]$/g,""):void 0}L&&u.push({moduleSpecifier:L,isTypeOnly:!1,namedImports:[]})}}catch{}}if(d.isCallExpression(a)){let S=a.getExpression();try{if(d.isIdentifier(S)&&S.getText()==="require"){let x=a.getParent();if(!(x&&d.isExternalModuleReference(x))){let w=a.getArguments()[0],M;if(w&&(d.isStringLiteral(w)||d.isNoSubstitutionTemplateLiteral(w)))try{M=w.getLiteralText()}catch{M=w.getText().replace(/^['"]|['"]$/g,"")}if(M){let _={moduleSpecifier:M,isTypeOnly:!1,namedImports:[]};if(x&&d.isVariableDeclaration(x)){let D=x.getNameNode();try{if(d.isIdentifier(D)){let A=D.getText();A&&(_.defaultImport=A,z(A,x))}}catch{}}u.push(_)}}}else if(S?.getKind?.()===ae.ImportKeyword){let v=a.getArguments()[0],w;if(v&&(d.isStringLiteral(v)||d.isNoSubstitutionTemplateLiteral(v)))try{w=v.getLiteralText()}catch{w=v.getText().replace(/^['"]|['"]$/g,"")}w&&u.push({moduleSpecifier:w,isTypeOnly:!1,namedImports:[]})}}catch{}}let j=!1;if(fe(a)){let S=O(a)??e(a),x=St(a);F.push({node:a,id:S,kind:x.kind,rawKind:x.rawKind,rawKindSource:x.rawKindSource,name:P??g,isExported:ke(a,ae.ExportKeyword)||f?.isExported||!1}),j=!0}a.forEachChild(Y),j&&F.pop()};if(C){let a=e(n);I.set(n,a),R.set(a,0);let f=ze(n);i.push({nodeId:a,nodeName:n.getBaseName?.()??null,containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:"SourceFile",rawKind:"SourceFile",rawKindSource:"ts-morph",semanticKind:"file",start:f.start,end:f.end,paramCount:null,metadata:null,parentNodeId:null,role:null,indexInParent:null,depth:0,bodyStart:f.start,bodyEnd:f.end})}if(n.forEachChild(Y),r?.includeComments===!0||C||process.env.AST_INDEX_COMMENTS==="1")try{let a=n.getFullText(),f=X.createScanner(X.ScriptTarget.Latest,!1,X.LanguageVariant.Standard,a),h=new Set;for(let N=f.scan();N!==X.SyntaxKind.EndOfFileToken;N=f.scan()){if(N!==X.SyntaxKind.SingleLineCommentTrivia&&N!==X.SyntaxKind.MultiLineCommentTrivia)continue;let g=f.getTokenPos(),y=f.getTextPos(),E=`${g}-${y}`;if(h.has(E)||(h.add(E),t.has(E)))continue;t.add(E);let P=a.substring(g,y),j=ht(N,P),x=e({getKindName:()=>j.name,getKind:()=>j.kind,getPos:()=>g,getEnd:()=>y,getStart:()=>g,getFullStart:()=>g,getText:()=>P,getSourceFile:()=>n,getParent:()=>n,__isComment:!0,__commentPosition:"standalone",__attachedTo:null},"COM"),v=I.get(n)??null,w=C&&v!=null?K.get(v)??0:null;C&&v!=null&&w!=null&&K.set(v,w+1),i.push({nodeId:x,nodeName:P.substring(0,100),containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:j.name,rawKind:j.name,rawKindSource:"ts-morph",semanticKind:null,start:g,end:y,paramCount:null,metadata:null,parentNodeId:v,role:"comment",indexInParent:w,depth:C?1:0,bodyStart:null,bodyEnd:null})}}catch{}return{nodes:i,symbolCandidateNodes:s,references:o,declaredNames:l,localDeclarations:c,imports:u,exports:yn(m)}}function Et(n){let e;try{let r=n.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let t;try{let r=n.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}if(t===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}var Rn=100;function In(n,e,t,r){let{start:i,end:s}=Et(e),o=Ie(e);Ae(o,{source:"ts-node-id",file:n,kind:o.kind});let l=r||Z.getAbbrev(o.kind,t);return`${n}#${i}-${s}:${l}`}function An(n,e){return Je.relative(n,e).replace(/\\/g,"/")}function wt(n,e){if(!n)return null;let t=n;try{let m=n.getAliasedSymbol();m&&(t=m)}catch{}let r=[];try{r=t.getDeclarations()??[]}catch{r=[]}if(!r.length)return null;let s=r.slice().sort((m,p)=>{let C=m.getSourceFile().getFilePath(),I=p.getSourceFile().getFilePath();if(C!==I)return C.localeCompare(I);let K=m.getStart(!1),R=p.getStart(!1);return K!==R?K-R:m.getEnd()-p.getEnd()})[0],o=An(e,s.getSourceFile().getFilePath()),l=s.getStart(!1),c=s.getEnd(),u="";try{u=t.getEscapedName()}catch{try{u=t.getName()}catch{u=""}}return`${o}#${l}-${c}:${u}`}function kn(n){try{return Q.isVariableDeclaration(n)||Q.isEnumMember(n)?n.getNameNode().getSymbol()??n.getSymbol():n.getSymbol()}catch{return}}function Mn(n,e){let t=n.getDescendantAtPos(e);if(!t)return;let r=t;if(!Q.isCallExpression(r)&&!Q.isNewExpression(r)&&(r=t.getFirstAncestor(s=>Q.isCallExpression(s)||Q.isNewExpression(s))??void 0),!r||!Q.isCallExpression(r)&&!Q.isNewExpression(r))return;let i=r.getExpression();try{return Q.isIdentifier(i)?i.getSymbol():Q.isPropertyAccessExpression(i)?i.getNameNode().getSymbol()??i.getSymbol():i.getSymbol()}catch{return}}async function Dn(n){let{sf:e,fileRel:t,content:r,preDeleted:i,meta:s,projectRoot:o,lang:l}=n,c=n.emitMode??"light",m=vt(e,(g,y)=>In(t,g,l,y),new Set,{includeComments:c==="full",emitMode:c}),p=new Map;for(let{nodeId:g,node:y}of m.symbolCandidateNodes){let E=wt(kn(y),o);E&&(p.has(g)||p.set(g,E))}let C=[],I=new Map,K=m.exports.filter(g=>g.kind!=="reexport"),R=m.exports.filter(g=>g.kind==="reexport");for(let g of K)if(g.kind==="local"){let y=g.isDefault?"default":g.name;if(!y||I.has(y))continue;let E=g.nodeId;C.push([t,y,E,0,null,null,g.isDefault?"default":"named"]),I.set(y,E)}else if(g.kind==="alias"){let y=g.exported;if(!y||I.has(y))continue;C.push([t,y,null,0,null,g.local,"alias"]),I.set(y,"alias")}for(let g of R){let y=g.moduleSpecifier;if(!y)continue;let E=y;if(g.isNamespace){let P=g.alias||"*";if(I.has(P))continue;C.push([t,P,null,1,E,g.name||P,"reexport_star"]),I.set(P,"reexport")}else{let P=g.alias||g.name;if(!P||I.has(P))continue;C.push([t,P,null,1,E,g.name||P,"reexport_named"]),I.set(P,"reexport")}}let F=[],O=typeof r=="string"?r:null;if(O==null)try{let g=e.getFullText();O=typeof g=="string"?g:null}catch{O=null}for(let g of m.nodes){let{nodeId:y,nodeName:E,containerKind:P,containerRawKind:j,containerRawKindSource:S,isExported:x,kind:v,rawKind:w,rawKindSource:M,semanticKind:_,start:D,end:A,paramCount:L,metadata:k,parentNodeId:J,role:Pe,indexInParent:ge,depth:cn,bodyStart:un,bodyEnd:dn}=g,pn=k&&Object.keys(k).length?JSON.stringify(k):null,mn=p.get(y)??null;F.push([y,E??null,v,w??v,M??null,_??null,D,A,x?1:0,P??"module",j??P??"module",S??null,L,null,null,mn,pn,J??null,Pe??null,ge??null,cn??0,un??null,dn??null])}let U=[];for(let g of m.references){let{name:y,kind:E,containerId:P,containerName:j,expression:S,objectName:x,start:v,end:w}=g,M=null,_=null,D=wt(g.symbol??Mn(e,v),o),A=y?m.localDeclarations.get(y):void 0;A&&(M=A,_=t,D||(D=p.get(A)??null));let L=Re({sourceFile:t,sourceStart:v,sourceEnd:w,refKind:E,refName:y,targetFile:_,targetNodeId:M}),k={};S&&(k.expression=S),x&&(k.objectName=x),j&&(k.containerName=j);let J=Object.keys(k).length?JSON.stringify(k):null;U.push([L,t,P,y,E,v,w,M,_,M?"resolved":"unresolved",x??null,null,null,D,J])}let z=[],V=[];for(let g of m.imports){let y=g.moduleSpecifier??null;z.push([t,y,g.isTypeOnly?1:0]),g.defaultImport&&V.push([t,y,"default",g.defaultImport,"default",g.isTypeOnly?1:0]),g.namespaceImport&&V.push([t,y,"namespace",g.namespaceImport,"*",g.isTypeOnly?1:0]);for(let E of g.namedImports){let P=E.alias||E.name;V.push([t,y,"named",P,E.name,g.isTypeOnly?1:0])}}let fe=Je.join(o,t),H=s?.size,Y=s?.mtime;if(H===void 0||Y===void 0)try{let g=Nn.statSync(fe);H=g.size,Y=Math.floor(g.mtimeMs)}catch{}let a=new Date().toISOString(),f=c==="full",h=[t,Y??null,H??null,"completed",a,f?1:0],N=null;if(typeof O=="string")N={blobOid:t,content:O};else try{let g=e.getFullText?.();typeof g=="string"&&(N={blobOid:t,content:g})}catch(g){console.log(`[TypescriptIndexer] Failed to compute FTS payload for ${t}:`,g?.message??g)}return{payload:{lang:l,fileRel:t,preDeleted:i,exportRows:C,nodeRows:F,referenceRows:U,importRows:z,importBindingRows:V,fileRow:h,fts:N,fullyIndexed:f},fileSize:H,mtime:Y}}var qe=class{constructor(e,t){this.project=null;this.filesProcessed=0;this.projectRoot=e,this.lang=t}getProject(){return this.project||(this.project=new Pn({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(),r;try{let i=t.createSourceFile(Je.join(this.projectRoot,e.relPath),e.content,{overwrite:!0});r=await Dn({sf:i,fileRel:e.relPath,content:e.content,preDeleted:!!e.preDeleted,meta:e.meta,projectRoot:this.projectRoot,lang:e.lang,emitMode:e.emitMode??"light"})}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>=Rn&&(this.disposeProject(),this.filesProcessed=0),{payload:r.payload,fileSize:r.fileSize,mtime:r.mtime}}};function Tn(n){return n==="ts"?[".ts",".tsx",".mts",".cts"]:n==="js"?[".js",".jsx",".mjs",".cjs"]:[]}function We(n){return{id:n,extensions:Tn(n),indexingMode:"worker",createIndexer:e=>new qe(e,n)}}import De from"fs";import ee from"path";import{spawn as Ln}from"child_process";import Kn from"fs";var le=class{constructor(e=5e3){this.maxEntries=e;this.cache=new Map}get(e,t){let r=this.cache.get(e);if(!r)return null;let i=t?.mtime??null,s=t?.size??null;return i!=null&&s!=null&&r.mtime===i&&r.size===s?r.result:null}set(e,t,r){let i=t?.mtime??null,s=t?.size??null;this.cache.set(e,{mtime:i,size:s,result:r}),this.cache.size>this.maxEntries&&this.cache.clear()}};var Ue=class{constructor(e,t,r,i){this.projectRoot=e;this.lang=t;this.parse=r;this.exportKind=i;this.cache=new le}async process(e){let t=e.meta?.mtime,r=e.meta?.size;if(t==null||r==null)try{let o=Kn.statSync(e.absPath);t=Math.floor(o.mtimeMs),r=o.size}catch{}let i=e.emitMode==="full"?null:this.cache.get(e.absPath,{mtime:t,size:r});if(i)return ye({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:r},preDeleted:e.preDeleted,parsed:i,resolveNodeId:Nt(e.relPath,i,this.lang),exportKind:this.exportKind??"cli",fullyIndexed:e.emitMode==="full"});let s=null;try{s=await this.parse({absPath:e.absPath,relPath:e.relPath,content:e.content,meta:{mtime:t,size:r},projectRoot:this.projectRoot,lang:this.lang,emitMode:e.emitMode??"light"})}catch(o){try{console.log(`[CliContract:${this.lang}] parse threw for ${e.relPath}: ${o?.message||String(o)}`)}catch{}return he(this.lang,e.relPath,{mtime:t,size:r})}return!s||s.error?he(this.lang,e.relPath,{mtime:t,size:r}):(e.emitMode!=="full"&&this.cache.set(e.absPath,{mtime:t,size:r},s),ye({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:r},preDeleted:e.preDeleted,parsed:s,resolveNodeId:Nt(e.relPath,s,this.lang),exportKind:this.exportKind??"cli",fullyIndexed:e.emitMode==="full"}))}};function Nt(n,e,t){let r=new Map;for(let i of e.nodes??[]){if(!i.name||r.has(i.name))continue;let s=`${n}#${i.start}-${i.end}:${Z.getAbbrev(i.kind,t)}`;r.set(i.name,s)}return i=>r.get(i)??null}function G(n){return{id:n.id,extensions:n.extensions,indexingMode:"worker",createIndexer:e=>new Ue(e,n.id,n.parse,n.exportKind),resolveSpan:n.resolve?async(e,t,r)=>n.resolve({projectRoot:e,absPath:t,nodePath:r,lang:n.id}):void 0}}import _n from"fs";import Me from"path";var Xe=null;function On(n){for(let e of n)if(_n.existsSync(e))return e;return null}function q(n){let e=Xe?.toolsRoot??process.env.PANDO_TOOLS_ROOT,t=Xe?.runtimeRoot??process.env.PANDO_RUNTIME_ROOT,r=Xe?.resourcesRoot??process.env.PANDO_RESOURCES_ROOT,i=[e?Me.join(e,n):null,t?Me.join(t,"tools",n):null,r?Me.join(r,"tools",n):null,Me.resolve(process.cwd(),"tools",n)].filter(s=>!!s);return On(i)}function W(...n){try{let e=n.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 Fn=Number(process.env.PANDO_PYTHON_WORKER_PARSE_TIMEOUT_MS||18e4),jn=Number(process.env.PANDO_PYTHON_WORKER_RESOLVE_TIMEOUT_MS||6e4),de=class extends Error{constructor(t,r){super(t);this.fatal=r;this.name="PythonWorkerRequestError"}},Te=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=Ln(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",r=>this.onData(r)),this.proc.stderr.on("data",r=>{W(`[PythonWorker] ${r.toString("utf8").trim()}`)}),this.proc.stdin.on("error",r=>this.handleError(r)),this.proc.on("error",r=>this.handleError(r)),this.proc.on("exit",r=>this.handleError(new Error(`python worker exited with code ${r}`))),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&&W("[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 r=this.buffer.slice(4,4+t);this.buffer=this.buffer.slice(4+t);let i=null;try{i=JSON.parse(r.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 de(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"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0),this.proc.stdin.write(r),this.proc.stdin.write(t)}async requestRaw(e,t,r=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((l,c)=>{let u=setTimeout(()=>{this.pending.delete(i);let m=new de(`python worker timeout (${e})`,!0);W("[PythonCliAdapter] worker timeout",{op:e,id:i,timeoutMs:r,pending:this.pending.size,interpreter:this.interpreter,...o}),c(m),this.handleError(m)},r);this.pending.set(i,{resolve:l,reject:c,timeout:u,summary:o}),this.pending.size%200===0&&W("[PythonCliAdapter] worker pending",{op:e,pending:this.pending.size,interpreter:this.interpreter});try{this.sendMessage(s)}catch(m){clearTimeout(u),this.pending.delete(i),c(m)}})}async enqueueRequest(e){let t=this.requestQueue.catch(()=>{}),r,i=new Promise(s=>{r=s});this.requestQueue=t.then(()=>i),await t;try{return await e()}finally{r()}}async request(e,t,r=1e4){await this.ready;let i=Date.now();return this.enqueueRequest(async()=>{let s=Date.now()-i,o=Date.now();s>2e3&&W("[PythonCliAdapter] worker queued",{op:e,queueMs:s,interpreter:this.interpreter,path:t?.path});let l=await this.requestRaw(e,t,r),c=Date.now()-o;return c>2e3&&W("[PythonCliAdapter] worker slow",{op:e,ms:c,queueMs:s,pending:this.pending.size,interpreter:this.interpreter,path:t?.path}),l})}async ping(){await this.requestRaw("ping",{},5e3)}async parse(e){let t=Buffer.from(e.content,"utf8").toString("base64"),r=await this.request("parse",{path:e.path,content_b64:t,encoding:e.encoding,emit_mode:e.emitMode??"light"},Fn);return r.nodes?r:null}async resolve(e){let t=Buffer.from(e.content,"utf8").toString("base64"),r=await this.request("resolve",{path:e.path,nodePath:e.nodePath,content_b64:t,encoding:e.encoding},jn);return typeof r.start=="number"&&typeof r.end=="number"?r: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{}}};function Pt(n){let e=ee.resolve(n,"tools/python-indexer/pando_python_worker.py");if(De.existsSync(e))return e;let t=q("python-indexer/pando_python_worker.py");if(t)return t;let r=ee.resolve(__dirname,"../../../../../tools/python-indexer/pando_python_worker.py");return De.existsSync(r)?r:null}var ue=new Map;function ce(n){try{return De.readFileSync(n,"utf8")}catch{return null}}function Ce(n){if(!n)return null;let e=n.match(/(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2])}:null}function Bn(n){let e=ce(ee.join(n,"pyproject.toml"));if(e){let l=e.match(/requires-python\s*=\s*"([^"]+)"/i),c=Ce(l?.[1]??null);if(c)return c}let t=ce(ee.join(n,"setup.cfg"));if(t){let l=t.match(/python_requires\s*=\s*([\w\d\.<>~=\s]+)/i),c=Ce(l?.[1]??null);if(c)return c}let r=ce(ee.join(n,"setup.py"));if(r){let l=r.match(/python_requires\s*=\s*['\"]([^'\"]+)['\"]/i),c=Ce(l?.[1]??null);if(c)return c}let i=ce(ee.join(n,"tox.ini"));if(i){let l=i.match(/envlist\s*=\s*([^\n]+)/i);if(l&&l[1]){let c=l[1].split(/[,\s]+/).filter(Boolean);for(let u of c){let m=u.match(/py(\d)(\d)/i);if(m)return{major:Number(m[1]),minor:Number(m[2])}}}}let s=ce(ee.join(n,".python-version"));if(s){let l=Ce(s.trim());if(l)return l}let o=ce(ee.join(n,"runtime.txt"));if(o){let l=o.match(/python-(\d+\.\d+)/i),c=Ce(l?.[1]??null);if(c)return c}return null}function Rt(n){return Bn(n)?.major===2?["python2","python","python3"]:["python3","python","python2"]}async function $n(n,e,t,r){let i=Pt(n);if(!i)return null;let s=Rt(n);for(let o of s){let l=`${o}::${i}`,c=ue.get(l);if(!c)try{c=new Te(o,i),ue.set(l,c)}catch{continue}try{let u=await c.parse({path:e,content:t,encoding:"utf-8",emitMode:r});if(u)return u}catch(u){let m=u?.message||String(u),p=u instanceof de?u.fatal:/timeout|closed|exited|EPIPE|ENOENT|spawn/i.test(m);W("[PythonCliAdapter] worker parse error",{file:e,interpreter:o,script:i,fatal:p,error:m}),p&&ue.delete(l)}}return null}async function zn(n,e,t,r){let i=Pt(n);if(!i)return null;let s=Rt(n);for(let o of s){let l=`${o}::${i}`,c=ue.get(l);if(!c)try{c=new Te(o,i),ue.set(l,c)}catch{continue}try{let u=await c.resolve({path:e,nodePath:r,content:t,encoding:"utf-8"});if(u)return u}catch(u){let m=u?.message||String(u),p=u instanceof de?u.fatal:/timeout|closed|exited|EPIPE|ENOENT|spawn/i.test(m);W("[PythonCliAdapter] worker resolve error",{file:e,interpreter:o,nodePath:r,script:i,fatal:p,error:m}),p&&ue.delete(l)}}return null}async function qn(n){let e=Date.now(),t=!1,r=null;try{r=await $n(n.projectRoot,n.absPath,n.content,n.emitMode??"light"),t=!!r}catch{}if(!r){W(`[PythonCliAdapter] parse failed for ${n.relPath} via python worker`);let o=Date.now()-e;return o>2e3&&W("[PythonCliAdapter] parse slow (failed)",{file:n.relPath,ms:o}),null}let i=[];for(let o of r.references||[]){let l={};o.expression&&(l.expression=o.expression),o.objectName&&(l.objectName=o.objectName),o.containerName&&(l.containerName=o.containerName),o.containerKind&&(l.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(l).length?l:null})}let s=Date.now()-e;return s>2e3&&W("[PythonCliAdapter] parse slow",{file:n.relPath,ms:s,usedWorker:t}),{nodes:r.nodes,imports:r.imports,importBindings:r.importBindings,references:i,modulePublic:r.modulePublic??void 0,explicitExports:r.explicitExports??void 0}}function It(){return G({id:"python",extensions:[".py",".pyw",".pyi"],exportKind:"named",parse:({absPath:n,relPath:e,projectRoot:t,content:r,emitMode:i})=>qn({absPath:n,relPath:e,projectRoot:t,content:r,emitMode:i}),resolve:async({absPath:n,nodePath:e,projectRoot:t})=>{try{let r=De.readFileSync(n,"utf8"),i=await zn(t,n,r,e);if(i)return i}catch{}return null}})}import At from"fs";import kt from"path";import{spawn as Jn,spawnSync as Wi}from"child_process";var Wn=256e3,Un=32;function ne(...n){try{let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
|
|
3
|
+
`)}catch{}}var Qe=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=Jn(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=>{ne(`[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(`
|
|
4
|
+
`);if(t<0)break;let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!r)continue;let i=null;try{i=JSON.parse(r)}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 r=this.seq++;return new Promise((i,s)=>{let o={id:r,...e};this.pending.set(r,{resolve:i,reject:s});try{this.proc.stdin.write(`${JSON.stringify(o)}
|
|
5
|
+
`)}catch(l){if(this.pending.delete(r),t>0){try{this.handleExit(l)}catch{}return this.request(e,t-1).then(i,s)}s(l)}})}async parseBatch(e){let t=await this.request({op:"parse",files:e});return"results"in t?t.results.map(r=>r.ok&&r.result?r.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{}}}},Ge=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((t,r)=>{this.queue.push({input:e,resolve:t,reject:r,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<Un;){let r=this.queue[0];if(e.length>0&&t+r.input.size>Wn)break;e.push(this.queue.shift()),t+=r.input.size}try{let r=await this.client.parseBatch(e.map(i=>({file:i.input.file,root:i.input.root,lang:i.input.lang,emitMode:i.input.emitMode})));for(let i=0;i<e.length;i+=1){let s=e[i],o=r[i]??null,l=Date.now()-s.startedAt;l>2e3&&ne(`[${new Date().toISOString()}] [CSharpCliAdapter] parse slow`,{file:s.input.file,ms:l,path:"custom",ok:!!o}),o||ne(`[${new Date().toISOString()}] [CSharpCliAdapter] parse failed`,{file:s.input.file,ms:l,path:"custom"}),s.resolve(o)}}catch(r){for(let i of e)i.reject(r)}}}},Mt=new Map,Dt=new Map;function Xn(n){let e=process.platform==="win32"?".cmd":"",t=q(`csharp-indexer/bin/pando-csharp-indexer${e}`);if(t)return t;if(n){let i=kt.resolve(n,"tools/csharp-indexer/bin/pando-csharp-indexer"+e);if(At.existsSync(i))return i}let r=kt.resolve(__dirname,"../../../../../tools/csharp-indexer/bin/pando-csharp-indexer"+e);return At.existsSync(r)?r:null}function Tt(n){let e=process.env.PANDO_CSHARP_INDEXER_CMD||Xn(n);if(!e)return null;let t=Mt.get(e);t||(t=new Qe(e),Mt.set(e,t));let r=Dt.get(e);return r||(r=new Ge(t),Dt.set(e,r)),{client:t,batcher:r}}async function Qn(n,e,t,r){let i=Tt(e);if(!i)return null;try{return await i.batcher.enqueue({file:n,root:e,lang:"csharp",size:t,emitMode:r})}catch(s){return ne(`[${new Date().toISOString()}] [CSharpCliAdapter] parse error`,{file:n,error:s?.message||s,path:"custom"}),null}}async function Gn(n,e,t,r){let i=await Qn(n,e,t,r);return i||null}function Kt(){return G({id:"csharp",extensions:[".cs",".csx",".cshtml",".razor"],parse:({absPath:n,projectRoot:e,content:t,meta:r,emitMode:i})=>{let s=r?.size??Buffer.byteLength(t,"utf8");return Gn(n,e,s,i??"light")},resolve:({absPath:n,nodePath:e,projectRoot:t})=>{let r=Date.now(),i=Tt(t);return i?i.client.resolve({file:n,root:t,lang:"csharp",nodePath:e}).then(s=>{let o=Date.now()-r;return o>2e3&&ne(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve slow`,{file:n,ms:o}),s||ne(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve failed`,{file:n,ms:o,nodePath:e}),s}).catch(s=>{let o=Date.now()-r;return ne(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve error`,{file:n,ms:o,nodePath:e,error:s?.message||s}),null}):null}})}import{spawnSync as or}from"child_process";import ar from"fs";import Ye from"path";import $ from"fs";import b from"path";var ve=new Map,Vn=["include","src","lib","libs","third_party","third-party","deps","vendor","build","build/src","build_pando","build_pando/src"],Ve=["build","out","build-debug","build-release","cmake-build-debug","cmake-build-release","build_pando"],Lt=new Set([".c",".cc",".cpp",".cxx",".c++",".cp",".m",".mm"]),Ft=new Set([".h",".hh",".hpp",".hxx",".h++",".inl",".ipp",".tcc"]);function me(n){let e=[],t="",r=null,i=!1;for(let s=0;s<n.length;s+=1){let o=n[s];if(i){t+=o,i=!1;continue}if(o==="\\"){i=!0;continue}if(r){o===r?r=null:t+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(o===" "||o===`
|
|
6
|
+
`||o===" "||o==="\r"){t&&(e.push(t),t="");continue}t+=o}return t&&e.push(t),e}function Hn(n,e){let t=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(i==="-c")continue;if(i==="-o"){r+=1;continue}if(i===e)continue;let s=b.extname(i).toLowerCase();Lt.has(s)||t.push(i)}return t}function jt(n,e){return b.isAbsolute(n)?b.resolve(n):e?b.resolve(e,n):b.resolve(n)}function Yn(n){try{let e=$.readFileSync(n,"utf8"),t=JSON.parse(e),r=new Map,i=[];for(let s of t){let o=s.directory?b.resolve(s.directory):void 0,l=s.file?jt(s.file,o):null;if(!l)continue;let c=o??b.dirname(l),u=Array.isArray(s.arguments)?s.arguments:s.command?me(s.command):[];if(u.length===0)continue;let p={args:Hn(u.slice(1),l),cwd:c,file:l};r.set(l,p),i.push(p)}return{map:r,entries:i}}catch{return null}}function Zn(n){try{let e=$.readFileSync(n,"utf8");return me(e.replace(/\r/g,`
|
|
7
|
+
`))}catch{return null}}function Bt(n){let e=b.join(n,"compile_commands.json");if($.existsSync(e))return e;for(let o of Ve){let l=b.join(n,o,"compile_commands.json");if($.existsSync(l))return l}let t=Ve.map(o=>b.join(n,o)).filter(o=>$.existsSync(o));t.push(n);let r=10,i=new Set,s=(o,l)=>{if(l>r)return null;let c=b.resolve(o);if(i.has(c))return null;i.add(c);try{let u=$.readdirSync(o,{withFileTypes:!0});for(let m of u)if(m.isFile()&&m.name==="compile_commands.json")return b.join(o,m.name);for(let m of u){if(!m.isDirectory()||m.name==="node_modules"||m.name.startsWith("."))continue;let p=s(b.join(o,m.name),l+1);if(p)return p}}catch{}return null};for(let o of t){let l=s(o,0);if(l)return l}return null}function er(n,e){let t=b.resolve(n),r=b.resolve(e);for(;;){let i=Bt(t);if(i)return i;if(t===r)break;let s=b.dirname(t);if(s===t)break;t=s}return null}function $t(n){let e=b.join(n,"compile_flags.txt");if($.existsSync(e))return e;for(let t of Ve){let r=b.join(n,t,"compile_flags.txt");if($.existsSync(r))return r}return null}function tr(n,e){let t=b.resolve(n),r=b.resolve(e);for(;;){let i=$t(t);if(i)return i;if(t===r)break;let s=b.dirname(t);if(s===t)break;t=s}return null}function Ee(n){if(n)try{return $.statSync(n).mtimeMs}catch{return}}function nr(n){let e=[],t=new Set([".clangd","CMakeLists.txt","meson.build","meson_options.txt","Makefile","makefile","GNUmakefile","configure.ac","configure.in"]),r=5,i=200,s=(o,l)=>{if(l>r||e.length>=i)return;let c;try{c=$.readdirSync(o,{withFileTypes:!0})}catch{return}for(let u of c){if(e.length>=i)break;let m=b.join(o,u.name);u.isFile()&&(t.has(u.name)||u.name.endsWith(".cmake"))&&e.push(m)}for(let u of c){if(e.length>=i)break;u.isDirectory()&&(u.name==="node_modules"||u.name===".git"||u.name===".pando"||u.name.startsWith(".cache")||s(b.join(o,u.name),l+1))}};return s(n,0),e}function te(n,e,t){if(!t)return;let r=t.trim();!r||e.has(r)||(e.add(r),n.push(r))}function pe(n,e,t,r){let i=r.trim().replace(/^["']|["']$/g,"");if(!i||i.startsWith("$")||i.includes("${")||i.includes("<"))return;let s=b.isAbsolute(i)?i:b.resolve(t,i);$.existsSync(s)&&te(n,e,`-I${s}`)}function _t(n){let e=[],t=new Set,r;for(let i of nr(n)){let s=Ee(i);s&&(!r||s>r)&&(r=s);let o="";try{o=$.readFileSync(i,"utf8")}catch{continue}let l=b.dirname(i),c=o.replace(/#[^\n]*/g," "),u=me(c.replace(/[()[\]{},;]/g," "));for(let m=0;m<u.length;m+=1){let p=u[m];(p==="-I"||p==="-isystem"||p==="/I")&&u[m+1]?(pe(e,t,l,u[m+1]),m+=1):p.startsWith("-I")&&p.length>2||p.startsWith("/I")&&p.length>2?pe(e,t,l,p.slice(2)):p.startsWith("-isystem")&&p.length>8?pe(e,t,l,p.slice(8)):p.startsWith("-D")||p.startsWith("/D")?te(e,t,p.startsWith("/D")?`-D${p.slice(2)}`:p):p.startsWith("-std=")&&te(e,t,p)}for(let m of o.matchAll(/\b(?:target_)?include_directories\s*\(([^)]*)\)/gims))for(let p of me(m[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE|SYSTEM|BEFORE|AFTER)$/i.test(p)||pe(e,t,l,p);for(let m of o.matchAll(/\b(?:add_compile_definitions|target_compile_definitions)\s*\(([^)]*)\)/gims))for(let p of me(m[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE)$/i.test(p)||p.includes("$")||te(e,t,p.startsWith("-D")?p:`-D${p}`);for(let m of o.matchAll(/\binclude_directories\s*:\s*\[([^\]]*)\]/gims))for(let p of me(m[1].replace(/,/g," ")))pe(e,t,l,p)}return{args:e,mtime:r}}function rr(n,e){let t=b.resolve(n).split(b.sep),r=b.resolve(e).split(b.sep),i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];)i+=1;return i}function ir(n,e){if(!n||n.length===0)return null;let t=b.dirname(e),r=b.extname(e).toLowerCase(),i=b.basename(e,r),s=null;for(let o of n){let l=b.extname(o.file).toLowerCase();if(!Lt.has(l))continue;let c=b.dirname(o.file),u=b.basename(o.file,l),m=rr(e,o.file);c===t&&(m+=100),u===i&&(m+=50),Ft.has(r)&&(m+=20),(!s||m>s.score)&&(s={entry:o,score:m})}return s?.entry??null}function Ot(n,e){let t=e?`${b.resolve(n)}::${b.resolve(e)}`:b.resolve(n),r=ve.get(t);if(r){let K=Ee(r.commandsPath);if(r.commandsPath&&K&&r.commandsMtime&&K!==r.commandsMtime)ve.delete(t);else if(r.flagsPath){let R=Ee(r.flagsPath);if(R&&r.flagsMtime&&R!==r.flagsMtime)ve.delete(t);else return r}else if(r.projectConfigFlags){let R=_t(e??n);if(r.projectConfigMtime&&R.mtime&&r.projectConfigMtime!==R.mtime)ve.delete(t);else return r}else return r}let i=e?er(e,n):Bt(n),s=i?Yn(i)??void 0:void 0,o=s?.map,l=s?.entries,c=Ee(i),u=o?null:e?tr(e,n):$t(n),m=u?Zn(u)??void 0:void 0,p=Ee(u),C=!o&&!m?_t(e??n):void 0,I={commands:o,commandEntries:l,flags:m,projectConfigFlags:C?.args,commandsPath:i,commandsMtime:c,flagsPath:u,flagsMtime:p,projectConfigMtime:C?.mtime};return ve.set(t,I),I}function zt(n,e,t){let r=b.dirname(e),i=Ot(n);!i.commands&&!i.flags&&(!i.projectConfigFlags||i.projectConfigFlags.length===0)&&(i=Ot(n,r));let s=jt(e);if(i.commands){let o=i.commands.get(s);if(o)return{args:o.args,cwd:o.cwd,source:"compile_commands"};let l=ir(i.commandEntries,s);if(l)return{args:l.args,cwd:l.cwd,source:"compile_commands"}}return i.flags?{args:i.flags,cwd:n,source:"compile_flags"}:i.projectConfigFlags&&i.projectConfigFlags.length>0?{args:qt(i.projectConfigFlags,n,t),cwd:n,source:"project_config"}:He(n,t)}function sr(n){let e=[],t=new Set,r=l=>{let c=b.resolve(l);!t.has(c)&&$.existsSync(c)&&(t.add(c),e.push(c))};r(n);for(let l of Vn)r(b.join(n,l));let i=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_DEPTH||"5"),s=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_MAX_DIRS||"300"),o=(l,c)=>{if(c>i||e.length>=s)return;let u;try{u=$.readdirSync(l,{withFileTypes:!0})}catch{return}u.some(p=>p.isFile()&&Ft.has(b.extname(p.name).toLowerCase()))&&r(l);for(let p of u){if(e.length>=s)break;p.isDirectory()&&(p.name==="node_modules"||p.name===".git"||p.name===".pando"||p.name.startsWith(".cache")||o(b.join(l,p.name),c+1))}};return o(n,0),e}function qt(n,e,t){let r=[...n],i=new Set(r);r.some(s=>s.startsWith("-std="))||te(r,i,"-std="+(t==="cpp"?"c++20":"c17"));for(let s of sr(e))te(r,i,`-I${s}`);for(let s of["-ferror-limit=0","-Wno-everything","-fparse-all-comments","-fms-extensions"])te(r,i,s);return t==="cpp"&&te(r,i,"-fdelayed-template-parsing"),r}function He(n,e){return{args:qt([],n,e),cwd:n,source:"fallback"}}var is=(()=>{let n=Number(process.env.PANDO_CLANG_AST_MAX_BUFFER_BYTES||"");if(Number.isFinite(n)&&n>0)return Math.floor(n);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 lr(){let n=process.env.PANDO_CLANG_INDEXER_CMD;if(n&&n.trim())return n.trim();let e=q("clang-indexer/bin/pando-clang-indexer");if(e)return e;let t=[process.env.PANDO_TOOLS_ROOT?Ye.join(process.env.PANDO_TOOLS_ROOT,"clang-indexer","bin","pando-clang-indexer"):null,process.env.PANDO_RUNTIME_ROOT?Ye.join(process.env.PANDO_RUNTIME_ROOT,"tools","clang-indexer","bin","pando-clang-indexer"):null,typeof __dirname=="string"?Ye.resolve(__dirname,"..","..","..","..","..","tools","clang-indexer","bin","pando-clang-indexer"):null].filter(r=>!!r);for(let r of t)try{if(ar.existsSync(r))return r}catch{}return"pando-clang-indexer"}function cr(n){if(!n)return null;let e=n;(e.startsWith("SyntaxError:")||e.startsWith("CompileError:"))&&(e=e.substring(e.indexOf(":")+1)),e.includes("#")&&(e=e.split("#")[1]);let t=e.lastIndexOf(":"),r=t>=0?e.slice(0,t):e,[i,s]=r.split("-"),o=Number(i),l=Number(s);return!Number.isFinite(o)||!Number.isFinite(l)||l<o?null:{start:o,end:l}}function Ze(n){return G({id:n,extensions:[],parse:({absPath:e,relPath:t,content:r,projectRoot:i})=>{let s=zt(i,e,n),o=u=>["--file",e,"--project-root",i,"--lang",n,"--cwd",u.cwd,"--",...u.args,"-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...u.source==="fallback"?["-x",n==="cpp"?"c++":"c"]:[]],l=u=>{let m=lr(),p=or(m,o(u),{encoding:"utf8",cwd:u.cwd,maxBuffer:32*1024*1024});if(p.error){try{console.error(`[ClangAdapter] pando-clang-indexer spawn failed ${JSON.stringify({file:e,command:m,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(C){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:C instanceof Error?C.message:String(C)})}`)}catch{}return null}},c=l(s);return!c&&s.source!=="fallback"&&(c=l(He(i,n))),!c||c.error?null:c},resolve:({absPath:e,nodePath:t,projectRoot:r})=>{try{let i=fn("fs").readFileSync(e,"utf8"),s=cr(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 et from"fs";import tt from"path";import{spawn as ur,spawnSync as cs}from"child_process";var dr=256e3,pr=32;function re(...n){try{let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
|
|
8
|
+
`)}catch{}}var nt=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("dart indexer stdio unavailable");this.proc.stdout.on("data",e=>this.onData(e)),this.proc.stderr.on("data",e=>{re(`[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(`
|
|
9
|
+
`);if(t<0)break;let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!r)continue;let i=null;try{i=JSON.parse(r)}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 r=this.seq++;return new Promise((i,s)=>{let o={id:r,...e};this.pending.set(r,{resolve:i,reject:s});try{this.proc.stdin.write(`${JSON.stringify(o)}
|
|
10
|
+
`)}catch(l){if(this.pending.delete(r),t>0){try{this.handleExit(l)}catch{}return this.request(e,t-1).then(i,s)}s(l)}})}async parseBatch(e){let t=await this.request({op:"parse",files:e});return"results"in t&&Array.isArray(t.results)?t.results.map(r=>r.ok&&r.result?r.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{}}}},rt=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((t,r)=>{this.queue.push({input:e,resolve:t,reject:r,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 r=this.queue[0];if(e.length>0&&t+r.input.size>dr)break;e.push(this.queue.shift()),t+=r.input.size}try{let r=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=r[i]??null,l=Date.now()-s.startedAt;l>2e3&&re(`[${new Date().toISOString()}] [DartCliAdapter] parse slow`,{file:s.input.file,ms:l,ok:!!o}),o||re(`[${new Date().toISOString()}] [DartCliAdapter] parse failed`,{file:s.input.file,ms:l}),s.resolve(o)}}catch(r){for(let i of e)i.reject(r)}}}},Jt=new Map,Wt=new Map;function mr(n){let e=process.platform==="win32"?".cmd":"",t=q(`dart-indexer/bin/pando-dart-indexer${e}`);if(t)return t;if(n){let s=tt.resolve(n,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(et.existsSync(s))return s}let r=process.env.PANDO_EXTENSION_ROOT;if(r){let s=tt.resolve(r,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(et.existsSync(s))return s}let i=tt.resolve(process.cwd(),"tools/dart-indexer/bin/pando-dart-indexer"+e);return et.existsSync(i)?i:null}function Ut(n){let e=process.env.PANDO_DART_INDEXER_CMD||mr(n);if(!e)return null;let t=Jt.get(e);t||(t=new nt(e),Jt.set(e,t));let r=Wt.get(e);return r||(r=new rt(t),Wt.set(e,r)),{client:t,batcher:r}}async function fr(n,e,t){let r=Ut(e);if(!r)return null;try{return await r.batcher.enqueue({file:n,root:e,lang:"dart",size:t})}catch(i){return re(`[${new Date().toISOString()}] [DartCliAdapter] parse error`,{file:n,error:i?.message||i}),null}}function Xt(){return G({id:"dart",extensions:[".dart"],parse:async({absPath:n,projectRoot:e,content:t,meta:r})=>{let i=r?.size??Buffer.byteLength(t,"utf8");return fr(n,e,i)},resolve:({absPath:n,nodePath:e,projectRoot:t})=>{let r=Date.now(),i=Ut(t);return i?i.client.resolve({file:n,root:t,lang:"dart",nodePath:e}).then(s=>{let o=Date.now()-r;return o>2e3&&re(`[${new Date().toISOString()}] [DartCliAdapter] resolve slow`,{file:n,ms:o}),s||re(`[${new Date().toISOString()}] [DartCliAdapter] resolve failed`,{file:n,ms:o,nodePath:e}),s}).catch(s=>{let o=Date.now()-r;return re(`[${new Date().toISOString()}] [DartCliAdapter] resolve error`,{file:n,ms:o,nodePath:e,error:s?.message||s}),null}):null},exportKind:"dart"})}import it from"fs";import we from"path";import{spawn as gr,spawnSync as hs}from"child_process";var hr=256e3,yr=32;function se(...n){try{let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
|
|
11
|
+
`)}catch{}}var st=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=gr(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=>{se(`[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(`
|
|
12
|
+
`);if(t<0)break;let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!r)continue;let i=null;try{i=JSON.parse(r)}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 r=this.seq++;return new Promise((i,s)=>{let o={id:r,...e},l=setTimeout(()=>{this.pending.delete(r),s(new Error("java indexer request timed out after 30s"))},3e4);this.pending.set(r,{resolve:i,reject:s,timer:l});try{this.proc.stdin.write(`${JSON.stringify(o)}
|
|
13
|
+
`)}catch(c){if(clearTimeout(l),this.pending.delete(r),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(r=>r.ok&&r.result?r.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{}}}},ot=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((t,r)=>{this.queue.push({input:e,resolve:t,reject:r,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<yr;){let r=this.queue[0];if(e.length>0&&t+r.input.size>hr)break;e.push(this.queue.shift()),t+=r.input.size}try{let r=await this.client.parseBatch(e.map(i=>({file:i.input.file,root:i.input.root,lang:i.input.lang,emitMode:i.input.emitMode})));for(let i=0;i<e.length;i+=1){let s=e[i],o=r[i]??null,l=Date.now()-s.startedAt;l>2e3&&se(`[${new Date().toISOString()}] [JavaCliAdapter] parse slow`,{file:s.input.file,ms:l,path:"custom",ok:!!o}),o||se(`[${new Date().toISOString()}] [JavaCliAdapter] parse failed`,{file:s.input.file,ms:l,path:"custom"}),s.resolve(o)}}catch(r){for(let i of e)i.reject(r)}}}},Qt=new Map,Gt=new Map;function br(){return typeof __dirname=="string"?__dirname:process.cwd()}var ie,xr;function Sr(n){if(ie!==void 0&&xr===n)return ie;let e=process.platform==="win32"?".cmd":"",t="tools/java-indexer/bin/pando-java-indexer"+e,r=q(`java-indexer/bin/pando-java-indexer${e}`);if(r)return ie=r,r;if(n){let s=we.resolve(n,t);if(it.existsSync(s))return ie=s,s}let i=br();for(let s=0;s<8;s++){let o=we.join(i,t);if(it.existsSync(o))return ie=o,o;let l=we.dirname(i);if(l===i)break;i=l}i=process.cwd();for(let s=0;s<8;s++){let o=we.join(i,t);if(it.existsSync(o))return ie=o,o;let l=we.dirname(i);if(l===i)break;i=l}return ie=null,null}function Vt(n){let e=process.env.PANDO_JAVA_INDEXER_CMD||Sr(n);if(!e)return null;let t=Qt.get(e);t||(t=new st(e),Qt.set(e,t));let r=Gt.get(e);return r||(r=new ot(t),Gt.set(e,r)),{client:t,batcher:r}}async function Cr(n,e,t,r){let i=Vt(e);if(!i)return null;try{return await i.batcher.enqueue({file:n,root:e,lang:"java",size:t,emitMode:r})}catch(s){return se(`[${new Date().toISOString()}] [JavaCliAdapter] parse error`,{file:n,error:s?.message||s,path:"custom"}),null}}async function vr(n,e,t,r){let i=await Cr(n,e,t,r);return i||null}function Ht(){return G({id:"java",extensions:[".java"],exportKind:"named",parse:({absPath:n,projectRoot:e,content:t,meta:r,emitMode:i})=>{let s=r?.size??Buffer.byteLength(t,"utf8");return vr(n,e,s,i??"light")},resolve:({absPath:n,nodePath:e,projectRoot:t})=>{let r=Date.now(),i=Vt(t);return i?i.client.resolve({file:n,root:t,lang:"java",nodePath:e}).then(s=>{let o=Date.now()-r;return o>2e3&&se(`[${new Date().toISOString()}] [JavaCliAdapter] resolve slow`,{file:n,ms:o}),s||se(`[${new Date().toISOString()}] [JavaCliAdapter] resolve failed`,{file:n,ms:o,nodePath:e}),s}).catch(s=>{let o=Date.now()-r;return se(`[${new Date().toISOString()}] [JavaCliAdapter] resolve error`,{file:n,ms:o,nodePath:e,error:s?.message||s}),null}):null}})}import Mr from"fs";import Ir from"os";import{spawn as Er}from"child_process";import at from"fs";import lt from"path";function Yt(n,e){let t=process.platform==="win32"?".cmd":"",r=n==="clojure-editor"?"pando-clojure-editor":"pando-clojure-indexer",i=q(`${n}/bin/${r}${t}`);if(i)return i;if(e){let l=lt.resolve(e,`tools/${n}/bin/${r}${t}`);if(at.existsSync(l))return l}let s=process.env.PANDO_EXTENSION_ROOT;if(s){let l=lt.resolve(s,`tools/${n}/bin/${r}${t}`);if(at.existsSync(l))return l}let o=lt.resolve(process.cwd(),`tools/${n}/bin/${r}${t}`);return at.existsSync(o)?o:null}var _e=3e4,wr=Math.max(_e,Number(process.env.PANDO_CLOJURE_PARSE_TIMEOUT_MS||`${300*1e3}`)),Nr=Math.max(_e,Number(process.env.PANDO_CLOJURE_CHANGE_SIGNATURE_TIMEOUT_MS||`${300*1e3}`)),Zt="__PANDO_CLOJURE_INDEX__";function Pr(...n){if(!oe())return;let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");B("ClojureIndexer",e)}function Ne(n,e){oe()&&B("ClojureIndex",n,e)}function Rr(n,e=0){let t=Math.max(1,n.length),r=Math.ceil(Math.max(0,e)/(32*1024))*500,i=15e3+t*2500+r;return Math.max(_e,Math.min(wr,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,Ne("node.server.spawn",{projectRoot:this.projectRoot,cmd:this.cmd}),this.proc=Er(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){Ne("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(`
|
|
14
|
+
`);if(t<0)break;let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!r)continue;let i=null;try{i=JSON.parse(r)}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(`
|
|
15
|
+
`);if(t<0)break;let r=this.stderrBuffer.slice(0,t).trim();if(this.stderrBuffer=this.stderrBuffer.slice(t+1),!!r){if(r.startsWith(Zt)){let i=r.slice(Zt.length);try{let s=JSON.parse(i);Ne(s.event||"jvm.trace",s)}catch(s){B("ClojureIndexer","stderr trace parse failed",{error:s?.message||String(s),line:r})}continue}Pr(r)}}}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 r=this.seq++,i=t?.retry??1,s=t?.timeoutMs??_e,o=Date.now();return new Promise((l,c)=>{let u={id:r,...e},m=setTimeout(()=>{this.pending.delete(r),c(new Error(`clojure indexer request timed out after ${s}ms`))},s);this.pending.set(r,{resolve:p=>{Ne("node.client.request.complete",{projectRoot:this.projectRoot,id:r,op:e.op,durationMs:Date.now()-o}),l(p)},reject:c,timer:m});try{Ne("node.client.request.start",{projectRoot:this.projectRoot,id:r,op:e.op,timeoutMs:s}),this.proc.stdin.write(`${JSON.stringify(u)}
|
|
16
|
+
`)}catch(p){if(clearTimeout(m),this.pending.delete(r),i>0){try{this.handleExit(p)}catch{}return this.request(e,{retry:i-1,timeoutMs:s}).then(l,c)}c(p)}})}async parseBatch(e,t){let r=Rr(e,t?.batchBytes??0),i=await this.request({op:"parse",files:e,analysisMode:t.emitMode==="full"?"full":"index",traceBatchId:t?.batchId,traceBatchBytes:t?.batchBytes},{timeoutMs:r});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 r=t.result;if(r&&typeof r.start=="number"&&typeof r.end=="number")return r}return null}async changeSignature(e){let t=await this.request({op:"change-signature",...e},{timeoutMs:Nr});return"result"in t&&t.result||null}},en=new Map;function tn(n){return process.env.PANDO_CLOJURE_INDEXER_CMD||Yt("clojure-indexer",n)}function nn(n){let e=tn(n);return e?new Ke(e,n):null}function rn(n){let e=tn(n);if(!e)return null;let t=`${e}::${n}`,r=en.get(t);return r||(r=new Ke(e,n),en.set(t,r)),r}function Ar(){let n=Number(process.env.PANDO_CLOJURE_ANALYZER_POOL_SIZE||"");if(Number.isFinite(n)&&n>=1)return Math.max(1,Math.floor(n));let e=Math.max(1,Ir.cpus()?.length||4);return Math.max(3,Math.min(8,Math.ceil(e/2)))}var kr=Ar();function Oe(n,e){B("ClojureIndex",n,e)}function Le(n,e){B("IndexTiming",n,e)}var Fe=class{constructor(e,t,r=kr){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,r);for(let s=0;s<i;s+=1){let o=nn(e);if(!o)break;this.clients.push(o),this.idleClients.push(o)}if(!this.clients.length)throw new Error("clojure indexer command unavailable");Oe("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((r,i)=>{this.queue.push({batchId:this.batchSeq++,batchKey:e,files:t,enqueuedAt:Date.now(),resolve:r,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(),r=this.runJob(t,e).finally(()=>{this.inFlight.delete(r),this.closed||this.idleClients.push(t),this.pump(),this.notifyIfIdle()});this.inFlight.add(r)}this.notifyIfIdle()}async runJob(e,t){let r=t.files.reduce((o,l)=>o+Math.max(0,l.size||0),0),i=Date.now(),s=Math.max(0,i-t.enqueuedAt);Oe("node.pool-batch.start",{batchId:t.batchId,batchKey:t.batchKey,purpose:this.purpose,fileCount:t.files.length,batchBytes:r,queueWaitMs:s,queuedBatchCount:this.queue.length,inFlightCount:this.inFlight.size});try{let o=await this.parseFiles(e,t.files,t.batchId,r);Le("clojure-pool.job.complete",{projectRoot:this.projectRoot,batchId:t.batchId,batchKey:t.batchKey,purpose:this.purpose,fileCount:t.files.length,batchBytes:r,queueWaitMs:s,durationMs:Date.now()-i}),Oe("node.pool-batch.complete",{batchId:t.batchId,batchKey:t.batchKey,purpose:this.purpose,fileCount:t.files.length,batchBytes:r,durationMs:Date.now()-i,successCount:Array.from(o.values()).filter(l=>!("error"in l)).length,errorCount:Array.from(o.values()).filter(l=>"error"in l).length}),t.resolve(o)}catch(o){let l=o instanceof Error?o:new Error(String(o));Oe("node.pool-batch.error",{batchId:t.batchId,batchKey:t.batchKey,fileCount:t.files.length,batchBytes:r,durationMs:Date.now()-i,error:l.message}),t.reject(l)}}async parseFiles(e,t,r,i){let s=Date.now();try{let o=await e.parseBatch(t.map(c=>({file:c.absPath,root:this.projectRoot,lang:c.lang,emitMode:c.emitMode})),{batchId:r,batchBytes:i,purpose:this.purpose,emitMode:t.some(c=>c.emitMode==="full")?"full":"light"});Le("clojure-parse-batch.complete",{projectRoot:this.projectRoot,batchId:r,fileCount:t.length,batchBytes:i,purpose:this.purpose,durationMs:Date.now()-s,split:!1});let l=new Map;for(let c=0;c<t.length;c+=1){let u=t[c],m=o[c]??null;m?l.set(u.fileKey,m):(B("IndexingAudit","clojure analysis returned no result",{projectRoot:this.projectRoot,batchId:r,file:u.absPath}),l.set(u.fileKey,{error:`clojure analysis returned no result for ${u.absPath}`}))}return l}catch(o){if(t.length>1){let u=Date.now(),m=Math.ceil(t.length/2),p=t.slice(0,m),C=t.slice(m),I=await this.parseFiles(e,p,r,p.reduce((R,F)=>R+Math.max(0,F.size||0),0)),K=await this.parseFiles(e,C,r,C.reduce((R,F)=>R+Math.max(0,F.size||0),0));return Le("clojure-parse-batch.split",{projectRoot:this.projectRoot,batchId:r,fileCount:t.length,batchBytes:i,purpose:this.purpose,durationMs:Date.now()-u,leftCount:p.length,rightCount:C.length,error:o instanceof Error?o.message:String(o)}),new Map([...I,...K])}let l=o instanceof Error?o:new Error(String(o));Le("clojure-parse-batch.error",{projectRoot:this.projectRoot,batchId:r,fileCount:t.length,batchBytes:i,purpose:this.purpose,durationMs:Date.now()-s,error:l.message});let c=new Map;for(let u of t)B("IndexingAudit","clojure analysis request failed",{projectRoot:this.projectRoot,batchId:r,file:u.absPath,error:l.message}),c.set(u.fileKey,{error:l.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 Dr(n,e){if(typeof e?.size=="number"&&typeof e?.mtime=="number")return{size:e.size,mtime:e.mtime};try{let t=Mr.statSync(n);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 Tr(n,e){let t=new Map;for(let r of e.nodes??[]){if(!r.name||r.containerKind||t.has(r.name))continue;let i=`${n}#${r.start}-${r.end}:${Z.getAbbrev(r.kind,"clojure")}:${r.name}`;t.set(r.name,i)}return r=>t.get(r)??null}function Kr(n){let e=n?.error;return typeof e=="string"&&e.trim().length>0?e.trim():null}var je=class{constructor(e,t){this.projectRoot=e;this.purpose=t;this.cache=new le;this.pool=new Fe(e,t)}prepare(e){let t=Dr(e.absPath,e.meta),r=e.emitMode??"light",i=r==="full"?null:this.cache.get(e.absPath,t);return{fileKey:e.relPath,absPath:e.absPath,relPath:e.relPath,meta:t,preDeleted:e.preDeleted,lang:e.lang,emitMode:r,cachedParsed:i??void 0}}batchKey(e){return`${this.projectRoot}::clojure::${this.purpose}::${e.emitMode}`}async analyzeBatch(e){let t=new Map,r=e.filter(s=>!s.cachedParsed);for(let s of e)s.cachedParsed&&t.set(s.fileKey,s.cachedParsed);if(!r.length)return t;let i=await this.pool.submit(this.batchKey(r[0]),r.map(s=>({fileKey:s.fileKey,absPath:s.absPath,lang:s.lang,size:s.meta?.size??0,emitMode:s.emitMode})));for(let s of r){let o=i.get(s.fileKey)??{error:`missing clojure analysis result for ${s.relPath}`};s.emitMode!=="full"&&!("error"in o)&&this.cache.set(s.absPath,s.meta??{},o),t.set(s.fileKey,o)}return t}buildProcessedFile(e,t,r){let i=Kr(r);return i?(B("IndexingAudit","clojure batch analysis failed",{projectRoot:this.projectRoot,relPath:e.relPath,error:i}),he("clojure",e.relPath,t.meta)):ye({lang:"clojure",fileRel:e.relPath,content:e.content,meta:t.meta,preDeleted:e.preDeleted,parsed:r,resolveNodeId:Tr(e.relPath,r),exportKind:"cli",fullyIndexed:t.emitMode==="full"})}async flush(){await this.pool.flush()}async close(){await this.pool.close()}};function _r(){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 Or(...n){let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");B("ClojureCliAdapter",e)}function sn(){return{id:"clojure",extensions:[".clj",".cljc",".cljs"],indexingMode:"batch",createBatchIndexer:(n,e)=>new je(n,e),getBatchSchedulerOptions:_r,resolveSpan:(n,e,t)=>{let r=rn(n);return r?r.resolve({file:e,root:n,lang:"clojure",nodePath:t}).catch(i=>(Or(`[${new Date().toISOString()}] [ClojureCliAdapter] resolve error`,{file:e,nodePath:t,error:i?.message||i}),null)):null}}}function io(n){return n.indexingMode==="worker"&&typeof n.createIndexer=="function"}var ct={ts:We("ts"),js:We("js"),python:It(),c:{...Ze("c"),extensions:[".c",".i",".inc"]},cpp:{...Ze("cpp"),extensions:[".cc",".cpp",".cxx",".c++",".cp",".ccm",".cppm",".cxxm",".ixx",".hpp",".h",".hh",".hxx",".h++",".ii",".inl",".ipp",".tcc",".tpp",".txx"]},csharp:Kt(),dart:Xt(),java:Ht(),clojure:sn()},on=new Map;for(let n of Object.values(ct))for(let e of n.extensions)on.set(e,n.id);function Lr(){return gt(mt())}function so(n){let e=n.toLowerCase().match(/\.[a-z0-9+]+$/);return e?on.get(e[0])??null:null}function oo(n){return ct[n]}function ao(n){let e=n??Lr(),t=new Set;for(let[i,s]of Object.entries(e.byLanguage))s.enabled&&t.add(i);let r=new Set;for(let i of Object.values(ct))if(t.has(i.id))for(let s of i.extensions)r.add(s);return r}import Fr from"fs";import an from"path";import{promises as jr}from"fs";import{execFileSync as Br}from"child_process";import go from"ignore";function ut(n){return n.replace(/\\/g,"/")}function ln(n,e){let t=n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(!t.length)return[];let r=e?`${e}/`:"";return t.map(s=>s.startsWith("\\#")||s.startsWith("\\!")?s.slice(1):s).filter(s=>!s.startsWith("#")).map(s=>{let o=s.startsWith("!"),l=o?s.slice(1):s;if(!l)return s;if((l.endsWith("/")?l.slice(0,-1):l).includes("/")){if(!r&&l.startsWith("/"))return o?`!${l}`:l;let p=l.startsWith("/")?l.slice(1):l,C=r?`${r}${p}`:p;return o?`!${C}`:C}let m=r?`${r}**/${l}`:l;return o?`!${m}`:m})}function ho(n,e){let t=an.join(n,".gitignore");try{let r=Fr.readFileSync(t,"utf8");return ln(r,e)}catch{return[]}}async function yo(n,e){let t=an.join(n,".gitignore");try{let r=await jr.readFile(t,"utf8");return ln(r,e)}catch{return[]}}function $r(n){let e=new Set,t=new Set;for(let r of n){let i=ut(r).replace(/^\/+/,"");if(!i)continue;e.add(i);let s=i.split("/");s.pop();let o="";for(let l of s)o=o?`${o}/${l}`:l,t.add(o)}return{files:e,dirs:t,hasFile(r){return e.has(ut(r))},hasDescendant(r){return t.has(ut(r).replace(/\/+$/,""))}}}function bo(n){try{let t=Br("git",["-C",n,"ls-files","-z"],{encoding:"buffer",stdio:["ignore","pipe","ignore"],maxBuffer:67108864}).toString("utf8").split("\0").filter(Boolean);return t.length?$r(t):null}catch{return null}}function zr(n,e="Operation cancelled"){let t=typeof n=="string"&&n.trim()?n.trim():n instanceof Error&&n.message.trim()?n.message.trim():e,r=new Error(t);return r.name="AbortError",r.code="ABORT_ERR",r}function So(n,e){if(n?.aborted)throw zr(n.reason,e)}export{he as a,io as b,Lr as c,so as d,oo as e,ao as f,So as g,ho as h,yo as i,bo as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as B,b as L,c as q,d as
|
|
1
|
+
import{a as B,b as L,c as q,d as R,e as C,f as z,i as F,j as N}from"./chunk-5T4KKWJC.mjs";import"./chunk-ODST7O2H.mjs";import{c as X}from"./chunk-AYCBSZ56.mjs";import{parentPort as l,threadId as ne}from"worker_threads";import K from"fs";import _ from"path";import{promises as G}from"fs";import H from"ignore";import{createHash as se}from"crypto";var te=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_FILES||"64")),re=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_BYTES||`${1024*1024}`)),ce=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_WAIT_MS||"15")),le=Math.max(te,Number(process.env.PANDO_BATCH_INDEX_MAX_PENDING_FILES||"256")),he=Math.max(re,Number(process.env.PANDO_BATCH_INDEX_MAX_PENDING_BYTES||`${8*1024*1024}`));var be=1*1024*1024,Me=Math.max(3e4,Number(process.env.PANDO_WORKER_INIT_TIMEOUT_MS||12e4)),ie=Math.max(1e3,Number(process.env.PANDO_ACTIVE_CONTEXT_STALL_LOG_MS||1e4)),We=Math.max(ie,Number(process.env.PANDO_ACTIVE_CONTEXT_STALL_FAIL_MS||6e5)),Be=q();function U(e,t){return Buffer.from(e).toString(t)}function D(e,t,o,r,d,u){let m=Buffer.from(e),n=se("sha1").update(m).digest("hex"),i=u??m.toString(d),c=i?i.split(/\r?\n/).length:0;return{relPath:t,size:o,mtime:r,objectId:n,lineCount:c,encoding:d}}if(!l)throw new Error("Indexer worker must be spawned as a worker thread");X();function h(e,t){try{if(t===void 0){console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e}`);return}console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e} ${JSON.stringify({pid:process.pid,threadId:ne,...t&&typeof t=="object"&&!Array.isArray(t)?t:{details:t}})}`)}catch{}}h("module loaded",{cwd:process.cwd(),hasParentPort:!!l,envWorkerRoot:process.env.PANDO_WORKER_SCRIPT_DIR??null,envRuntimeRoot:process.env.PANDO_RUNTIME_ROOT??null});var J=new Map,E="",T="index",b=new Map,v=new Set;function Y(e,t){return _.relative(e,t).replace(/\\/g,"/")}function ae(e,t){let o=(t||[]).map(r=>typeof r=="string"?r.trim():"").filter(Boolean).map(r=>r.replace(/^[\\/]+/,"").replace(/[\\/]+$/,"")).map(r=>r.endsWith("/")?r:`${r}/`);return o.length?r=>{let d=Y(e,r);if(!d||d.startsWith(".."))return!1;let u=d.endsWith("/")?d:`${d}/`;return o.some(m=>u.startsWith(m))}:null}async function oe(e){await new Promise(t=>{b.set(e,t)})}l.on("message",async e=>{if(e.cmd==="scan-ack"){let t=b.get(e.requestId);if(t){b.delete(e.requestId);try{t()}catch{}}return}if(e.cmd==="scan-cancel"){v.add(e.requestId);let t=b.get(e.requestId);if(t){b.delete(e.requestId);try{t()}catch{}}return}if(e.cmd==="init"){try{h("init received",{mode:e.mode??"index",projectRoot:typeof e.projectRoot=="string"?e.projectRoot:null}),typeof e.projectRoot=="string"&&(E=e.projectRoot),T=e.mode??"index",h("init completed",{mode:T,projectRoot:E}),l.postMessage({type:"ready"})}catch(t){h("init failed",{error:t?.message||String(t),stack:t?.stack??null}),l.postMessage({type:"error",message:`init failed: ${t?.message||t}`,stack:t?.stack})}return}if(e.cmd==="scan"){let t=e.requestId,o=typeof e.projectRoot=="string"?e.projectRoot:E;if(h("scan received",{requestId:t,projectRoot:o||null,batchSize:e.batchSize??null,maxFileBytes:e.maxFileBytes??null,excludeDirs:Array.isArray(e.excludeDirs)?e.excludeDirs.slice(0,20):[]}),!o){l.postMessage({type:"error",requestId:t,message:"worker not initialized"});return}let r=Math.max(1,Math.min(500,Number(e.batchSize||100))),d=Math.max(1,Number(e.maxFileBytes||1*1024*1024)),u=e.languageSupport,m=z(u),n=ae(o,e.excludeDirs??[]),i=N(o),c=new Set(["node_modules",".git",".pando-data"]),S=a=>a.replace(/\\/g,"/"),w=await F(o,""),g=H().add(w),f=[{dir:o,relDir:"",rules:w,ig:g}],y=0,s=0,p=[],x=async()=>{p.length&&(l.postMessage({type:"scan:batch",requestId:t,files:p}),p=[],await oe(t))};try{for(;f.length&&!v.has(t);){let a=f.pop(),$=[];try{$=await G.readdir(a.dir,{withFileTypes:!0})}catch{s+=1;continue}for(let k of $){if(v.has(t))break;let I=_.join(a.dir,k.name);if(k.isSymbolicLink?.()){s+=1;continue}if(k.isDirectory()){if(c.has(k.name)){s+=1;continue}if(n?.(I)){s+=1;continue}let Q=a.relDir?`${a.relDir}/${k.name}`:k.name,W=S(Q);if(a.ig.ignores(W)&&!i?.hasDescendant(W)){s+=1;continue}let A=a.rules.slice(),j=await F(I,W);j.length&&A.push(...j);let Z=H().add(A);f.push({dir:I,relDir:W,rules:A,ig:Z});continue}if(!k.isFile()){s+=1;continue}if(n?.(I)){s+=1;continue}let P=Y(o,I);if(!P||P.startsWith("..")){s+=1;continue}if(a.ig.ignores(P)&&!i?.hasFile(P)){s+=1;continue}let V=_.extname(k.name).toLowerCase();if(!m.has(V)){s+=1;continue}let O=R(P);if(!O){s+=1;continue}let M;try{M=await G.stat(I)}catch{s+=1;continue}if(M.size>d){s+=1;continue}p.push({relPath:P,absPath:I,mtimeMs:Math.floor(M.mtimeMs),size:M.size,lang:O}),y+=1,p.length>=r&&await x()}}v.has(t)||await x(),l.postMessage({type:"scan:done",requestId:t,discovered:y,skipped:s,cancelled:v.has(t)}),h("scan complete",{requestId:t,discovered:y,skipped:s,cancelled:v.has(t)})}catch(a){h("scan failed",{requestId:t,error:a?.message||String(a),stack:a?.stack??null}),l.postMessage({type:"error",requestId:t,message:a?.message||String(a),stack:a?.stack})}finally{v.delete(t),b.delete(t)}return}if(e.cmd==="process"){let t=e.role??T,o=typeof e.projectRoot=="string"?e.projectRoot:E;if(!o){l.postMessage({type:"error",requestId:e.requestId,message:"worker not initialized"});return}let{file:r}=e,d=r.encoding??"utf8",u=r.sharedBuffer,m={size:r.size,mtime:r.mtime};try{let n=r.lang??"ts",i,c,S=()=>{if(c&&typeof i=="string")return{content:i,sharedBuffer:c};if(u instanceof SharedArrayBuffer)return c=u,i=U(u,d),{content:i,sharedBuffer:c};if(u instanceof ArrayBuffer){let x=Buffer.from(u),a=new SharedArrayBuffer(x.byteLength);return new Uint8Array(a).set(x),c=a,i=x.toString(d),{content:i,sharedBuffer:c}}let s=K.readFileSync(r.absPath),p=new SharedArrayBuffer(s.byteLength);return new Uint8Array(p).set(s),c=p,i=s.toString(d),{content:i,sharedBuffer:c}},w=()=>{let s=B(n,r.relPath,m),p=S();l.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:r.relPath,result:{payload:s.payload,meta:{size:s.fileSize,mtime:s.mtime},snapshotSummary:D(p.sharedBuffer,r.relPath,r.size,r.mtime,d,p.content)}})},g=`${o}:${n}`,f=J.get(g);if(!f)try{h("creating language indexer",{role:t,requestId:e.requestId,lang:n,projectRoot:o});let s=C(n);if(!L(s))throw new Error(`${n} is not a worker-indexed language`);f=s.createIndexer(o),J.set(g,f),h("language indexer ready",{role:t,requestId:e.requestId,lang:n,projectRoot:o})}catch(s){h("language indexer create failed",{role:t,requestId:e.requestId,lang:n,error:s?.message||String(s),stack:s?.stack??null}),w();return}({content:i,sharedBuffer:c}=S());let y;try{y=await f.process({absPath:r.absPath,relPath:r.relPath,content:i,meta:m,preDeleted:!!r.preDeleted,lang:n,emitMode:r.emitMode})}catch(s){h("process failed",{role:t,requestId:e.requestId,lang:n,relPath:r.relPath,error:s?.message||String(s),stack:s?.stack??null}),w();return}l.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:r.relPath,result:{payload:y.payload,meta:{size:y.fileSize,mtime:y.mtime},snapshotSummary:D(c,r.relPath,r.size,r.mtime,d,i)}})}catch(n){h("process wrapper failed",{role:t,requestId:e.requestId,relPath:r.relPath,error:n?.message||String(n),stack:n?.stack??null});try{let i=r.lang??"ts",c=K.readFileSync(r.absPath),S=new SharedArrayBuffer(c.byteLength);new Uint8Array(S).set(c);let w=c.toString(d),g=B(i,r.relPath,m);l.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:r.relPath,result:{payload:g.payload,meta:{size:g.fileSize,mtime:g.mtime},snapshotSummary:D(S,r.relPath,r.size,r.mtime,d,w)}})}catch(i){l.postMessage({type:"error",requestId:e.requestId,message:i?.message||n?.message||String(i??n),stack:i?.stack??n?.stack})}}return}e.cmd==="close"&&l.postMessage({type:"closed"})});process.on("uncaughtException",e=>{try{l.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch{}});process.on("unhandledRejection",e=>{try{l.postMessage({type:"error",message:String(e)})}catch{}});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{g as P,h as J,j as ot}from"./chunk-
|
|
1
|
+
import{g as P,h as J,j as ot}from"./chunk-5T4KKWJC.mjs";import{a as V,b as st,c as K,e as R}from"./chunk-ODST7O2H.mjs";import{a as Q,b as xt}from"./chunk-Z5RGEDVQ.mjs";import{a as Et,c as at}from"./chunk-AYCBSZ56.mjs";import{parentPort as $}from"worker_threads";import it from"path";import*as o from"fs";import*as I from"path";import*as g from"isomorphic-git";function Pt(){return new Date().toISOString()}function U(r,t,e){let i=`[${Pt()}] [${r.toUpperCase()}] ${t}`;if(!e)return i;try{return i+" "+JSON.stringify(e)}catch{return i}}var B={debug:(r,t)=>{try{process.stderr.write(U("debug",r,t)+`
|
|
2
2
|
`)}catch{}},info:(r,t)=>{try{process.stderr.write(U("info",r,t)+`
|
|
3
3
|
`)}catch{}},warn:(r,t)=>{try{process.stderr.write(U("warn",r,t)+`
|
|
4
4
|
`)}catch{}},error:(r,t)=>{try{process.stderr.write(U("error",r,t)+`
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{d as
|
|
1
|
+
import{d as pe,e as ie,f as F}from"./chunk-ODST7O2H.mjs";import{a as se,b as Ue}from"./chunk-Z5RGEDVQ.mjs";import{c as Re}from"./chunk-AYCBSZ56.mjs";Ue();import{parentPort as S,threadId as Ae}from"worker_threads";import K from"path";import ce from"fs";import{inspect as Be}from"util";import Pe from"os";function Ge(e){e.exec(`
|
|
2
2
|
PRAGMA journal_mode=WAL;
|
|
3
3
|
PRAGMA synchronous=OFF;
|
|
4
4
|
PRAGMA temp_store=MEMORY;
|
|
5
5
|
PRAGMA busy_timeout=5000;
|
|
6
|
-
`);try{let r=
|
|
6
|
+
`);try{let r=Pe.totalmem(),t=Math.min(Math.floor(r*.5),30*1024*1024*1024),n=Math.min(Math.floor(r/1024*.1),4*1024*1024);e.pragma(`mmap_size = ${t}`),e.pragma(`cache_size = -${n}`),e.pragma("wal_autocheckpoint = 10000")}catch{}}function ge(e){Ge(e),e.exec(`
|
|
7
7
|
CREATE TABLE IF NOT EXISTS dict_kinds (
|
|
8
8
|
id INTEGER PRIMARY KEY,
|
|
9
9
|
text TEXT UNIQUE
|
|
@@ -25,7 +25,8 @@ import{d as Ne,e as re,f as U}from"./chunk-ODST7O2H.mjs";import{a as ie,b as Ce}
|
|
|
25
25
|
last_modified INTEGER,
|
|
26
26
|
file_size INTEGER,
|
|
27
27
|
status TEXT DEFAULT 'completed',
|
|
28
|
-
indexed_at DATETIME
|
|
28
|
+
indexed_at DATETIME,
|
|
29
|
+
fully_indexed INTEGER DEFAULT 0
|
|
29
30
|
);
|
|
30
31
|
|
|
31
32
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
@@ -47,7 +48,13 @@ import{d as Ne,e as re,f as U}from"./chunk-ODST7O2H.mjs";import{a as ie,b as Ce}
|
|
|
47
48
|
qualified_name TEXT,
|
|
48
49
|
scope_chain TEXT,
|
|
49
50
|
symbol_key TEXT,
|
|
50
|
-
metadata TEXT
|
|
51
|
+
metadata TEXT,
|
|
52
|
+
parent_node_id INTEGER,
|
|
53
|
+
role TEXT,
|
|
54
|
+
index_in_parent INTEGER,
|
|
55
|
+
depth INTEGER DEFAULT 0,
|
|
56
|
+
body_start_pos INTEGER,
|
|
57
|
+
body_end_pos INTEGER
|
|
51
58
|
);
|
|
52
59
|
|
|
53
60
|
CREATE TABLE IF NOT EXISTS exports (
|
|
@@ -77,6 +84,7 @@ import{d as Ne,e as re,f as U}from"./chunk-ODST7O2H.mjs";import{a as ie,b as Ce}
|
|
|
77
84
|
CREATE INDEX IF NOT EXISTS idx_nodes_qualified_name ON nodes(qualified_name);
|
|
78
85
|
CREATE INDEX IF NOT EXISTS idx_nodes_scope_chain ON nodes(scope_chain);
|
|
79
86
|
CREATE INDEX IF NOT EXISTS idx_nodes_symbol_key ON nodes(symbol_key);
|
|
87
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent_node_id);
|
|
80
88
|
CREATE TABLE IF NOT EXISTS file_symbol_mentions (
|
|
81
89
|
file_id INTEGER NOT NULL,
|
|
82
90
|
lang TEXT,
|
|
@@ -230,5 +238,7 @@ import{d as Ne,e as re,f as U}from"./chunk-ODST7O2H.mjs";import{a as ie,b as Ce}
|
|
|
230
238
|
CREATE INDEX IF NOT EXISTS idx_resolver_cache_symbol ON resolver_cache(symbol_id);
|
|
231
239
|
CREATE INDEX IF NOT EXISTS idx_resolver_cache_file ON resolver_cache(file_path);
|
|
232
240
|
|
|
233
|
-
`)}var Le=Number(process.env.PANDO_SQLITE_RETRY_MIN_MS||"100"),Ae=Number(process.env.PANDO_SQLITE_RETRY_MAX_MS||"500"),ge=Math.max(0,Number(process.env.PANDO_SQLITE_RETRY_ATTEMPTS||"5")),A=Ne();if(!S)throw new Error("SQLite writer worker must be spawned as a worker thread");pe();function f(...e){process.env.PANDO_QUIET||console.log(Be([`[${new Date().toISOString()}]`,...e]))}function Be(e){return e.map(Ke).join(" ")}function Ke(e){if(typeof e=="string")return e;if(e instanceof Error)return e.stack||e.message;try{let r=JSON.stringify(e);if(typeof r=="string")return r}catch{}return Ge(e,{depth:null,breakLength:1/0,compact:!0})}function R(...e){A&&console.log(...e)}function Ye(e){A&&re("WriterWorker",e,{threadId:Me})}function ze(e){A&&re("WriterWorker","clojure-source-node",{threadId:Me,...e})}var D=null,be=null;function $e(){be||(be=setInterval(()=>{if(!D)return;let e=Date.now()-D.startedAt;e>5e3&&f("[WriterWorker] op still running",{cmd:D.cmd,id:D.id,ms:e,fileRel:D.fileRel})},2e3))}function X(e,r,t){D={cmd:e,id:r,startedAt:Date.now(),fileRel:t},$e()}function g(){D=null}var x=()=>({writeMs:0,writeTrackedMs:0,writePreDeleteMs:0,writeInsertExportsMs:0,writeInsertNodesMs:0,writeInsertReferencesMs:0,writeInsertImportsMs:0,writeInsertImportBindingsMs:0,writeInsertFileMs:0,writeFinalizeMs:0,writeInsertFtsMs:0,writeResidualMs:0}),G=Math.max(0,Math.min(Le,Ae)),Se=Math.max(G,Math.max(Le,Ae)),je=e=>new Promise(r=>setTimeout(r,e));function we(e){if(!e)return!1;let r=e.code,t=e.errcode;if(r==="ERR_SQLITE_BUSY"||r==="SQLITE_BUSY"||r==="ERR_SQLITE_ERROR"&&t===5)return!0;let n=e?.message??String(e);return typeof n=="string"&&n.toLowerCase().includes("database is locked")}function He(){if(Se<=G)return G;let e=Se-G;return G+Math.floor(Math.random()*(e+1))}async function se(e,r){let t=0,n=Date.now();for(;;)try{let i=e();return A&&t>0&&f(`[WriterWorker] ${r} recovered after retry`,{attempts:t,ms:Date.now()-n}),i}catch(i){if(!we(i)||t>=ge)throw f(`[WriterWorker] ${r} failed`,{attempts:t,ms:Date.now()-n,error:i?.message??String(i),locked:we(i)}),i;t+=1;let o=He();f(`[WriterWorker] ${r} retry ${t}/${ge} after locked database; waiting ${o}ms`),await je(o)}}var L=null,v=null,de=null,_e=null,Te=null,me=null,fe=null,C=null,K=null,w=null,h=null,V=null,q=null,H=new Map,M=new Map,Y=new Map,le=new Map,ae=Math.max(1e4,Number(process.env.PANDO_DICT_CACHE_MAX_ENTRIES||"200000")),Qe=Math.max(64,Number(process.env.PANDO_DICT_CACHE_MAX_KEY_LENGTH||"1024")),he=Math.floor(ae*.7),$=0,Q=null,O=null,z=null,J=null,Z=null,ee=null,ce,W=null,j={reference:1,call:2,new:4,type:8,import:16,export:32};function ue(){if(!L)throw new Error("writer not initialized");return L}function ve(e){v||(v=e.prepare("DELETE FROM nodes WHERE file_id = ?"),de=e.prepare("DELETE FROM exports WHERE file_id = ?"),_e=e.prepare("DELETE FROM files WHERE file_id = ?"),Te=e.prepare("DELETE FROM file_imports WHERE file_id = ?"),me=e.prepare("DELETE FROM file_import_bindings WHERE file_id = ?"),fe=e.prepare("DELETE FROM file_symbol_mentions WHERE file_id = ?"))}function te(e){C||(C=e.prepare("INSERT OR IGNORE INTO dict_kinds (text) VALUES (?)"),K=e.prepare("SELECT id FROM dict_kinds WHERE text = ?")),w||(w=e.prepare("INSERT OR IGNORE INTO dict_symbols (text) VALUES (?)"),h=e.prepare("SELECT id FROM dict_symbols WHERE text = ?")),V||(V=e.prepare("INSERT OR IGNORE INTO dict_files (path) VALUES (?)"),q=e.prepare("SELECT id FROM dict_files WHERE path = ?"))}function b(e,r,t,n,i){if(!i)return null;let o=i.length<=Qe,l=o?r.get(i):void 0;if(l!=null)return l;t.run(i);let c=n.get(i);if(!c||typeof c.id!="number")return null;if(o){if(r.size>=ae){let T=0;for(let p of r.keys())if(r.delete(p),T+=1,r.size<=he)break;$+=1,($<=10||$%25===0)&&f("[WriterWorker] dictionary cache trimmed",{trimCount:$,removed:T,maxEntries:ae,targetAfterTrim:he,cacheSizeAfter:r.size})}r.set(i,c.id)}return c.id}function Ve(e,r){te(e);let t=Y.get(r);if(t!=null)return t;V.run(r);let n=q.get(r);if(!n||typeof n.id!="number")throw new Error(`Failed to resolve file id for ${r}`);return Y.set(r,n.id),n.id}function qe(e,r){te(e);let t=Y.get(r);if(t!=null)return t;let n=q.get(r);return!n||typeof n.id!="number"?null:(Y.set(r,n.id),n.id)}function Je(e,r,t){te(e);let n=new Map;if(Array.isArray(r.symbolMentionRows)&&r.symbolMentionRows.length>0){for(let i of r.symbolMentionRows){let o=typeof i?.[0]=="string"?String(i[0]).trim():"";if(!o)continue;let l=b(e,M,w,h,o);if(l==null)continue;let c=typeof i?.[1]=="string"?String(i[1]).trim().toLowerCase():"",T=j[c]??j.reference,p=typeof i?.[2]=="string"?String(i[2]).trim():"",a=typeof i?.[3]=="string"?String(i[3]).trim():"",s=Number(i?.[4]),I=Number.isFinite(s)&&s>0?Math.floor(s):1,E=`${l}\0${p}\0${a}`,_=n.get(E);if(_){_.mentionKinds|=T,_.mentionCount+=I;continue}n.set(E,{symbolId:l,targetSymbolKey:p,containerQualifiedName:a,mentionKinds:T,mentionCount:I})}return Array.from(n.values()).map(i=>[t,r.lang,i.symbolId,i.targetSymbolKey,i.containerQualifiedName,i.mentionKinds,i.mentionCount])}for(let i of r.referenceRows||[]){let o=typeof i?.[3]=="string"?String(i[3]).trim():"";if(!o)continue;let l=b(e,M,w,h,o);if(l==null)continue;let c=typeof i?.[4]=="string"?String(i[4]).trim().toLowerCase():"",T=j[c]??j.reference,p=typeof i?.[13]=="string"?String(i[13]).trim():"",a=typeof i?.[12]=="string"?String(i[12]).trim():"",s=`${l}\0${p}\0${a}`,I=n.get(s);if(I){I.mentionKinds|=T,I.mentionCount+=1;continue}n.set(s,{symbolId:l,targetSymbolKey:p,containerQualifiedName:a,mentionKinds:T,mentionCount:1})}return Array.from(n.values()).map(i=>[t,r.lang,i.symbolId,i.targetSymbolKey,i.containerQualifiedName,i.mentionKinds,i.mentionCount])}function ke(e,r){let t=r?.journal_mode||"WAL";e.pragma(`journal_mode=${t}`),e.pragma("synchronous=OFF"),e.pragma("temp_store=MEMORY"),e.pragma("cache_size=-20000"),e.pragma("mmap_size=268435456"),e.pragma("journal_size_limit=134217728"),e.pragma("wal_autocheckpoint=1000"),e.pragma("busy_timeout=5000")}function oe(e){try{return Ee.statSync(e).size}catch{return null}}function P(e){if(!W)return;let r=`${W}-wal`,t=`${W}-shm`,n=oe(W),i=oe(r),o=oe(t);f("[WriterWorker] db sizes",{reason:e,dbPath:W,dbSize:n,walSize:i,shmSize:o})}function Ze(e){let r=B.dirname(e),t=B.basename(e),n=t.replace(".pando-index-chunk-",".pando-fts-chunk-");return B.join(r,n===t?`${t}.fts`:n)}function ye(){if(!Q)throw new Error("FTS database path not configured");if(!O){try{Ee.mkdirSync(B.dirname(Q),{recursive:!0})}catch{}O=new ie(Q),ke(O,ce)}return O}function et(e){z||(e.exec("CREATE VIRTUAL TABLE IF NOT EXISTS blob_content_fts USING fts5(blob_oid UNINDEXED, content)"),e.exec("CREATE TABLE IF NOT EXISTS blob_fts_presence (blob_oid TEXT PRIMARY KEY)"),z=e.prepare("SELECT 1 FROM blob_fts_presence WHERE blob_oid = ?"),J=e.prepare("INSERT INTO blob_content_fts (blob_oid, content) VALUES (?, ?)"),Z=e.prepare("INSERT OR REPLACE INTO blob_fts_presence (blob_oid) VALUES (?)"),ee=e.prepare("DELETE FROM blob_content_fts WHERE blob_oid = ?"))}function tt(e,r){if(!e||typeof e.blobOid!="string"||e.blobOid.length===0)return;let t=ye();et(t);let n=Date.now();r?.inTransaction||t.exec("BEGIN");try{z.get(e.blobOid)&&ee.run(e.blobOid),J.run(e.blobOid,e.content??""),Z.run(e.blobOid),r?.inTransaction||t.exec("COMMIT")}catch(o){if(!r?.inTransaction)try{t.exec("ROLLBACK")}catch(l){R("[WriterWorker] rollback failed:",l?.message??l)}throw o}let i=Date.now()-n;i>2e3&&f("[WriterWorker] slow fts insert",{blobOid:e.blobOid,ms:i,contentBytes:e.content?e.content.length:0})}function nt(e,r,t,n){let i=`${r}|${t}|${n}`,o=le.get(i);if(!o){let l=Array.from({length:n},()=>`(${new Array(t).fill("?").join(",")})`).join(","),c=`${r} VALUES ${l}`;o=e.prepare(c),le.set(i,o)}return o}function F(e,r,t,n){if(!n.length||t<=0)return;let i=Date.now(),o=Math.max(1,Math.floor(999/t));for(let c=0;c<n.length;c+=o){let T=n.slice(c,c+o);if(!T.length)continue;let p=nt(e,r,t,T.length),a=[];for(let E of T)a.push(...E);let s=Date.now();p.run(...a);let I=Date.now()-s;I>500&&f("[WriterWorker] slow insert chunk",{sqlPrefix:r,columnCount:t,rows:T.length,ms:I})}let l=Date.now()-i;l>2e3&&f("[WriterWorker] slow insertRows",{sqlPrefix:r,columnCount:t,rows:n.length,ms:l})}function De(e,r){ve(e);let t=qe(e,r);t!=null&&(v.run(t),de.run(t),_e.run(t),Te.run(t),me.run(t),fe.run(t))}function rt(e){if(!e.length)return x();let r=ue(),t=x(),n=Date.now();r.exec("BEGIN");try{for(let i of e)De(r,i);r.exec("COMMIT")}catch(i){try{r.exec("ROLLBACK")}catch(o){R("[WriterWorker] rollback failed:",o?.message??o)}throw i}return t.writePreDeleteMs=Date.now()-n,t.writeTrackedMs=t.writePreDeleteMs,t.writeMs=t.writePreDeleteMs,t}function xe(e,r){let t=ue();te(t);let n=x(),i=Date.now(),o=Ve(t,e.fileRel),l={exports:e.exportRows.length,nodes:e.nodeRows.length,refs:e.referenceRows.length,imports:e.importRows.length,importBindings:e.importBindingRows.length,fileRow:e.fileRow?1:0,fts:e.fts?1:0},c=l.exports+l.nodes+l.refs+l.imports+l.importBindings;r?.inTransaction||t.exec("BEGIN");try{if(t.exec("SAVEPOINT idx_file"),!e.preDeleted){let a=Date.now();De(t,e.fileRel),n.writePreDeleteMs+=Date.now()-a}let T=(a,s,I,E)=>{let _=Date.now();A&&f("[WriterWorker] section begin",{file:e.fileRel,label:s,count:I});let k=Date.now();E();let d=Date.now()-k;n[a]+=d,A&&f("[WriterWorker] section end",{file:e.fileRel,label:s,count:I,ms:d,elapsedSinceWriteStartMs:Date.now()-_}),d>2e3&&f("[WriterWorker] section slow",{file:e.fileRel,label:s,count:I,ms:d})};T("writeInsertExportsMs","exports",e.exportRows.length,()=>{let a=e.exportRows.map(E=>[o,e.lang,b(t,M,w,h,E[1]),U(E[2]),E[3],E[4]??null,b(t,M,w,h,E[5]),E[6]??null,E[7]??null]),s=[],I=new Map;for(let E of a){let _=E[2];_!=null&&(I.has(_)||(I.set(_,E),s.push(E)))}s.length!==a.length&&R("[WriterWorker] export rows deduped",{file:e.fileRel,lang:e.lang,before:a.length,after:s.length});try{F(t,"INSERT OR REPLACE INTO exports (file_id, lang, export_name_id, node_id, is_reexport, reexport_from, reexport_name_id, export_kind, target_symbol_key)",9,s)}catch(E){try{let _=new Map;for(let d of a){let u=d[2];u!=null&&_.set(u,(_.get(u)??0)+1)}let k=Array.from(_.entries()).filter(([,d])=>d>1);if(k.length){let d=t.prepare("SELECT text FROM dict_symbols WHERE id = ?"),u=k.map(([m,ne])=>{let Fe=d.get(m)?.text??null,We=a.filter(y=>y[2]===m).map(y=>({node_id:y[3],is_reexport:y[4],reexport_from:y[5],reexport_name_id:y[6],export_kind:y[7],target_symbol_key:y[8]}));return{id:m,count:ne,name:Fe,rows:We}});R("[WriterWorker] export duplicates detected",{file:e.fileRel,lang:e.lang,totalExports:a.length,duplicates:u});let N=a.map(m=>{let ne=m[2]!=null?d.get(m[2]):void 0,Ie=m[6]?d.get(m[6]):void 0;return{name_id:m[2],name:ne?.text??null,node_id:m[3],is_reexport:m[4],reexport_from:m[5],reexport_name_id:m[6],reexport_name:Ie?.text??null,export_kind:m[7],target_symbol_key:m[8]}});R("[WriterWorker] export rows dump",{file:e.fileRel,lang:e.lang,rows:N})}}catch(_){R("[WriterWorker] failed to compute export duplicates",_?.message??_)}throw R("[WriterWorker] export insert failed",{file:e.fileRel,lang:e.lang,exportCount:s.length,error:E?.message??E}),E}}),T("writeInsertNodesMs","nodes",e.nodeRows.length,()=>{for(let s of e.nodeRows){let I=s[2],E=s[3],_=s[4];if(!I||!String(I).trim())throw new Error(`[WriterWorker] Missing normalized kind for node in ${e.fileRel}`);if(!E||!String(E).trim())throw new Error(`[WriterWorker] Missing raw kind for node in ${e.fileRel}`);if(!_||!String(_).trim())throw new Error(`[WriterWorker] Missing raw kind source for node in ${e.fileRel}`)}let a=e.nodeRows.map(s=>[U(s[0]),o,e.lang,b(t,M,w,h,s[1]),b(t,H,C,K,s[2]),s[3],s[4],b(t,H,C,K,s[5]),s[6],s[7],s[8],b(t,H,C,K,s[9]),s[10],s[11],s[12],s[13],s[14],s[15],s[16]]);try{F(t,"INSERT OR REPLACE INTO nodes (id, file_id, lang, name_id, kind_id, raw_kind, raw_kind_source, semantic_kind_id, start_pos, end_pos, is_exported, container_kind_id, container_raw_kind, container_raw_kind_source, param_count, qualified_name, scope_chain, symbol_key, metadata)",19,a)}catch(s){if((s?.message??String(s)).includes("UNIQUE constraint failed: nodes.id")){try{let E=new Map;for(let d of e.nodeRows){let u=U(d[0]);if(u==null)continue;let N=u.toString(),m=E.get(N);m?(m.count+=1,m.rawSample.length<3&&m.rawSample.push(d[0])):E.set(N,{count:1,rawSample:[d[0]]})}let _=Array.from(E.entries()).filter(([,d])=>d.count>1).slice(0,5).map(([d,u])=>({id:d,count:u.count,rawSample:u.rawSample})),k=_.map(d=>{let u=e.nodeRows.filter(N=>{let m=U(N[0]);return m!=null&&m.toString()===d.id}).slice(0,3);return{id:d.id,count:d.count,rows:u.map(N=>({rawId:N[0],name:N[1],kind:N[2],rawKind:N[3],semanticKind:N[5],start:N[6],end:N[7],containerKind:N[9],paramCount:N[12]}))}});f("[WriterWorker] UNIQUE nodes.id collision",{file:e.fileRel,lang:e.lang,nodeCount:a.length,duplicateCount:_.length,duplicates:_,duplicateDetails:k})}catch{}try{let E=t.prepare("SELECT id, file_id, lang, start_pos, end_pos FROM nodes WHERE id = ?"),_=t.prepare("SELECT path FROM dict_files WHERE id = ?");for(let k of a){let d=k[0];if(d==null)continue;let u=E.get(d);if(u&&typeof u.file_id=="number"){let N=_.get(u.file_id);f("[WriterWorker] nodes.id collision existing row",{file:e.fileRel,lang:e.lang,nodeId:d?.toString?.()??String(d),existingFileId:u.file_id,existingPath:N?.path,existingLang:u.lang,existingRange:{start:u.start_pos,end:u.end_pos}});break}}}catch{}}throw s}}),T("writeInsertReferencesMs","references",e.referenceRows.length,()=>{let a=Je(t,e,o);A&&e.lang==="clojure"&&a.length>0&&ze({stage:"writer-symbol-mentions",file:e.fileRel,refs:e.referenceRows.length,mentionRows:a.length,sample:a.slice(0,5).map(s=>({symbolId:s[2],mentionKinds:s[3],mentionCount:s[4]}))}),F(t,"INSERT OR REPLACE INTO file_symbol_mentions (file_id, lang, symbol_id, target_symbol_key, container_qualified_name, mention_kinds, mention_count)",7,a)}),T("writeInsertImportsMs","imports",e.importRows.length,()=>{let a=e.importRows.map(s=>[o,e.lang,s[1]??null,s[2]]);F(t,"INSERT INTO file_imports (file_id, lang, module_spec, is_type_only)",4,a)}),T("writeInsertImportBindingsMs","import_bindings",e.importBindingRows.length,()=>{let a=e.importBindingRows.map(s=>[o,e.lang,s[1]??null,b(t,M,w,h,s[2]),b(t,M,w,h,s[3]),b(t,M,w,h,s[4]),s[5]]);F(t,"INSERT INTO file_import_bindings (file_id, lang, module_spec, binding_kind_id, local_name_id, imported_name_id, is_type_only)",7,a)}),T("writeInsertFileMs","files",e.fileRow?1:0,()=>{let a=e.fileRow,s=[o,e.lang,a[1],a[2],a[3],a[4]];F(t,"INSERT OR REPLACE INTO files (file_id, lang, last_modified, file_size, status, indexed_at)",6,[s])}),T("writeInsertFtsMs","fts",e.fts?1:0,()=>tt(e.fts,{inTransaction:r?.inTransaction}));let p=Date.now();t.exec("RELEASE SAVEPOINT idx_file"),r?.inTransaction||t.exec("COMMIT"),n.writeFinalizeMs+=Date.now()-p}catch(T){try{t.exec("ROLLBACK TO SAVEPOINT idx_file")}catch(p){R("[WriterWorker] rollback to savepoint failed:",p?.message??p)}if(!r?.inTransaction)try{t.exec("ROLLBACK")}catch(p){R("[WriterWorker] rollback failed:",p?.message??p)}throw T}return n.writeMs=Date.now()-i,n.writeTrackedMs=n.writePreDeleteMs+n.writeInsertExportsMs+n.writeInsertNodesMs+n.writeInsertImportsMs+n.writeInsertImportBindingsMs+n.writeInsertFileMs+n.writeInsertFtsMs+n.writeFinalizeMs,n.writeResidualMs=Math.max(0,n.writeMs-n.writeTrackedMs),n}function it(e){if(!e.length)return x();let r=Date.now(),t=x(),n=ue(),i=e.some(l=>l.fts&&typeof l.fts.blobOid=="string"&&l.fts.blobOid.length>0),o=null;n.exec("BEGIN");try{i&&(o=ye(),o.exec("BEGIN"));for(let l of e){let c=xe(l,{inTransaction:!0});t.writePreDeleteMs+=c.writePreDeleteMs,t.writeInsertExportsMs+=c.writeInsertExportsMs,t.writeInsertNodesMs+=c.writeInsertNodesMs,t.writeInsertReferencesMs+=c.writeInsertReferencesMs,t.writeInsertImportsMs+=c.writeInsertImportsMs,t.writeInsertImportBindingsMs+=c.writeInsertImportBindingsMs,t.writeInsertFileMs+=c.writeInsertFileMs,t.writeFinalizeMs+=c.writeFinalizeMs,t.writeInsertFtsMs+=c.writeInsertFtsMs}o&&o.exec("COMMIT"),n.exec("COMMIT")}catch(l){if(f("[WriterWorker] handleWriteBatch error",{error:l?.message??l,stack:l?.stack?.split(`
|
|
234
|
-
|
|
241
|
+
`),k(e,"files","fully_indexed","INTEGER DEFAULT 0"),k(e,"nodes","parent_node_id","INTEGER"),k(e,"nodes","role","TEXT"),k(e,"nodes","index_in_parent","INTEGER"),k(e,"nodes","depth","INTEGER DEFAULT 0"),k(e,"nodes","body_start_pos","INTEGER"),k(e,"nodes","body_end_pos","INTEGER"),e.exec(`
|
|
242
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent_node_id);
|
|
243
|
+
`)}function k(e,r,t,n){e.prepare(`PRAGMA table_info("${r.replace(/"/g,'""')}")`).all().some(o=>o.name===t)||e.exec(`ALTER TABLE "${r.replace(/"/g,'""')}" ADD COLUMN ${t} ${n}`)}var Le=Number(process.env.PANDO_SQLITE_RETRY_MIN_MS||"100"),ye=Number(process.env.PANDO_SQLITE_RETRY_MAX_MS||"500"),be=Math.max(0,Number(process.env.PANDO_SQLITE_RETRY_ATTEMPTS||"5")),L=pe();if(!S)throw new Error("SQLite writer worker must be spawned as a worker thread");Re();function u(...e){process.env.PANDO_QUIET||console.log(Ke([`[${new Date().toISOString()}]`,...e]))}function Ke(e){return e.map(Ye).join(" ")}function Ye(e){if(typeof e=="string")return e;if(e instanceof Error)return e.stack||e.message;try{let r=JSON.stringify(e);if(typeof r=="string")return r}catch{}return Be(e,{depth:null,breakLength:1/0,compact:!0})}function R(...e){L&&console.log(...e)}function $e(e){L&&ie("WriterWorker",e,{threadId:Ae})}function ze(e){L&&ie("WriterWorker","clojure-source-node",{threadId:Ae,...e})}var x=null,Se=null;function je(){Se||(Se=setInterval(()=>{if(!x)return;let e=Date.now()-x.startedAt;e>5e3&&u("[WriterWorker] op still running",{cmd:x.cmd,id:x.id,ms:e,fileRel:x.fileRel})},2e3))}function C(e,r,t){x={cmd:e,id:r,startedAt:Date.now(),fileRel:t},je()}function g(){x=null}var X=()=>({writeMs:0,writeTrackedMs:0,writePreDeleteMs:0,writeInsertExportsMs:0,writeInsertNodesMs:0,writeInsertReferencesMs:0,writeInsertImportsMs:0,writeInsertImportBindingsMs:0,writeInsertFileMs:0,writeFinalizeMs:0,writeInsertFtsMs:0,writeResidualMs:0}),B=Math.max(0,Math.min(Le,ye)),we=Math.max(B,Math.max(Le,ye)),He=e=>new Promise(r=>setTimeout(r,e));function he(e){if(!e)return!1;let r=e.code,t=e.errcode;if(r==="ERR_SQLITE_BUSY"||r==="SQLITE_BUSY"||r==="ERR_SQLITE_ERROR"&&t===5)return!0;let n=e?.message??String(e);return typeof n=="string"&&n.toLowerCase().includes("database is locked")}function Qe(){if(we<=B)return B;let e=we-B;return B+Math.floor(Math.random()*(e+1))}async function oe(e,r){let t=0,n=Date.now();for(;;)try{let i=e();return L&&t>0&&u(`[WriterWorker] ${r} recovered after retry`,{attempts:t,ms:Date.now()-n}),i}catch(i){if(!he(i)||t>=be)throw u(`[WriterWorker] ${r} failed`,{attempts:t,ms:Date.now()-n,error:i?.message??String(i),locked:he(i)}),i;t+=1;let o=Qe();u(`[WriterWorker] ${r} retry ${t}/${be} after locked database; waiting ${o}ms`),await He(o)}}var A=null,V=null,_e=null,Te=null,me=null,fe=null,ue=null,P=null,Y=null,w=null,h=null,q=null,J=null,Q=new Map,M=new Map,$=new Map,ae=new Map,Ee=Math.max(1e4,Number(process.env.PANDO_DICT_CACHE_MAX_ENTRIES||"200000")),ve=Math.max(64,Number(process.env.PANDO_DICT_CACHE_MAX_KEY_LENGTH||"1024")),Oe=Math.floor(Ee*.7),j=0,v=null,O=null,z=null,Z=null,ee=null,te=null,de,U=null,H={reference:1,call:2,new:4,type:8,import:16,export:32};function Ie(){if(!A)throw new Error("writer not initialized");return A}function Ve(e){V||(V=e.prepare("DELETE FROM nodes WHERE file_id = ?"),_e=e.prepare("DELETE FROM exports WHERE file_id = ?"),Te=e.prepare("DELETE FROM files WHERE file_id = ?"),me=e.prepare("DELETE FROM file_imports WHERE file_id = ?"),fe=e.prepare("DELETE FROM file_import_bindings WHERE file_id = ?"),ue=e.prepare("DELETE FROM file_symbol_mentions WHERE file_id = ?"))}function ne(e){P||(P=e.prepare("INSERT OR IGNORE INTO dict_kinds (text) VALUES (?)"),Y=e.prepare("SELECT id FROM dict_kinds WHERE text = ?")),w||(w=e.prepare("INSERT OR IGNORE INTO dict_symbols (text) VALUES (?)"),h=e.prepare("SELECT id FROM dict_symbols WHERE text = ?")),q||(q=e.prepare("INSERT OR IGNORE INTO dict_files (path) VALUES (?)"),J=e.prepare("SELECT id FROM dict_files WHERE path = ?"))}function b(e,r,t,n,i){if(!i)return null;let o=i.length<=ve,l=o?r.get(i):void 0;if(l!=null)return l;t.run(i);let E=n.get(i);if(!E||typeof E.id!="number")return null;if(o){if(r.size>=Ee){let T=0;for(let p of r.keys())if(r.delete(p),T+=1,r.size<=Oe)break;j+=1,(j<=10||j%25===0)&&u("[WriterWorker] dictionary cache trimmed",{trimCount:j,removed:T,maxEntries:Ee,targetAfterTrim:Oe,cacheSizeAfter:r.size})}r.set(i,E.id)}return E.id}function qe(e,r){ne(e);let t=$.get(r);if(t!=null)return t;q.run(r);let n=J.get(r);if(!n||typeof n.id!="number")throw new Error(`Failed to resolve file id for ${r}`);return $.set(r,n.id),n.id}function Je(e,r){ne(e);let t=$.get(r);if(t!=null)return t;let n=J.get(r);return!n||typeof n.id!="number"?null:($.set(r,n.id),n.id)}function Ze(e,r,t){ne(e);let n=new Map;if(Array.isArray(r.symbolMentionRows)&&r.symbolMentionRows.length>0){for(let i of r.symbolMentionRows){let o=typeof i?.[0]=="string"?String(i[0]).trim():"";if(!o)continue;let l=b(e,M,w,h,o);if(l==null)continue;let E=typeof i?.[1]=="string"?String(i[1]).trim().toLowerCase():"",T=H[E]??H.reference,p=typeof i?.[2]=="string"?String(i[2]).trim():"",a=typeof i?.[3]=="string"?String(i[3]).trim():"",s=Number(i?.[4]),f=Number.isFinite(s)&&s>0?Math.floor(s):1,d=`${l}\0${p}\0${a}`,_=n.get(d);if(_){_.mentionKinds|=T,_.mentionCount+=f;continue}n.set(d,{symbolId:l,targetSymbolKey:p,containerQualifiedName:a,mentionKinds:T,mentionCount:f})}return Array.from(n.values()).map(i=>[t,r.lang,i.symbolId,i.targetSymbolKey,i.containerQualifiedName,i.mentionKinds,i.mentionCount])}for(let i of r.referenceRows||[]){let o=typeof i?.[3]=="string"?String(i[3]).trim():"";if(!o)continue;let l=b(e,M,w,h,o);if(l==null)continue;let E=typeof i?.[4]=="string"?String(i[4]).trim().toLowerCase():"",T=H[E]??H.reference,p=typeof i?.[13]=="string"?String(i[13]).trim():"",a=typeof i?.[12]=="string"?String(i[12]).trim():"",s=`${l}\0${p}\0${a}`,f=n.get(s);if(f){f.mentionKinds|=T,f.mentionCount+=1;continue}n.set(s,{symbolId:l,targetSymbolKey:p,containerQualifiedName:a,mentionKinds:T,mentionCount:1})}return Array.from(n.values()).map(i=>[t,r.lang,i.symbolId,i.targetSymbolKey,i.containerQualifiedName,i.mentionKinds,i.mentionCount])}function De(e,r){let t=r?.journal_mode||"WAL";e.pragma(`journal_mode=${t}`),e.pragma("synchronous=OFF"),e.pragma("temp_store=MEMORY"),e.pragma("cache_size=-20000"),e.pragma("mmap_size=268435456"),e.pragma("journal_size_limit=134217728"),e.pragma("wal_autocheckpoint=1000"),e.pragma("busy_timeout=5000")}function le(e){try{return ce.statSync(e).size}catch{return null}}function G(e){if(!U)return;let r=`${U}-wal`,t=`${U}-shm`,n=le(U),i=le(r),o=le(t);u("[WriterWorker] db sizes",{reason:e,dbPath:U,dbSize:n,walSize:i,shmSize:o})}function et(e){let r=K.dirname(e),t=K.basename(e),n=t.replace(".pando-index-chunk-",".pando-fts-chunk-");return K.join(r,n===t?`${t}.fts`:n)}function ke(){if(!v)throw new Error("FTS database path not configured");if(!O){try{ce.mkdirSync(K.dirname(v),{recursive:!0})}catch{}O=new se(v),De(O,de)}return O}function tt(e){z||(e.exec("CREATE VIRTUAL TABLE IF NOT EXISTS blob_content_fts USING fts5(blob_oid UNINDEXED, content)"),e.exec("CREATE TABLE IF NOT EXISTS blob_fts_presence (blob_oid TEXT PRIMARY KEY)"),z=e.prepare("SELECT 1 FROM blob_fts_presence WHERE blob_oid = ?"),Z=e.prepare("INSERT INTO blob_content_fts (blob_oid, content) VALUES (?, ?)"),ee=e.prepare("INSERT OR REPLACE INTO blob_fts_presence (blob_oid) VALUES (?)"),te=e.prepare("DELETE FROM blob_content_fts WHERE blob_oid = ?"))}function nt(e,r){if(!e||typeof e.blobOid!="string"||e.blobOid.length===0)return;let t=ke();tt(t);let n=Date.now();r?.inTransaction||t.exec("BEGIN");try{z.get(e.blobOid)&&te.run(e.blobOid),Z.run(e.blobOid,e.content??""),ee.run(e.blobOid),r?.inTransaction||t.exec("COMMIT")}catch(o){if(!r?.inTransaction)try{t.exec("ROLLBACK")}catch(l){R("[WriterWorker] rollback failed:",l?.message??l)}throw o}let i=Date.now()-n;i>2e3&&u("[WriterWorker] slow fts insert",{blobOid:e.blobOid,ms:i,contentBytes:e.content?e.content.length:0})}function rt(e,r,t,n){let i=`${r}|${t}|${n}`,o=ae.get(i);if(!o){let l=Array.from({length:n},()=>`(${new Array(t).fill("?").join(",")})`).join(","),E=`${r} VALUES ${l}`;o=e.prepare(E),ae.set(i,o)}return o}function W(e,r,t,n){if(!n.length||t<=0)return;let i=Date.now(),o=Math.max(1,Math.floor(999/t));for(let E=0;E<n.length;E+=o){let T=n.slice(E,E+o);if(!T.length)continue;let p=rt(e,r,t,T.length),a=[];for(let d of T)a.push(...d);let s=Date.now();p.run(...a);let f=Date.now()-s;f>500&&u("[WriterWorker] slow insert chunk",{sqlPrefix:r,columnCount:t,rows:T.length,ms:f})}let l=Date.now()-i;l>2e3&&u("[WriterWorker] slow insertRows",{sqlPrefix:r,columnCount:t,rows:n.length,ms:l})}function xe(e,r){Ve(e);let t=Je(e,r);t!=null&&(V.run(t),_e.run(t),Te.run(t),me.run(t),fe.run(t),ue.run(t))}function it(e){if(!e.length)return X();let r=Ie(),t=X(),n=Date.now();r.exec("BEGIN");try{for(let i of e)xe(r,i);r.exec("COMMIT")}catch(i){try{r.exec("ROLLBACK")}catch(o){R("[WriterWorker] rollback failed:",o?.message??o)}throw i}return t.writePreDeleteMs=Date.now()-n,t.writeTrackedMs=t.writePreDeleteMs,t.writeMs=t.writePreDeleteMs,t}function Xe(e,r){let t=Ie();ne(t);let n=X(),i=Date.now(),o=qe(t,e.fileRel),l={exports:e.exportRows.length,nodes:e.nodeRows.length,refs:e.referenceRows.length,imports:e.importRows.length,importBindings:e.importBindingRows.length,fileRow:e.fileRow?1:0,fts:e.fts?1:0},E=l.exports+l.nodes+l.refs+l.imports+l.importBindings;r?.inTransaction||t.exec("BEGIN");try{if(t.exec("SAVEPOINT idx_file"),!e.preDeleted){let a=Date.now();xe(t,e.fileRel),n.writePreDeleteMs+=Date.now()-a}let T=(a,s,f,d)=>{let _=Date.now();L&&u("[WriterWorker] section begin",{file:e.fileRel,label:s,count:f});let y=Date.now();d();let c=Date.now()-y;n[a]+=c,L&&u("[WriterWorker] section end",{file:e.fileRel,label:s,count:f,ms:c,elapsedSinceWriteStartMs:Date.now()-_}),c>2e3&&u("[WriterWorker] section slow",{file:e.fileRel,label:s,count:f,ms:c})};T("writeInsertExportsMs","exports",e.exportRows.length,()=>{let a=e.exportRows.map(d=>[o,e.lang,b(t,M,w,h,d[1]),F(d[2]),d[3],d[4]??null,b(t,M,w,h,d[5]),d[6]??null,d[7]??null]),s=[],f=new Map;for(let d of a){let _=d[2];_!=null&&(f.has(_)||(f.set(_,d),s.push(d)))}s.length!==a.length&&R("[WriterWorker] export rows deduped",{file:e.fileRel,lang:e.lang,before:a.length,after:s.length});try{W(t,"INSERT OR REPLACE INTO exports (file_id, lang, export_name_id, node_id, is_reexport, reexport_from, reexport_name_id, export_kind, target_symbol_key)",9,s)}catch(d){try{let _=new Map;for(let c of a){let I=c[2];I!=null&&_.set(I,(_.get(I)??0)+1)}let y=Array.from(_.entries()).filter(([,c])=>c>1);if(y.length){let c=t.prepare("SELECT text FROM dict_symbols WHERE id = ?"),I=y.map(([m,re])=>{let Ce=c.get(m)?.text??null,We=a.filter(D=>D[2]===m).map(D=>({node_id:D[3],is_reexport:D[4],reexport_from:D[5],reexport_name_id:D[6],export_kind:D[7],target_symbol_key:D[8]}));return{id:m,count:re,name:Ce,rows:We}});R("[WriterWorker] export duplicates detected",{file:e.fileRel,lang:e.lang,totalExports:a.length,duplicates:I});let N=a.map(m=>{let re=m[2]!=null?c.get(m[2]):void 0,Ne=m[6]?c.get(m[6]):void 0;return{name_id:m[2],name:re?.text??null,node_id:m[3],is_reexport:m[4],reexport_from:m[5],reexport_name_id:m[6],reexport_name:Ne?.text??null,export_kind:m[7],target_symbol_key:m[8]}});R("[WriterWorker] export rows dump",{file:e.fileRel,lang:e.lang,rows:N})}}catch(_){R("[WriterWorker] failed to compute export duplicates",_?.message??_)}throw R("[WriterWorker] export insert failed",{file:e.fileRel,lang:e.lang,exportCount:s.length,error:d?.message??d}),d}}),T("writeInsertNodesMs","nodes",e.nodeRows.length,()=>{for(let s of e.nodeRows){let f=s[2],d=s[3],_=s[4];if(!f||!String(f).trim())throw new Error(`[WriterWorker] Missing normalized kind for node in ${e.fileRel}`);if(!d||!String(d).trim())throw new Error(`[WriterWorker] Missing raw kind for node in ${e.fileRel}`);if(!_||!String(_).trim())throw new Error(`[WriterWorker] Missing raw kind source for node in ${e.fileRel}`)}let a=e.nodeRows.map(s=>[F(s[0]),o,e.lang,b(t,M,w,h,s[1]),b(t,Q,P,Y,s[2]),s[3],s[4],b(t,Q,P,Y,s[5]),s[6],s[7],s[8],b(t,Q,P,Y,s[9]),s[10],s[11],s[12],s[13],s[14],s[15],s[16],F(s[17]),s[18]??null,s[19]??null,s[20]??null,s[21]??null,s[22]??null]);try{W(t,"INSERT OR REPLACE INTO nodes (id, file_id, lang, name_id, kind_id, raw_kind, raw_kind_source, semantic_kind_id, start_pos, end_pos, is_exported, container_kind_id, container_raw_kind, container_raw_kind_source, param_count, qualified_name, scope_chain, symbol_key, metadata, parent_node_id, role, index_in_parent, depth, body_start_pos, body_end_pos)",25,a)}catch(s){if((s?.message??String(s)).includes("UNIQUE constraint failed: nodes.id")){try{let d=new Map;for(let c of e.nodeRows){let I=F(c[0]);if(I==null)continue;let N=I.toString(),m=d.get(N);m?(m.count+=1,m.rawSample.length<3&&m.rawSample.push(c[0])):d.set(N,{count:1,rawSample:[c[0]]})}let _=Array.from(d.entries()).filter(([,c])=>c.count>1).slice(0,5).map(([c,I])=>({id:c,count:I.count,rawSample:I.rawSample})),y=_.map(c=>{let I=e.nodeRows.filter(N=>{let m=F(N[0]);return m!=null&&m.toString()===c.id}).slice(0,3);return{id:c.id,count:c.count,rows:I.map(N=>({rawId:N[0],name:N[1],kind:N[2],rawKind:N[3],semanticKind:N[5],start:N[6],end:N[7],containerKind:N[9],paramCount:N[12]}))}});u("[WriterWorker] UNIQUE nodes.id collision",{file:e.fileRel,lang:e.lang,nodeCount:a.length,duplicateCount:_.length,duplicates:_,duplicateDetails:y})}catch{}try{let d=t.prepare("SELECT id, file_id, lang, start_pos, end_pos FROM nodes WHERE id = ?"),_=t.prepare("SELECT path FROM dict_files WHERE id = ?");for(let y of a){let c=y[0];if(c==null)continue;let I=d.get(c);if(I&&typeof I.file_id=="number"){let N=_.get(I.file_id);u("[WriterWorker] nodes.id collision existing row",{file:e.fileRel,lang:e.lang,nodeId:c?.toString?.()??String(c),existingFileId:I.file_id,existingPath:N?.path,existingLang:I.lang,existingRange:{start:I.start_pos,end:I.end_pos}});break}}}catch{}}throw s}}),T("writeInsertReferencesMs","references",e.referenceRows.length,()=>{let a=Ze(t,e,o);L&&e.lang==="clojure"&&a.length>0&&ze({stage:"writer-symbol-mentions",file:e.fileRel,refs:e.referenceRows.length,mentionRows:a.length,sample:a.slice(0,5).map(s=>({symbolId:s[2],mentionKinds:s[3],mentionCount:s[4]}))}),W(t,"INSERT OR REPLACE INTO file_symbol_mentions (file_id, lang, symbol_id, target_symbol_key, container_qualified_name, mention_kinds, mention_count)",7,a)}),T("writeInsertImportsMs","imports",e.importRows.length,()=>{let a=e.importRows.map(s=>[o,e.lang,s[1]??null,s[2]]);W(t,"INSERT INTO file_imports (file_id, lang, module_spec, is_type_only)",4,a)}),T("writeInsertImportBindingsMs","import_bindings",e.importBindingRows.length,()=>{let a=e.importBindingRows.map(s=>[o,e.lang,s[1]??null,b(t,M,w,h,s[2]),b(t,M,w,h,s[3]),b(t,M,w,h,s[4]),s[5]]);W(t,"INSERT INTO file_import_bindings (file_id, lang, module_spec, binding_kind_id, local_name_id, imported_name_id, is_type_only)",7,a)}),T("writeInsertFileMs","files",e.fileRow?1:0,()=>{let a=e.fileRow,s=e.fullyIndexed===!0||a[5]===1||a[5]===!0?1:0,f=[o,e.lang,a[1],a[2],a[3],a[4],s];W(t,"INSERT OR REPLACE INTO files (file_id, lang, last_modified, file_size, status, indexed_at, fully_indexed)",7,[f])}),T("writeInsertFtsMs","fts",e.fts?1:0,()=>nt(e.fts,{inTransaction:r?.inTransaction}));let p=Date.now();t.exec("RELEASE SAVEPOINT idx_file"),r?.inTransaction||t.exec("COMMIT"),n.writeFinalizeMs+=Date.now()-p}catch(T){try{t.exec("ROLLBACK TO SAVEPOINT idx_file")}catch(p){R("[WriterWorker] rollback to savepoint failed:",p?.message??p)}if(!r?.inTransaction)try{t.exec("ROLLBACK")}catch(p){R("[WriterWorker] rollback failed:",p?.message??p)}throw T}return n.writeMs=Date.now()-i,n.writeTrackedMs=n.writePreDeleteMs+n.writeInsertExportsMs+n.writeInsertNodesMs+n.writeInsertImportsMs+n.writeInsertImportBindingsMs+n.writeInsertFileMs+n.writeInsertFtsMs+n.writeFinalizeMs,n.writeResidualMs=Math.max(0,n.writeMs-n.writeTrackedMs),n}function st(e){if(!e.length)return X();let r=Date.now(),t=X(),n=Ie(),i=e.some(l=>l.fts&&typeof l.fts.blobOid=="string"&&l.fts.blobOid.length>0),o=null;n.exec("BEGIN");try{i&&(o=ke(),o.exec("BEGIN"));for(let l of e){let E=Xe(l,{inTransaction:!0});t.writePreDeleteMs+=E.writePreDeleteMs,t.writeInsertExportsMs+=E.writeInsertExportsMs,t.writeInsertNodesMs+=E.writeInsertNodesMs,t.writeInsertReferencesMs+=E.writeInsertReferencesMs,t.writeInsertImportsMs+=E.writeInsertImportsMs,t.writeInsertImportBindingsMs+=E.writeInsertImportBindingsMs,t.writeInsertFileMs+=E.writeInsertFileMs,t.writeFinalizeMs+=E.writeFinalizeMs,t.writeInsertFtsMs+=E.writeInsertFtsMs}o&&o.exec("COMMIT"),n.exec("COMMIT")}catch(l){if(u("[WriterWorker] handleWriteBatch error",{error:l?.message??l,stack:l?.stack?.split(`
|
|
244
|
+
`).slice(0,3).join(" | ")}),o)try{o.exec("ROLLBACK")}catch(E){R("[WriterWorker] fts batch rollback failed:",E?.message??E)}try{n.exec("ROLLBACK")}catch(E){R("[WriterWorker] batch rollback failed:",E?.message??E)}throw l}return t.writeTrackedMs=t.writePreDeleteMs+t.writeInsertExportsMs+t.writeInsertNodesMs+t.writeInsertReferencesMs+t.writeInsertImportsMs+t.writeInsertImportBindingsMs+t.writeInsertFileMs+t.writeInsertFtsMs+t.writeFinalizeMs,t.writeMs=Date.now()-r,t.writeResidualMs=Math.max(0,t.writeMs-t.writeTrackedMs),t}function Fe(){return X()}function Me(){try{Fe()}catch(e){R("[WriterWorker] backfill on shutdown failed:",e?.message??e)}if(A){try{A.close()}catch(e){R("[WriterWorker] failed to close database:",e?.message??e)}A=null}if(O){try{O.close()}catch(e){R("[WriterWorker] failed to close FTS database:",e?.message??e)}O=null}V=null,_e=null,Te=null,me=null,fe=null,ue=null,z=null,Z=null,ee=null,te=null,P=null,Y=null,w=null,h=null,q=null,J=null,ae.clear(),Q.clear(),M.clear(),$.clear()}S.on("message",async e=>{let r=(t,n)=>{let i=n instanceof Error?n:new Error(String(n));S.postMessage({type:"error",id:t,message:i.message,stack:i.stack})};if(e.cmd==="init"){try{let t=Date.now();C("init"),A&&Me();let n=e.dbPath;U=n,de=e.pragmas;try{ce.mkdirSync(K.dirname(n),{recursive:!0})}catch{}if(A=new se(n),De(A,de),ge(A),v=et(n),O)try{O.close()}catch(i){R("[WriterWorker] failed to close FTS database:",i?.message??i)}O=null,z=null,Z=null,ee=null,te=null,S.postMessage({type:"ready"}),u("[WriterWorker] init complete",{dbPath:n,ms:Date.now()-t}),G("init"),g()}catch(t){g(),r(void 0,t)}return}if(e.cmd==="write"){try{let t=Date.now(),n=e.payload,i=Array.isArray(n?.fileRow)&&typeof n.fileRow[0]=="string"?n.fileRow[0]:void 0;C("write",e.id,i);let o=await oe(()=>Xe(n),"write");S.postMessage({type:"response",id:e.id,metrics:o});let l=Date.now()-t;l>2e3&&(u("[WriterWorker] slow write",{id:e.id,ms:l}),G("slow write")),g()}catch(t){g(),r(e.id,t)}return}if(e.cmd==="batchPreDelete"){try{let t=Date.now();C("batchPreDelete",e.id);let n=await oe(()=>it(e.files),"batchPreDelete");S.postMessage({type:"response",id:e.id,metrics:n});let i=Date.now()-t;i>2e3&&(u("[WriterWorker] slow batchPreDelete",{id:e.id,ms:i,count:Array.isArray(e.files)?e.files.length:0}),G("slow batchPreDelete")),g()}catch(t){g(),r(e.id,t)}return}if(e.cmd==="writeBatch"){try{let t=Date.now(),n=Array.isArray(e.payloads)?e.payloads:[],i=n.length?n[0].fileRel:void 0;C("writeBatch",e.id,i),$e(`writeBatch received id=${e.id} count=${n.length} sample=${n[0]?.fileRel??""}`),L&&u("[WriterWorker] writeBatch begin",{id:e.id,count:n.length,sample:n.slice(0,5).map(E=>E.fileRel)});let o=await oe(()=>st(n),"writeBatch");S.postMessage({type:"response",id:e.id,metrics:o});let l=Date.now()-t;L&&u("[WriterWorker] writeBatch end",{id:e.id,ms:l,count:n.length,metrics:o}),l>2e3&&(u("[WriterWorker] slow write batch",{id:e.id,ms:l,count:n.length}),G("slow write batch")),g()}catch(t){g(),r(e.id,t)}return}if(e.cmd==="flush"){try{let t=Date.now();C("flush",e.id);let n=Fe();S.postMessage({type:"response",id:e.id,metrics:n});let i=Date.now()-t;i>2e3&&(u("[WriterWorker] slow flush",{id:e.id,ms:i}),G("slow flush")),g()}catch(t){g(),r(e.id,t)}return}if(e.cmd==="shutdown"){try{C("shutdown",e.id),Me(),S.postMessage({type:"response",id:e.id,metrics:X()}),g()}catch(t){g(),r(e.id,t)}return}});process.on("uncaughtException",e=>{try{S.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch(r){R("[WriterWorker] failed to notify parent about uncaughtException:",r?.message??r)}});process.on("unhandledRejection",e=>{try{S.postMessage({type:"error",message:String(e)})}catch(r){R("[WriterWorker] failed to notify parent about unhandledRejection:",r?.message??r)}});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pando-ai",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "AI coding firewall for Codex and Claude Code: supervised launchers, Pando MCP, policy enforcement, Claude hooks, and local provider gateway.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"pando-ai": "bin/pando-ai.js"
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"name": "read-this-first",
|
|
64
64
|
"category": "pando",
|
|
65
65
|
"signature": "read-this-first()",
|
|
66
|
-
"description": "Pando is an AST-aware code navigation and editing layer for large repos. It keeps a light index of supported source files, uses that index to narrow candidate files, then parses exact AST details at query or edit time.\n\nUse Pando for source-code search, navigation, references, callers, exports, renames, inserts, replacements, and deletes. Use shell/text tools for builds, tests, generated files, non-code files, and unsupported languages.\n\nRead next:\n- workspace-overview: quick inventory of indexed files and symbols.\n- find-nodes: search by language, scope, and Datalog; request include.self/topN when you need paths and hashes for edits.\n- get-content: read files or node paths returned by search tools.\n- list-exports, find-references, and find-callers: follow symbols before changing them.\n- Writers: rename, replace, replace-body, insert, and delete. Re-run find-nodes first if a path or hash is stale.\n\nUnnamed nodes can and should still be edited with Pando. Statements, returns, calls, arguments, branches, literals, and other unnamed syntax are normal AST nodes; find them by starting from a named entity or file, then narrowing by kind, text, role, parent, or child index.\n\nExamples:\n- In one find-nodes call, search for a function by name within the workspace and request include.self/topN to get the exact node path and hash.\n- To edit a statement inside a named function, find the function with include.self, then call find-nodes again with scope.node set to { path, expectedHash } for that function. Use predicates such as :node/kind \"ReturnStatement\" or :node/text \"oldValue\", then pass the returned statement path and hash without @ to replace or insert; delete uses expectedHashes.\n- For scripts or top-level code, scope find-nodes to the file path instead of a named node, find the statement by kind/text/role/index, then edit that returned node with a writer.\n- Insert code is literal: include the newline and indentation you want when inserting before or after a statement anchor.",
|
|
66
|
+
"description": "Pando is an AST-aware code navigation and editing layer for large repos. It keeps a light index of supported source files, uses that index to narrow candidate files, then parses exact AST details at query or edit time.\n\nFiles do not need to be indexed first. To work in a file that is not yet in the index, pass its workspace-relative path directly: as scope.files or scope.node on find-nodes, or as the target path of a writer. Pando indexes that file just-in-time, in any supported language. The light index only limits workspace-wide discovery (scope.workspace); an explicit file path always works even if the file has never been indexed. This means you can edit any AST node in any supported file without a separate indexing step.\n\nUse Pando for source-code search, navigation, references, callers, exports, renames, inserts, replacements, and deletes. Use shell/text tools for builds, tests, generated files, non-code files, and unsupported languages.\n\nRead next:\n- workspace-overview: quick inventory of indexed files and symbols.\n- find-nodes: search by language, scope, and Datalog; request include.self/topN when you need paths and hashes for edits.\n- get-content: read files or node paths returned by search tools.\n- list-exports, find-references, and find-callers: follow symbols before changing them.\n- Writers: rename, replace, replace-body, insert, and delete. Re-run find-nodes first if a path or hash is stale.\n\nUnnamed nodes can and should still be edited with Pando. Statements, returns, calls, arguments, branches, literals, and other unnamed syntax are normal AST nodes; find them by starting from a named entity or file, then narrowing by kind, text, role, parent, or child index.\n\nExamples:\n- In one find-nodes call, search for a function by name within the workspace and request include.self/topN to get the exact node path and hash.\n- To edit a statement inside a named function, find the function with include.self, then call find-nodes again with scope.node set to { path, expectedHash } for that function. Use predicates such as :node/kind \"ReturnStatement\" or :node/text \"oldValue\", then pass the returned statement path and hash without @ to replace or insert; delete uses expectedHashes.\n- For scripts or top-level code, scope find-nodes to the file path instead of a named node, find the statement by kind/text/role/index, then edit that returned node with a writer.\n- Insert code is literal: include the newline and indentation you want when inserting before or after a statement anchor.\n- Edit an unnamed node end to end: find the enclosing function with find-nodes include.self to get its { path, expectedHash }; re-run find-nodes with scope.node set to that path+hash and a predicate like :node/kind \"ReturnStatement\" or :node/text \"return null\" to get the exact statement's path and hash; then call replace with that path and expectedHash (no @) to rewrite it, or insert with an anchor to add code beside it. No indexing step is needed even if the file was never indexed.",
|
|
67
67
|
"parameters": {
|
|
68
68
|
"type": "object",
|
|
69
69
|
"properties": {},
|
|
@@ -146,7 +146,7 @@
|
|
|
146
146
|
"name": "find-nodes",
|
|
147
147
|
"category": "pando",
|
|
148
148
|
"signature": "find-nodes(lang, snapshot, scope, datalog, prefilter, include, page)",
|
|
149
|
-
"description": "Search code nodes with per-file lazy Datalog execution. Candidate files are discovered from indexed file/module metadata, then processed in deterministic order one file at a time; exact AST facts are materialized per candidate file as needed, and execution stops as soon as page.limit items have been emitted. Pagination is cursor-only via page.cursor. page.limit defaults to 5 when omitted and caps at 20. Optional prefilter.fts narrows candidate files before Datalog execution. This operation is per-file structural search only; cross-file Datalog joins are not supported here. AST nodes do not need names. For arbitrary unnamed nodes such as if/return/call/argument/etc., first find a stable enclosing node such as a function/class, then re-run find-nodes with scope.node and use :node/kind, :node/text, :node/parent, :node/role, :node/index-in-parent, include.self, and include.parents to disambiguate the exact child node before editing.",
|
|
149
|
+
"description": "Search code nodes with per-file lazy Datalog execution. Candidate files are discovered from indexed file/module metadata, then processed in deterministic order one file at a time; exact AST facts are materialized per candidate file as needed, and execution stops as soon as page.limit items have been emitted. Files do not need to be indexed first: when scope.files or scope.node names an explicit workspace-relative path, that file is indexed just-in-time even if it was never indexed, in any supported language. Only scope.workspace and scope.dir discovery are limited to already-indexed files. Pagination is cursor-only via page.cursor. page.limit defaults to 5 when omitted and caps at 20. Optional prefilter.fts narrows candidate files before Datalog execution. This operation is per-file structural search only; cross-file Datalog joins are not supported here. AST nodes do not need names. For arbitrary unnamed nodes such as if/return/call/argument/etc., first find a stable enclosing node such as a function/class, then re-run find-nodes with scope.node and use :node/kind, :node/text, :node/parent, :node/role, :node/index-in-parent, include.self, and include.parents to disambiguate the exact child node before editing.",
|
|
150
150
|
"parameters": {
|
|
151
151
|
"type": "object",
|
|
152
152
|
"properties": {
|
|
@@ -174,22 +174,22 @@
|
|
|
174
174
|
"properties": {
|
|
175
175
|
"workspace": {
|
|
176
176
|
"type": "boolean",
|
|
177
|
-
"description": "Search all candidate files for the selected languages."
|
|
177
|
+
"description": "Search all already-indexed candidate files for the selected languages. Workspace-wide discovery does not pull in unindexed files; name them via scope.files to reach those."
|
|
178
178
|
},
|
|
179
179
|
"dir": {
|
|
180
180
|
"type": "string",
|
|
181
|
-
"description": "Workspace-relative directory prefix."
|
|
181
|
+
"description": "Workspace-relative directory prefix; limited to already-indexed files under it. Use scope.files to reach a specific not-yet-indexed file."
|
|
182
182
|
},
|
|
183
183
|
"files": {
|
|
184
184
|
"type": "array",
|
|
185
|
-
"description": "Explicit workspace-relative candidate files.",
|
|
185
|
+
"description": "Explicit workspace-relative candidate files. A named file is indexed just-in-time if it is not already indexed, so you can target any supported file directly.",
|
|
186
186
|
"items": {
|
|
187
187
|
"type": "string"
|
|
188
188
|
}
|
|
189
189
|
},
|
|
190
190
|
"node": {
|
|
191
191
|
"type": "object",
|
|
192
|
-
"description": "Restrict fact materialization to a verified node subtree/span.",
|
|
192
|
+
"description": "Restrict fact materialization to a verified node subtree/span. The file is indexed just-in-time if needed, so an explicit node path works even in a not-yet-indexed file.",
|
|
193
193
|
"properties": {
|
|
194
194
|
"path": {
|
|
195
195
|
"type": "string",
|
|
@@ -447,6 +447,32 @@
|
|
|
447
447
|
"limit": 10,
|
|
448
448
|
"cursor": null
|
|
449
449
|
}
|
|
450
|
+
},
|
|
451
|
+
{
|
|
452
|
+
"_comment": "Locate an unnamed return statement inside a function in an explicit file (indexed on demand if needed); the returned path+hash are passed straight to replace/insert.",
|
|
453
|
+
"scope": {
|
|
454
|
+
"node": {
|
|
455
|
+
"path": "src/util/parse.ts#120-260:FunctionDeclaration",
|
|
456
|
+
"expectedHash": "p123:c456"
|
|
457
|
+
}
|
|
458
|
+
},
|
|
459
|
+
"datalog": {
|
|
460
|
+
"query": "[:find ?n :where [?n :node/kind \"ReturnStatement\"] [?n :node/text \"return null\"]]",
|
|
461
|
+
"bindings": [
|
|
462
|
+
"?n"
|
|
463
|
+
],
|
|
464
|
+
"result": {
|
|
465
|
+
"nodeVar": "?n"
|
|
466
|
+
}
|
|
467
|
+
},
|
|
468
|
+
"include": {
|
|
469
|
+
"self": true,
|
|
470
|
+
"topN": 1
|
|
471
|
+
},
|
|
472
|
+
"page": {
|
|
473
|
+
"limit": 5,
|
|
474
|
+
"cursor": null
|
|
475
|
+
}
|
|
450
476
|
}
|
|
451
477
|
]
|
|
452
478
|
},
|
|
@@ -1229,7 +1255,7 @@
|
|
|
1229
1255
|
"name": "rename",
|
|
1230
1256
|
"category": "pando",
|
|
1231
1257
|
"signature": "rename(path, newName, expectedHash, boundary, requireConfirmation, confirmed, includeStrings, includeComments, page, reachabilityDepth, reachabilityOptions)",
|
|
1232
|
-
"description": "Rename a symbol and update references. expectedHash (no @) required. Cross-project renames may require confirmed=true. Example: { path:'src/app.ts#FD:0', newName:'initApp', expectedHash:'p123:c456' }",
|
|
1258
|
+
"description": "Rename a symbol and update references. expectedHash (no @) required. If the target file is not fully indexed yet, Pando materializes and persists its full AST on demand before resolving/editing the node; no separate indexing step is needed. Cross-project renames may require confirmed=true. Example: { path:'src/app.ts#FD:0', newName:'initApp', expectedHash:'p123:c456' }",
|
|
1233
1259
|
"parameters": {
|
|
1234
1260
|
"type": "object",
|
|
1235
1261
|
"properties": {
|
|
@@ -1350,7 +1376,7 @@
|
|
|
1350
1376
|
"name": "delete",
|
|
1351
1377
|
"category": "pando",
|
|
1352
1378
|
"signature": "delete(path, expectedHashes, forceDeleteReferencesMayBreakSyntax)",
|
|
1353
|
-
"description": "Delete code targets and their references. expectedHashes must align with path list and omit '@'. Requires forceDeleteReferencesMayBreakSyntax=true. Example: { path:'src/app.ts#FD:0', expectedHashes:['p123:c456'], forceDeleteReferencesMayBreakSyntax:true }",
|
|
1379
|
+
"description": "Delete code targets and their references. If a target file is not fully indexed yet, Pando materializes and persists its full AST on demand before resolving/editing the node; no separate indexing step is needed. expectedHashes must align with path list and omit '@'. Requires forceDeleteReferencesMayBreakSyntax=true. Example: { path:'src/app.ts#FD:0', expectedHashes:['p123:c456'], forceDeleteReferencesMayBreakSyntax:true }",
|
|
1354
1380
|
"parameters": {
|
|
1355
1381
|
"type": "object",
|
|
1356
1382
|
"properties": {
|
|
@@ -1400,7 +1426,7 @@
|
|
|
1400
1426
|
"name": "insert",
|
|
1401
1427
|
"category": "pando",
|
|
1402
1428
|
"signature": "insert(to, code, replaceExistingNodeAtPath, expectedHash, createFileIfMissing, newFileInitialContent, forceInsertWillBreakSyntax)",
|
|
1403
|
-
"description": "Insert raw code at an explicit anchor. to can be a node path or anchor object (exactly one of before/after/start/end/bodyStartOf/bodyEndOf). replaceExistingNodeAtPath is required. expectedHash (no @) is required unless createFileIfMissing=true with a single file anchor. Example: { to:{ bodyEndOf:'src/a.ts#FD:0' }, code:'\\nreturn 1;', replaceExistingNodeAtPath:false, expectedHash:'p123:c456' }",
|
|
1429
|
+
"description": "Insert raw code at an explicit anchor. to can be a node path or anchor object (exactly one of before/after/start/end/bodyStartOf/bodyEndOf). If the anchor file is not fully indexed yet, Pando materializes and persists its full AST on demand before resolving/editing the node; no separate indexing step is needed. replaceExistingNodeAtPath is required. expectedHash (no @) is required unless createFileIfMissing=true with a single file anchor. Example: { to:{ bodyEndOf:'src/a.ts#FD:0' }, code:'\\nreturn 1;', replaceExistingNodeAtPath:false, expectedHash:'p123:c456' }",
|
|
1404
1430
|
"parameters": {
|
|
1405
1431
|
"type": "object",
|
|
1406
1432
|
"properties": {
|
|
@@ -1492,7 +1518,7 @@
|
|
|
1492
1518
|
"name": "replace",
|
|
1493
1519
|
"category": "pando",
|
|
1494
1520
|
"signature": "replace(path, expectedHash, with, scope, forceReplaceWillBreakSyntax)",
|
|
1495
|
-
"description": "Replace a node. scope='node' replaces the entire node (default). scope='body' replaces only the inner body span and fails if the target has no body. For scope='body', provide body contents only, not enclosing delimiters; body replacement is pass-through and preserves the exact whitespace you provide. Requires expectedHash (no @). Example: { path:'src/app.ts#FD:0', expectedHash:'p123:c456', with:'function x() {}' }",
|
|
1521
|
+
"description": "Replace a node. scope='node' replaces the entire node (default). scope='body' replaces only the inner body span and fails if the target has no body. If the target file is not fully indexed yet, Pando materializes and persists its full AST on demand before resolving/editing the node; no separate indexing step is needed. For scope='body', provide body contents only, not enclosing delimiters; body replacement is pass-through and preserves the exact whitespace you provide. Requires expectedHash (no @). Example: { path:'src/app.ts#FD:0', expectedHash:'p123:c456', with:'function x() {}' }",
|
|
1496
1522
|
"parameters": {
|
|
1497
1523
|
"type": "object",
|
|
1498
1524
|
"properties": {
|
|
@@ -1546,7 +1572,7 @@
|
|
|
1546
1572
|
"name": "replace-body",
|
|
1547
1573
|
"category": "pando",
|
|
1548
1574
|
"signature": "replace-body(path, expectedHash, with, forceReplaceWillBreakSyntax)",
|
|
1549
|
-
"description": "Replace only a node body. This is equivalent to pando_replace with scope='body', but exposed as a dedicated tool for callers that need an explicit replace-body operation. Provide body contents only, not enclosing delimiters; the replacement text is written as-is, including indentation and leading/trailing whitespace. Requires expectedHash (no @). Example: { path:'src/app.ts#FD:0', expectedHash:'p123:c456', with:'console.log(1);' }",
|
|
1575
|
+
"description": "Replace only a node body. This is equivalent to pando_replace with scope='body', but exposed as a dedicated tool for callers that need an explicit replace-body operation. If the target file is not fully indexed yet, Pando materializes and persists its full AST on demand before resolving/editing the node; no separate indexing step is needed. Provide body contents only, not enclosing delimiters; the replacement text is written as-is, including indentation and leading/trailing whitespace. Requires expectedHash (no @). Example: { path:'src/app.ts#FD:0', expectedHash:'p123:c456', with:'console.log(1);' }",
|
|
1550
1576
|
"parameters": {
|
|
1551
1577
|
"type": "object",
|
|
1552
1578
|
"properties": {
|
|
@@ -1586,7 +1612,7 @@
|
|
|
1586
1612
|
"name": "change-signature",
|
|
1587
1613
|
"category": "pando",
|
|
1588
1614
|
"signature": "change-signature(path, expectedHash, parameters, returnType, makeAsync, makeSyncFromAsync, forceChangeWillBreakSyntax, boundary, batchSaves)",
|
|
1589
|
-
"description": "Modify a function or method signature with best-effort call-site updates. Supports parameter add/remove/modify/reorder, return type changes, and async/sync conversion. Requires path and expectedHash (no @). Writes create automatic snapshots before and after the operation.",
|
|
1615
|
+
"description": "Modify a function or method signature with best-effort call-site updates. Supports parameter add/remove/modify/reorder, return type changes, and async/sync conversion. If the target file is not fully indexed yet, Pando materializes and persists its full AST on demand before resolving/editing the node; no separate indexing step is needed. Requires path and expectedHash (no @). Writes create automatic snapshots before and after the operation.",
|
|
1590
1616
|
"parameters": {
|
|
1591
1617
|
"type": "object",
|
|
1592
1618
|
"properties": {
|
|
Binary file
|
|
Binary file
|
|
Binary file
|