pando-ai 0.0.16 → 0.0.18
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/README.md +14 -14
- package/bin/pando-ai.js +38 -0
- package/dist/cli.js +182 -189
- package/dist/watcher-process.js +434 -441
- package/dist/workers/chunk-HQDE7M4W.mjs +4 -0
- package/dist/workers/chunk-UIWCIYYF.mjs +522 -0
- package/dist/workers/indexer-worker.mjs +1 -1
- package/dist/workers/snapshot-worker.mjs +4 -4
- package/dist/workers/sqlite-writer-worker.mjs +6 -8
- package/package.json +3 -2
- package/resources/tools/pando-tools.json +63 -2
- 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/dist/workers/chunk-2YGY7BLN.mjs +0 -1
- package/dist/workers/chunk-QOET4233.mjs +0 -528
|
@@ -1,528 +0,0 @@
|
|
|
1
|
-
import{a as Ct}from"./chunk-2YGY7BLN.mjs";import{a as Tn,b as te}from"./chunk-AYCBSZ56.mjs";var Y,le=te(()=>{"use strict";Y={getAbbrev(t,e="ts"){return t},getKindFromAbbrev(t,e="ts"){return t}}});import F from"path";import On from"os";import Z from"fs";import jn from"crypto";function Re(){return process.env.PANDO_DATA_DIR||F.join(On.homedir(),Ee)}function Et(t){let e=t,n=F.parse(e);for(;e.length>n.root.length&&/[\\/]+$/.test(e);)e=e.replace(/[\\/]+$/,"");return e}function ne(t){let e=F.resolve(t),n=e;try{let r=Z.realpathSync.native;n=typeof r=="function"?r(e):Z.realpathSync(e)}catch{}return Et(n)}function Mn(t){let e=t.trim().replace(/\.git$/,"");if(!e)return null;let n=e.match(/^git@([^:]+):(.+)$/);if(n){let r=n[1],s=n[2].replace(/^\/+/,"").split("/");if(s.length>=2)return`${r}/${s[0]}/${s[1]}`}try{let r=new URL(e),i=r.hostname,a=r.pathname.replace(/^\/+/,"").split("/");if(i&&a.length>=2)return`${i}/${a[0]}/${a[1]}`}catch{}return null}function we(t){return jn.createHash("sha1").update(t).digest("hex").slice(0,12)}function $n(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").slice(0,64).replace(/^[-._]+|[-._]+$/g,"")||"workspace"}function Ln(t,e){let n=F.basename(Et(t));return`${$n(n)}-${e}`}function Rt(){return F.join(Re(),"workspace-registry.json")}function ce(t){try{return Z.readFileSync(t,"utf8").trim()}catch{return null}}function _t(t){let e=F.join(t,".git");try{let n=Z.statSync(e);if(n.isDirectory())return e;if(n.isFile()){let i=ce(e)?.match(/^gitdir:\s*(.+)$/i);if(i){let s=i[1].trim();return F.isAbsolute(s)?s:F.resolve(t,s)}}}catch{return null}return null}function Bn(t){let e=F.join(t,"commondir"),n=ce(e);if(!n)return ne(t);let r=F.isAbsolute(n)?n:F.resolve(t,n);return ne(r)}function zn(t){return ne(F.join(t,"objects"))}function qn(t){let e=ne(t);for(;;){let n=F.join(e,".git");if(Z.existsSync(n))return e;let r=F.dirname(e);if(r===e)break;e=r}return null}function Hn(t){let e=ne(t),n=qn(e);return n?ne(n):null}function Jn(t){let e=F.join(t,"config"),n=ce(e);if(!n)return null;let r=n.split(/\r?\n/),i=!1,s=null;for(let a of r){if(a.match(/^\s*\[remote\s+"([^"]+)"\]\s*$/)){i=!0;continue}if(a.startsWith("[")&&(i=!1),i){let c=a.match(/^\s*url\s*=\s*(.+)$/);if(c&&(s=c[1].trim(),s))return s}}return s}function Wn(t){let e=F.join(t,"HEAD"),n=ce(e);if(!n)return{branch:null,commit:null};if(n.startsWith("ref:")){let r=n.replace("ref:","").trim(),i=r.split("/").slice(-1)[0]||null,s=F.join(t,r),a=ce(s);if(!a){let o=ce(F.join(t,"packed-refs"));if(o){let c=o.split(/\r?\n/).find(h=>h.endsWith(` ${r}`));c&&(a=c.split(" ")[0])}}return{branch:i,commit:a||null}}return{branch:"HEAD",commit:n||null}}function Xn(){try{let t=Z.readFileSync(Rt(),"utf8"),e=JSON.parse(t);if(e&&e.version===1&&e.entries&&typeof e.entries=="object")return{version:1,entries:e.entries}}catch{}return{version:1,entries:{}}}function Un(t){let e=Rt(),n=F.dirname(e);Z.mkdirSync(n,{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;Z.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
2
|
-
`,"utf8"),Z.renameSync(r,e)}function Vn(t,e){if(!e)return{canonicalRepoRoot:t,gitCommonDir:null,gitObjectDir:null,fingerprint:`non-git:path:${t}`};let n=_t(e),r=n?Bn(n):null,i=r?zn(r):null;return{canonicalRepoRoot:e,gitCommonDir:r,gitObjectDir:i,fingerprint:["git",`root:${e}`,`common:${r??""}`,`objects:${i??""}`].join("|")}}function Gn(t){try{let e=Xn();e.entries[t.storageRoot]={workspaceId:t.id,workspaceDirName:t.dirName,locationId:t.locationId,incarnationId:t.incarnationId,canonicalProjectRoot:t.canonicalProjectRoot,canonicalRepoRoot:t.canonicalRepoRoot,storageRoot:t.storageRoot,repoIdentity:t.repoIdentity??null,gitCommonDir:t.gitCommonDir??null,gitObjectDir:t.gitObjectDir??null,remote:t.remote??null,branch:t.branch??null,commit:t.commit??null,updatedAt:new Date().toISOString()},Un(e)}catch{}}function Qn(t){let e=ne(t),n=Hn(e),r=n??e,i=n,s=we(r),a=Vn(r,i),o=we(a.fingerprint),c=`ws-${we(`${s}:${o}`)}`,h=Ln(r,c);if(!i)return{id:c,dirName:h,locationId:s,incarnationId:o,canonicalProjectRoot:e,canonicalRepoRoot:r,storageRoot:r,gitCommonDir:a.gitCommonDir,gitObjectDir:a.gitObjectDir,repoIdentity:null,remote:null,branch:null,commit:null};let p=_t(i),g=p?Jn(p):null,b=g?Mn(g):null,_=p?Wn(p):{branch:null,commit:null};return{id:c,dirName:h,locationId:s,incarnationId:o,canonicalProjectRoot:e,canonicalRepoRoot:i,storageRoot:r,gitCommonDir:a.gitCommonDir,gitObjectDir:a.gitObjectDir,repoIdentity:b??`local:${we(r)}`,remote:g,branch:_.branch,commit:_.commit}}function Yn(t){let e=Qn(t);return Gn(e),F.join(Re(),"workspaces",e.dirName)}function es(t){return F.join(Yn(t),".pando-snapshots.db")}var Ee,At=te(()=>{"use strict";Ee=".pando-data"});import{Node as $}from"ts-morph";function xe(t){let e=t.getKindName?.()||"Unknown",n=Ft(t,e);return{kind:n.kind,semanticKind:n.semanticKind,rawKind:e,rawKindSource:Kt.TS_MORPH}}function Ot(t){let e=t.getKindName?.()||"Unknown";return{kind:Ft(t,e).kind,rawKind:e,rawKindSource:Kt.TS_MORPH}}function _e(t,e){if(!t.kind||!t.kind.trim())throw new Error(`Invalid normalized kind: missing kind ${e?JSON.stringify(e):""}`);if(!t.rawKind||!t.rawKind.trim())throw new Error(`Invalid normalized kind: missing rawKind ${e?JSON.stringify(e):""}`);if(!t.rawKindSource||!String(t.rawKindSource).trim())throw new Error(`Invalid normalized kind: missing rawKindSource ${e?JSON.stringify(e):""}`)}var Kt,Ft,Ae=te(()=>{"use strict";Kt={TS_MORPH:"ts-morph",PYTHON_AST:"python-ast",CLANG:"clang",ROSLYN:"roslyn",JAVA_AST:"java-ast",CLI:"cli",UNKNOWN:"unknown"},Ft=(t,e)=>$.isFunctionDeclaration(t)||$.isFunctionExpression(t)||$.isArrowFunction(t)?{kind:"Function",semanticKind:"function"}:$.isGetAccessorDeclaration(t)||$.isSetAccessorDeclaration(t)?{kind:"Method",semanticKind:"property"}:$.isMethodDeclaration(t)||$.isMethodSignature(t)||$.isConstructorDeclaration(t)?{kind:"Method",semanticKind:"method"}:$.isClassDeclaration(t)||$.isClassExpression(t)?{kind:"Class",semanticKind:"class"}:$.isInterfaceDeclaration(t)?{kind:"Interface",semanticKind:"interface"}:$.isEnumDeclaration(t)?{kind:"Enum",semanticKind:"enum"}:$.isEnumMember(t)?{kind:"EnumMember",semanticKind:"enum"}:$.isTypeAliasDeclaration(t)?{kind:"TypeAlias",semanticKind:"type"}:$.isModuleDeclaration(t)?{kind:"Namespace",semanticKind:"namespace"}:$.isPropertyDeclaration(t)||$.isPropertySignature(t)?{kind:"Field",semanticKind:"property"}:$.isVariableDeclaration(t)?{kind:"Variable",semanticKind:"variable"}:{kind:e,semanticKind:null}});var Ye=te(()=>{"use strict";le();Ae()});function ur(){return new Date().toISOString()}function De(t,e,n){let r=`[${ur()}] [${t.toUpperCase()}] ${e}`;if(!n)return r;try{return r+" "+JSON.stringify(n)}catch{return r}}var dr,jt=te(()=>{"use strict";dr={debug:(t,e)=>{try{process.stderr.write(De("debug",t,e)+`
|
|
3
|
-
`)}catch{}},info:(t,e)=>{try{process.stderr.write(De("info",t,e)+`
|
|
4
|
-
`)}catch{}},warn:(t,e)=>{try{process.stderr.write(De("warn",t,e)+`
|
|
5
|
-
`)}catch{}},error:(t,e)=>{try{process.stderr.write(De("error",t,e)+`
|
|
6
|
-
`)}catch{}}}});import{Node as bs}from"ts-morph";var Mt=te(()=>{"use strict";Ze();Ye();jt()});import*as gr from"xxhash-wasm";var hr,yr,_s,Ze=te(()=>{"use strict";Mt();hr="__pando_xxhash_instance__",yr=globalThis,_s=yr[hr]??null});le();import wt from"fs";import Kn from"os";import Fn from"path";function Pe(t){let e=`${t.sourceFile}#${t.sourceStart}-${t.sourceEnd}`,n=t.refKind??"",r=t.refName??"",i=t.targetFile??"",s=t.targetStart!=null&&t.targetEnd!=null?`#${t.targetStart}-${t.targetEnd}`:"",a=t.targetNodeId??"",o=`${e}:REF:${n}:${r}|${i}${s}|${a}`;return Ct(o)}function Pt(t){let e=[],n=new Set,r=i=>{!i?.name||n.has(i.name)||(n.add(i.name),e.push(i))};for(let i of t.exports??[])r(i);for(let i of t.explicitExports??[])r({name:i});for(let i of t.modulePublic??[])r({name:i});return e}function he(t,e,n){let r=new Date().toISOString();return{payload:{lang:t,fileRel:e,preDeleted:!1,exportRows:[],nodeRows:[],referenceRows:[],importRows:[],importBindingRows:[],fileRow:[e,n?.mtime??null,n?.size??null,"failed",r],fts:null},fileSize:n?.size,mtime:n?.mtime}}function ye(t){let{lang:e,fileRel:n,content:r,meta:i,preDeleted:s,parsed:a,resolveNodeId:o,exportKind:c}=t,h=[];for(let d of a.nodes??[]){let N=d.rawKind??d.kind,v=d.rawKindSource??"cli",A=d.containerRawKind??d.containerKind??null,B=d.containerRawKindSource??(A?"cli":null),m=d.scopeChain??null,y=Array.isArray(m)?JSON.stringify(m):typeof m=="string"?m:null,C=`${n}#${d.start}-${d.end}:${Y.getAbbrev(d.kind,e)}`,S=(e==="c"||e==="cpp"||e==="java"||e==="clojure")&&d.name?`${C}:${d.name}`:C,K=d.metadata&&Object.keys(d.metadata).length?JSON.stringify(d.metadata):null;h.push([S,d.name,d.kind,N,v,d.semanticKind??null,d.start,d.end,typeof d.isExported=="number"?d.isExported:0,d.containerKind??null,A,B,typeof d.paramCount=="number"?d.paramCount:null,d.qualifiedName??null,y,d.symbolKey??null,K])}let p=[],g=new Set;for(let d of Pt(a)){if(!d.name||g.has(d.name))continue;g.add(d.name);let N=d.nodeId??(o?o(d.name):null);p.push([n,d.name,N??null,d.isReexport?1:0,d.reexportFrom??null,d.reexportName??null,d.exportKind??c??"cli",d.targetSymbolKey??null])}let b=[],_=new Map,P=new Map;for(let d of h){let N=d[0]!=null?String(d[0]):null,v=d[13]!=null?String(d[13]):null,A=d[15]!=null?String(d[15]):null;N&&(v&&!_.has(v)&&_.set(v,N),A&&!P.has(A)&&P.set(A,N))}if(e==="clojure"&&(a.references??[]).length>0){let d=Array.from(_.keys()).slice(0,10),N=Array.from(P.keys()).slice(0,10),v=(a.references??[]).slice(0,10).map(B=>B.containerQualifiedName),A={file:n,nodeCount:h.length,refCount:(a.references??[]).length,nodeQualifiedNames:d,nodeSymbolKeys:N,refContainers:v,qualifiedNameMapSize:_.size,symbolKeyMapSize:P.size};try{console.error("[CliPayload][CLOJURE-DEBUG] source_node_id lookup context",A),wt.appendFileSync("/tmp/pando-clj-source-debug.log",JSON.stringify(A,null,2)+`
|
|
7
|
-
---
|
|
8
|
-
`)}catch{}}for(let d of a.references??[]){let N=d.targetNodeId??(o&&d.refName?o(d.refName):null),v=d.targetFile??(N?n:null),A=d.sourceNodeId??(d.containerQualifiedName?_.get(d.containerQualifiedName)??null:null)??(d.containerQualifiedName?P.get(d.containerQualifiedName)??null:null),B=Pe({sourceFile:n,sourceStart:d.sourceStart,sourceEnd:d.sourceEnd,refKind:d.refKind,refName:d.refName,targetFile:v??null,targetStart:d.targetStart??null,targetEnd:d.targetEnd??null,targetNodeId:N??d.targetNodeId??null}),m=d.metadata&&Object.keys(d.metadata).length?JSON.stringify(d.metadata):null;b.push([B,n,A,d.refName??null,d.refKind,d.sourceStart,d.sourceEnd,N??d.targetNodeId??null,v??null,N||d.targetNodeId||d.targetFile?"resolved":"unresolved",d.receiverName??null,typeof d.arity=="number"?d.arity:null,d.containerQualifiedName??null,d.targetSymbolKey??null,d.confidence??null,m])}if(e==="clojure"&&b.length>0){let d=b.reduce((v,A)=>v+(A?.[2]!=null?1:0),0),N=b.reduce((v,A)=>v+(A?.[12]!=null?1:0),0);try{console.error("[CliPayload] clojure source-node summary",{file:n,refs:b.length,sourceNodeCount:d,containerCount:N,sample:b.slice(0,5).map(v=>({sourceNodeId:v[2]==null?null:String(v[2]),refName:v[3],refKind:v[4],containerQualifiedName:v[12]}))}),wt.appendFileSync(Fn.join(Kn.tmpdir(),"pando-clj-source-node.log"),`${JSON.stringify({stage:"cli-payload",file:n,refs:b.length,sourceNodeCount:d,containerCount:N,sample:b.slice(0,5).map(v=>({sourceNodeId:v[2]==null?null:String(v[2]),refName:v[3],refKind:v[4],containerQualifiedName:v[12]}))})}
|
|
9
|
-
`)}catch{}}let w=[];for(let d of a.imports??[])w.push([n,d.module??null,d.isTypeOnly??0]);let j=[];for(let d of a.importBindings??[])j.push([n,d.module??null,d.kind,d.localName,d.importedName,d.isTypeOnly??0]);let l=new Date().toISOString(),E=[n,i?.mtime??null,i?.size??null,"completed",l];return{payload:{lang:e,fileRel:n,preDeleted:!!s,exportRows:p,nodeRows:h,referenceRows:b,importRows:w,importBindingRows:j,fileRow:E,fts:typeof r=="string"?{blobOid:n,content:r}:null},fileSize:i?.size,mtime:i?.mtime}}At();import It from"fs";import Dt from"os";import Ve from"path";import{inspect as Zn}from"util";var kt=(()=>{let t=process.env.PANDO_LOG_DIR||process.env.PANDO_WORKSPACE_DATA_DIR;if(t)return t;try{return Re()}catch{let n=typeof Dt.homedir=="function"?Dt.homedir():process.env.HOME;if(n)return Ve.join(n,Ee)}let e=process.env.HOME||process.cwd();return Ve.join(e,Ee)})(),er=Ve.join(kt,"pando.log"),Ge=t=>{if(t==null)return!1;let e=t.trim().toLowerCase();return e!=="0"&&e!=="false"&&e!=="off"&&e!=="no"},tr=Ge(process.env.PANDO_LOG_DISABLED),nr=Ge(process.env.PANDO_INDEX_HOT_LOG??"1"),rr=Ge(process.env.PANDO_INDEX_TIMING??"1"),ir=new Set(["BatchAnalysisScheduler","ClojureIndex","ClojureIndexer","ThreadedIndexer"]),sr=new Set(["IndexTiming"]);function ar(){try{It.mkdirSync(kt,{recursive:!0})}catch{}}function or(t){if(t!==void 0)try{return typeof t=="string"?t:Zn(t,{depth:null,breakLength:1/0,maxArrayLength:1/0})}catch{try{return JSON.stringify(t)}catch{return String(t)}}}var lr=!1;function cr(t){return tr?!1:sr.has(t)?rr:!(!nr&&ir.has(t))}function H(t,e,n){if(!cr(t))return;let r=new Date().toISOString(),i=or(n),s=i?`[${r}] [${t}] ${e} :: ${i}`:`[${r}] [${t}] ${e}`;if(!lr&&!process.env.PANDO_QUIET)try{process.stderr.write(s+`
|
|
10
|
-
`)}catch{}try{ar(),It.appendFileSync(er,s+`
|
|
11
|
-
`,"utf8")}catch{}}import rt from"path";import _r from"fs";import{Project as Ar,Node as x}from"ts-morph";import{Node as f,SyntaxKind as ue}from"ts-morph";import*as W from"typescript";import{SyntaxKind as be}from"ts-morph";var Qe={LINE_COMMENT:{kind:9001,name:"LineComment",triviaKind:be.SingleLineCommentTrivia},BLOCK_COMMENT:{kind:9002,name:"BlockComment",triviaKind:be.MultiLineCommentTrivia},JSDOC_COMMENT:{kind:9003,name:"JSDocComment",triviaKind:be.MultiLineCommentTrivia}};function Tt(t,e){return t===be.SingleLineCommentTrivia?Qe.LINE_COMMENT:t===be.MultiLineCommentTrivia&&e.startsWith("/**")?Qe.JSDOC_COMMENT:Qe.BLOCK_COMMENT}Ze();Ye();import{Node as O,SyntaxKind as u,Scope as et}from"ts-morph";var js=new Set([u.ArrayLiteralExpression,u.ArrayType,u.ArrowFunction,u.AsExpression,u.AssertClause,u.AssertEntry,u.AwaitExpression,u.BigIntLiteral,u.BinaryExpression,u.BindingElement,u.Block,u.CallExpression,u.CallSignature,u.CaseClause,u.CatchClause,u.ClassDeclaration,u.ClassExpression,u.ClassStaticBlockDeclaration,u.ComputedPropertyName,u.ConditionalExpression,u.ConditionalType,u.ConstructSignature,u.Constructor,u.ConstructorType,u.Decorator,u.DefaultClause,u.DoStatement,u.ElementAccessExpression,u.EnumDeclaration,u.EnumMember,u.ExportAssignment,u.ExportDeclaration,u.ExportSpecifier,u.ExpressionStatement,u.ExpressionWithTypeArguments,u.FalseKeyword,u.ForInStatement,u.ForOfStatement,u.ForStatement,u.FunctionDeclaration,u.FunctionExpression,u.FunctionType,u.GetAccessor,u.Identifier,u.IfStatement,u.ImportAttribute,u.ImportAttributes,u.ImportClause,u.ImportDeclaration,u.ImportEqualsDeclaration,u.ImportSpecifier,u.ImportType,u.IndexSignature,u.IndexedAccessType,u.InferType,u.InterfaceDeclaration,u.IntersectionType,u.JsxAttribute,u.JsxClosingElement,u.JsxClosingFragment,u.JsxElement,u.JsxExpression,u.JsxFragment,u.JsxOpeningElement,u.JsxOpeningFragment,u.JsxSelfClosingElement,u.JsxSpreadAttribute,u.JsxText,u.LiteralType,u.MappedType,u.MetaProperty,u.MethodDeclaration,u.MethodSignature,u.ModuleDeclaration,u.NamedExports,u.NamedImports,u.NamedTupleMember,u.NamespaceExport,u.NamespaceExportDeclaration,u.NamespaceImport,u.NewExpression,u.NoSubstitutionTemplateLiteral,u.NonNullExpression,u.NullKeyword,u.NumericLiteral,u.ObjectLiteralExpression,u.OptionalType,u.Parameter,u.ParenthesizedType,u.PostfixUnaryExpression,u.PrefixUnaryExpression,u.PrivateIdentifier,u.PropertyAccessExpression,u.PropertyAssignment,u.PropertyDeclaration,u.PropertySignature,u.QualifiedName,u.RegularExpressionLiteral,u.RestType,u.ReturnStatement,u.SatisfiesExpression,u.SetAccessor,u.ShorthandPropertyAssignment,u.SourceFile,u.SpreadAssignment,u.SpreadElement,u.StringLiteral,u.SwitchStatement,u.TaggedTemplateExpression,u.TemplateExpression,u.TemplateLiteralType,u.ThisType,u.ThrowStatement,u.TrueKeyword,u.TryStatement,u.TupleType,u.TypeAliasDeclaration,u.TypeLiteral,u.TypeOfExpression,u.TypeOperator,u.TypeParameter,u.TypePredicate,u.TypeQuery,u.TypeReference,u.UnionType,u.VariableDeclaration,u.VariableStatement,u.WhileStatement,u.YieldExpression]);function br(t){try{let e=t.getDecorators;if(typeof e!="function")return[];let n=new Set;for(let r of e.call(t)){let i;try{i=r.getName?.()}catch{i=void 0}if(!i)try{i=r.getExpression?.()?.getText?.()}catch{i=void 0}if(i){let s=String(i).trim();s&&n.add(s)}}return Array.from(n)}catch{return[]}}function xr(t){try{if(!O.isClassDeclaration(t))return[];let e=t.getImplements();if(!e||e.length===0)return[];let n=new Set;for(let r of e)try{let i=r.getExpression(),s=i?i.getText():r.getText();s&&n.add(s.trim())}catch{}return Array.from(n)}catch{return[]}}function Sr(t){try{let e=new Set;if(O.isClassDeclaration(t)){let n=t.getExtends();if(n)try{let r=n.getExpression(),i=r?r.getText():n.getText();i&&e.add(i.trim())}catch{}}else if(O.isInterfaceDeclaration(t)){let n=t.getExtends();for(let r of n)try{let i=r.getText();i&&e.add(i.trim())}catch{}}return Array.from(e)}catch{return[]}}function $t(t){try{if("getReturnTypeNode"in t&&typeof t.getReturnTypeNode=="function"){let e=t.getReturnTypeNode();if(e)return e.getText()}if("getReturnType"in t&&typeof t.getReturnType=="function"){let e=t.getReturnType();if(e&&typeof e.getText=="function"){let n=e.getText();if(n)return String(n)}}return null}catch{return null}}function vr(t){try{if(typeof t.getScope!="function")return null;let e=t.getScope();return e===et.Private||e===et.Protected||e===et.Public?e:null}catch{return null}}function Lt(t){let e={kind:t.getKindName()},n=br(t);if(n.length&&(e.decorators=n),k(e,"flags",()=>t.getFlags()),(O.isFunctionDeclaration(t)||O.isMethodDeclaration(t)||O.isFunctionExpression(t))&&(k(e,"isAsync",()=>t.isAsync()),k(e,"isGenerator",()=>t.isGenerator()),k(e,"parameterCount",()=>t.getParameters().length),k(e,"returnType",()=>$t(t)),O.isFunctionDeclaration(t)&&k(e,"isExported",()=>t.isExported())),O.isClassDeclaration(t)){k(e,"isAbstract",()=>t.isAbstract()),k(e,"isExported",()=>t.isExported());let i=Sr(t);i.length&&(e.extends=i);let s=xr(t);s.length&&(e.implements=s)}if(O.isVariableDeclaration(t)&&(k(e,"declarationKind",()=>t.getVariableStatement()?.getDeclarationKind()),k(e,"hasInitializer",()=>t.hasInitializer()),k(e,"type",()=>t.getTypeNode()?.getText())),(O.isPropertyDeclaration(t)||O.isPropertySignature(t)||O.isParameterDeclaration(t))&&(k(e,"isStatic",()=>t.isStatic?.()),k(e,"isReadonly",()=>t.isReadonly?.()),k(e,"isOptional",()=>t.hasQuestionToken?.()),k(e,"scope",()=>t.getScope?.())),(O.isMethodDeclaration(t)||O.isMethodSignature(t)||O.isGetAccessorDeclaration(t)||O.isSetAccessorDeclaration(t))&&(k(e,"isStatic",()=>t.isStatic?.()),k(e,"isAbstract",()=>t.isAbstract?.()),k(e,"isAsync",()=>t.isAsync?.()),k(e,"returnType",()=>$t(t)),k(e,"scope",()=>t.getScope?.())),O.isCallExpression(t)){let i=t.getExpression();if(O.isPropertyAccessExpression(i)){e.propertyName=i.getName();let s=i.getExpression();O.isIdentifier(s)&&(e.objectName=s.getText())}else O.isIdentifier(i)&&(e.functionName=i.getText());e.argumentCount=t.getArguments().length,e.callExpression=i.getText()}let r=vr(t);return r&&(e.visibility=r),e.isReadonly||k(e,"isReadonly",()=>t.isReadonly?.()),O.isImportDeclaration(t)&&(k(e,"moduleSpecifier",()=>t.getModuleSpecifier()?.getLiteralText()),k(e,"isTypeOnly",()=>t.isTypeOnly()),k(e,"namedImports",()=>t.getNamedImports()?.map(i=>i.getName()).join(", ")),k(e,"defaultImport",()=>t.getDefaultImport()?.getText())),Object.keys(e).forEach(i=>{e[i]===void 0&&delete e[i]}),e}function k(t,e,n){try{let r=n();r!=null&&(t[e]=r)}catch{}}Ae();function Nr(t){if(t.kind==="local"){let r=t.isDefault?"default":t.name;return r?{name:r,priority:t.isDefault?4:3}:null}if(t.kind==="alias")return t.exported?{name:t.exported,priority:2}:null;let e=t.isNamespace??!1,n=t.alias||t.name||(e?"*":null);return n?{name:n,priority:e?0:1}:null}function Cr(t){if(t.length<2)return t;let e=new Map;for(let n of t){let r=Nr(n);if(!r)continue;let i=e.get(r.name);(!i||r.priority>i.priority)&&e.set(r.name,{record:n,priority:r.priority})}return Array.from(e.values()).map(n=>n.record)}function Ie(t){try{if(t&&typeof t.getName=="function"){let e=t.getName();if(typeof e=="string"&&e.length>0)return e}}catch{}return null}function tt(t){let e;try{let r=t.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=t.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=t.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let n;try{let r=t.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(n=r)}catch{}if(n===void 0)try{let r=t.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(n=r)}catch{}return n===void 0&&(n=e),n<e&&(n=e),{start:e,end:n}}function Pr(t){try{if(f.isFunctionDeclaration(t)||f.isMethodDeclaration(t)||f.isConstructorDeclaration(t)||f.isFunctionExpression(t)||f.isArrowFunction(t)){let e=t.getParameters?.();if(Array.isArray(e))return e.length}}catch{}return null}function ke(t,e){try{return typeof t?.hasModifier=="function"&&t.hasModifier(e)}catch{return!1}}function wr(t,e,n){if(!f.isImportDeclaration(t))return;let i={moduleSpecifier:t.getModuleSpecifierValue(),isTypeOnly:t.isTypeOnly(),namedImports:[]};try{let s=t.getDefaultImport();if(s){let a=s.getText();i.defaultImport=a,n(a,s)}}catch{}try{let s=t.getNamespaceImport();if(s){let a=s.getText();i.namespaceImport=a,n(a,s)}}catch{}try{t.getNamedImports().forEach(s=>{try{let a=s.getName(),o=s.getAliasNode(),c=o?o.getText():void 0;a&&(i.namedImports.push({name:a,alias:c||void 0}),n(c||a,s.getNameNode()))}catch{}})}catch{}e.push(i)}function Er(t,e){if(f.isExportDeclaration(t)){let n=t.getModuleSpecifierValue();if(n){if(t.getNamedExports().length>0)try{t.getNamedExports().forEach(r=>{try{let i=r.getName(),s=r.getAliasNode(),a=s?s.getText():void 0;e.push({kind:"reexport",moduleSpecifier:n,name:i||void 0,alias:a||void 0,isNamespace:!1})}catch{}})}catch{}else if(t.isNamespaceExport())try{let i=t.getNamespaceExport()?.getName();e.push({kind:"reexport",moduleSpecifier:n,name:i||"*",alias:i||void 0,isNamespace:!0})}catch{e.push({kind:"reexport",moduleSpecifier:n,name:"*",isNamespace:!0})}else e.push({kind:"reexport",moduleSpecifier:n,name:"*",isNamespace:!0});return}try{t.getNamedExports().forEach(r=>{try{let i=r.getName();if(!i)return;let s=r.getAliasNode(),a=s?s.getText():i;e.push({kind:"alias",local:i,exported:a})}catch{}})}catch{}return}if(f.isExportAssignment(t))try{let n=t.getExpression();if(n&&f.isIdentifier(n)){let r=n.getText();e.push({kind:"alias",local:r,exported:"default"})}}catch{}}function Rr(t,e,n,r){if(!ke(t,ue.ExportKeyword))return;let i=ke(t,ue.DefaultKeyword);if(f.isVariableStatement(t)){try{let s=t.getDeclarationList().getDeclarations();for(let a of s){let o=Ie(a)??a.getName?.()??null;if(o){n(o,a);let c=r(a);c&&e.push({kind:"local",name:o,isDefault:i,nodeId:c})}}}catch{}return}if(f.isFunctionDeclaration(t)||f.isClassDeclaration(t)||f.isInterfaceDeclaration(t)||f.isEnumDeclaration(t)||f.isTypeAliasDeclaration(t)||f.isModuleDeclaration(t)){let s=Ie(t)||(i?"default":null),a=r(t);a&&e.push({kind:"local",name:s??"default",isDefault:i,nodeId:a})}}function Bt(t,e,n,r){let i=[],s=[],a=new Set,o=new Map,c=[],h=[],p=[{node:t,id:null,kind:"module",rawKind:"SourceFile",rawKindSource:"ts-morph",name:null,isExported:!1}],g=l=>{if(!l)return null;try{return e(l)}catch{return null}},b=(l,E)=>{if(l&&(a.has(l)||a.add(l),E&&!o.has(l))){let R=g(E);R&&o.set(l,R)}},_=l=>f.isFunctionDeclaration(l)||f.isFunctionExpression(l)||f.isArrowFunction(l)||f.isClassDeclaration(l)||f.isClassExpression(l)||f.isInterfaceDeclaration(l)||f.isEnumDeclaration(l)||f.isEnumMember(l)||f.isTypeAliasDeclaration(l)||f.isModuleDeclaration(l)||f.isMethodDeclaration(l)||f.isMethodSignature(l)||f.isPropertyDeclaration(l)||f.isPropertySignature(l)||f.isGetAccessorDeclaration(l)||f.isSetAccessorDeclaration(l)||f.isConstructorDeclaration(l)||f.isVariableDeclaration(l)||f.isReturnStatement(l)||f.isIfStatement(l)||f.isForStatement(l)||f.isForInStatement(l)||f.isForOfStatement(l)||f.isWhileStatement(l)||f.isDoStatement(l)||f.isSwitchStatement(l)||f.isCaseClause(l)||f.isDefaultClause(l)||f.isTryStatement(l)||f.isCatchClause(l)||f.isThrowStatement(l)||f.isExpressionStatement(l)||f.isBlock(l),P=l=>f.isSourceFile(l)||f.isFunctionDeclaration(l)||f.isFunctionExpression(l)||f.isArrowFunction(l)||f.isMethodDeclaration(l)||f.isConstructorDeclaration(l)||f.isClassDeclaration(l)||f.isClassExpression(l)||f.isModuleDeclaration(l),w=l=>{let E=Ie(l);if(E)return E;if(f.isConstructorDeclaration(l))return"constructor";if(f.isArrowFunction(l)||f.isFunctionExpression(l)){let R=l.getParent();try{if(f.isVariableDeclaration(R))return R.getName();if(f.isPropertyAssignment(R)||f.isPropertyDeclaration(R)||f.isPropertySignature(R))return R.getName?.()??null;if(f.isShorthandPropertyAssignment(R))return R.getNameNode()?.getText()??null;if(f.isExportAssignment(R))return"default"}catch{}}if(f.isEnumMember(l))try{return l.getName()}catch{return null}if(f.isVariableDeclaration(l))try{return l.getName()}catch{return null}return null},j=l=>{let E=p[p.length-1],R=E?.id??null,d=E?.kind??"module",N=E?.name??null;if(f.isImportDeclaration(l))wr(l,c,b);else if(f.isImportEqualsDeclaration(l))try{let m=l.getModuleReference();if(m&&f.isExternalModuleReference(m)){let y=m.getExpression(),C;if(y&&f.isStringLiteral(y))C=y.getLiteralText();else if(y){let S=y.getText();C=typeof S=="string"?S.replace(/^['"]|['"]$/g,""):void 0}if(C){let K=l.getNameNode()?.getText(),L={moduleSpecifier:C,isTypeOnly:!1,namedImports:[]};K&&(L.defaultImport=K,b(K,l)),c.push(L)}}}catch{}(f.isExportDeclaration(l)||f.isExportAssignment(l))&&Er(l,h),Rr(l,h,b,g);let v=_(l),A=w(l);if(v){let m=e(l),y=ke(l,ue.ExportKeyword)||E?.isExported||!1,C=l.getNameNode?.()?.getText?.()??null,S=A??Ie(l)??C;A?b(A,l):S&&b(S,l);let K=tt(l),L=Pr(l),D={...Lt(l)};if(R&&(D.containerId=R),d&&(D.containerKind=d),N&&(D.containerName=N),f.isModuleDeclaration(l))try{let z=l.getNameNode?.();if(z){let q=tt(z);Number.isFinite(q.start)&&Number.isFinite(q.end)&&(D.moduleNameStart=q.start,D.moduleNameEnd=q.end)}}catch{}let T=Object.keys(D).length?D:null,M=xe(l);_e(M,{source:"ts-node-collector",file:t.getFilePath(),name:S??null}),i.push({nodeId:m,nodeName:S??null,containerId:R,containerKind:d,containerRawKind:E?.rawKind??null,containerRawKindSource:E?.rawKindSource??null,containerName:N,isExported:y,kind:M.kind,rawKind:M.rawKind,rawKindSource:M.rawKindSource,semanticKind:M.semanticKind??null,start:K.start,end:K.end,paramCount:L,metadata:T})}if(f.isCallExpression(l)||f.isNewExpression(l)){let m=l.getExpression(),y=null,C;try{if(f.isIdentifier(m))y=m.getText();else if(f.isPropertyAccessExpression(m)){y=m.getName();let L=m.getExpression();f.isIdentifier(L)&&(C=L.getText())}}catch{}let S="";try{S=m.getText()}catch{}let K=tt(l);if(s.push({name:y,kind:f.isNewExpression(l)?"new":"call",containerId:R,containerKind:d,containerName:N,expression:S,objectName:C,start:K.start,end:K.end}),f.isCallExpression(l))try{if(f.isIdentifier(m)&&m.getText()==="require"){let D=l.getArguments()[0],T;if(D&&(f.isStringLiteral(D)||f.isNoSubstitutionTemplateLiteral(D)))try{T=D.getLiteralText()}catch{let M=D.getText();T=typeof M=="string"?M.replace(/^['"]|['"]$/g,""):void 0}if(T){let M={moduleSpecifier:T,isTypeOnly:!1,namedImports:[]},z=l.getParent();if(z&&f.isVariableDeclaration(z)){let q=z.getNameNode();try{if(f.isIdentifier(q)){let G=q.getText();G&&(M.defaultImport=G,b(G,z))}}catch{}}c.push(M)}}else if(m?.getKind?.()===ue.ImportKeyword){let D=l.getArguments()[0],T;if(D&&(f.isStringLiteral(D)||f.isNoSubstitutionTemplateLiteral(D)))try{T=D.getLiteralText()}catch{let M=D.getText();T=typeof M=="string"?M.replace(/^['"]|['"]$/g,""):void 0}T&&c.push({moduleSpecifier:T,isTypeOnly:!1,namedImports:[]})}}catch{}}if(f.isCallExpression(l)){let m=l.getExpression();try{if(f.isIdentifier(m)&&m.getText()==="require"){let y=l.getParent();if(!(y&&f.isExternalModuleReference(y))){let S=l.getArguments()[0],K;if(S&&(f.isStringLiteral(S)||f.isNoSubstitutionTemplateLiteral(S)))try{K=S.getLiteralText()}catch{K=S.getText().replace(/^['"]|['"]$/g,"")}if(K){let L={moduleSpecifier:K,isTypeOnly:!1,namedImports:[]};if(y&&f.isVariableDeclaration(y)){let D=y.getNameNode();try{if(f.isIdentifier(D)){let T=D.getText();T&&(L.defaultImport=T,b(T,y))}}catch{}}c.push(L)}}}else if(m?.getKind?.()===ue.ImportKeyword){let C=l.getArguments()[0],S;if(C&&(f.isStringLiteral(C)||f.isNoSubstitutionTemplateLiteral(C)))try{S=C.getLiteralText()}catch{S=C.getText().replace(/^['"]|['"]$/g,"")}S&&c.push({moduleSpecifier:S,isTypeOnly:!1,namedImports:[]})}}catch{}}let B=!1;if(P(l)){let m=g(l)??e(l),y=Ot(l);p.push({node:l,id:m,kind:y.kind,rawKind:y.rawKind,rawKindSource:y.rawKindSource,name:A??N,isExported:ke(l,ue.ExportKeyword)||E?.isExported||!1}),B=!0}l.forEachChild(j),B&&p.pop()};if(t.forEachChild(j),r?.includeComments===!0||process.env.AST_INDEX_COMMENTS==="1")try{let l=t.getFullText(),E=W.createScanner(W.ScriptTarget.Latest,!1,W.LanguageVariant.Standard,l),R=new Set;for(let d=E.scan();d!==W.SyntaxKind.EndOfFileToken;d=E.scan()){if(d!==W.SyntaxKind.SingleLineCommentTrivia&&d!==W.SyntaxKind.MultiLineCommentTrivia)continue;let N=E.getTokenPos(),v=E.getTextPos(),A=`${N}-${v}`;if(R.has(A)||(R.add(A),n.has(A)))continue;n.add(A);let B=l.substring(N,v),m=Tt(d,B),C=e({getKindName:()=>m.name,getKind:()=>m.kind,getPos:()=>N,getEnd:()=>v,getStart:()=>N,getFullStart:()=>N,getText:()=>B,getSourceFile:()=>t,getParent:()=>t,__isComment:!0,__commentPosition:"standalone",__attachedTo:null},"COM");i.push({nodeId:C,nodeName:B.substring(0,100),containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:m.name,rawKind:m.name,rawKindSource:"ts-morph",semanticKind:null,start:N,end:v,paramCount:null,metadata:null})}}catch{}return{nodes:i,references:s,declaredNames:a,localDeclarations:o,imports:c,exports:Cr(h)}}le();function zt(t){let e;try{let r=t.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=t.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=t.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let n;try{let r=t.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(n=r)}catch{}if(n===void 0)try{let r=t.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(n=r)}catch{}return n===void 0&&(n=e),n<e&&(n=e),{start:e,end:n}}Ae();var Dr=100;function qt(t,e,n,r){let{start:i,end:s}=zt(e),a=xe(e);_e(a,{source:"ts-node-id",file:t,kind:a.kind});let o=r||Y.getAbbrev(a.kind,n);return`${t}#${i}-${s}:${o}`}function Ir(t,e){return rt.relative(t,e).replace(/\\/g,"/")}function Ht(t,e){if(!t)return null;let n=t;try{let p=t.getAliasedSymbol();p&&(n=p)}catch{}let r=[];try{r=n.getDeclarations()??[]}catch{r=[]}if(!r.length)return null;let s=r.slice().sort((p,g)=>{let b=p.getSourceFile().getFilePath(),_=g.getSourceFile().getFilePath();if(b!==_)return b.localeCompare(_);let P=p.getStart(!1),w=g.getStart(!1);return P!==w?P-w:p.getEnd()-g.getEnd()})[0],a=Ir(e,s.getSourceFile().getFilePath()),o=s.getStart(!1),c=s.getEnd(),h="";try{h=n.getEscapedName()}catch{try{h=n.getName()}catch{h=""}}return`${a}#${o}-${c}:${h}`}function kr(t){return x.isFunctionDeclaration(t)||x.isFunctionExpression(t)||x.isArrowFunction(t)||x.isClassDeclaration(t)||x.isClassExpression(t)||x.isInterfaceDeclaration(t)||x.isEnumDeclaration(t)||x.isEnumMember(t)||x.isTypeAliasDeclaration(t)||x.isModuleDeclaration(t)||x.isMethodDeclaration(t)||x.isMethodSignature(t)||x.isPropertyDeclaration(t)||x.isPropertySignature(t)||x.isGetAccessorDeclaration(t)||x.isSetAccessorDeclaration(t)||x.isConstructorDeclaration(t)||x.isVariableDeclaration(t)||x.isReturnStatement(t)||x.isIfStatement(t)||x.isForStatement(t)||x.isForInStatement(t)||x.isForOfStatement(t)||x.isWhileStatement(t)||x.isDoStatement(t)||x.isSwitchStatement(t)||x.isCaseClause(t)||x.isDefaultClause(t)||x.isTryStatement(t)||x.isCatchClause(t)||x.isThrowStatement(t)||x.isExpressionStatement(t)||x.isBlock(t)}function Tr(t){try{return x.isVariableDeclaration(t)||x.isEnumMember(t)?t.getNameNode().getSymbol()??t.getSymbol():t.getSymbol()}catch{return}}function Kr(t,e){let n=t.getDescendantAtPos(e);if(!n)return;let r=n;if(!x.isCallExpression(r)&&!x.isNewExpression(r)&&(r=n.getFirstAncestor(s=>x.isCallExpression(s)||x.isNewExpression(s))??void 0),!r||!x.isCallExpression(r)&&!x.isNewExpression(r))return;let i=r.getExpression();try{return x.isIdentifier(i)?i.getSymbol():x.isPropertyAccessExpression(i)?i.getNameNode().getSymbol()??i.getSymbol():i.getSymbol()}catch{return}}async function Fr(t){let{sf:e,fileRel:n,preDeleted:r,meta:i,projectRoot:s,lang:a}=t,c=Bt(e,(m,y)=>qt(n,m,a,y),new Set,{includeComments:!1}),h=new Map;e.forEachDescendant(m=>{if(!kr(m))return;let y;try{y=qt(n,m,a)}catch{return}let C=Ht(Tr(m),s);C&&(h.has(y)||h.set(y,C))});let p=[],g=new Map,b=c.exports.filter(m=>m.kind!=="reexport"),_=c.exports.filter(m=>m.kind==="reexport");for(let m of b)if(m.kind==="local"){let y=m.isDefault?"default":m.name;if(!y||g.has(y))continue;let C=m.nodeId;p.push([n,y,C,0,null,null,m.isDefault?"default":"named"]),g.set(y,C)}else if(m.kind==="alias"){let y=m.exported;if(!y||g.has(y))continue;p.push([n,y,null,0,null,m.local,"alias"]),g.set(y,"alias")}for(let m of _){let y=m.moduleSpecifier;if(!y)continue;let C=y;if(m.isNamespace){let S=m.alias||"*";if(g.has(S))continue;p.push([n,S,null,1,C,m.name||S,"reexport_star"]),g.set(S,"reexport")}else{let S=m.alias||m.name;if(!S||g.has(S))continue;p.push([n,S,null,1,C,m.name||S,"reexport_named"]),g.set(S,"reexport")}}let P=[],w=null;try{let m=e.getFullText?.();typeof m=="string"&&(w=m)}catch{w=null}if(w==null)try{let m=e.getFullText();w=typeof m=="string"?m:null}catch{w=null}for(let m of c.nodes){let{nodeId:y,nodeName:C,containerKind:S,containerRawKind:K,containerRawKindSource:L,isExported:D,kind:T,rawKind:M,rawKindSource:z,semanticKind:q,start:G,end:ge,paramCount:Xe,metadata:Q}=m,Ue=Q&&Object.keys(Q).length?JSON.stringify(Q):null,kn=h.get(y)??null;P.push([y,C??null,T,M??T,z??null,q??null,G,ge,D?1:0,S??"module",K??S??"module",L??null,Xe,null,null,kn,Ue])}let j=[];for(let m of c.references){let{name:y,kind:C,containerId:S,containerName:K,expression:L,objectName:D,start:T,end:M}=m,z=null,q=null,G=Ht(Kr(e,T),s),ge=y?c.localDeclarations.get(y):void 0;ge&&(z=ge,q=n,G||(G=h.get(ge)??null));let Xe=Pe({sourceFile:n,sourceStart:T,sourceEnd:M,refKind:C,refName:y,targetFile:q,targetNodeId:z}),Q={};L&&(Q.expression=L),D&&(Q.objectName=D),K&&(Q.containerName=K);let Ue=Object.keys(Q).length?JSON.stringify(Q):null;j.push([Xe,n,S,y,C,T,M,z,q,z?"resolved":"unresolved",D??null,null,null,G,Ue])}let l=[],E=[];for(let m of c.imports){let y=m.moduleSpecifier??null;l.push([n,y,m.isTypeOnly?1:0]),m.defaultImport&&E.push([n,y,"default",m.defaultImport,"default",m.isTypeOnly?1:0]),m.namespaceImport&&E.push([n,y,"namespace",m.namespaceImport,"*",m.isTypeOnly?1:0]);for(let C of m.namedImports){let S=C.alias||C.name;E.push([n,y,"named",S,C.name,m.isTypeOnly?1:0])}}let R=rt.join(s,n),d=i?.size,N=i?.mtime;if(d===void 0||N===void 0)try{let m=_r.statSync(R);d=m.size,N=Math.floor(m.mtimeMs)}catch{}let v=new Date().toISOString(),A=[n,N??null,d??null,"completed",v],B=null;if(typeof w=="string")B={blobOid:n,content:w};else try{let m=e.getFullText?.();typeof m=="string"&&(B={blobOid:n,content:m})}catch(m){console.log(`[TypescriptIndexer] Failed to compute FTS payload for ${n}:`,m?.message??m)}return{payload:{lang:a,fileRel:n,preDeleted:r,exportRows:p,nodeRows:P,referenceRows:j,importRows:l,importBindingRows:E,fileRow:A,fts:B},fileSize:d,mtime:N}}var nt=class{constructor(e,n){this.project=null;this.filesProcessed=0;this.projectRoot=e,this.lang=n}getProject(){return this.project||(this.project=new Ar({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 r=this.getProject().createSourceFile(rt.join(this.projectRoot,e.relPath),e.content,{overwrite:!0}),i=await Fr({sf:r,fileRel:e.relPath,preDeleted:!!e.preDeleted,meta:e.meta,projectRoot:this.projectRoot,lang:e.lang});return this.filesProcessed++,this.filesProcessed>=Dr&&(this.disposeProject(),this.filesProcessed=0),{payload:i.payload,fileSize:i.fileSize,mtime:i.mtime}}};function Or(t){return t==="ts"?[".ts",".tsx",".mts",".cts"]:t==="js"?[".js",".jsx",".mjs",".cjs"]:[]}function it(t){return{id:t,extensions:Or(t),indexingMode:"worker",createIndexer:e=>new nt(e,t)}}import Te from"fs";import ee from"path";import{spawn as Lr,spawnSync as Vt}from"child_process";import jr from"fs";var de=class{constructor(e=5e3){this.maxEntries=e;this.cache=new Map}get(e,n){let r=this.cache.get(e);if(!r)return null;let i=n?.mtime??null,s=n?.size??null;return i!=null&&s!=null&&r.mtime===i&&r.size===s?r.result:null}set(e,n,r){let i=n?.mtime??null,s=n?.size??null;this.cache.set(e,{mtime:i,size:s,result:r}),this.cache.size>this.maxEntries&&this.cache.clear()}};le();var st=class{constructor(e,n,r,i){this.projectRoot=e;this.lang=n;this.parse=r;this.exportKind=i;this.cache=new de}async process(e){let n=e.meta?.mtime,r=e.meta?.size;if(n==null||r==null)try{let a=jr.statSync(e.absPath);n=Math.floor(a.mtimeMs),r=a.size}catch{}let i=this.cache.get(e.absPath,{mtime:n,size:r});if(i)return ye({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:n,size:r},preDeleted:e.preDeleted,parsed:i,resolveNodeId:Jt(e.relPath,i,this.lang),exportKind:this.exportKind??"cli"});let s=null;try{s=await this.parse({absPath:e.absPath,relPath:e.relPath,content:e.content,meta:{mtime:n,size:r},projectRoot:this.projectRoot,lang:this.lang})}catch(a){try{console.log(`[CliContract:${this.lang}] parse threw for ${e.relPath}: ${a?.message||String(a)}`)}catch{}return he(this.lang,e.relPath,{mtime:n,size:r})}return!s||s.error?he(this.lang,e.relPath,{mtime:n,size:r}):(this.cache.set(e.absPath,{mtime:n,size:r},s),ye({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:n,size:r},preDeleted:e.preDeleted,parsed:s,resolveNodeId:Jt(e.relPath,s,this.lang),exportKind:this.exportKind??"cli"}))}};function Jt(t,e,n){let r=new Map;for(let i of e.nodes??[]){if(!i.name||i.containerKind||r.has(i.name))continue;let s=`${t}#${i.start}-${i.end}:${Y.getAbbrev(i.kind,n)}`;r.set(i.name,s)}return i=>r.get(i)??null}function X(t){return{id:t.id,extensions:t.extensions,indexingMode:"worker",createIndexer:e=>new st(e,t.id,t.parse,t.exportKind),resolveSpan:t.resolve?async(e,n,r)=>t.resolve({projectRoot:e,absPath:n,nodePath:r,lang:t.id}):void 0}}import Mr from"fs";import at from"path";var Wt=null;function $r(t){for(let e of t)if(Mr.existsSync(e))return e;return null}function U(t){let e=Wt?.toolsRoot??process.env.PANDO_TOOLS_ROOT,n=Wt?.runtimeRoot??process.env.PANDO_RUNTIME_ROOT,r=[e?at.join(e,t):null,n?at.join(n,"tools",t):null,at.resolve(process.cwd(),"tools",t)].filter(i=>!!i);return $r(r)}function J(...t){try{let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");process.stderr.write(e+`
|
|
12
|
-
`)}catch{}}var Ke=class{constructor(e,n){this.interpreter=e;this.scriptPath=n;this.buffer=Buffer.alloc(0);this.pending=new Map;this.seq=1;this.closed=!1;if(this.proc=Lr(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=>{J(`[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[,n]of this.pending)n.timeout&&clearTimeout(n.timeout),n.summary&&J("[PythonCliAdapter] worker error",{interpreter:this.interpreter,error:e.message,...n.summary}),n.reject(e);this.pending.clear()}}onData(e){for(this.buffer=Buffer.concat([this.buffer,e]);this.buffer.length>=4;){let n=this.buffer.readUInt32BE(0);if(this.buffer.length<4+n)return;let r=this.buffer.slice(4,4+n);this.buffer=this.buffer.slice(4+n);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 Error(i.error||"python worker error")))}}sendMessage(e){if(this.closed)throw new Error("python worker is closed");let n=Buffer.from(JSON.stringify(e),"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(n.length,0),this.proc.stdin.write(r),this.proc.stdin.write(n)}async requestRaw(e,n,r=1e4){let i=this.seq++,s={id:i,op:e,...n},a=Date.now(),o={op:e,id:i};return typeof n?.path=="string"&&(o.path=n.path),typeof n?.nodePath=="string"&&(o.nodePath=n.nodePath),typeof n?.content_b64=="string"&&(o.contentBytes=n.content_b64.length),new Promise((c,h)=>{let p=setTimeout(()=>{this.pending.delete(i),J("[PythonCliAdapter] worker timeout",{op:e,id:i,timeoutMs:r,pending:this.pending.size,interpreter:this.interpreter,...o}),h(new Error(`python worker timeout (${e})`))},r);this.pending.set(i,{resolve:c,reject:h,timeout:p,summary:o}),this.pending.size%200===0&&J("[PythonCliAdapter] worker pending",{op:e,pending:this.pending.size,interpreter:this.interpreter});try{this.sendMessage(s)}catch(g){clearTimeout(p),this.pending.delete(i),h(g)}})}async request(e,n,r=1e4){await this.ready;let i=Date.now(),s=await this.requestRaw(e,n,r),a=Date.now()-i;return a>2e3&&J("[PythonCliAdapter] worker slow",{op:e,ms:a,pending:this.pending.size,interpreter:this.interpreter,path:n?.path}),s}async ping(){await this.requestRaw("ping",{},5e3)}async parse(e){let n=Buffer.from(e.content,"utf8").toString("base64"),r=await this.request("parse",{path:e.path,content_b64:n,encoding:e.encoding});return r.nodes?r:null}async resolve(e){let n=Buffer.from(e.content,"utf8").toString("base64"),r=await this.request("resolve",{path:e.path,nodePath:e.nodePath,content_b64:n,encoding:e.encoding});return typeof r.start=="number"&&typeof r.end=="number"?r:null}},Br=`
|
|
13
|
-
import ast, json, sys, os
|
|
14
|
-
|
|
15
|
-
path = sys.argv[1]
|
|
16
|
-
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
|
|
17
|
-
src = f.read()
|
|
18
|
-
|
|
19
|
-
# line start offsets
|
|
20
|
-
line_starts = [0]
|
|
21
|
-
for line in src.splitlines(True):
|
|
22
|
-
line_starts.append(line_starts[-1] + len(line))
|
|
23
|
-
|
|
24
|
-
def offset(lineno, col):
|
|
25
|
-
if lineno is None:
|
|
26
|
-
return 0
|
|
27
|
-
if lineno < 1:
|
|
28
|
-
lineno = 1
|
|
29
|
-
if lineno >= len(line_starts):
|
|
30
|
-
return line_starts[-1]
|
|
31
|
-
return line_starts[lineno - 1] + (col or 0)
|
|
32
|
-
|
|
33
|
-
def node_span(n):
|
|
34
|
-
start = offset(getattr(n, 'lineno', None), getattr(n, 'col_offset', 0))
|
|
35
|
-
end = offset(getattr(n, 'end_lineno', getattr(n, 'lineno', None)), getattr(n, 'end_col_offset', 0))
|
|
36
|
-
if end < start:
|
|
37
|
-
end = start
|
|
38
|
-
return start, end
|
|
39
|
-
|
|
40
|
-
nodes = []
|
|
41
|
-
imports = []
|
|
42
|
-
bindings = []
|
|
43
|
-
references = []
|
|
44
|
-
class_names = set()
|
|
45
|
-
module_public = set()
|
|
46
|
-
all_exports = None
|
|
47
|
-
|
|
48
|
-
module_name = os.path.splitext(os.path.basename(path))[0] if path else "__main__"
|
|
49
|
-
scope_stack = [module_name]
|
|
50
|
-
nodes.append({
|
|
51
|
-
'name': module_name,
|
|
52
|
-
'kind': 'Namespace',
|
|
53
|
-
'rawKind': 'Module',
|
|
54
|
-
'rawKindSource': 'python-ast',
|
|
55
|
-
'semanticKind': 'namespace',
|
|
56
|
-
'start': 0,
|
|
57
|
-
'end': len(src),
|
|
58
|
-
'isExported': 1,
|
|
59
|
-
'containerKind': None,
|
|
60
|
-
'containerRawKind': None,
|
|
61
|
-
'containerRawKindSource': None,
|
|
62
|
-
'paramCount': None,
|
|
63
|
-
'qualifiedName': module_name,
|
|
64
|
-
'scopeChain': [module_name],
|
|
65
|
-
'metadata': { 'path': path },
|
|
66
|
-
})
|
|
67
|
-
|
|
68
|
-
def decorator_names(node_list):
|
|
69
|
-
out = []
|
|
70
|
-
for d in node_list or []:
|
|
71
|
-
try:
|
|
72
|
-
if isinstance(d, ast.Name):
|
|
73
|
-
out.append(d.id)
|
|
74
|
-
elif isinstance(d, ast.Attribute):
|
|
75
|
-
out.append(d.attr)
|
|
76
|
-
elif hasattr(ast, 'Call') and isinstance(d, ast.Call):
|
|
77
|
-
if isinstance(d.func, ast.Name):
|
|
78
|
-
out.append(d.func.id)
|
|
79
|
-
elif isinstance(d.func, ast.Attribute):
|
|
80
|
-
out.append(d.func.attr)
|
|
81
|
-
except Exception:
|
|
82
|
-
pass
|
|
83
|
-
return out
|
|
84
|
-
|
|
85
|
-
def annotation_text(n):
|
|
86
|
-
try:
|
|
87
|
-
return ast.get_source_segment(src, n)
|
|
88
|
-
except Exception:
|
|
89
|
-
return None
|
|
90
|
-
|
|
91
|
-
def raw_kind(n):
|
|
92
|
-
try:
|
|
93
|
-
return n.__class__.__name__
|
|
94
|
-
except Exception:
|
|
95
|
-
return None
|
|
96
|
-
|
|
97
|
-
def base_name(txt):
|
|
98
|
-
try:
|
|
99
|
-
return txt.split('.')[-1]
|
|
100
|
-
except Exception:
|
|
101
|
-
return txt
|
|
102
|
-
|
|
103
|
-
ENUM_BASES = set(['Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag'])
|
|
104
|
-
META_BASES = set(['type', 'ABCMeta', 'EnumMeta'])
|
|
105
|
-
|
|
106
|
-
def is_enum_base(txt):
|
|
107
|
-
if not txt:
|
|
108
|
-
return False
|
|
109
|
-
name = base_name(txt)
|
|
110
|
-
return name in ENUM_BASES
|
|
111
|
-
|
|
112
|
-
def is_metaclass_base(txt):
|
|
113
|
-
if not txt:
|
|
114
|
-
return False
|
|
115
|
-
name = base_name(txt)
|
|
116
|
-
return name in META_BASES
|
|
117
|
-
|
|
118
|
-
class Visitor(ast.NodeVisitor):
|
|
119
|
-
def __init__(self):
|
|
120
|
-
self.class_name = None
|
|
121
|
-
self.class_is_enum = False
|
|
122
|
-
self.class_stack = []
|
|
123
|
-
self.func_name = None
|
|
124
|
-
self.func_stack = []
|
|
125
|
-
self.scope_stack = list(scope_stack)
|
|
126
|
-
|
|
127
|
-
def visit_ClassDef(self, n):
|
|
128
|
-
start, end = node_span(n)
|
|
129
|
-
name = n.name
|
|
130
|
-
class_names.add(name)
|
|
131
|
-
deco = decorator_names(getattr(n, 'decorator_list', None))
|
|
132
|
-
bases = []
|
|
133
|
-
is_enum = False
|
|
134
|
-
is_meta = False
|
|
135
|
-
meta_value = None
|
|
136
|
-
try:
|
|
137
|
-
for kw in getattr(n, 'keywords', []) or []:
|
|
138
|
-
if getattr(kw, 'arg', None) == 'metaclass':
|
|
139
|
-
meta_value = annotation_text(kw.value)
|
|
140
|
-
except Exception:
|
|
141
|
-
meta_value = None
|
|
142
|
-
try:
|
|
143
|
-
for b in getattr(n, 'bases', []) or []:
|
|
144
|
-
txt = annotation_text(b)
|
|
145
|
-
if txt:
|
|
146
|
-
bases.append(txt)
|
|
147
|
-
if is_enum_base(txt):
|
|
148
|
-
is_enum = True
|
|
149
|
-
if is_metaclass_base(txt):
|
|
150
|
-
is_meta = True
|
|
151
|
-
except Exception:
|
|
152
|
-
pass
|
|
153
|
-
is_exported = 0 if name.startswith('_') else 1
|
|
154
|
-
if is_exported:
|
|
155
|
-
module_public.add(name)
|
|
156
|
-
metadata = {
|
|
157
|
-
'decorators': deco,
|
|
158
|
-
'extends': bases if bases else None,
|
|
159
|
-
'visibility': 'private' if name.startswith('_') else 'public'
|
|
160
|
-
}
|
|
161
|
-
if meta_value:
|
|
162
|
-
metadata['metaclass'] = meta_value
|
|
163
|
-
if is_meta:
|
|
164
|
-
metadata['isMetaclass'] = True
|
|
165
|
-
if is_enum:
|
|
166
|
-
metadata['isEnum'] = True
|
|
167
|
-
scope_chain = self.scope_stack + [name]
|
|
168
|
-
nodes.append({
|
|
169
|
-
'name': name,
|
|
170
|
-
'kind': 'Enum' if is_enum else 'Class',
|
|
171
|
-
'rawKind': raw_kind(n),
|
|
172
|
-
'rawKindSource': 'python-ast',
|
|
173
|
-
'semanticKind': 'enum' if is_enum else 'class',
|
|
174
|
-
'start': start,
|
|
175
|
-
'end': end,
|
|
176
|
-
'isExported': is_exported,
|
|
177
|
-
'containerKind': None,
|
|
178
|
-
'containerRawKind': None,
|
|
179
|
-
'containerRawKindSource': None,
|
|
180
|
-
'paramCount': None,
|
|
181
|
-
'qualifiedName': '.'.join(scope_chain),
|
|
182
|
-
'scopeChain': scope_chain,
|
|
183
|
-
'metadata': metadata,
|
|
184
|
-
})
|
|
185
|
-
prev = self.class_name
|
|
186
|
-
prev_enum = self.class_is_enum
|
|
187
|
-
self.class_stack.append({ 'name': name, 'is_enum': is_enum })
|
|
188
|
-
self.class_name = name
|
|
189
|
-
self.class_is_enum = is_enum
|
|
190
|
-
self.scope_stack.append(name)
|
|
191
|
-
self.generic_visit(n)
|
|
192
|
-
self.scope_stack.pop()
|
|
193
|
-
self.class_stack.pop()
|
|
194
|
-
self.class_name = prev
|
|
195
|
-
self.class_is_enum = prev_enum
|
|
196
|
-
|
|
197
|
-
def visit_FunctionDef(self, n):
|
|
198
|
-
start, end = node_span(n)
|
|
199
|
-
name = n.name
|
|
200
|
-
param_count = len(getattr(n, 'args', {}).args) if hasattr(n, 'args') else None
|
|
201
|
-
is_async = isinstance(n, ast.AsyncFunctionDef)
|
|
202
|
-
deco = decorator_names(getattr(n, 'decorator_list', None))
|
|
203
|
-
ret = annotation_text(getattr(n, 'returns', None)) if hasattr(n, 'returns') else None
|
|
204
|
-
is_static = 'staticmethod' in deco
|
|
205
|
-
is_abstract = 'abstractmethod' in deco
|
|
206
|
-
is_readonly = 'property' in deco
|
|
207
|
-
visibility = 'private' if name.startswith('_') else 'public'
|
|
208
|
-
scope_chain = self.scope_stack + [name]
|
|
209
|
-
if self.class_name:
|
|
210
|
-
sem_kind = 'property' if is_readonly else 'method'
|
|
211
|
-
nodes.append({
|
|
212
|
-
'name': name,
|
|
213
|
-
'kind': 'Method',
|
|
214
|
-
'rawKind': raw_kind(n),
|
|
215
|
-
'rawKindSource': 'python-ast',
|
|
216
|
-
'semanticKind': sem_kind,
|
|
217
|
-
'start': start,
|
|
218
|
-
'end': end,
|
|
219
|
-
'isExported': 0,
|
|
220
|
-
'containerKind': 'Class',
|
|
221
|
-
'containerRawKind': 'ClassDef',
|
|
222
|
-
'containerRawKindSource': 'python-ast',
|
|
223
|
-
'paramCount': param_count,
|
|
224
|
-
'qualifiedName': '.'.join(scope_chain),
|
|
225
|
-
'scopeChain': scope_chain,
|
|
226
|
-
'metadata': { 'isAsync': is_async, 'containerName': self.class_name, 'decorators': deco, 'returnType': ret, 'isStatic': is_static, 'isAbstract': is_abstract, 'isReadonly': is_readonly, 'visibility': visibility },
|
|
227
|
-
})
|
|
228
|
-
else:
|
|
229
|
-
is_exported = 0 if name.startswith('_') else 1
|
|
230
|
-
if is_exported:
|
|
231
|
-
module_public.add(name)
|
|
232
|
-
nodes.append({
|
|
233
|
-
'name': name,
|
|
234
|
-
'kind': 'Function',
|
|
235
|
-
'rawKind': raw_kind(n),
|
|
236
|
-
'rawKindSource': 'python-ast',
|
|
237
|
-
'semanticKind': 'function',
|
|
238
|
-
'start': start,
|
|
239
|
-
'end': end,
|
|
240
|
-
'isExported': is_exported,
|
|
241
|
-
'containerKind': None,
|
|
242
|
-
'containerRawKind': None,
|
|
243
|
-
'containerRawKindSource': None,
|
|
244
|
-
'paramCount': param_count,
|
|
245
|
-
'qualifiedName': '.'.join(scope_chain),
|
|
246
|
-
'scopeChain': scope_chain,
|
|
247
|
-
'metadata': { 'isAsync': is_async, 'decorators': deco, 'returnType': ret, 'isAbstract': is_abstract, 'visibility': visibility },
|
|
248
|
-
})
|
|
249
|
-
prev = self.func_name
|
|
250
|
-
self.func_name = name
|
|
251
|
-
self.func_stack.append(name)
|
|
252
|
-
self.scope_stack.append(name)
|
|
253
|
-
self.generic_visit(n)
|
|
254
|
-
self.scope_stack.pop()
|
|
255
|
-
self.func_stack.pop()
|
|
256
|
-
self.func_name = prev
|
|
257
|
-
|
|
258
|
-
def visit_AsyncFunctionDef(self, n):
|
|
259
|
-
self.visit_FunctionDef(n)
|
|
260
|
-
|
|
261
|
-
def visit_Import(self, n):
|
|
262
|
-
for alias in n.names:
|
|
263
|
-
module = alias.name
|
|
264
|
-
imports.append({ 'module': module, 'isTypeOnly': 0 })
|
|
265
|
-
local = alias.asname or alias.name
|
|
266
|
-
if local and not local.startswith('_'):
|
|
267
|
-
module_public.add(local)
|
|
268
|
-
bindings.append({
|
|
269
|
-
'module': module,
|
|
270
|
-
'localName': local,
|
|
271
|
-
'importedName': alias.name,
|
|
272
|
-
'kind': 'named',
|
|
273
|
-
'isTypeOnly': 0,
|
|
274
|
-
})
|
|
275
|
-
|
|
276
|
-
def visit_ImportFrom(self, n):
|
|
277
|
-
module = n.module
|
|
278
|
-
imports.append({ 'module': module, 'isTypeOnly': 0 })
|
|
279
|
-
for alias in n.names:
|
|
280
|
-
if alias.name == '*':
|
|
281
|
-
bindings.append({
|
|
282
|
-
'module': module,
|
|
283
|
-
'localName': alias.asname or '*',
|
|
284
|
-
'importedName': '*',
|
|
285
|
-
'kind': 'namespace',
|
|
286
|
-
'isTypeOnly': 0,
|
|
287
|
-
})
|
|
288
|
-
else:
|
|
289
|
-
bindings.append({
|
|
290
|
-
'module': module,
|
|
291
|
-
'localName': alias.asname or alias.name,
|
|
292
|
-
'importedName': alias.name,
|
|
293
|
-
'kind': 'named',
|
|
294
|
-
'isTypeOnly': 0,
|
|
295
|
-
})
|
|
296
|
-
local_name = alias.asname or alias.name
|
|
297
|
-
if local_name and not local_name.startswith('_'):
|
|
298
|
-
module_public.add(local_name)
|
|
299
|
-
|
|
300
|
-
def visit_Assign(self, n):
|
|
301
|
-
# module-level or class-level names
|
|
302
|
-
global all_exports
|
|
303
|
-
targets = getattr(n, 'targets', [])
|
|
304
|
-
for t in targets:
|
|
305
|
-
if isinstance(t, ast.Name):
|
|
306
|
-
start, end = node_span(t)
|
|
307
|
-
name = t.id
|
|
308
|
-
is_exported = 0 if name.startswith('_') else 1
|
|
309
|
-
scope_chain = self.scope_stack + [name]
|
|
310
|
-
if self.class_name:
|
|
311
|
-
if self.class_is_enum:
|
|
312
|
-
nodes.append({
|
|
313
|
-
'name': name,
|
|
314
|
-
'kind': 'EnumMember',
|
|
315
|
-
'rawKind': raw_kind(t),
|
|
316
|
-
'rawKindSource': 'python-ast',
|
|
317
|
-
'semanticKind': 'enum',
|
|
318
|
-
'start': start,
|
|
319
|
-
'end': end,
|
|
320
|
-
'isExported': 0,
|
|
321
|
-
'containerKind': 'Enum',
|
|
322
|
-
'containerRawKind': 'ClassDef',
|
|
323
|
-
'containerRawKindSource': 'python-ast',
|
|
324
|
-
'paramCount': None,
|
|
325
|
-
'qualifiedName': '.'.join(scope_chain),
|
|
326
|
-
'scopeChain': scope_chain,
|
|
327
|
-
'metadata': { 'containerName': self.class_name, 'visibility': 'private' if name.startswith('_') else 'public' },
|
|
328
|
-
})
|
|
329
|
-
continue
|
|
330
|
-
nodes.append({
|
|
331
|
-
'name': name,
|
|
332
|
-
'kind': 'Field',
|
|
333
|
-
'rawKind': raw_kind(t),
|
|
334
|
-
'rawKindSource': 'python-ast',
|
|
335
|
-
'semanticKind': 'field',
|
|
336
|
-
'start': start,
|
|
337
|
-
'end': end,
|
|
338
|
-
'isExported': 0,
|
|
339
|
-
'containerKind': 'Class',
|
|
340
|
-
'containerRawKind': 'ClassDef',
|
|
341
|
-
'containerRawKindSource': 'python-ast',
|
|
342
|
-
'paramCount': None,
|
|
343
|
-
'qualifiedName': '.'.join(scope_chain),
|
|
344
|
-
'scopeChain': scope_chain,
|
|
345
|
-
'metadata': { 'containerName': self.class_name, 'visibility': 'private' if name.startswith('_') else 'public' },
|
|
346
|
-
})
|
|
347
|
-
else:
|
|
348
|
-
if is_exported:
|
|
349
|
-
module_public.add(name)
|
|
350
|
-
nodes.append({
|
|
351
|
-
'name': name,
|
|
352
|
-
'kind': 'Variable',
|
|
353
|
-
'rawKind': raw_kind(t),
|
|
354
|
-
'rawKindSource': 'python-ast',
|
|
355
|
-
'semanticKind': 'variable',
|
|
356
|
-
'start': start,
|
|
357
|
-
'end': end,
|
|
358
|
-
'isExported': is_exported,
|
|
359
|
-
'containerKind': None,
|
|
360
|
-
'containerRawKind': None,
|
|
361
|
-
'containerRawKindSource': None,
|
|
362
|
-
'paramCount': None,
|
|
363
|
-
'qualifiedName': '.'.join(scope_chain),
|
|
364
|
-
'scopeChain': scope_chain,
|
|
365
|
-
'metadata': { 'visibility': 'private' if name.startswith('_') else 'public' },
|
|
366
|
-
})
|
|
367
|
-
if (not self.class_name) and name == '__all__':
|
|
368
|
-
try:
|
|
369
|
-
if isinstance(n.value, (ast.List, ast.Tuple)):
|
|
370
|
-
all_list = []
|
|
371
|
-
for elt in n.value.elts:
|
|
372
|
-
if isinstance(elt, ast.Str):
|
|
373
|
-
all_list.append(elt.s)
|
|
374
|
-
elif hasattr(ast, 'Constant') and isinstance(elt, ast.Constant) and isinstance(elt.value, str):
|
|
375
|
-
all_list.append(elt.value)
|
|
376
|
-
if all_list:
|
|
377
|
-
all_exports = all_list
|
|
378
|
-
except Exception:
|
|
379
|
-
pass
|
|
380
|
-
self.generic_visit(n)
|
|
381
|
-
|
|
382
|
-
def visit_Call(self, n):
|
|
383
|
-
try:
|
|
384
|
-
func = n.func
|
|
385
|
-
call_name = None
|
|
386
|
-
object_name = None
|
|
387
|
-
expr_text = None
|
|
388
|
-
if isinstance(func, ast.Name):
|
|
389
|
-
call_name = func.id
|
|
390
|
-
elif isinstance(func, ast.Attribute):
|
|
391
|
-
call_name = func.attr
|
|
392
|
-
if isinstance(func.value, ast.Name):
|
|
393
|
-
object_name = func.value.id
|
|
394
|
-
try:
|
|
395
|
-
expr_text = ast.get_source_segment(src, func)
|
|
396
|
-
except Exception:
|
|
397
|
-
expr_text = None
|
|
398
|
-
start, end = node_span(n)
|
|
399
|
-
kind = 'new' if call_name in class_names else 'call'
|
|
400
|
-
container_name = self.class_name or self.func_name
|
|
401
|
-
container_kind = 'Class' if self.class_name else ('Function' if self.func_name else None)
|
|
402
|
-
try:
|
|
403
|
-
arity = len(getattr(n, 'args', []) or []) + len(getattr(n, 'keywords', []) or [])
|
|
404
|
-
except Exception:
|
|
405
|
-
arity = 0
|
|
406
|
-
container_qualified_name = '.'.join(self.scope_stack) if self.scope_stack else None
|
|
407
|
-
references.append({
|
|
408
|
-
'name': call_name,
|
|
409
|
-
'kind': kind,
|
|
410
|
-
'start': start,
|
|
411
|
-
'end': end,
|
|
412
|
-
'expression': expr_text,
|
|
413
|
-
'objectName': object_name,
|
|
414
|
-
'containerName': container_name,
|
|
415
|
-
'containerKind': container_kind,
|
|
416
|
-
'receiverName': object_name,
|
|
417
|
-
'arity': arity,
|
|
418
|
-
'containerQualifiedName': container_qualified_name,
|
|
419
|
-
})
|
|
420
|
-
except Exception:
|
|
421
|
-
pass
|
|
422
|
-
self.generic_visit(n)
|
|
423
|
-
|
|
424
|
-
try:
|
|
425
|
-
tree = ast.parse(src, filename=path)
|
|
426
|
-
Visitor().visit(tree)
|
|
427
|
-
out = { 'nodes': nodes, 'imports': imports, 'importBindings': bindings, 'references': references, 'modulePublic': sorted(list(module_public)), 'explicitExports': all_exports }
|
|
428
|
-
print(json.dumps(out))
|
|
429
|
-
except Exception as e:
|
|
430
|
-
print(json.dumps({ 'error': str(e) }))
|
|
431
|
-
sys.exit(2)
|
|
432
|
-
`,zr=`
|
|
433
|
-
import ast, json, sys
|
|
434
|
-
|
|
435
|
-
path = sys.argv[1]
|
|
436
|
-
node_path = sys.argv[2]
|
|
437
|
-
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
|
|
438
|
-
src = f.read()
|
|
439
|
-
|
|
440
|
-
# line start offsets
|
|
441
|
-
line_starts = [0]
|
|
442
|
-
for line in src.splitlines(True):
|
|
443
|
-
line_starts.append(line_starts[-1] + len(line))
|
|
444
|
-
|
|
445
|
-
def offset(lineno, col):
|
|
446
|
-
if lineno is None:
|
|
447
|
-
return 0
|
|
448
|
-
if lineno < 1:
|
|
449
|
-
lineno = 1
|
|
450
|
-
if lineno >= len(line_starts):
|
|
451
|
-
return line_starts[-1]
|
|
452
|
-
return line_starts[lineno - 1] + (col or 0)
|
|
453
|
-
|
|
454
|
-
def node_span(n):
|
|
455
|
-
start = offset(getattr(n, 'lineno', None), getattr(n, 'col_offset', 0))
|
|
456
|
-
end = offset(getattr(n, 'end_lineno', getattr(n, 'lineno', None)), getattr(n, 'end_col_offset', 0))
|
|
457
|
-
if end < start:
|
|
458
|
-
end = start
|
|
459
|
-
return start, end
|
|
460
|
-
|
|
461
|
-
def parse_range(node_path):
|
|
462
|
-
clean = node_path
|
|
463
|
-
if clean.startswith('SyntaxError:') or clean.startswith('CompileError:'):
|
|
464
|
-
clean = clean.split(':', 1)[1]
|
|
465
|
-
if '#' in clean:
|
|
466
|
-
clean = clean.split('#', 1)[1]
|
|
467
|
-
if ':' in clean:
|
|
468
|
-
clean = clean.rsplit(':', 1)[0]
|
|
469
|
-
if '-' not in clean:
|
|
470
|
-
return None
|
|
471
|
-
parts = clean.split('-', 1)
|
|
472
|
-
try:
|
|
473
|
-
return int(parts[0]), int(parts[1])
|
|
474
|
-
except Exception:
|
|
475
|
-
return None
|
|
476
|
-
|
|
477
|
-
target = parse_range(node_path)
|
|
478
|
-
if target is None:
|
|
479
|
-
print(json.dumps({ 'error': 'invalid nodePath' }))
|
|
480
|
-
sys.exit(2)
|
|
481
|
-
|
|
482
|
-
target_start, target_end = target
|
|
483
|
-
resolved = None
|
|
484
|
-
|
|
485
|
-
try:
|
|
486
|
-
tree = ast.parse(src, filename=path)
|
|
487
|
-
for n in ast.walk(tree):
|
|
488
|
-
s, e = node_span(n)
|
|
489
|
-
if s == target_start and e == target_end:
|
|
490
|
-
body_start = None
|
|
491
|
-
body_end = None
|
|
492
|
-
if hasattr(n, 'body') and isinstance(n.body, list) and len(n.body) > 0:
|
|
493
|
-
try:
|
|
494
|
-
bs, _ = node_span(n.body[0])
|
|
495
|
-
_, be = node_span(n.body[-1])
|
|
496
|
-
body_start = bs
|
|
497
|
-
body_end = be
|
|
498
|
-
except Exception:
|
|
499
|
-
body_start = None
|
|
500
|
-
body_end = None
|
|
501
|
-
try:
|
|
502
|
-
text = src[s:e]
|
|
503
|
-
except Exception:
|
|
504
|
-
text = None
|
|
505
|
-
resolved = { 'start': s, 'end': e, 'bodyStart': body_start, 'bodyEnd': body_end, 'text': text }
|
|
506
|
-
break
|
|
507
|
-
if not resolved:
|
|
508
|
-
print(json.dumps({ 'error': 'node not found' }))
|
|
509
|
-
sys.exit(2)
|
|
510
|
-
print(json.dumps(resolved))
|
|
511
|
-
except Exception as e:
|
|
512
|
-
print(json.dumps({ 'error': str(e) }))
|
|
513
|
-
sys.exit(2)
|
|
514
|
-
`;function Gt(t){let e=ee.resolve(t,"tools/python-indexer/pando_python_worker.py");if(Te.existsSync(e))return e;let n=U("python-indexer/pando_python_worker.py");if(n)return n;let r=ee.resolve(__dirname,"../../../../../tools/python-indexer/pando_python_worker.py");return Te.existsSync(r)?r:null}var fe=new Map;function pe(t){try{return Te.readFileSync(t,"utf8")}catch{return null}}function Se(t){if(!t)return null;let e=t.match(/(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2])}:null}function qr(t){let e=pe(ee.join(t,"pyproject.toml"));if(e){let o=e.match(/requires-python\s*=\s*"([^"]+)"/i),c=Se(o?.[1]??null);if(c)return c}let n=pe(ee.join(t,"setup.cfg"));if(n){let o=n.match(/python_requires\s*=\s*([\w\d\.<>~=\s]+)/i),c=Se(o?.[1]??null);if(c)return c}let r=pe(ee.join(t,"setup.py"));if(r){let o=r.match(/python_requires\s*=\s*['\"]([^'\"]+)['\"]/i),c=Se(o?.[1]??null);if(c)return c}let i=pe(ee.join(t,"tox.ini"));if(i){let o=i.match(/envlist\s*=\s*([^\n]+)/i);if(o&&o[1]){let c=o[1].split(/[,\s]+/).filter(Boolean);for(let h of c){let p=h.match(/py(\d)(\d)/i);if(p)return{major:Number(p[1]),minor:Number(p[2])}}}}let s=pe(ee.join(t,".python-version"));if(s){let o=Se(s.trim());if(o)return o}let a=pe(ee.join(t,"runtime.txt"));if(a){let o=a.match(/python-(\d+\.\d+)/i),c=Se(o?.[1]??null);if(c)return c}return null}function Fe(t){return qr(t)?.major===2?["python2","python","python3"]:["python3","python","python2"]}async function Hr(t,e,n){let r=Gt(t);if(!r)return null;let i=Fe(t);for(let s of i){let a=`${s}::${r}`,o=fe.get(a);if(!o)try{o=new Ke(s,r),fe.set(a,o)}catch{continue}try{let c=await o.parse({path:e,content:n,encoding:"utf-8"});if(c)return c}catch{J("[PythonCliAdapter] worker parse error",{file:e,interpreter:s}),fe.delete(a)}}return null}async function Jr(t,e,n,r){let i=Gt(t);if(!i)return null;let s=Fe(t);for(let a of s){let o=`${a}::${i}`,c=fe.get(o);if(!c)try{c=new Ke(a,i),fe.set(o,c)}catch{continue}try{let h=await c.resolve({path:e,nodePath:r,content:n,encoding:"utf-8"});if(h)return h}catch{J("[PythonCliAdapter] worker resolve error",{file:e,interpreter:a,nodePath:r}),fe.delete(o)}}return null}function Xt(t,e){let n=Vt(t,["-c",Br,e],{encoding:"utf8"});if(n.error||typeof n.stdout!="string")return null;try{let r=JSON.parse(n.stdout.trim()||"{}");return r&&r.error?null:r}catch{return null}}function Ut(t,e,n){let r=Vt(t,["-c",zr,e,n],{encoding:"utf8"});if(r.error||typeof r.stdout!="string")return null;try{let i=JSON.parse(r.stdout.trim()||"{}");return i&&i.error||typeof i.start!="number"||typeof i.end!="number"?null:i}catch{return null}}async function Wr(t){let e=Date.now(),n=!1,r=null;try{r=await Hr(t.projectRoot,t.absPath,t.content),n=!!r}catch{}if(!r){let a=Fe(t.projectRoot),o=null;for(let c of a)if(r=Xt(c,t.absPath),r){o=c;break}if(!r&&a.length>1){for(let c of a.slice().reverse())if(r=Xt(c,t.absPath),r){o=c;break}}if(!r){J(`[PythonCliAdapter] parse failed for ${t.relPath} (interpreters tried: ${a.join(", ")})`);let c=Date.now()-e;return c>2e3&&J("[PythonCliAdapter] parse slow (failed)",{file:t.relPath,ms:c}),null}o&&J(`[PythonCliAdapter] parse ok for ${t.relPath} via ${o}`)}let i=[];for(let a of r.references||[]){let o={};a.expression&&(o.expression=a.expression),a.objectName&&(o.objectName=a.objectName),a.containerName&&(o.containerName=a.containerName),a.containerKind&&(o.containerKind=a.containerKind),i.push({sourceStart:a.start,sourceEnd:a.end,refKind:a.kind,refName:a.name,receiverName:a.receiverName??a.objectName??null,arity:typeof a.arity=="number"?a.arity:null,containerQualifiedName:a.containerQualifiedName??null,targetSymbolKey:a.targetSymbolKey??null,metadata:Object.keys(o).length?o:null})}let s=Date.now()-e;return s>2e3&&J("[PythonCliAdapter] parse slow",{file:t.relPath,ms:s,usedWorker:n}),{nodes:r.nodes,imports:r.imports,importBindings:r.importBindings,references:i,modulePublic:r.modulePublic??void 0,explicitExports:r.explicitExports??void 0}}function Qt(){return X({id:"python",extensions:[".py",".pyw",".pyi"],exportKind:"named",parse:({absPath:t,relPath:e,projectRoot:n,content:r})=>Wr({absPath:t,relPath:e,projectRoot:n,content:r}),resolve:async({absPath:t,nodePath:e,projectRoot:n})=>{try{let i=Te.readFileSync(t,"utf8"),s=await Jr(n,t,i,e);if(s)return s}catch{}let r=Fe(n);for(let i of r){let s=Ut(i,t,e);if(s)return s}for(let i of r.slice().reverse()){let s=Ut(i,t,e);if(s)return s}return null}})}import Yt from"fs";import Zt from"path";import{spawn as Xr,spawnSync as Pa}from"child_process";var Ur=256e3,Vr=32;function re(...t){try{let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");process.stderr.write(e+`
|
|
515
|
-
`)}catch{}}var ot=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=Xr(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=>{re(`[CSharpIndexer] ${e.toString("utf8").trim()}`)}),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[,n]of this.pending)n.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let n=this.buffer.indexOf(`
|
|
516
|
-
`);if(n<0)break;let r=this.buffer.slice(0,n).trim();if(this.buffer=this.buffer.slice(n+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,n=1){this.ensureProcess();let r=this.seq++;return new Promise((i,s)=>{let a={id:r,...e};this.pending.set(r,{resolve:i,reject:s});try{this.proc.stdin.write(`${JSON.stringify(a)}
|
|
517
|
-
`)}catch(o){if(this.pending.delete(r),n>0){try{this.handleExit(o)}catch{}return this.request(e,n-1).then(i,s)}s(o)}})}async parseBatch(e){let n=await this.request({op:"parse",files:e});return"results"in n?n.results.map(r=>r.ok&&r.result?r.result:null):"result"in n?[n.result]:e.map(()=>null)}async resolve(e){let n=await this.request({op:"resolve",...e});return"result"in n&&n.result&&typeof n.result.start=="number"?n.result:null}async resolveReferences(e){let n=await this.request({op:"resolve-references",...e});return"result"in n&&n.result?n.result:null}},lt=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((n,r)=>{this.queue.push({input:e,resolve:n,reject:r,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],n=0;for(;this.queue.length&&e.length<Vr;){let r=this.queue[0];if(e.length>0&&n+r.input.size>Ur)break;e.push(this.queue.shift()),n+=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],a=r[i]??null,o=Date.now()-s.startedAt;o>2e3&&re(`[${new Date().toISOString()}] [CSharpCliAdapter] parse slow`,{file:s.input.file,ms:o,path:"custom",ok:!!a}),a||re(`[${new Date().toISOString()}] [CSharpCliAdapter] parse failed`,{file:s.input.file,ms:o,path:"custom"}),s.resolve(a)}}catch(r){for(let i of e)i.reject(r)}}}},en=new Map,tn=new Map;function Gr(t){let e=process.platform==="win32"?".cmd":"",n=U(`csharp-indexer/bin/pando-csharp-indexer${e}`);if(n)return n;if(t){let i=Zt.resolve(t,"tools/csharp-indexer/bin/pando-csharp-indexer"+e);if(Yt.existsSync(i))return i}let r=Zt.resolve(__dirname,"../../../../../tools/csharp-indexer/bin/pando-csharp-indexer"+e);return Yt.existsSync(r)?r:null}function nn(t){let e=process.env.PANDO_CSHARP_INDEXER_CMD||Gr(t);if(!e)return null;let n=en.get(e);n||(n=new ot(e),en.set(e,n));let r=tn.get(e);return r||(r=new lt(n),tn.set(e,r)),{client:n,batcher:r}}async function Qr(t,e,n){let r=nn(e);if(!r)return null;try{return await r.batcher.enqueue({file:t,root:e,lang:"csharp",size:n})}catch(i){return re(`[${new Date().toISOString()}] [CSharpCliAdapter] parse error`,{file:t,error:i?.message||i,path:"custom"}),null}}async function Yr(t,e,n){let r=await Qr(t,e,n);return r||null}function rn(){return X({id:"csharp",extensions:[".cs",".csx",".cshtml",".razor"],parse:({absPath:t,projectRoot:e,content:n,meta:r})=>{let i=r?.size??Buffer.byteLength(n,"utf8");return Yr(t,e,i)},resolve:({absPath:t,nodePath:e,projectRoot:n})=>{let r=Date.now(),i=nn(n);return i?i.client.resolve({file:t,root:n,lang:"csharp",nodePath:e}).then(s=>{let a=Date.now()-r;return a>2e3&&re(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve slow`,{file:t,ms:a}),s||re(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve failed`,{file:t,ms:a,nodePath:e}),s}).catch(s=>{let a=Date.now()-r;return re(`[${new Date().toISOString()}] [CSharpCliAdapter] resolve error`,{file:t,ms:a,nodePath:e,error:s?.message||s}),null}):null}})}import{spawnSync as si}from"child_process";import ai from"path";import V from"fs";import I from"path";var Oe=new Map,Zr=["include","src","lib","libs","third_party","third-party","deps","vendor"];function an(t){let e=[],n="",r=null,i=!1;for(let s=0;s<t.length;s+=1){let a=t[s];if(i){n+=a,i=!1;continue}if(a==="\\"){i=!0;continue}if(r){a===r?r=null:n+=a;continue}if(a==='"'||a==="'"){r=a;continue}if(a===" "||a===`
|
|
518
|
-
`||a===" "||a==="\r"){n&&(e.push(n),n="");continue}n+=a}return n&&e.push(n),e}function ei(t,e){let n=[];for(let r=0;r<t.length;r+=1){let i=t[r];if(i!=="-c"){if(i==="-o"){r+=1;continue}i!==e&&((i.endsWith(".c")||i.endsWith(".cc")||i.endsWith(".cpp")||i.endsWith(".cxx")||i.endsWith(".c++"))&&I.isAbsolute(i)||n.push(i))}}return n}function on(t,e){return I.isAbsolute(t)?I.resolve(t):e?I.resolve(e,t):I.resolve(t)}function ti(t){try{let e=V.readFileSync(t,"utf8"),n=JSON.parse(e),r=new Map;for(let i of n){let s=i.directory?I.resolve(i.directory):void 0,a=i.file?on(i.file,s):null;if(!a)continue;let o=s??I.dirname(a),c=Array.isArray(i.arguments)?i.arguments:i.command?an(i.command):[];if(c.length===0)continue;let h=ei(c.slice(1),a);r.set(a,{args:h,cwd:o})}return r}catch{return null}}function ni(t){try{let e=V.readFileSync(t,"utf8");return an(e.replace(/\r/g,`
|
|
519
|
-
`))}catch{return null}}function ln(t){let e=I.join(t,"compile_commands.json");if(V.existsSync(e))return e;let n=["build","out","build-debug","build-release","cmake-build-debug","cmake-build-release"];for(let o of n){let c=I.join(t,o,"compile_commands.json");if(V.existsSync(c))return c}let r=n.map(o=>I.join(t,o)).filter(o=>V.existsSync(o));r.push(t);let i=10,s=new Set,a=(o,c)=>{if(c>i)return null;let h=I.resolve(o);if(s.has(h))return null;s.add(h);try{let p=V.readdirSync(o,{withFileTypes:!0});for(let g of p)if(g.isFile()&&g.name==="compile_commands.json")return I.join(o,g.name);for(let g of p){if(!g.isDirectory()||g.name==="node_modules"||g.name.startsWith("."))continue;let b=a(I.join(o,g.name),c+1);if(b)return b}}catch{}return null};for(let o of r){let c=a(o,0);if(c)return c}return null}function ri(t,e){let n=I.resolve(t),r=I.resolve(e);for(;;){let i=ln(n);if(i)return i;if(n===r)break;let s=I.dirname(n);if(s===n)break;n=s}return null}function cn(t){let e=I.join(t,"compile_flags.txt");if(V.existsSync(e))return e;let n=["build","out","build-debug","build-release","cmake-build-debug","cmake-build-release"];for(let r of n){let i=I.join(t,r,"compile_flags.txt");if(V.existsSync(i))return i}return null}function ii(t,e){let n=I.resolve(t),r=I.resolve(e);for(;;){let i=cn(n);if(i)return i;if(n===r)break;let s=I.dirname(n);if(s===n)break;n=s}return null}function je(t){if(t)try{return V.statSync(t).mtimeMs}catch{return}}function sn(t,e){let n=e?`${I.resolve(t)}::${I.resolve(e)}`:I.resolve(t),r=Oe.get(n);if(r){let g=je(r.commandsPath);if(r.commandsPath&&g&&r.commandsMtime&&g!==r.commandsMtime)Oe.delete(n);else if(r.flagsPath){let b=je(r.flagsPath);b&&r.flagsMtime&&b!==r.flagsMtime&&Oe.delete(n)}else return r}let i=e?ri(e,t):ln(t),s=i?ti(i)??void 0:void 0,a=je(i),o=s?null:e?ii(e,t):cn(t),c=o?ni(o)??void 0:void 0,h=je(o),p={commands:s,flags:c,commandsPath:i,commandsMtime:a,flagsPath:o,flagsMtime:h};return Oe.set(n,p),p}function ct(t,e,n){let r=I.dirname(e),i=sn(t);!i.commands&&!i.flags&&(i=sn(t,r));let s=on(e);if(i.commands){let a=i.commands.get(s);if(a)return{args:a.args,cwd:a.cwd,source:"compile_commands"}}return i.flags?{args:i.flags,cwd:t,source:"compile_flags"}:ut(t,n)}function ut(t,e){let n=["-std="+(e==="cpp"?"c++20":"c17")];n.push("-I",t);for(let r of Zr){let i=I.join(t,r);V.existsSync(i)&&n.push("-I",i)}return n.push("-ferror-limit=0"),{args:n,cwd:t,source:"fallback"}}function pn(t){let e=[0];for(let n=0;n<t.length;n+=1)t.charCodeAt(n)===10&&e.push(n+1);return e}function un(t,e,n){if(!e||e<1)return 0;let r=Math.min(e-1,t.length-1),i=t[r]??0,s=Math.max((n??1)-1,0);return i+s}function me(t){return t?ai.resolve(t):null}function dn(t,e,n){let r=Math.max(0,Math.min(n-1,t.length-1)),i=t[r]??0,s=r+1<t.length?t[r+1]:e;return Math.max(0,s-i)}function ie(t,e,n){let r=t.range?.begin??t.loc,i=t.range?.end??t.loc;if(!r?.line||r.line<1||r.line>e.length||r.col==null||r.col<1||i?.line&&(i.line<1||i.line>e.length)||i?.col!=null&&i.col<1)return null;let s=dn(e,n,r.line);if((r.col??1)-1>s)return null;if(i?.line){let c=dn(e,n,i.line);if((i.col??r.col??1)-1>c)return null}let a=un(e,r.line,r.col),o=un(e,i?.line??r.line,i?.col??r.col);return{start:a,end:Math.max(o,a)}}function Le(t){let e=t.range?.begin?.file||t.loc?.file||t.range?.end?.file||null;if(e)return me(e);let n=t.range?.begin?.includedFrom?.file||t.range?.end?.includedFrom?.file||null;return me(n)}function oi(t){let e=t.access;return typeof e=="string"?e:null}function li(t,e){let n={};e.containerName&&(n.containerName=e.containerName);let r=oi(t);r&&(n.visibility=r);let i=t.storageClass;i&&(n.storageClass=i);let s=t.isInline;typeof s=="boolean"&&(n.isInline=s);let a=t.isConstexpr;typeof a=="boolean"&&(n.isConstexpr=a);let o=t.isVirtual;typeof o=="boolean"&&(n.isVirtual=o);let c=t.isStatic;typeof c=="boolean"&&(n.isStatic=c);let h=t.type;return typeof h=="string"&&(n.type=h),n}function dt(t,e,n){switch(t){case"FunctionDecl":return{kind:"Function",semanticKind:"function"};case"CXXMethodDecl":case"CXXConstructorDecl":case"CXXDestructorDecl":case"CXXConversionDecl":return{kind:"Method",semanticKind:"method"};case"FunctionTemplateDecl":case"ClassTemplateDecl":case"TypeAliasTemplateDecl":return{kind:"Template",semanticKind:"template"};case"ConceptDecl":return{kind:"Concept",semanticKind:"type"};case"TemplateTypeParmDecl":case"NonTypeTemplateParmDecl":case"TemplateTemplateParmDecl":return{kind:"TemplateParameter",semanticKind:"template"};case"NamespaceDecl":return{kind:"Namespace",semanticKind:"namespace"};case"NamespaceAliasDecl":return{kind:"NamespaceAlias",semanticKind:"namespace"};case"RecordDecl":return e==="struct"?{kind:"Struct",semanticKind:"struct"}:e==="union"?{kind:"Union",semanticKind:"union"}:{kind:"Class",semanticKind:"class"};case"EnumDecl":return{kind:"Enum",semanticKind:"enum"};case"EnumConstantDecl":return{kind:"EnumMember",semanticKind:"enum"};case"FieldDecl":return{kind:"Field",semanticKind:"field"};case"VarDecl":return{kind:n?"Field":"Variable",semanticKind:n?"field":"variable"};case"TypedefDecl":case"TypeAliasDecl":case"UsingDecl":case"UsingDirectiveDecl":case"UsingEnumDecl":return{kind:"TypeAlias",semanticKind:"type"};case"ParmVarDecl":return{kind:"Param",semanticKind:"variable"};case"MacroDefinition":return{kind:"Macro",semanticKind:"macro"};default:return null}}function ci(t,e,n,r){let i=[],s=me(e),a=(o,c)=>{let h=Le(o),g=h&&(!s||h===s)?dt(o.kind,o.tagUsed,c.containerKind):null,b=o.name;if(g&&b){g.kind==="Method"&&typeof b=="string"&&b.startsWith("operator")&&(g={kind:"Operator",semanticKind:"method"});let P=ie(o,n,r);if(P){let w=li(o,c);(g.kind==="Template"||g.kind==="TemplateParameter")&&(w.isTemplate=!0),g.kind==="Operator"&&(w.isOperator=!0),i.push({name:b,kind:g.kind,rawKind:o.kind??null,rawKindSource:"clang",semanticKind:g.semanticKind??null,start:P.start,end:P.end,isExported:c.containerKind?0:1,containerKind:c.containerKind??null,containerRawKind:c.containerRawKind??null,containerRawKindSource:c.containerRawKind?"clang":null,paramCount:null,metadata:Object.keys(w).length?w:null})}}let _=c;if(o.kind==="RecordDecl"&&o.name){let P=dt(o.kind,o.tagUsed,c.containerKind);P&&(_={containerKind:P.kind,containerName:o.name,containerRawKind:o.kind??null})}o.kind==="EnumDecl"&&o.name&&(_={containerKind:"Enum",containerName:o.name,containerRawKind:o.kind??null}),o.kind==="NamespaceDecl"&&o.name&&(_={containerKind:"Namespace",containerName:o.name,containerRawKind:o.kind??null});for(let P of o.inner??[])a(P,_)};return a(t,{}),{nodes:i}}function pt(t,e,n){let r=si(t,e,{encoding:"utf8",cwd:n});if(r.error)return null;let i=(r.stdout||"").trim();if(!i)return null;try{return JSON.parse(i)}catch{return null}}function fn(t){let e=`PANDO_${t.toUpperCase()}_INDEXER_CMD`;return process.env[e]||(t==="cpp"?"clang++":"clang")}function ve(t){let e=t?.referencedDecl?.name||t.name;if(e)return e;for(let n of t.inner??[]){let r=ve(n);if(r)return r}return null}function ui(t,e){let n=[],r=me(e),i=s=>{let a=Le(s);if(a&&(!r||a===r)&&s.kind==="InclusionDirective"){let h=s.spelling||s.includeName||null||s.file||s.filename||s.includedFile||s.headerName||null;h&&n.push({module:String(h),isTypeOnly:0})}for(let c of s.inner??[])i(c)};return i(t),{imports:n}}function $e(t){if(t.kind==="MemberExpr"||t.kind==="ImplicitCastExpr")for(let e of t.inner??[]){if(e.kind==="DeclRefExpr"||e.kind==="MemberExpr")return e?.referencedDecl?.name||e.name||null;if(e.kind==="CXXThisExpr")return null;if(e.kind==="ImplicitCastExpr")return $e(e)}if(t.kind==="CallExpr"||t.kind==="CXXMemberCallExpr"){for(let e of t.inner??[])if(e.kind==="MemberExpr")return $e(e)}return null}function di(t){return!t.inner||t.inner.length===0?null:t.kind==="CallExpr"?Math.max(0,t.inner.length-1):t.kind==="CXXConstructExpr"||t.kind==="CXXNewExpr"?t.inner.length:null}function pi(t){if(t.kind!=="CallExpr")return null;let e=t.inner?.[0];return e&&e.kind==="MemberExpr"?$e(e):null}function Me(t,e){return t.containerQualifiedName?`${t.containerQualifiedName}::${e}`:e}function fi(t,e,n,r){let i=[],s=me(e),a=r.length,o=(p,g,b)=>{let _=Le(p),P=_&&(!s||_===s);if(P&&(p.kind==="CallExpr"||p.kind==="CXXConstructExpr"||p.kind==="CXXNewExpr")){let l=ie(p,n,a);if(l){let E=ve(p),R=p.kind==="CallExpr"?"call":"new",d=r.slice(l.start,l.end),N=pi(p),v=di(p);i.push({sourceStart:l.start,sourceEnd:l.end,refKind:R,refName:E,receiverName:N??void 0,arity:typeof v=="number"?v:void 0,containerQualifiedName:g.containerQualifiedName??void 0,metadata:d?{expression:d,containerName:g.containerName,containerKind:g.containerKind}:null})}}if(P&&p.kind==="TypeRef"){let l=ie(p,n,a);if(l){let E=ve(p);i.push({sourceStart:l.start,sourceEnd:l.end,refKind:"type",refName:E,containerQualifiedName:g.containerQualifiedName??void 0,metadata:{containerName:g.containerName,containerKind:g.containerKind}})}}if(P&&(p.kind==="DeclRefExpr"||p.kind==="MemberExpr")&&!(b.includes("CallExpr")||b.includes("CXXConstructExpr")||b.includes("CXXNewExpr"))){let E=ie(p,n,a);if(E){let R=ve(p),d=p.kind==="MemberExpr"?$e(p):void 0;i.push({sourceStart:E.start,sourceEnd:E.end,refKind:"reference",refName:R,receiverName:d??void 0,containerQualifiedName:g.containerQualifiedName??void 0,metadata:{containerName:g.containerName,containerKind:g.containerKind}})}}if(P&&(p.kind==="MacroExpansion"||p.kind==="MacroInstantiation")){let l=ie(p,n,a);if(l){let E=ve(p);i.push({sourceStart:l.start,sourceEnd:l.end,refKind:"macro",refName:E,containerQualifiedName:g.containerQualifiedName??void 0,metadata:{containerName:g.containerName,containerKind:g.containerKind}})}}let w=g;if(p.kind==="RecordDecl"&&p.name){let l=dt(p.kind,p.tagUsed,g.containerKind);l&&(w={containerKind:l.kind,containerName:p.name,containerQualifiedName:Me(g,p.name)})}p.kind==="EnumDecl"&&p.name&&(w={containerKind:"Enum",containerName:p.name,containerQualifiedName:Me(g,p.name)}),p.kind==="NamespaceDecl"&&p.name&&(w={containerKind:"Namespace",containerName:p.name,containerQualifiedName:Me(g,p.name)}),(p.kind==="FunctionDecl"||p.kind==="CXXMethodDecl"||p.kind==="CXXConstructorDecl"||p.kind==="CXXDestructorDecl")&&p.name&&(w={...w,containerQualifiedName:Me(g,p.name)});let j=b.slice();p.kind&&j.push(p.kind);for(let l of p.inner??[])o(l,w,j)};o(t,{},[]);let c=new Set,h=[];for(let p of i){let g=`${p.sourceStart}:${p.sourceEnd}:${p.refKind}:${p.refName??""}:${p.targetNodeId??""}:${p.targetFile??""}`;c.has(g)||(c.add(g),h.push(p))}return{references:h}}function mi(t){if(!t)return null;let e=t;(e.startsWith("SyntaxError:")||e.startsWith("CompileError:"))&&(e=e.substring(e.indexOf(":")+1)),e.includes("#")&&(e=e.split("#")[1]);let n=e.lastIndexOf(":"),r=n>=0?e.slice(0,n):e,[i,s]=r.split("-"),a=Number(i),o=Number(s);return!Number.isFinite(a)||!Number.isFinite(o)||o<a?null:{start:a,end:o}}function gi(t,e,n,r,i){let s=mi(n);if(!s)return null;let a=fn(t),o=ct(i,e,t),c=[...o.args,"-Xclang","-ast-dump=json","-Xclang","-detailed-preprocessing-record","-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...o.source==="fallback"?["-x",t==="cpp"?"c++":"c"]:[],e],h=pt(a,c,o.cwd);if(!h||h.kind!=="TranslationUnitDecl")return null;let p=pn(r),g=r.length,b=me(e),_=null,P=j=>{if(_)return;let l=Le(j),R=l&&(!b||l===b)?ie(j,p,g):null;if(R&&R.start===s.start&&R.end===s.end){let d=null,N=null;for(let v of j.inner??[])if(v.kind==="CompoundStmt"){let A=ie(v,p,g);if(A){d=A.start,N=A.end;break}}_={start:R.start,end:R.end,bodyStart:d,bodyEnd:N};return}for(let d of j.inner??[])P(d)};if(P(h),!_)return null;let w=_;return{start:w.start,end:w.end,bodyStart:w.bodyStart??null,bodyEnd:w.bodyEnd??null,text:r.slice(w.start,w.end)}}function ft(t){return X({id:t,extensions:[],parse:({absPath:e,relPath:n,content:r,projectRoot:i})=>{let s=fn(t),a=ct(i,e,t),o=P=>[...P.args,"-Xclang","-ast-dump=json","-Xclang","-detailed-preprocessing-record","-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...P.source==="fallback"?["-x",t==="cpp"?"c++":"c"]:[],e],c=pt(s,o(a),a.cwd);if(!c&&a.source!=="fallback"){let P=ut(i,t);c=pt(s,o(P),P.cwd)}if(!c||c.kind!=="TranslationUnitDecl")return null;let h=pn(r??""),p=(r??"").length,{nodes:g}=ci(c,e,h,p),{imports:b}=ui(c,e),{references:_}=fi(c,e,h,r??"");return{nodes:g,imports:b,importBindings:[],references:_}},resolve:({absPath:e,nodePath:n,projectRoot:r})=>{try{let i=Tn("fs").readFileSync(e,"utf8");return gi(t,e,n,i,r)}catch{return null}}})}import mt from"fs";import gt from"path";import{spawn as hi,spawnSync as La}from"child_process";var yi=256e3,bi=32;function se(...t){try{let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");process.stderr.write(e+`
|
|
520
|
-
`)}catch{}}var ht=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=hi(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=>{se(`[DartIndexer] ${e.toString("utf8").trim()}`)}),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[,n]of this.pending)n.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let n=this.buffer.indexOf(`
|
|
521
|
-
`);if(n<0)break;let r=this.buffer.slice(0,n).trim();if(this.buffer=this.buffer.slice(n+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,n=1){this.ensureProcess();let r=this.seq++;return new Promise((i,s)=>{let a={id:r,...e};this.pending.set(r,{resolve:i,reject:s});try{this.proc.stdin.write(`${JSON.stringify(a)}
|
|
522
|
-
`)}catch(o){if(this.pending.delete(r),n>0){try{this.handleExit(o)}catch{}return this.request(e,n-1).then(i,s)}s(o)}})}async parseBatch(e){let n=await this.request({op:"parse",files:e});return"results"in n&&Array.isArray(n.results)?n.results.map(r=>r.ok&&r.result?r.result:null):"result"in n&&n.result?[n.result]:e.map(()=>null)}async resolve(e){let n=await this.request({op:"resolve",...e});return"result"in n&&n.result&&typeof n.result.start=="number"?n.result:null}},yt=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((n,r)=>{this.queue.push({input:e,resolve:n,reject:r,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],n=0;for(;this.queue.length&&e.length<bi;){let r=this.queue[0];if(e.length>0&&n+r.input.size>yi)break;e.push(this.queue.shift()),n+=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],a=r[i]??null,o=Date.now()-s.startedAt;o>2e3&&se(`[${new Date().toISOString()}] [DartCliAdapter] parse slow`,{file:s.input.file,ms:o,ok:!!a}),a||se(`[${new Date().toISOString()}] [DartCliAdapter] parse failed`,{file:s.input.file,ms:o}),s.resolve(a)}}catch(r){for(let i of e)i.reject(r)}}}},mn=new Map,gn=new Map;function xi(t){let e=process.platform==="win32"?".cmd":"",n=U(`dart-indexer/bin/pando-dart-indexer${e}`);if(n)return n;if(t){let s=gt.resolve(t,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(mt.existsSync(s))return s}let r=process.env.PANDO_EXTENSION_ROOT;if(r){let s=gt.resolve(r,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(mt.existsSync(s))return s}let i=gt.resolve(process.cwd(),"tools/dart-indexer/bin/pando-dart-indexer"+e);return mt.existsSync(i)?i:null}function hn(t){let e=process.env.PANDO_DART_INDEXER_CMD||xi(t);if(!e)return null;let n=mn.get(e);n||(n=new ht(e),mn.set(e,n));let r=gn.get(e);return r||(r=new yt(n),gn.set(e,r)),{client:n,batcher:r}}async function Si(t,e,n){let r=hn(e);if(!r)return null;try{return await r.batcher.enqueue({file:t,root:e,lang:"dart",size:n})}catch(i){return se(`[${new Date().toISOString()}] [DartCliAdapter] parse error`,{file:t,error:i?.message||i}),null}}function yn(){return X({id:"dart",extensions:[".dart"],parse:async({absPath:t,projectRoot:e,content:n,meta:r})=>{let i=r?.size??Buffer.byteLength(n,"utf8");return Si(t,e,i)},resolve:({absPath:t,nodePath:e,projectRoot:n})=>{let r=Date.now(),i=hn(n);return i?i.client.resolve({file:t,root:n,lang:"dart",nodePath:e}).then(s=>{let a=Date.now()-r;return a>2e3&&se(`[${new Date().toISOString()}] [DartCliAdapter] resolve slow`,{file:t,ms:a}),s||se(`[${new Date().toISOString()}] [DartCliAdapter] resolve failed`,{file:t,ms:a,nodePath:e}),s}).catch(s=>{let a=Date.now()-r;return se(`[${new Date().toISOString()}] [DartCliAdapter] resolve error`,{file:t,ms:a,nodePath:e,error:s?.message||s}),null}):null},exportKind:"dart"})}import bt from"fs";import Ne from"path";import{spawn as vi,spawnSync as Xa}from"child_process";var Ni=256e3,Ci=32;function oe(...t){try{let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");process.stderr.write(e+`
|
|
523
|
-
`)}catch{}}var xt=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=vi(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=>{oe(`[JavaCliAdapter] ${e.toString("utf8").trim()}`)}),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[,n]of this.pending)clearTimeout(n.timer),n.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let n=this.buffer.indexOf(`
|
|
524
|
-
`);if(n<0)break;let r=this.buffer.slice(0,n).trim();if(this.buffer=this.buffer.slice(n+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,n=1){this.ensureProcess();let r=this.seq++;return new Promise((i,s)=>{let a={id:r,...e},o=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:o});try{this.proc.stdin.write(`${JSON.stringify(a)}
|
|
525
|
-
`)}catch(c){if(clearTimeout(o),this.pending.delete(r),n>0){try{this.handleExit(c)}catch{}return this.request(e,n-1).then(i,s)}s(c)}})}async parseBatch(e){let n=await this.request({op:"parse",files:e});return"results"in n?n.results.map(r=>r.ok&&r.result?r.result:null):"result"in n?[n.result]:e.map(()=>null)}async resolve(e){let n=await this.request({op:"resolve",...e});return"result"in n&&n.result&&typeof n.result.start=="number"?n.result:null}},St=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((n,r)=>{this.queue.push({input:e,resolve:n,reject:r,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],n=0;for(;this.queue.length&&e.length<Ci;){let r=this.queue[0];if(e.length>0&&n+r.input.size>Ni)break;e.push(this.queue.shift()),n+=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],a=r[i]??null,o=Date.now()-s.startedAt;o>2e3&&oe(`[${new Date().toISOString()}] [JavaCliAdapter] parse slow`,{file:s.input.file,ms:o,path:"custom",ok:!!a}),a||oe(`[${new Date().toISOString()}] [JavaCliAdapter] parse failed`,{file:s.input.file,ms:o,path:"custom"}),s.resolve(a)}}catch(r){for(let i of e)i.reject(r)}}}},bn=new Map,xn=new Map;function Pi(){return typeof __dirname=="string"?__dirname:process.cwd()}var ae,wi;function Ei(t){if(ae!==void 0&&wi===t)return ae;let e=process.platform==="win32"?".cmd":"",n="tools/java-indexer/bin/pando-java-indexer"+e,r=U(`java-indexer/bin/pando-java-indexer${e}`);if(r)return ae=r,r;if(t){let s=Ne.resolve(t,n);if(bt.existsSync(s))return ae=s,s}let i=Pi();for(let s=0;s<8;s++){let a=Ne.join(i,n);if(bt.existsSync(a))return ae=a,a;let o=Ne.dirname(i);if(o===i)break;i=o}i=process.cwd();for(let s=0;s<8;s++){let a=Ne.join(i,n);if(bt.existsSync(a))return ae=a,a;let o=Ne.dirname(i);if(o===i)break;i=o}return ae=null,null}function Sn(t){let e=process.env.PANDO_JAVA_INDEXER_CMD||Ei(t);if(!e)return null;let n=bn.get(e);n||(n=new xt(e),bn.set(e,n));let r=xn.get(e);return r||(r=new St(n),xn.set(e,r)),{client:n,batcher:r}}async function Ri(t,e,n){let r=Sn(e);if(!r)return null;try{return await r.batcher.enqueue({file:t,root:e,lang:"java",size:n})}catch(i){return oe(`[${new Date().toISOString()}] [JavaCliAdapter] parse error`,{file:t,error:i?.message||i,path:"custom"}),null}}async function _i(t,e,n){let r=await Ri(t,e,n);return r||null}function vn(){return X({id:"java",extensions:[".java"],exportKind:"named",parse:({absPath:t,projectRoot:e,content:n,meta:r})=>{let i=r?.size??Buffer.byteLength(n,"utf8");return _i(t,e,i)},resolve:({absPath:t,nodePath:e,projectRoot:n})=>{let r=Date.now(),i=Sn(n);return i?i.client.resolve({file:t,root:n,lang:"java",nodePath:e}).then(s=>{let a=Date.now()-r;return a>2e3&&oe(`[${new Date().toISOString()}] [JavaCliAdapter] resolve slow`,{file:t,ms:a}),s||oe(`[${new Date().toISOString()}] [JavaCliAdapter] resolve failed`,{file:t,ms:a,nodePath:e}),s}).catch(s=>{let a=Date.now()-r;return oe(`[${new Date().toISOString()}] [JavaCliAdapter] resolve error`,{file:t,ms:a,nodePath:e,error:s?.message||s}),null}):null}})}le();import Ti from"fs";import{spawn as Ai}from"child_process";import vt from"fs";import Nt from"path";function Nn(t,e){let n=process.platform==="win32"?".cmd":"",r=t==="clojure-editor"?"pando-clojure-editor":"pando-clojure-indexer",i=U(`${t}/bin/${r}${n}`);if(i)return i;if(e){let o=Nt.resolve(e,`tools/${t}/bin/${r}${n}`);if(vt.existsSync(o))return o}let s=process.env.PANDO_EXTENSION_ROOT;if(s){let o=Nt.resolve(s,`tools/${t}/bin/${r}${n}`);if(vt.existsSync(o))return o}let a=Nt.resolve(process.cwd(),`tools/${t}/bin/${r}${n}`);return vt.existsSync(a)?a:null}var wn=3e4,Di=Math.max(wn,Number(process.env.PANDO_CLOJURE_CHANGE_SIGNATURE_TIMEOUT_MS||`${5*60*1e3}`)),Cn="__PANDO_CLOJURE_INDEX__";function Ii(...t){let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");H("ClojureIndexer",e)}function Ce(t,e){H("ClojureIndex",t,e)}var Be=class{constructor(e,n){this.cmd=e;this.projectRoot=n;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,Ce("node.server.spawn",{projectRoot:this.projectRoot,cmd:this.cmd}),this.proc=Ai(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){Ce("node.server.exit",{projectRoot:this.projectRoot,error:e?.message||String(e),pendingRequestCount:this.pending.size}),this.closed=!0;for(let[,n]of this.pending)clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.proc=null}}onData(e){for(this.buffer+=e.toString("utf8");;){let n=this.buffer.indexOf(`
|
|
526
|
-
`);if(n<0)break;let r=this.buffer.slice(0,n).trim();if(this.buffer=this.buffer.slice(n+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 n=this.stderrBuffer.indexOf(`
|
|
527
|
-
`);if(n<0)break;let r=this.stderrBuffer.slice(0,n).trim();if(this.stderrBuffer=this.stderrBuffer.slice(n+1),!!r){if(r.startsWith(Cn)){let i=r.slice(Cn.length);try{let s=JSON.parse(i);Ce(s.event||"jvm.trace",s)}catch(s){H("ClojureIndexer","stderr trace parse failed",{error:s?.message||String(s),line:r})}continue}Ii(r)}}}close(){if(this.closed)return;this.closed=!0;for(let[,n]of this.pending)clearTimeout(n.timer),n.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,n){this.ensureProcess();let r=this.seq++,i=n?.retry??1,s=n?.timeoutMs??wn,a=Date.now();return new Promise((o,c)=>{let h={id:r,...e},p=setTimeout(()=>{this.pending.delete(r),c(new Error(`clojure indexer request timed out after ${s}ms`))},s);this.pending.set(r,{resolve:g=>{Ce("node.client.request.complete",{projectRoot:this.projectRoot,id:r,op:e.op,durationMs:Date.now()-a}),o(g)},reject:c,timer:p});try{Ce("node.client.request.start",{projectRoot:this.projectRoot,id:r,op:e.op}),this.proc.stdin.write(`${JSON.stringify(h)}
|
|
528
|
-
`)}catch(g){if(clearTimeout(p),this.pending.delete(r),i>0){try{this.handleExit(g)}catch{}return this.request(e,{retry:i-1,timeoutMs:s}).then(o,c)}c(g)}})}async parseBatch(e,n){let r=await this.request({op:"parse",files:e,traceBatchId:n?.batchId,traceBatchBytes:n?.batchBytes});return"results"in r?r.results.map(i=>i.ok&&i.result?i.result:null):[]}async resolve(e){let n=await this.request({op:"resolve",...e});if("result"in n){let r=n.result;if(r&&typeof r.start=="number"&&typeof r.end=="number")return r}return null}async changeSignature(e){let n=await this.request({op:"change-signature",...e},{timeoutMs:Di});return"result"in n&&n.result||null}},Pn=new Map;function En(t){return process.env.PANDO_CLOJURE_INDEXER_CMD||Nn("clojure-indexer",t)}function Rn(t){let e=En(t);return e?new Be(e,t):null}function _n(t){let e=En(t);if(!e)return null;let n=`${e}::${t}`,r=Pn.get(n);return r||(r=new Be(e,t),Pn.set(n,r)),r}var ki=Math.max(1,Number(process.env.PANDO_CLOJURE_ANALYZER_POOL_SIZE||"3"));function ze(t,e){H("ClojureIndex",t,e)}function qe(t,e){H("IndexTiming",t,e)}var He=class{constructor(e,n=ki){this.projectRoot=e;this.clients=[];this.idleClients=[];this.queue=[];this.inFlight=new Set;this.drainWaiters=[];this.batchSeq=1;this.closed=!1;let r=Math.max(1,n);for(let i=0;i<r;i+=1){let s=Rn(e);if(!s)break;this.clients.push(s),this.idleClients.push(s)}if(!this.clients.length)throw new Error("clojure indexer command unavailable");ze("node.pool.init",{projectRoot:e,configuredPoolSize:r,actualClientCount:this.clients.length})}submit(e,n){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:n,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(),n=this.idleClients.shift(),r=this.runJob(n,e).finally(()=>{this.inFlight.delete(r),this.closed||this.idleClients.push(n),this.pump(),this.notifyIfIdle()});this.inFlight.add(r)}this.notifyIfIdle()}async runJob(e,n){let r=n.files.reduce((a,o)=>a+Math.max(0,o.size||0),0),i=Date.now(),s=Math.max(0,i-n.enqueuedAt);ze("node.pool-batch.start",{batchId:n.batchId,batchKey:n.batchKey,fileCount:n.files.length,batchBytes:r,queueWaitMs:s,queuedBatchCount:this.queue.length,inFlightCount:this.inFlight.size});try{let a=await this.parseFiles(e,n.files,n.batchId,r);qe("clojure-pool.job.complete",{projectRoot:this.projectRoot,batchId:n.batchId,batchKey:n.batchKey,fileCount:n.files.length,batchBytes:r,queueWaitMs:s,durationMs:Date.now()-i}),ze("node.pool-batch.complete",{batchId:n.batchId,batchKey:n.batchKey,fileCount:n.files.length,batchBytes:r,durationMs:Date.now()-i,successCount:Array.from(a.values()).filter(o=>!("error"in o)).length,errorCount:Array.from(a.values()).filter(o=>"error"in o).length}),n.resolve(a)}catch(a){let o=a instanceof Error?a:new Error(String(a));ze("node.pool-batch.error",{batchId:n.batchId,batchKey:n.batchKey,fileCount:n.files.length,batchBytes:r,durationMs:Date.now()-i,error:o.message}),n.reject(o)}}async parseFiles(e,n,r,i){let s=Date.now();try{let a=await e.parseBatch(n.map(c=>({file:c.absPath,root:this.projectRoot,lang:c.lang})),{batchId:r,batchBytes:i});qe("clojure-parse-batch.complete",{projectRoot:this.projectRoot,batchId:r,fileCount:n.length,batchBytes:i,durationMs:Date.now()-s,split:!1});let o=new Map;for(let c=0;c<n.length;c+=1){let h=n[c],p=a[c]??null;p?o.set(h.fileKey,p):(H("IndexingAudit","clojure analysis returned no result",{projectRoot:this.projectRoot,batchId:r,file:h.absPath}),o.set(h.fileKey,{error:`clojure analysis returned no result for ${h.absPath}`}))}return o}catch(a){if(n.length>1){let h=Date.now(),p=Math.ceil(n.length/2),g=n.slice(0,p),b=n.slice(p),_=await this.parseFiles(e,g,r,g.reduce((w,j)=>w+Math.max(0,j.size||0),0)),P=await this.parseFiles(e,b,r,b.reduce((w,j)=>w+Math.max(0,j.size||0),0));return qe("clojure-parse-batch.split",{projectRoot:this.projectRoot,batchId:r,fileCount:n.length,batchBytes:i,durationMs:Date.now()-h,leftCount:g.length,rightCount:b.length,error:a instanceof Error?a.message:String(a)}),new Map([..._,...P])}let o=a instanceof Error?a:new Error(String(a));qe("clojure-parse-batch.error",{projectRoot:this.projectRoot,batchId:r,fileCount:n.length,batchBytes:i,durationMs:Date.now()-s,error:o.message});let c=new Map;for(let h of n)H("IndexingAudit","clojure analysis request failed",{projectRoot:this.projectRoot,batchId:r,file:h.absPath,error:o.message}),c.set(h.fileKey,{error:o.message});return c}}notifyIfIdle(){if(this.queue.length||this.inFlight.size)return;let e=this.drainWaiters.splice(0,this.drainWaiters.length);for(let n of e)try{n()}catch{}}};function Ki(t,e){if(typeof e?.size=="number"&&typeof e?.mtime=="number")return{size:e.size,mtime:e.mtime};try{let n=Ti.statSync(t);return{size:typeof e?.size=="number"?e.size:n.size,mtime:typeof e?.mtime=="number"?e.mtime:Math.floor(n.mtimeMs)}}catch{return{size:e?.size,mtime:e?.mtime}}}function Fi(t,e){let n=new Map;for(let r of e.nodes??[]){if(!r.name||r.containerKind||n.has(r.name))continue;let i=`${t}#${r.start}-${r.end}:${Y.getAbbrev(r.kind,"clojure")}:${r.name}`;n.set(r.name,i)}return r=>n.get(r)??null}function Oi(t){let e=t?.error;return typeof e=="string"&&e.trim().length>0?e.trim():null}var Je=class{constructor(e){this.projectRoot=e;this.cache=new de;this.pool=new He(e)}prepare(e){let n=Ki(e.absPath,e.meta),r=this.cache.get(e.absPath,n);return{fileKey:e.relPath,absPath:e.absPath,relPath:e.relPath,meta:n,preDeleted:e.preDeleted,lang:e.lang,cachedParsed:r??void 0}}batchKey(e){return`${this.projectRoot}::clojure`}async analyzeBatch(e){let n=new Map,r=e.filter(s=>!s.cachedParsed);for(let s of e)s.cachedParsed&&n.set(s.fileKey,s.cachedParsed);if(!r.length)return n;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})));for(let s of r){let a=i.get(s.fileKey)??{error:`missing clojure analysis result for ${s.relPath}`};"error"in a||this.cache.set(s.absPath,s.meta??{},a),n.set(s.fileKey,a)}return n}buildProcessedFile(e,n,r){let i=Oi(r);return i?(H("IndexingAudit","clojure batch analysis failed",{projectRoot:this.projectRoot,relPath:e.relPath,error:i}),he("clojure",e.relPath,n.meta)):ye({lang:"clojure",fileRel:e.relPath,content:e.content,meta:n.meta,preDeleted:e.preDeleted,parsed:r,resolveNodeId:Fi(e.relPath,r),exportKind:"cli"})}async flush(){await this.pool.flush()}async close(){await this.pool.close()}};function ji(...t){let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");H("ClojureCliAdapter",e)}function An(){return{id:"clojure",extensions:[".clj",".cljc",".cljs"],indexingMode:"batch",createBatchIndexer:t=>new Je(t),resolveSpan:(t,e,n)=>{let r=_n(t);return r?r.resolve({file:e,root:t,lang:"clojure",nodePath:n}).catch(i=>(ji(`[${new Date().toISOString()}] [ClojureCliAdapter] resolve error`,{file:e,nodePath:n,error:i?.message||i}),null)):null}}}function _o(t){return t.indexingMode==="worker"&&typeof t.createIndexer=="function"}var We={ts:it("ts"),js:it("js"),python:Qt(),c:{...ft("c"),extensions:[".c",".h",".i",".inc"]},cpp:{...ft("cpp"),extensions:[".cc",".cpp",".cxx",".c++",".cp",".ccm",".cppm",".cxxm",".ixx",".hpp",".hh",".hxx",".h++",".ii",".inl",".ipp",".tcc",".tpp",".txx"]},csharp:rn(),dart:yn(),java:vn(),clojure:An()},Dn=new Map;for(let t of Object.values(We))for(let e of t.extensions)Dn.set(e,t.id);function In(){return{byLanguage:{ts:{enabled:!0,source:"embedded"},js:{enabled:!0,source:"embedded"},python:{enabled:!0,source:"embedded"},c:{enabled:!0,source:"embedded"},cpp:{enabled:!0,source:"embedded"},csharp:{enabled:!0,source:"embedded"},dart:{enabled:!0,source:"embedded"},java:{enabled:!0,source:"embedded"},clojure:{enabled:!0,source:"embedded"}}}}function Ao(t){let e=t.toLowerCase().match(/\.[a-z0-9+]+$/);return e?Dn.get(e[0])??null:null}function Do(t){return We[t]}function Io(t){let e=t??In(),n=new Set;for(let[i,s]of Object.entries(e.byLanguage))s.enabled&&n.add(i);let r=new Set;for(let i of Object.values(We))if(n.has(i.id))for(let s of i.extensions)r.add(s);return r}function ko(t){let e=t??In(),n=new Set;for(let[i,s]of Object.entries(e.byLanguage))s.enabled&&n.add(i);let r=new Set;for(let i of Object.values(We))if(n.has(i.id))for(let s of i.extensions)r.add(s);return r}function Mi(t,e="Operation cancelled"){let n=typeof t=="string"&&t.trim()?t.trim():t instanceof Error&&t.message.trim()?t.message.trim():e,r=new Error(n);return r.name="AbortError",r.code="ABORT_ERR",r}function Ko(t,e){if(t?.aborted)throw Mi(t.reason,e)}export{dr as a,jt as b,he as c,Yn as d,es as e,At as f,H as g,_o as h,In as i,Ao as j,Do as k,Io as l,ko as m,Ko as n};
|