@constellationdev/cli 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +86 -128
- package/package.json +2 -2
package/dist/main.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {base32}from'@scure/base';import {Readable}from'stream';import p from'ansi-colors';import*as xe from'os';import xe__default from'os';import*as qt from'fs';import {readFileSync,existsSync}from'fs';import {pipeline}from'stream/promises';import*as ln from'zlib';import ln__default from'zlib';import {fetch as fetch$1,Agent}from'undici';import {execFile,execFileSync,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import {confirm,password,input,select,checkbox}from'@inquirer/prompts';import*as P from'path';import P__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as B from'fs/promises';import B__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import {z}from'zod';import Qs from'tree-sitter-javascript';import Zs from'tree-sitter-python';import ea from'tree-sitter-typescript';import Ka from'tree-sitter';import ei from'ignore';import {performance}from'perf_hooks';import {parseDocument,isMap,isSeq}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var ao=Object.defineProperty;var f=(i,e)=>()=>(i&&(e=i(i=0)),e);var Vn=(i,e)=>{for(var t in e)ao(i,t,{get:e[t],enumerable:true});};var et,Wt=f(()=>{et=["help","--help","-h","--version","-V","-v"];});function qn(i){return base32.encode(Buffer.from(i))}var Xn=f(()=>{});function Qn(i,e,t){let r=`${i}:${e}${t?`:${t}`:""}`;return qn(r)}var Zn=f(()=>{Xn();});var tt,er=f(()=>{tt=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let r=JSON.stringify(e)+`
|
|
3
|
-
`,o=Buffer.from(
|
|
4
|
-
Caused by: ${
|
|
2
|
+
import {z}from'zod';import {base32}from'@scure/base';import {Readable}from'stream';import u from'ansi-colors';import*as Ie from'os';import Ie__default from'os';import*as ir from'fs';import {readFileSync,existsSync}from'fs';import {pipeline}from'stream/promises';import*as hr from'zlib';import hr__default from'zlib';import {Agent,fetch as fetch$1}from'undici';import {execFile,execFileSync,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import {confirm,password,input,select,checkbox}from'@inquirer/prompts';import*as P from'path';import P__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as B from'fs/promises';import B__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import wa from'tree-sitter-javascript';import _a from'tree-sitter-python';import Sa from'tree-sitter-typescript';import fl from'tree-sitter';import mi from'ignore';import {performance}from'perf_hooks';import {parseDocument,isMap,isSeq,stringify}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var Co=Object.defineProperty;var h=(i,e)=>()=>(i&&(e=i(i=0)),e);var en=(i,e)=>{for(var t in e)Co(i,t,{get:e[t],enumerable:true});};var it,qt=h(()=>{it=["help","--help","-h","--version","-V","-v"];});var _o,Y,Ne,So,fe,Te,xo,Eo,Po,$e,Io,Ro,No,To,$o,jo,ko,Ao,Lo,Fo,Oo,Do,Mo,Uo,Bo,Ho,Go,rn,zo,Wo,Jo,Ko,Vo,qo,Yo,Xo,Qo,Zo,es,ts,rs,ns,is,os,on,ss,as,Yt,ls,cs,ps,us,je,ds,ms,gs,fs,hs,sn,an,nn,ys,bs,vs,Cs,ws,_s,Ss,xs,ln,cn,pn,un,Es,Ps,Is,dn,mn,ke=h(()=>{_o=z.object({total:z.number().int().nonnegative(),returned:z.number().int().nonnegative(),hasMore:z.boolean(),nextOffset:z.number().int().nonnegative().optional(),currentOffset:z.number().int().nonnegative().optional()}),z.object({overall:z.number().min(0).max(1),factors:z.object({dataFreshness:z.number().min(0).max(1).optional(),coverageComplete:z.number().min(0).max(1).optional(),heuristicAccuracy:z.number().min(0).max(1).optional(),semanticAnalysisDepth:z.number().min(0).max(1).optional(),patternMatchQuality:z.number().min(0).max(1).optional()}).optional(),warnings:z.array(z.string()).optional(),recommendations:z.array(z.string()).optional()}),z.object({qualityScore:z.number().min(0).max(100).optional(),lastUpdated:z.string().optional(),cached:z.boolean().optional(),executionTime:z.number().nonnegative().optional(),coveragePercentage:z.number().min(0).max(100).optional(),issues:z.array(z.string()).optional()}),Y=z.object({language:z.string(),features:z.array(z.string()).optional(),visibility:z.string().optional(),decorators:z.array(z.string()).optional(),typeInfo:z.any().optional(),custom:z.record(z.string(),z.any()).optional()}),z.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),Ne=z.enum(["low","medium","high","critical"]),So=z.enum(["low","moderate","high","very_high"]),fe=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:So}),Te=z.object({filePath:z.string(),line:z.number().int().positive().optional(),lineStart:z.number().int().positive().optional(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional()}),Te.extend({symbolId:z.string().optional(),symbolName:z.string().optional(),symbolKind:z.string().optional()}),z.object({outgoing:z.array(z.string()),incoming:z.array(z.string())}),xo=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),Eo=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),Po=z.object({nodes:z.array(xo),edges:z.array(Eo),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),$e=new Set(["abc","aifc","argparse","array","ast","asynchat","asyncio","asyncore","atexit","audioop","base64","bdb","binascii","bisect","builtins","bz2","cProfile","calendar","cgi","cgitb","chunk","cmath","cmd","code","codecs","codeop","collections","colorsys","compileall","concurrent","configparser","contextlib","contextvars","copy","copyreg","crypt","csv","ctypes","curses","dataclasses","datetime","dbm","decimal","difflib","dis","distutils","doctest","email","encodings","ensurepip","enum","errno","faulthandler","fcntl","filecmp","fileinput","fnmatch","fractions","ftplib","functools","gc","getopt","getpass","gettext","glob","graphlib","grp","gzip","hashlib","heapq","hmac","html","http","idlelib","imaplib","imghdr","imp","importlib","inspect","io","ipaddress","itertools","json","keyword","lib2to3","linecache","locale","logging","lzma","mailbox","mailcap","marshal","math","mimetypes","mmap","modulefinder","msilib","msvcrt","multiprocessing","netrc","nis","nntplib","numbers","operator","optparse","os","ossaudiodev","pathlib","pdb","pickle","pickletools","pipes","pkgutil","platform","plistlib","poplib","posix","posixpath","pprint","profile","pstats","pty","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","readline","reprlib","resource","rlcompleter","runpy","sched","secrets","select","selectors","shelve","shlex","shutil","signal","site","sitecustomize","smtpd","smtplib","sndhdr","socket","socketserver","spwd","sqlite3","ssl","stat","statistics","string","stringprep","struct","subprocess","sunau","symtable","sys","sysconfig","syslog","tabnanny","tarfile","telnetlib","tempfile","termios","test","textwrap","threading","time","timeit","tkinter","token","tokenize","tomllib","trace","traceback","tracemalloc","tty","turtle","turtledemo","types","typing","unicodedata","unittest","urllib","usercustomize","uu","uuid","venv","warnings","wave","weakref","webbrowser","winreg","winsound","wsgiref","xdrlib","xml","xmlrpc","zipapp","zipfile","zipimport","zlib","zoneinfo","_thread","_tkinter","__future__","__main__"]),z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.any().optional()})}),z.object({query:z.string().max(200),filterByKind:z.array(z.string()).optional(),filterByVisibility:z.array(z.string()).optional(),isExported:z.boolean().optional(),filterByFile:z.string().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeUsageCount:z.boolean().optional(),includeDocumentation:z.boolean().optional()}).refine(i=>i.query.length>0||i.filterByKind&&i.filterByKind.length>0||i.filterByVisibility&&i.filterByVisibility.length>0||i.isExported!==void 0||i.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),Io=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),isExported:z.boolean(),usageCount:z.number().int().nonnegative().optional(),complexity:fe.optional(),languageMetadata:Y.optional()}),z.object({symbols:z.array(Io),pagination:_o.optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeReferences:z.boolean().optional(),includeRelationships:z.boolean().optional(),includeImpactScore:z.boolean().optional()}),Ro=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),modifiers:z.array(z.string()).optional(),typeInfo:z.any().optional(),decorators:z.array(z.string()).optional(),isExported:z.boolean(),isDeprecated:z.boolean(),complexity:fe.optional(),languageMetadata:Y.optional()}),No=Te.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),To=z.object({calls:z.array(z.string()),calledBy:z.array(z.string()),inheritsFrom:z.array(z.string()),inheritedBy:z.array(z.string()),children:z.array(z.string())}),$o=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Ne}),z.object({symbol:Ro,references:z.array(No).optional(),relationships:To.optional(),impactScore:$o.optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includePackages:z.boolean().optional(),includeSymbols:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),jo=z.object({type:z.enum(["file","module"]),filePath:z.string().nullable(),moduleName:z.string().nullable().optional(),importedSymbols:z.array(z.string()).optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),ko=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),Ao=z.object({name:z.string(),version:z.string().optional(),type:z.string()}),z.object({totalFiles:z.number().int().nonnegative(),totalPackages:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()}),z.object({file:z.string(),directDependencies:z.array(jo),transitiveDependencies:z.array(ko).optional(),packages:z.array(Ao).optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includeSymbols:z.boolean().optional(),includeImpactMetrics:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),Lo=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),Fo=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),z.object({totalFiles:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative(),riskLevel:Ne}),z.object({file:z.string(),directDependents:z.array(Lo),transitiveDependents:z.array(Fo).optional(),detailedMetrics:z.object({byDepth:z.record(z.string(),z.number()),criticalPaths:z.array(z.array(z.string())),mostImpactedFiles:z.array(z.string())}).optional()}),z.object({filePath:z.string().min(1).optional(),minCycleLength:z.number().int().min(2).max(10).optional(),maxCycleLength:z.number().int().min(2).max(10).optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeImpactScore:z.boolean().optional(),includeConfidence:z.boolean().optional()}),Oo=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Ne}),z.object({cycles:z.array(Oo)}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),filterByUsageType:z.array(z.string()).optional(),filterByRelationshipType:z.array(z.string()).optional(),includeTransitive:z.boolean().optional(),includeContext:z.boolean().optional(),excludeTests:z.boolean().optional(),excludeGenerated:z.boolean().optional(),includeImportanceWeight:z.boolean().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0)}),Do=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:fe.optional(),languageMetadata:Y.optional()}),Mo=z.object({filePath:z.string(),usageType:z.string(),relationshipType:z.string(),line:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional(),enclosingSymbol:z.object({name:z.string(),kind:z.string()}).optional(),context:z.string().optional(),aliasName:z.string().optional(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),importanceWeight:z.number().min(0).max(1).optional()}),Uo=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:Do,directUsages:z.array(Mo),transitiveUsages:z.array(Uo).optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:z.enum(["callers","callees","both"]).default("both"),depth:z.number().int().positive().max(10).default(3),excludeExternal:z.boolean().optional(),includeGraph:z.boolean().optional(),limit:z.number().int().positive().max(100).default(25),offset:z.number().int().nonnegative().default(0)}),Bo=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),complexity:fe.optional(),languageMetadata:Y.optional()}),Ho=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),depth:z.number().int().nonnegative(),complexity:fe.optional(),languageMetadata:Y.optional()}),Go=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isAsync:z.boolean(),depth:z.number().int().nonnegative(),complexity:fe.optional(),languageMetadata:Y.optional()}),z.object({root:Bo,callers:z.array(Ho).optional(),callees:z.array(Go).optional(),graph:Po.optional()}),z.object({symbolId:z.string().optional(),qualifiedName:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeDirectDependents:z.boolean().default(true),includeTransitiveDependents:z.boolean().default(true),depth:z.number().int().min(1).max(5).default(3),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),rn=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),relationshipType:z.string(),depth:z.number().int().positive(),isExported:z.boolean().optional(),transitiveImpactCount:z.number().int().nonnegative().optional(),languageMetadata:Y.optional()}),zo=z.object({filePath:z.string(),symbolCount:z.number().int().positive(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),symbols:z.array(z.object({id:z.string(),name:z.string(),kind:z.string(),line:z.number().int().positive()}))}),Wo=z.object({riskLevel:Ne,factors:z.array(z.object({factor:z.string(),severity:z.enum(["low","medium","high"]),description:z.string()})),recommendations:z.array(z.string())}),z.object({symbol:z.object({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isExported:z.boolean().optional(),languageMetadata:Y.optional()}),directDependents:z.array(rn).optional(),transitiveDependents:z.array(rn).optional(),impactedFiles:z.array(zo),breakingChangeRisk:Wo.optional(),summary:z.object({directDependentCount:z.number().int().nonnegative(),transitiveDependentCount:z.number().int().nonnegative(),impactedFileCount:z.number().int().nonnegative(),testFileCount:z.number().int().nonnegative(),productionFileCount:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()})}),z.object({filePattern:z.string().optional(),filterByKind:z.array(z.string()).optional(),exportedOnly:z.boolean().optional(),excludeTests:z.boolean().default(true),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeConfidence:z.boolean().optional()}),Jo=z.object({symbolId:z.string(),name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),isExported:z.boolean(),reason:z.string(),confidence:z.number().min(0).max(1),languageMetadata:Y.optional()}),Ko=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(Jo),orphanedFiles:z.array(Ko)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),Vo=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),qo=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),Yo=z.object({languages:z.array(Vo),frameworks:z.array(qo),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),Xo=z.object({files:z.object({total:z.number().int().nonnegative(),byType:z.record(z.string(),z.number()),byParadigm:z.record(z.string(),z.number())}),symbols:z.object({total:z.number().int().nonnegative(),byKind:z.record(z.string(),z.number()),exported:z.number().int().nonnegative(),public:z.number().int().nonnegative()}),modules:z.object({total:z.number().int().nonnegative(),averageSize:z.number().nonnegative(),largest:z.string()})}),Qo=z.object({internal:z.object({totalConnections:z.number().int().nonnegative(),averagePerFile:z.number().nonnegative(),mostConnectedFiles:z.array(z.object({path:z.string(),incomingCount:z.number().int().nonnegative(),outgoingCount:z.number().int().nonnegative()}))}),external:z.object({totalPackages:z.number().int().nonnegative(),directDependencies:z.number().int().nonnegative(),topPackages:z.array(z.object({name:z.string(),usageCount:z.number().int().nonnegative()}))})}),Zo=z.object({complexity:z.object({average:z.number().nonnegative(),high:z.number().int().nonnegative()}),maintainability:z.object({score:z.number().min(0).max(100),issues:z.array(z.string())}),testCoverage:z.object({percentage:z.number().min(0).max(100),testedFiles:z.number().int().nonnegative(),totalFiles:z.number().int().nonnegative()}).optional()}),es=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),ts=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),rs=z.object({nodes:z.array(es),edges:z.array(ts)}),z.object({metadata:Yo,structure:Xo,dependencies:Qo,metrics:Zo.optional(),moduleGraph:rs.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),ns=z.enum(["relative","workspace","alias","external","builtin"]),is=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:ns}),os=z.record(z.string(),is),on=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),ss=on.exclude(["import-use","declaration"]),as=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:on}).strict(),Yt=z.object({filePath:z.string().min(1),entries:z.array(as)}).strict(),z.object({file:z.string().min(1),language:z.string().min(1),commit:z.string().min(1),timestamp:z.string().datetime(),ast:z.string().min(1),importResolutions:os.optional(),classificationMap:Yt.optional()}).strict(),ls=z.object({file:z.string(),error:z.string()}),cs=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),ps=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(cs)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(ls).optional(),relationships:ps}),z.object({projectId:z.string(),projectName:z.string(),branch:z.string(),latestCommit:z.string().nullable(),fileCount:z.number().int().nonnegative(),lastIndexedAt:z.string().nullable(),languages:z.array(z.string())}),us=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(us),isType:z.boolean(),isDynamic:z.boolean(),isConditional:z.boolean().optional(),isLazy:z.boolean().optional(),isWildcard:z.boolean().optional(),line:z.number(),column:z.number()}),z.object({referencerId:z.string(),referencedName:z.string(),referenceType:ss,line:z.number(),column:z.number(),scope:z.string().optional(),objectContext:z.string().optional(),language:z.string().optional()}),z.enum(["processing","completed","failed","cancelled","queued","superseded","cleaned_up"]),z.enum(["acquired","current","duplicate","superseded","queued"]),je={branchName:z.string().optional(),effectiveBranchName:z.string().optional(),remapped:z.boolean().optional()},ds=z.object({status:z.literal("acquired"),attemptId:z.string().uuid(),...je}),ms=z.object({status:z.literal("current"),...je}),gs=z.object({status:z.literal("duplicate"),...je}),fs=z.object({status:z.literal("superseded"),activeCommit:z.string().optional(),...je}),hs=z.object({status:z.literal("queued"),queuedAttemptId:z.string().uuid(),...je}),sn=z.discriminatedUnion("status",[ds,ms,gs,fs,hs]),z.object({"x-attempt-id":z.string().uuid(),"x-project-id":z.string(),"x-branch-name":z.string(),"x-commit-hash":z.string().length(40),"x-constellation-dirty":z.union([z.literal("true"),z.literal("false")]).optional()}),an=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),nn=an.extend({name:z.string().min(1)}).strict(),ys=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().optional()}).strict(),bs=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:ys.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(an).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(nn).max(200),outgoingCalls:z.array(nn).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(bs)}).strict(),z.object({projectId:z.string().min(1),branch:z.string().min(1),commit:z.string().regex(/^[0-9a-f]{40}$/),timestamp:z.string().datetime()}).strict(),z.enum(["pending","processing","completed","failed","skipped"]),vs=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),Cs=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),ws=z.object({id:z.string(),label:z.string(),type:vs,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),_s=z.object({id:z.string(),source:z.string(),target:z.string(),type:Cs,label:z.string().optional()}),Ss=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Ne.optional()}),xs=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(ws),edges:z.array(_s),summary:Ss,metadata:xs,features:z.record(z.string(),z.boolean()).optional()}),ln=z.object({projectId:z.string(),projectName:z.string(),defaultBranch:z.string(),lastIndexedAt:z.string().datetime().optional(),fileCount:z.number().int().nonnegative().optional(),languages:z.array(z.string()).optional()}),z.object({projects:z.array(ln)}),ln.pick({projectId:true,projectName:true,defaultBranch:true}),cn=z.enum(["unresolved","resolved","archived"]),pn=z.enum(["succeeded","failed"]),un=z.enum(["full","incremental"]),Es=z.enum(["info","warn","error"]),Ps=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),Is=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),dn=z.object({errors:z.array(Ps),warnings:z.array(Is)}),mn=z.object({level:Es,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:dn,logEntries:z.array(mn),cliVersion:z.string(),outcome:pn,indexType:un}),z.object({status:cn.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:un,status:cn,outcome:pn,errorSummary:z.string(),errorData:dn,logEntries:z.array(mn),cliVersion:z.string(),resolvedAt:z.string().nullable(),resolvedBy:z.string().nullable(),createdAt:z.string(),updatedAt:z.string(),organizationName:z.string().optional(),projectName:z.string().optional(),userEmail:z.string().optional(),resolvedByEmail:z.string().optional()}),z.object({unresolvedCount:z.number(),failedRunCount:z.number(),resolvedLast30d:z.number(),avgResolutionDays:z.number().nullable(),affectedOrgCount:z.number()});});function gn(i){return base32.encode(Buffer.from(i))}var fn=h(()=>{});function hn(i,e,t){let n=`${i}:${e}${t?`:${t}`:""}`;return gn(n)}var yn=h(()=>{fn();});var ot,bn=h(()=>{ot=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
|
|
3
|
+
`,o=Buffer.from(n,"utf8");if(!this.push(o))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};});function Ts(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Ie.platform()==="win32"?!!(process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"||process.env.TERM_PROGRAM==="Hyper"||process.env.TERM&&process.env.TERM!=="cygwin"&&process.env.TERM!=="dumb"):true}var $s,js,ks,As,Ls,Fs,Os,Ds,Ms,Us,Le,C,E,b,v,te,D=h(()=>{$s="\u2714",js="\u2717",ks="\u26A0",As="\u2139",Ls="\u26A1",Fs="[OK]",Os="[ERR]",Ds="[WARN]",Ms="[INFO]",Us="[>>]",Le=Ts(),C=u.green(Le?$s:Fs),E=u.red(Le?js:Os),b=u.yellow(Le?ks:Ds),v=u.blue(Le?As:Ms),te=u.yellow(Le?Ls:Us);});var st,at,T,re,U,he,ne,lt=h(()=>{ke();yn();bn();D();st=class{constructor(e,t,n=false){this.config=e;this.accessKey=t;this.dirty=n;}apiVersion="intel/v1";features={};isFeatureEnabled(e){return this.features[e]===true}parseFeatureHeader(e){if(Object.keys(this.features).length>0)return;let t=e.headers.get("X-Features");if(t)for(let n of t.split(",")){let[o,s]=n.split("=");o&&s!==void 0&&(this.features[o]=s==="true");}}async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),this.parseFeatureHeader(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new U(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new U(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new U(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new re("Project not found - no previous index exists");default:throw e.status===404?new re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof U||t instanceof re?t:e.status===404?new re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let s=await this.sendRequest(o,null,"GET");return !s||!s.ok?null:await s.json()}catch(s){if(s instanceof T)throw s;return null}}async claimAstLock(e,t,n,o,s){let a=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":n?"incremental":"full","x-commit-hash":o,"x-commit-timestamp":s,"x-constellation-dirty":this.dirty?"true":"false"});if(!a)throw new Error("Failed to claim indexing lock: no response");if(a.status===409)throw await this.parseIndexingConflict(a);if(a.status===401)throw new T("Authentication failed");if(!a.ok){let p=await this.formatErrorBody(a);throw new Error(`Failed to claim indexing lock: ${a.status}${p?` \u2014 ${p}`:""}`)}let l=await a.json(),c=sn.safeParse(l);if(!c.success)throw new Error(`Invalid lock response from server: ${c.error.issues.map(p=>p.message).join("; ")}`);return c.data}async pollIndexStatus(e,t,n,o=300*1e3){let s=Date.now(),a=2e3,l=3e4;for(;Date.now()-s<o;){try{let c=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(n)}`,null,"GET",{"x-constellation-dirty":this.dirty?"true":"false"});if(!c)continue;if(c.status===401)throw new T("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let p=await c.json();if(p.status==="current")return !0;if(p.status==="stale"||p.status==="failed")return !1}}catch(c){if(c instanceof T)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadToQueue(e,t,n,o,s){return this.streamToApi(e,"ast/queue",t,n,true,o,s)}async startEnrichment(e,t,n){let o=new Agent({headersTimeout:1e4,bodyTimeout:1e4});try{let s=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment/start`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/json; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-attempt-id":e,"x-constellation-dirty":this.dirty?"true":"false"},dispatcher:o});if(s.ok)return !0;let a=`status ${s.status}`;try{let l=await s.json();l?.message?a=Array.isArray(l.message)?l.message.join("; "):String(l.message):l?.code&&(a=`status ${s.status} (${String(l.code)})`);}catch{}return console.warn(`Enrichment start heartbeat rejected: ${a}`),!1}catch(s){return console.warn(`Enrichment start heartbeat failed: ${s instanceof Error?s.message:String(s)}`),false}finally{o.destroy().catch(()=>{});}}async uploadEnrichment(e,t,n,o){let s=[5e3,1e4,2e4];for(let a=0;a<=s.length;a++)try{let l=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-commit-hash":o,"x-constellation-dirty":this.dirty?"true":"false"},body:e,dispatcher:new Agent({headersTimeout:0,bodyTimeout:0})});if(l.status===401)throw new T("Authentication failed during enrichment upload");if(l.status===409){if((await l.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return console.warn("Enrichment skipped: index state changed since AST upload"),!1;if(a<s.length){await new Promise(p=>setTimeout(p,s[a]));continue}return console.warn("Enrichment skipped: indexing still in progress after retries"),!1}return l.ok||l.status===202?!0:(console.warn(`Enrichment upload failed with status ${l.status}`),!1)}catch(l){if(l instanceof T)throw l;if(a<s.length){console.warn(`Enrichment upload network error (attempt ${a+1}/${s.length+1}): ${l instanceof Error?l.message:String(l)}`),await new Promise(c=>setTimeout(c,s[a]));continue}return console.warn(`Enrichment upload error: ${l instanceof Error?l.message:String(l)}`),false}return false}async deleteFiles(e){for(let t of e){let n=hn(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",n;try{let o=await e.json();t=o?.message||t,n=o?.details?.branchName;}catch{}return new he(t,n)}async formatErrorBody(e){try{let t=await e.json();if(typeof t?.message=="string"){let n=typeof t.code=="string"&&t.code.length>0?` [${t.code}]`:"";return `${t.message}${n}`}if(Array.isArray(t?.message))return t.message.join("; ");if(typeof t?.code=="string")return t.code}catch{}return ""}async streamToApi(e,t,n,o,s,a,l){try{let{Readable:c}=await import('stream'),p=new ot(e),d=process.env.CAPTURE_PAYLOAD_PATH,m=null,g=c.toWeb(p);if(d){let[y,x]=g.tee(),_=ir.createWriteStream(d);m=pipeline(c.fromWeb(x),hr.createGzip(),_).catch(S=>{console.warn(`[constellation] capture tap failed: ${S instanceof Error?S.message:String(S)}`);}),g=y;}let f=new Agent({headersTimeout:0,bodyTimeout:0});try{let y=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":n,"x-branch-name":o,"x-constellation-index":s?"incremental":"full","x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`,...a&&{"x-commit-hash":a},...l&&{"x-attempt-id":l}},body:g,duplex:"half",dispatcher:f});if(!y.ok&&typeof p.destroy=="function"&&p.destroy(),y.status===401)throw new T("Authentication failed");if(y.status===409)throw await this.parseIndexingConflict(y);if(y.status===200)try{let _=await y.json();if(_?.status==="current")return console.log(`${C} Index already up to date for ${o} at commit ${_.commitHash||"unknown"}`),!0}catch{}if(y.ok||y.status===202)return !0;let x=`Server returned ${y.status}`;try{let _=await y.json();_?.message&&(x=Array.isArray(_.message)?_.message.join("; "):_.message);}catch{}throw new Error(x)}finally{m&&await m;}}catch(c){if(c instanceof T||c instanceof he)throw c;let p=c instanceof Error?c:new Error(String(c)),d="";if(p.message==="fetch failed"||c.code){let g=[],f=c.code||c.cause?.code;if(c.code&&g.push(`Error Code: ${c.code}`),c.cause){let y=c.cause;y.code&&g.push(`Cause Code: ${y.code}`),y.errno&&g.push(`Errno: ${y.errno}`),y.syscall&&g.push(`System Call: ${y.syscall}`),y.address&&g.push(`Address: ${y.address}`),y.port&&g.push(`Port: ${y.port}`);}f==="ERR_INVALID_ARG_VALUE"?d="Invalid argument value - check stream/body format and duplex option":f==="ECONNREFUSED"?d="Connection refused - service may be down or unreachable":f==="ENOTFOUND"?d="DNS lookup failed - check service URL":f==="ETIMEDOUT"?d="Connection timeout - service not responding":f==="ECONNRESET"?d="Connection reset by server":f==="EHOSTUNREACH"?d="Host unreachable - check network connectivity":d="Network failure",g.length>0&&(d+=` (${g.join(", ")})`);}else d=p.message;let m=new Error(`Failed to upload data to Constellation Service: ${d}`);throw m.cause=p,m.stack=`${m.stack}
|
|
4
|
+
Caused by: ${p.stack}`,m}}async sendRequest(e,t,n,o={},s=0,a=3,l=1e3,c=250){for(let p=1;p<=a;p++){let d;try{let m=new AbortController;s>0&&(d=setTimeout(()=>m.abort(),s));let g={...o,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},f=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:g,body:t?JSON.stringify(t):void 0,signal:m.signal});if(d&&clearTimeout(d),f.status===401)throw new T("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new at(`${f.statusText} (${f.status})`);return f}catch(m){if(d&&clearTimeout(d),!(m instanceof T)){let g=m instanceof Error?`${m.message}${m.cause?` (Cause: ${m.cause})`:""}`:String(m);console.log(`HTTP request attempt ${p}/${a} failed: ${g}`);}if(p<a&&m instanceof at){let g=l+Math.floor(Math.random()*c);await new Promise(f=>setTimeout(f,g));}else throw m}}}async reportErrors(e){try{let t=await this.sendRequest("error-reports",e,"POST",{"x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false"},1e4,1,0,0);if(!t){console.warn("Failed to upload error report: no response received");return}if(t.status===403){console.warn("Error reporting is not available on your current plan");return}t.ok||console.warn(`Failed to upload error report: ${t.statusText} (${t.status})`);}catch(t){console.warn(`Failed to upload error report: ${t?.message||"Unknown error"}`);}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false"},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},at=class extends Error{constructor(e){super(e),this.name="RetryableError";}},T=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},re=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},U=class extends Error{constructor(t,n,o){super(t);this.code=n;this.projectId=o;this.name="ProjectValidationError";}},he=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}},ne=class extends Error{constructor(t,n){super(t);this.errorCode=n;this.name="GitValidationError";}};});var k,ct=h(()=>{k={prefix:{idle:u.blue("\u25C6"),done:u.green("\u2714")},style:{highlight:i=>u.blue(i),answer:i=>u.green(i),error:i=>u.red(`\u2716 ${i}`),help:i=>u.gray(i)},icon:{checked:u.green("\u25FC"),unchecked:u.gray("\u25FB"),cursor:u.blue("\u276F")}};});async function _n(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await Zt("open",[i]),!0;case "linux":return await Zt("xdg-open",[i]),!0;case "win32":return await Zt("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var Zt,Sn=h(()=>{Zt=promisify(execFile);});function Ks(i,e){if(!e)return false;let t,n;try{t=new URL(e),n=new URL(i);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"?false:n.origin===t.origin}function xn(i={}){let e=i.allowedOrigin;return new Promise((t,n)=>{let o=createServer(),s,a=false;o.listen(0,"127.0.0.1",()=>{let l=o.address();if(!l||typeof l=="string"){o.close(),n(new Error("Failed to bind callback server"));return}t({port:l.port,close(){s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections();},waitForCallback(c,p=3e5){return new Promise((d,m)=>{s=setTimeout(()=>{s=void 0,a=true,o.close(),o.closeAllConnections(),m(new Error("Authentication timed out"));},p),o.on("request",(g,f)=>{let y=new URL(g.url??"/",`http://127.0.0.1:${l.port}`);if(y.pathname!=="/callback"){f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not found");return}let x=y.searchParams.get("key");if(y.searchParams.get("state")!==c){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid state parameter");return}if(!x||!Ws.test(x)){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid key format");return}if(a)return;a=true;let S=y.searchParams.get("return_url");S&&Ks(S,e)?(f.writeHead(302,{Location:S}),f.end()):(f.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),f.end(Js)),s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections(),d(x);});})}});}),o.on("error",l=>{n(l);});})}var Ws,Js,En=h(()=>{Ws=/^ak:[0-9a-f]{32}$/i,Js=`<!DOCTYPE html>
|
|
5
5
|
<html><head><title>Authentication Successful</title></head>
|
|
6
|
-
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function
|
|
7
|
-
\u2502 ${
|
|
8
|
-
\u2502 _____ ${
|
|
9
|
-
\u2502 ${
|
|
10
|
-
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${
|
|
11
|
-
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${
|
|
12
|
-
\u2502 ${
|
|
13
|
-
\u2502${
|
|
14
|
-
\u2502 ${
|
|
6
|
+
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function er(i){console.log(`\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
|
|
7
|
+
\u2502 ${u.gray("'")} ${u.blueBright(".")} ${u.dim("`")} ${u.yellowBright("'")} ${u.blueBright("+")} ${u.whiteBright(".")} ${u.gray(".")} ${u.yellowBright("'")} ${u.yellowBright("*")} ${u.whiteBright("'")} ${u.blueBright("+")} ${u.gray(".")} ${u.yellowBright("*")} ${u.whiteBright(",")} ${u.gray.dim(".")}\u2502
|
|
8
|
+
\u2502 _____ ${u.yellowBright("*")} ${u.dim("`")} __${u.whiteBright(".")} ${u.whiteBright("'")} ____ ${u.dim(".")} __ _ ${u.gray("`")} . . ${u.yellowBright("o")} ${u.blueBright("+")} \u2502
|
|
9
|
+
\u2502 ${u.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${u.gray(".")} ${u.yellowBright("'")} ${u.gray("+")} ${u.gray("\\")} ${u.gray("`")} \u2502
|
|
10
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${u.gray("'")} ${u.blueBright("o")}${u.gray("\u2014\u2014\u2014\u2014")}${u.yellowBright("o")} ${u.whiteBright("o")} ${u.whiteBright(".")} \u2502
|
|
11
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${u.gray(".")} ${u.whiteBright("*")} ${u.gray(" \\ \\ ")}${u.gray("/")} \u2502
|
|
12
|
+
\u2502 ${u.whiteBright("'")} ${u.blueBright(".")} ${u.gray("'")} ${u.whiteBright(".")} ${u.blueBright(".")} ${u.gray(".")} ${u.yellowBright("*")} ${u.blueBright.dim("+")} ${u.whiteBright("o o")}${u.gray("\u2014")}${u.blueBright("o")} ${u.yellowBright("*")} \u2502
|
|
13
|
+
\u2502${u.yellowBright("'")} ${u.whiteBright("*")} ${u.blueBright("+")} ${u.yellowBright("*")} ${u.gray(",")} ${u.whiteBright("'")} + ${u.whiteBright("constellationdev.io")} ${u.whiteBright("' .")} ${u.gray(",")} ${u.blueBright("*")} ${u.yellowBright(".")} ${u.whiteBright("+")} \u2502`),i&&i.length>0?console.log(`\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u252C${"\u2500".repeat(59-i.length)}\u256F
|
|
14
|
+
\u2502 ${u.bold(`constellation \u203A ${i}`)} \u2502
|
|
15
15
|
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u256F
|
|
16
|
-
`):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var
|
|
16
|
+
`):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var ie,Pn,pt=h(()=>{`
|
|
17
17
|
\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
|
|
18
|
-
\u2502 ${
|
|
19
|
-
\u2502 _____ ${
|
|
20
|
-
\u2502 ${
|
|
21
|
-
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${
|
|
22
|
-
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${
|
|
23
|
-
\u2502 ${
|
|
24
|
-
\u2502${
|
|
18
|
+
\u2502 ${u.gray("'")} ${u.blueBright(".")} ${u.dim("`")} ${u.yellowBright("'")} ${u.blueBright("+")} ${u.whiteBright(".")} ${u.gray(".")} ${u.yellowBright("'")} ${u.yellowBright("*")} ${u.whiteBright("'")} ${u.blueBright("+")} ${u.gray(".")} ${u.yellowBright("*")} ${u.whiteBright(",")} ${u.gray.dim(".")}\u2502
|
|
19
|
+
\u2502 _____ ${u.yellowBright("*")} ${u.dim("`")} __${u.whiteBright(".")} ${u.whiteBright("'")} ____ ${u.dim(".")} __ _ ${u.gray("`")} . . ${u.yellowBright("o")} ${u.blueBright("+")} \u2502
|
|
20
|
+
\u2502 ${u.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${u.gray(".")} ${u.yellowBright("'")} ${u.gray("+")} ${u.gray("\\")} ${u.gray("`")} \u2502
|
|
21
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${u.gray("'")} ${u.blueBright("o")}${u.gray("\u2014\u2014\u2014\u2014")}${u.yellowBright("o")} ${u.whiteBright("o")} ${u.whiteBright(".")} \u2502
|
|
22
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${u.gray(".")} ${u.whiteBright("*")} ${u.gray(" \\ \\ ")}${u.gray("/")} \u2502
|
|
23
|
+
\u2502 ${u.whiteBright("'")} ${u.blueBright(".")} ${u.gray("'")} ${u.whiteBright(".")} ${u.blueBright(".")} ${u.gray(".")} ${u.yellowBright("*")} ${u.blueBright.dim("+")} ${u.whiteBright("o o")}${u.gray("\u2014")}${u.blueBright("o")} ${u.yellowBright("*")} \u2502
|
|
24
|
+
\u2502${u.yellowBright("'")} ${u.whiteBright("*")} ${u.blueBright("+")} ${u.yellowBright("*")} ${u.gray(",")} ${u.whiteBright("'")} + ${u.whiteBright("constellationdev.io")} ${u.whiteBright("' .")} ${u.gray(",")} ${u.blueBright("*")} ${u.yellowBright(".")} ${u.whiteBright("+")} \u2502
|
|
25
25
|
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F
|
|
26
26
|
`,`
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
`,
|
|
27
|
+
${u.yellowBright(" o")}
|
|
28
|
+
${u.gray(" \\")}
|
|
29
|
+
${u.blueBright(" o")}${u.blueBright("----")}${u.yellowBright("o")} ${u.gray("o")}
|
|
30
|
+
${u.gray(" \\ \\ ")}${u.blueBright("/")}
|
|
31
|
+
${u.whiteBright(" o o")}${u.blueBright("-")}${u.blueBright("o")}
|
|
32
|
+
`,ie="CONSTELLATION_ACCESS_KEY",Pn="CONSTELLATION_WEB_URL";});var oe,ut=h(()=>{oe=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};});function Qs(i){return Xs.test(i)}function Zs(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Xs,Fe,In=h(()=>{ct();Sn();En();pt();D();ut();Xs=/^ak:[0-9a-f]{32}$/i;Fe=class extends oe{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${te}Configuring access key authentication...
|
|
33
33
|
`),this.env.isCI()){console.error(`${E} Cannot configure authentication in CI/CD environments
|
|
34
34
|
|
|
35
|
-
The ${
|
|
35
|
+
The ${ie} environment variable must be configured
|
|
36
36
|
directly in your pipeline settings:
|
|
37
37
|
|
|
38
38
|
- GitHub Actions: Repository Settings -> Secrets and variables -> Actions
|
|
@@ -40,50 +40,56 @@ ${p.whiteBright(" o o")}${p.blueBright("-")}${p.blueBright("o")}
|
|
|
40
40
|
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
41
41
|
- Jenkins: Manage Jenkins -> Credentials
|
|
42
42
|
- CircleCI: Project Settings -> Environment Variables
|
|
43
|
-
`);return}if(await this.env.getKey(
|
|
44
|
-
${o}`);}}async manualAuthFlow(){let e,t=0,
|
|
45
|
-
`),t++;continue}if(!
|
|
46
|
-
Attempts remaining: ${
|
|
47
|
-
`);else {console.error(`${E} Invalid access key format after ${
|
|
48
|
-
Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),
|
|
43
|
+
`);return}if(await this.env.getKey(ie)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:k})){console.log(`${C} Keeping existing Constellation access key`);return}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred",o=Zs(n);console.error(`${E} Failed to store Constellation access key
|
|
44
|
+
${o}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await password({message:"Constellation Access Key:",theme:k})).trim(),!e){console.log(`${b} Access key cannot be empty.
|
|
45
|
+
`),t++;continue}if(!Qs(e)){if(t++,t<n)console.log(`${b} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
46
|
+
Attempts remaining: ${n-t}
|
|
47
|
+
`);else {console.error(`${E} Invalid access key format after ${n} attempts.
|
|
48
|
+
Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),t=process.env[Pn]||"https://app.constellationdev.io",{port:n,waitForCallback:o}=await xn({allowedOrigin:t}),s=`${t}/auth/cli?callback_port=${n}&state=${e}`;console.log(`${v} Opening browser for authentication...`),await _n(s)||console.log(`${b} Could not open browser automatically.
|
|
49
49
|
Please open this URL manually:
|
|
50
50
|
|
|
51
51
|
${s}
|
|
52
52
|
`),console.log(`${v} Waiting for authentication... (press Ctrl+C to cancel)
|
|
53
|
-
`);try{let l=await
|
|
54
|
-
Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(
|
|
53
|
+
`);try{let l=await o(e);await this.storeKey(l);}catch{console.error(`${E} Authentication timed out.
|
|
54
|
+
Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(ie,e),console.log(`${C} Stored access key in ${ie} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${v} To activate in this session, run:
|
|
55
55
|
|
|
56
56
|
source ${t}
|
|
57
57
|
|
|
58
|
-
New terminal sessions will load it automatically.`);}};});function
|
|
58
|
+
New terminal sessions will load it automatically.`);}};});function Rn(i){return i.replace(/\\/g,"/")}function dt(i){return Rn(i).replace(/^\.?\//,"")}function M(i,e){return Rn(P.relative(i,e))}var pe=h(()=>{});var ta,ra,nr,na,Nn,Tn,mt,$n=h(()=>{pe();D();ta={function:{hover:true,references:true,callHierarchy:true},method:{hover:true,references:true,callHierarchy:true},class:{hover:false,references:true,callHierarchy:false},interface:{hover:false,references:true,callHierarchy:false},variable:{hover:true,references:true,callHierarchy:false},property:{hover:true,references:true,callHierarchy:false},import:{hover:true,references:false,callHierarchy:false}},ra={hover:true,references:true,callHierarchy:false},nr=1e4,na=1200*1e3,Nn=50,Tn={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},mt=class{constructor(e){this.projectRoot=e;}async enrich(e,t,n){let o=[],s=Date.now(),a={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null};for(let[l,c]of e){let p=n.get(l);if(!p)continue;let d=0,m=c.length;for(let g of c){if(Date.now()-s>na)return console.log(`${v} Enrichment timeout reached. Uploading partial results.`),this.logDiagnostics(a),o;let f=t.get(g)||[];if(f.length===0){let x=P.resolve(this.projectRoot,g),_=pathToFileURL(x).href,S;try{S=ir.readFileSync(x,"utf-8");}catch(L){a.filesUnreadable++,a.firstFileError||(a.firstFileError=`${g}: ${L instanceof Error?L.message:String(L)}`);continue}try{p.sendNotification("textDocument/didOpen",{textDocument:{uri:_,languageId:this.getLanguageId(g),version:1,text:S}});}catch(L){a.filesOpenFailed++,a.firstOpenError||(a.firstOpenError=`${g}: ${L instanceof Error?L.message:String(L)}`);continue}if(f=await this.discoverSymbols(p,g,a),f.length===0){a.filesNoSymbols++;try{p.sendNotification("textDocument/didClose",{textDocument:{uri:_}});}catch{}continue}let I=await this.enrichFile(p,g,f,a,S);if(I.length>0&&o.push({filePath:g,language:l,symbols:I}),d++,d%Nn===0){let L=Math.round(d/m*100);console.log(`${v} ${Tn[l]??l} index enrichment: ${L}% (${d}/${m} files)`);}continue}let y=await this.enrichFile(p,g,f,a);if(y.length>0&&o.push({filePath:g,language:l,symbols:y}),d++,d%Nn===0){let x=Math.round(d/m*100);console.log(`${v} ${Tn[l]??l} index enrichment: ${x}% (${d}/${m} files)`);}}}return this.logDiagnostics(a),o}logDiagnostics(e){let t=[];e.filesUnreadable>0&&t.push(`${e.filesUnreadable} files unreadable`),e.filesOpenFailed>0&&t.push(`${e.filesOpenFailed} files failed to open in language server`),e.discoveryErrors>0&&t.push(`${e.discoveryErrors} symbol discovery failures`),e.symbolQueryErrors>0&&t.push(`${e.symbolQueryErrors} symbol query failures`),e.queryRejections>0&&t.push(`${e.queryRejections} individual LSP query rejections`);let n=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(n.length>0){let o=n.reduce((a,[,l])=>a+l,0),s=n.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(console.log(`${b} Enrichment issues: ${t.join(", ")}`),e.firstFileError&&console.log(`${b} First file read error: ${e.firstFileError}`),e.firstOpenError&&console.log(`${b} First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&console.log(`${b} First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&console.log(`${b} First symbol query error: ${e.firstSymbolError}`));}async enrichFile(e,t,n,o,s){let a=P.resolve(this.projectRoot,t),l=pathToFileURL(a).href;if(!(s!==void 0)){let d;try{d=ir.readFileSync(a,"utf-8");}catch(m){return o.filesUnreadable++,o.firstFileError||(o.firstFileError=`${t}: ${m instanceof Error?m.message:String(m)}`),[]}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:l,languageId:this.getLanguageId(t),version:1,text:d}});}catch(m){return o.filesOpenFailed++,o.firstOpenError||(o.firstOpenError=`${t}: ${m instanceof Error?m.message:String(m)}`),[]}}let p=[];for(let d of n)try{let m=await this.querySymbol(e,l,d,o);m&&p.push(m);}catch(m){o.symbolQueryErrors++,o.firstSymbolError||(o.firstSymbolError=`${d.name} in ${t}: ${m instanceof Error?m.message:String(m)}`);}try{e.sendNotification("textDocument/didClose",{textDocument:{uri:l}});}catch{}return p}async querySymbol(e,t,n,o){let s=ta[n.kind.toLowerCase()]||ra,a={line:n.line-1,character:n.column},l={textDocument:{uri:t},position:a},c={name:n.name,line:n.line,column:n.column,kind:n.kind},p=false,[d,m]=await Promise.allSettled([s.hover?e.sendRequest("textDocument/hover",l,nr):null,s.references?e.sendRequest("textDocument/references",{...l,context:{includeDeclaration:false}},nr):null]);for(let g of [d,m])g.status==="rejected"&&o.queryRejections++;if(d.status==="fulfilled"&&d.value?.contents){let g=d.value,f=typeof g.contents=="string"?g.contents:g.contents.value||"";f&&(c.typeInfo={resolvedType:f},p=true);}if(m.status==="fulfilled"&&m.value){let g=m.value;if(g.length>0){let f=g.slice(0,100).map(y=>({filePath:M(this.projectRoot,this.uriToPath(y.uri||"")),line:(y.range?.start?.line??0)+1,column:y.range?.start?.character??0}));c.references={count:g.length,locations:f},p=true;}}if(s.callHierarchy)try{let g=await e.sendRequest("textDocument/prepareCallHierarchy",l,nr);if(g&&g.length>0){let f=g[0],[y,x]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:f}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:f}).catch(()=>[])]),_=(y||[]).slice(0,200).map(I=>({name:I.from?.name||"",filePath:M(this.projectRoot,this.uriToPath(I.from?.uri||"")),line:(I.from?.range?.start?.line??0)+1,column:I.from?.selectionRange?.start?.character??I.from?.range?.start?.character??0})),S=(x||[]).slice(0,200).map(I=>({name:I.to?.name||"",filePath:M(this.projectRoot,this.uriToPath(I.to?.uri||"")),line:(I.to?.range?.start?.line??0)+1,column:I.to?.selectionRange?.start?.character??I.to?.range?.start?.character??0}));(_.length>0||S.length>0)&&(c.callHierarchy={incomingCalls:_,outgoingCalls:S},p=!0);}}catch{o.queryRejections++;}if(!p){let g=n.kind.toLowerCase();o.symbolsWithNoEnrichment[g]=(o.symbolsWithNoEnrichment[g]??0)+1;}return p?c:null}async discoverSymbols(e,t,n){let o=P.resolve(this.projectRoot,t),s=pathToFileURL(o).href;try{let a=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:s}});return !a||!Array.isArray(a)?[]:this.flattenDocumentSymbols(a)}catch(a){return n.discoveryErrors++,n.firstDiscoveryError||(n.firstDiscoveryError=`${t}: ${a instanceof Error?a.message:String(a)}`),[]}}flattenDocumentSymbols(e){let t=[],n={1:"file",2:"module",3:"namespace",4:"package",5:"class",6:"method",7:"property",8:"field",9:"constructor",10:"enum",11:"interface",12:"function",13:"variable",14:"constant",15:"string",16:"number",17:"boolean",18:"array",19:"object",20:"key",21:"null",22:"enumMember",23:"struct",24:"event",25:"operator",26:"typeParameter"};for(let o of e){let s=n[o.kind]||"variable",a=o.selectionRange||o.range||o.location?.range;a&&t.push({name:o.name,line:(a.start?.line??0)+1,column:a.start?.character??0,kind:s}),o.children&&Array.isArray(o.children)&&t.push(...this.flattenDocumentSymbols(o.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=P.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function jn(i){return i.map(e=>JSON.stringify(e)).join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}var
|
|
60
|
+
`}var kn=h(()=>{});function gt(i){try{return execFileSync(process.platform==="win32"?"where":"which",[i],{stdio:"ignore"}),!0}catch{return false}}var w,J=h(()=>{w={async directoryExists(i){try{return (await B__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await B__default.access(i,B__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await B__default.readFile(i,{encoding:e,flag:B__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let n=Buffer.from(e,t);await B__default.writeFile(i,n,{encoding:t,flag:B__default.constants.O_WRONLY|B__default.constants.O_CREAT|B__default.constants.O_TRUNC});},async getFileStats(i){return await B__default.stat(i)},async getFileHandle(i,e,t){return await B__default.open(i,e,t)}};});var ft,An=h(()=>{ft=class i{constructor(e,t,n=1e4){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=n;this.stdout.on("data",o=>this.handleData(o)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
|
|
61
61
|
\r
|
|
62
|
-
`);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,
|
|
62
|
+
`);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,n){if(this.disposed)return Promise.reject(new Error("LspClient disposed"));let o=this.nextId++,s={jsonrpc:"2.0",id:o,method:e,...t!==void 0&&{params:t}};return new Promise((a,l)=>{let c=setTimeout(()=>{this.pendingRequests.delete(o),l(new Error(`LSP request '${e}' timed out after ${n??this.defaultTimeoutMs}ms`));},n??this.defaultTimeoutMs);this.pendingRequests.set(o,{resolve:a,reject:l,timer:c}),this.writeMessage(s);})}sendNotification(e,t){if(this.disposed)return;let n={jsonrpc:"2.0",method:e,...t!==void 0&&{params:t}};this.writeMessage(n);}dispose(){this.disposed=true;for(let[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("LspClient disposed"));this.pendingRequests.clear(),this.stdout.removeAllListeners("data");}writeMessage(e){let t=JSON.stringify(e),o=`Content-Length: ${Buffer.byteLength(t,"utf-8")}\r
|
|
63
63
|
\r
|
|
64
|
-
`;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(i.HEADER_SEPARATOR);if(t===-1)break;let o=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!o){this.buffer=this.buffer.subarray(t+4);continue}let s=parseInt(o[1],10),a=t+4;if(this.buffer.length-a<s)break;let l=this.buffer.subarray(a,a+s).toString("utf-8");this.buffer=this.buffer.subarray(a+s);try{let c=JSON.parse(l);this.handleResponse(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,console.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var Qt,dt,me,gt=f(()=>{Qt=P.join(xe.homedir(),".constellation","lsp-servers"),dt=P.join(Qt,"node_modules",".bin"),me=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});var Go,mt,_r=f(()=>{K();br();gt();Go={log:i=>console.log(i),warn:i=>console.warn(i),error:i=>console.error(i)},mt=class{constructor(e,t){this.projectRoot=e;this.logger=t??Go;}servers=new Map;unavailable=new Set;nextId=1;logger;async startServer(e,t){if(t===false||this.unavailable.has(e))return null;let r=this.servers.get(e);if(r)return this.toConnection(r);let o=this.resolveCommand(e,t);if(!o)return this.unavailable.add(e),null;let{command:s,args:a}=o;try{let l=spawn(s,a,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((d,m)=>{l.once("spawn",d),l.once("error",m);}),l.stderr?.on("data",d=>{let m=d.toString().trim();m.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${m}`);});let c=new ut(l.stdin,l.stdout,12e4),u=await c.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);c.sendNotification("initialized",{});let g={language:e,process:l,client:c};return this.servers.set(e,g),l.on("exit",d=>{let m=this.servers.get(e);m&&(m.client.dispose(),this.servers.delete(e)),d!==0&&d!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${d}`);}),this.toConnection(g)}catch(l){this.unavailable.add(e);let c=`[LSP:${e}] Failed to start: ${l instanceof Error?l.message:String(l)}`,u=l?.code;return u==="ENOENT"||u==="EACCES"?this.logger.warn(c):this.logger.error(c),null}}async shutdown(e){let t=this.servers.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(r=>{let o=setTimeout(()=>{t.process.kill("SIGKILL"),r();},3e3);t.process.on("exit",()=>{clearTimeout(o),r();});});}catch(r){this.logger.warn(`[LSP:${e}] Graceful shutdown failed, force killing: ${r instanceof Error?r.message:String(r)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.servers.delete(e);}}async shutdownAll(){let e=[...this.servers.keys()];await Promise.allSettled(e.map(t=>this.shutdown(t)));}destroyAll(){for(let e of this.servers.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.servers.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let r=me.get(e);if(!r)return null;let o=P.join(dt,r.command);return existsSync(o)?{command:o,args:r.args}:pt(r.command)?{command:r.command,args:r.args}:null}toConnection(e){let t=`lsp-${e.language}-${this.nextId++}`;return {language:e.language,process:e.process,id:t,sendRequest:(r,o,s)=>e.client.sendRequest(r,o,s),sendNotification:(r,o)=>e.client.sendNotification(r,o)}}};});var re,ft=f(()=>{re=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var fe,Zt=f(()=>{D();fe=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:r=>r==="node_modules"||r===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:r=>r==="node_modules"||r===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${b} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),r=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}if(r){if(this.isJavaScriptEnabled)try{let o=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let s=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,s),s}throw o}if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let r=await find(e,{root:this.projectRoot,configName:t});return !r||this.failedConfigFiles.has(r)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let r=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(r&&!this.failedConfigFiles.has(r)){this.failedConfigFiles.add(r);let o=t instanceof Error?t.message:String(t);console.warn(`${b} Failed to parse ${r}: ${o}`),console.warn(`${b} Path alias resolution will be skipped for files using this config`);}else r||console.warn(`${b} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var ht,wr=f(()=>{ae();ht=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let r=await this.loadFromTsConfig();Object.assign(e,r),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,r]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),s=await this.resolveSubPath(r,o);if(s)return this.toProjectRelative(s)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,r=this.tsconfigResult.tsconfigFile?P.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,s]of Object.entries(t)){if(o.includes("*")||!Array.isArray(s))continue;let a=s[0];if(!a)continue;let l=P.resolve(r,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=P.join(this.projectRoot,"package.json"),r=await B.readFile(t,"utf-8"),s=JSON.parse(r).workspaces;if(!s)return e;let a=Array.isArray(s)?s:s.packages||[];for(let l of a){let c=await this.findWorkspaceDirs(l);for(let u of c){let g=await this.loadWorkspacePackage(u);g&&Object.assign(e,g);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let r=e.slice(0,-2),o=P.join(this.projectRoot,r);try{let s=await B.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(P.join(o,a.name));}catch{}}else {let r=P.join(this.projectRoot,e);try{(await B.stat(r)).isDirectory()&&t.push(r);}catch{}}return t}async loadWorkspacePackage(e){try{let t=P.join(e,"package.json"),r=await B.readFile(t,"utf-8"),o=JSON.parse(r),s=o.name;if(!s)return null;let a=await this.findPackageEntryPoint(e,o);return a?{[s]:a}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return P.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return P.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return P.join(e,a)}}}if(t.main)return P.join(e,t.main);let r=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let o of r){let s=P.join(e,o);try{if((await B.stat(s)).isFile())return s}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let r of t){let o=P.join(e,r);try{if((await B.stat(o)).isFile())return o}catch{}}try{if((await B.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let r=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?P.dirname(e):P.dirname(e),o=[P.join(r,t+".ts"),P.join(r,t+".tsx"),P.join(r,t+".js"),P.join(r,t+".jsx"),P.join(r,t+".d.ts"),P.join(r,t,"index.ts"),P.join(r,t,"index.tsx"),P.join(r,t,"index.js"),P.join(r,t,"index.jsx")];for(let s of o)try{if((await B.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=M(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var he,en=f(()=>{ae();wr();he=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=P.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new ht(this.projectRoot,t);let r=e.toLowerCase(),o=r.endsWith(".ts")||r.endsWith(".tsx")||r.endsWith(".d.ts"),s=r.endsWith(".js")||r.endsWith(".jsx")||r.endsWith(".mjs")||r.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:s?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=P.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=P.resolve(this.tsconfigDir,a.baseUrl)),a.paths&&typeof a.paths=="object"&&(this.paths=a.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let r=P.resolve(this.sourceDir,e),o=await this.findFileWithExtensions(r);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let r=await this.resolveWithPackageImports(e);return r?this.toProjectRelative(r):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let r=await this.resolveWithPaths(e);if(r)return this.toProjectRelative(r)}if(this.baseUrl){let r=await this.resolveWithBaseUrl(e);if(r)return this.toProjectRelative(r)}return e}toProjectRelative(e){let t=M(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,r]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let s of r){let a=await this.trySubstitution(e,t,s,o);if(a)return a}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[r,o]=t.split("*");if(!e.startsWith(r)||o&&!e.endsWith(o))return null;let s=r.length,a=o?e.length-o.length:e.length;return e.substring(s,a)}async trySubstitution(e,t,r,o){let s=r.replaceAll("*",o),a=P.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=P.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(a=>e.endsWith(a));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let r=[".js",".jsx",".mjs",".cjs"],o=r.some(a=>e.endsWith(a)),s=e;if(o&&!t){for(let a of r)if(e.endsWith(a)){s=e.slice(0,-a.length);break}}if(!t)for(let a of this.extensions){let l=s+a;if(await this.fileExists(l))return await this.resolveSymlink(l)}for(let a of this.extensions){let l=P.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await B.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await B.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let r=P.join(t,"package.json");try{if((await B.stat(r)).isFile())return r}catch{}let o=P.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await B.readFile(e,"utf-8"),r=JSON.parse(t);this.packageJsonDir=P.dirname(e),r.imports&&typeof r.imports=="object"&&(this.packageImports=r.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,r]of Object.entries(this.packageImports)){let o=this.matchPathPattern(e,t);if(o!==null){if(typeof r=="string"){let s=await this.tryPackageImportSubstitution(r,o);if(s)return s}if(Array.isArray(r)){for(let s of r)if(typeof s=="string"){let a=await this.tryPackageImportSubstitution(s,o);if(a)return a}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let r=e.replaceAll("*",t),o=P.resolve(this.packageJsonDir,r);return await this.findFileWithExtensions(o)}};});var yt,xr=f(()=>{ft();Zt();en();yt=class extends re{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new fe(e,t)}getImportResolver(e,t){return new he(e,t)}};});var bt,Er=f(()=>{ft();Zt();en();bt=class extends re{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new fe(e,t)}getImportResolver(e,t){return new he(e,t)}};});var Ko,Y,Re,Jo,ye,Te,Vo,Yo,qo,$e,Xo,Qo,Zo,es,ts,ns,rs,is,os,ss,as,ls,cs,ps,us,ds,gs,Pr,ms,fs,hs,ys,bs,vs,Cs,_s,Ss,ws,xs,Es,Ps,Is,Ns,Rs,Nr,Ts,$s,tn,ks,js,As,Ls,Rr,Ir,Fs,Os,Ds,Ms,Us,Bs,Hs,Gs,Tr,$r,kr,jr,Ws,zs,Ks,Ar,Lr,vt=f(()=>{Ko=z.object({total:z.number().int().nonnegative(),returned:z.number().int().nonnegative(),hasMore:z.boolean(),nextOffset:z.number().int().nonnegative().optional(),currentOffset:z.number().int().nonnegative().optional()}),z.object({overall:z.number().min(0).max(1),factors:z.object({dataFreshness:z.number().min(0).max(1).optional(),coverageComplete:z.number().min(0).max(1).optional(),heuristicAccuracy:z.number().min(0).max(1).optional(),semanticAnalysisDepth:z.number().min(0).max(1).optional(),patternMatchQuality:z.number().min(0).max(1).optional()}).optional(),warnings:z.array(z.string()).optional(),recommendations:z.array(z.string()).optional()}),z.object({qualityScore:z.number().min(0).max(100).optional(),lastUpdated:z.string().optional(),cached:z.boolean().optional(),executionTime:z.number().nonnegative().optional(),coveragePercentage:z.number().min(0).max(100).optional(),issues:z.array(z.string()).optional()}),Y=z.object({language:z.string(),features:z.array(z.string()).optional(),visibility:z.string().optional(),decorators:z.array(z.string()).optional(),typeInfo:z.any().optional(),custom:z.record(z.string(),z.any()).optional()}),z.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),Re=z.enum(["low","medium","high","critical"]),Jo=z.enum(["low","moderate","high","very_high"]),ye=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:Jo}),Te=z.object({filePath:z.string(),line:z.number().int().positive().optional(),lineStart:z.number().int().positive().optional(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional()}),Te.extend({symbolId:z.string().optional(),symbolName:z.string().optional(),symbolKind:z.string().optional()}),z.object({outgoing:z.array(z.string()),incoming:z.array(z.string())}),Vo=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),Yo=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),qo=z.object({nodes:z.array(Vo),edges:z.array(Yo),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),$e=new Set(["abc","aifc","argparse","array","ast","asynchat","asyncio","asyncore","atexit","audioop","base64","bdb","binascii","bisect","builtins","bz2","cProfile","calendar","cgi","cgitb","chunk","cmath","cmd","code","codecs","codeop","collections","colorsys","compileall","concurrent","configparser","contextlib","contextvars","copy","copyreg","crypt","csv","ctypes","curses","dataclasses","datetime","dbm","decimal","difflib","dis","distutils","doctest","email","encodings","ensurepip","enum","errno","faulthandler","fcntl","filecmp","fileinput","fnmatch","fractions","ftplib","functools","gc","getopt","getpass","gettext","glob","graphlib","grp","gzip","hashlib","heapq","hmac","html","http","idlelib","imaplib","imghdr","imp","importlib","inspect","io","ipaddress","itertools","json","keyword","lib2to3","linecache","locale","logging","lzma","mailbox","mailcap","marshal","math","mimetypes","mmap","modulefinder","msilib","msvcrt","multiprocessing","netrc","nis","nntplib","numbers","operator","optparse","os","ossaudiodev","pathlib","pdb","pickle","pickletools","pipes","pkgutil","platform","plistlib","poplib","posix","posixpath","pprint","profile","pstats","pty","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","readline","reprlib","resource","rlcompleter","runpy","sched","secrets","select","selectors","shelve","shlex","shutil","signal","site","sitecustomize","smtpd","smtplib","sndhdr","socket","socketserver","spwd","sqlite3","ssl","stat","statistics","string","stringprep","struct","subprocess","sunau","symtable","sys","sysconfig","syslog","tabnanny","tarfile","telnetlib","tempfile","termios","test","textwrap","threading","time","timeit","tkinter","token","tokenize","tomllib","trace","traceback","tracemalloc","tty","turtle","turtledemo","types","typing","unicodedata","unittest","urllib","usercustomize","uu","uuid","venv","warnings","wave","weakref","webbrowser","winreg","winsound","wsgiref","xdrlib","xml","xmlrpc","zipapp","zipfile","zipimport","zlib","zoneinfo","_thread","_tkinter","__future__","__main__"]),z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.any().optional()})}),z.object({query:z.string().max(200),filterByKind:z.array(z.string()).optional(),filterByVisibility:z.array(z.string()).optional(),isExported:z.boolean().optional(),filterByFile:z.string().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeUsageCount:z.boolean().optional(),includeDocumentation:z.boolean().optional()}).refine(i=>i.query.length>0||i.filterByKind&&i.filterByKind.length>0||i.filterByVisibility&&i.filterByVisibility.length>0||i.isExported!==void 0||i.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),Xo=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),isExported:z.boolean(),usageCount:z.number().int().nonnegative().optional(),complexity:ye.optional(),languageMetadata:Y.optional()}),z.object({symbols:z.array(Xo),pagination:Ko.optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeReferences:z.boolean().optional(),includeRelationships:z.boolean().optional(),includeImpactScore:z.boolean().optional()}),Qo=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),modifiers:z.array(z.string()).optional(),typeInfo:z.any().optional(),decorators:z.array(z.string()).optional(),isExported:z.boolean(),isDeprecated:z.boolean(),complexity:ye.optional(),languageMetadata:Y.optional()}),Zo=Te.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),es=z.object({calls:z.array(z.string()),calledBy:z.array(z.string()),inheritsFrom:z.array(z.string()),inheritedBy:z.array(z.string()),children:z.array(z.string())}),ts=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Re}),z.object({symbol:Qo,references:z.array(Zo).optional(),relationships:es.optional(),impactScore:ts.optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includePackages:z.boolean().optional(),includeSymbols:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),ns=z.object({type:z.enum(["file","module"]),filePath:z.string().nullable(),moduleName:z.string().nullable().optional(),importedSymbols:z.array(z.string()).optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),rs=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),is=z.object({name:z.string(),version:z.string().optional(),type:z.string()}),z.object({totalFiles:z.number().int().nonnegative(),totalPackages:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()}),z.object({file:z.string(),directDependencies:z.array(ns),transitiveDependencies:z.array(rs).optional(),packages:z.array(is).optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includeSymbols:z.boolean().optional(),includeImpactMetrics:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),os=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),ss=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),z.object({totalFiles:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative(),riskLevel:Re}),z.object({file:z.string(),directDependents:z.array(os),transitiveDependents:z.array(ss).optional(),detailedMetrics:z.object({byDepth:z.record(z.string(),z.number()),criticalPaths:z.array(z.array(z.string())),mostImpactedFiles:z.array(z.string())}).optional()}),z.object({filePath:z.string().min(1).optional(),minCycleLength:z.number().int().min(2).max(10).optional(),maxCycleLength:z.number().int().min(2).max(10).optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeImpactScore:z.boolean().optional(),includeConfidence:z.boolean().optional()}),as=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Re}),z.object({cycles:z.array(as)}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),filterByUsageType:z.array(z.string()).optional(),filterByRelationshipType:z.array(z.string()).optional(),includeTransitive:z.boolean().optional(),includeContext:z.boolean().optional(),excludeTests:z.boolean().optional(),excludeGenerated:z.boolean().optional(),includeImportanceWeight:z.boolean().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0)}),ls=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:ye.optional(),languageMetadata:Y.optional()}),cs=z.object({filePath:z.string(),usageType:z.string(),relationshipType:z.string(),line:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional(),enclosingSymbol:z.object({name:z.string(),kind:z.string()}).optional(),context:z.string().optional(),aliasName:z.string().optional(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),importanceWeight:z.number().min(0).max(1).optional()}),ps=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:ls,directUsages:z.array(cs),transitiveUsages:z.array(ps).optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:z.enum(["callers","callees","both"]).default("both"),depth:z.number().int().positive().max(10).default(3),excludeExternal:z.boolean().optional(),includeGraph:z.boolean().optional(),limit:z.number().int().positive().max(100).default(25),offset:z.number().int().nonnegative().default(0)}),us=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),complexity:ye.optional(),languageMetadata:Y.optional()}),ds=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),depth:z.number().int().nonnegative(),complexity:ye.optional(),languageMetadata:Y.optional()}),gs=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isAsync:z.boolean(),depth:z.number().int().nonnegative(),complexity:ye.optional(),languageMetadata:Y.optional()}),z.object({root:us,callers:z.array(ds).optional(),callees:z.array(gs).optional(),graph:qo.optional()}),z.object({symbolId:z.string().optional(),qualifiedName:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeDirectDependents:z.boolean().default(true),includeTransitiveDependents:z.boolean().default(true),depth:z.number().int().min(1).max(5).default(3),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),Pr=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),relationshipType:z.string(),depth:z.number().int().positive(),isExported:z.boolean().optional(),transitiveImpactCount:z.number().int().nonnegative().optional(),languageMetadata:Y.optional()}),ms=z.object({filePath:z.string(),symbolCount:z.number().int().positive(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),symbols:z.array(z.object({id:z.string(),name:z.string(),kind:z.string(),line:z.number().int().positive()}))}),fs=z.object({riskLevel:Re,factors:z.array(z.object({factor:z.string(),severity:z.enum(["low","medium","high"]),description:z.string()})),recommendations:z.array(z.string())}),z.object({symbol:z.object({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isExported:z.boolean().optional(),languageMetadata:Y.optional()}),directDependents:z.array(Pr).optional(),transitiveDependents:z.array(Pr).optional(),impactedFiles:z.array(ms),breakingChangeRisk:fs.optional(),summary:z.object({directDependentCount:z.number().int().nonnegative(),transitiveDependentCount:z.number().int().nonnegative(),impactedFileCount:z.number().int().nonnegative(),testFileCount:z.number().int().nonnegative(),productionFileCount:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()})}),z.object({filePattern:z.string().optional(),filterByKind:z.array(z.string()).optional(),exportedOnly:z.boolean().optional(),excludeTests:z.boolean().default(true),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeConfidence:z.boolean().optional()}),hs=z.object({symbolId:z.string(),name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),isExported:z.boolean(),reason:z.string(),confidence:z.number().min(0).max(1),languageMetadata:Y.optional()}),ys=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(hs),orphanedFiles:z.array(ys)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),bs=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),vs=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),Cs=z.object({languages:z.array(bs),frameworks:z.array(vs),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),_s=z.object({files:z.object({total:z.number().int().nonnegative(),byType:z.record(z.string(),z.number()),byParadigm:z.record(z.string(),z.number())}),symbols:z.object({total:z.number().int().nonnegative(),byKind:z.record(z.string(),z.number()),exported:z.number().int().nonnegative(),public:z.number().int().nonnegative()}),modules:z.object({total:z.number().int().nonnegative(),averageSize:z.number().nonnegative(),largest:z.string()})}),Ss=z.object({internal:z.object({totalConnections:z.number().int().nonnegative(),averagePerFile:z.number().nonnegative(),mostConnectedFiles:z.array(z.object({path:z.string(),incomingCount:z.number().int().nonnegative(),outgoingCount:z.number().int().nonnegative()}))}),external:z.object({totalPackages:z.number().int().nonnegative(),directDependencies:z.number().int().nonnegative(),topPackages:z.array(z.object({name:z.string(),usageCount:z.number().int().nonnegative()}))})}),ws=z.object({complexity:z.object({average:z.number().nonnegative(),high:z.number().int().nonnegative()}),maintainability:z.object({score:z.number().min(0).max(100),issues:z.array(z.string())}),testCoverage:z.object({percentage:z.number().min(0).max(100),testedFiles:z.number().int().nonnegative(),totalFiles:z.number().int().nonnegative()}).optional()}),xs=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),Es=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),Ps=z.object({nodes:z.array(xs),edges:z.array(Es)}),z.object({metadata:Cs,structure:_s,dependencies:Ss,metrics:ws.optional(),moduleGraph:Ps.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),Is=z.enum(["relative","workspace","alias","external","builtin"]),Ns=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:Is}),Rs=z.record(z.string(),Ns),Nr=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),Ts=Nr.exclude(["import-use","declaration"]),$s=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:Nr}).strict(),tn=z.object({filePath:z.string().min(1),entries:z.array($s)}).strict(),z.object({file:z.string().min(1),language:z.string().min(1),commit:z.string().min(1),timestamp:z.string().datetime(),ast:z.string().min(1),importResolutions:Rs.optional(),classificationMap:tn.optional()}).strict(),ks=z.object({file:z.string(),error:z.string()}),js=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),As=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(js)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(ks).optional(),relationships:As}),z.object({projectId:z.string(),projectName:z.string(),branch:z.string(),latestCommit:z.string().nullable(),fileCount:z.number().int().nonnegative(),lastIndexedAt:z.string().nullable(),languages:z.array(z.string())}),Ls=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(Ls),isType:z.boolean(),isDynamic:z.boolean(),isConditional:z.boolean().optional(),isLazy:z.boolean().optional(),isWildcard:z.boolean().optional(),line:z.number(),column:z.number()}),z.object({referencerId:z.string(),referencedName:z.string(),referenceType:Ts,line:z.number(),column:z.number(),scope:z.string().optional(),objectContext:z.string().optional(),language:z.string().optional()}),Rr=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),Ir=Rr.extend({name:z.string().min(1)}).strict(),Fs=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().optional()}).strict(),Os=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:Fs.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(Rr).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(Ir).max(200),outgoingCalls:z.array(Ir).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(Os)}).strict(),z.object({projectId:z.string().min(1),branch:z.string().min(1),commit:z.string().regex(/^[0-9a-f]{40}$/),timestamp:z.string().datetime()}).strict(),z.enum(["pending","processing","completed","failed","skipped"]),Ds=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),Ms=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),Us=z.object({id:z.string(),label:z.string(),type:Ds,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),Bs=z.object({id:z.string(),source:z.string(),target:z.string(),type:Ms,label:z.string().optional()}),Hs=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Re.optional()}),Gs=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(Us),edges:z.array(Bs),summary:Hs,metadata:Gs,features:z.record(z.string(),z.boolean()).optional()}),Tr=z.object({projectId:z.string(),projectName:z.string(),defaultBranch:z.string(),lastIndexedAt:z.string().datetime().optional(),fileCount:z.number().int().nonnegative().optional(),languages:z.array(z.string()).optional()}),z.object({projects:z.array(Tr)}),Tr.pick({projectId:true,projectName:true,defaultBranch:true}),$r=z.enum(["unresolved","resolved","archived"]),kr=z.enum(["succeeded","failed"]),jr=z.enum(["full","incremental"]),Ws=z.enum(["info","warn","error"]),zs=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),Ks=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),Ar=z.object({errors:z.array(zs),warnings:z.array(Ks)}),Lr=z.object({level:Ws,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:Ar,logEntries:z.array(Lr),cliVersion:z.string(),outcome:kr,indexType:jr}),z.object({status:$r.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:jr,status:$r,outcome:kr,errorSummary:z.string(),errorData:Ar,logEntries:z.array(Lr),cliVersion:z.string(),resolvedAt:z.string().nullable(),resolvedBy:z.string().nullable(),createdAt:z.string(),updatedAt:z.string(),organizationName:z.string().optional(),projectName:z.string().optional(),userEmail:z.string().optional(),resolvedByEmail:z.string().optional()}),z.object({unresolvedCount:z.number(),failedRunCount:z.number(),resolvedLast30d:z.number(),avgResolutionDays:z.number().nullable(),affectedOrgCount:z.number()});});async function ie(i,e,t,r,o,s=[]){let a=await t.resolve(i),l=Fr(i,a),c=o(i,a,l),u=l?void 0:lt(a);r[e.toString()]={source:i,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function Fr(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var nn,ke=f(()=>{ae();nn=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function Vs(i,e,t,r){let o=i.childForFieldName("name");if(!o)return;let s,a;if(o.type==="aliased_import"){let l=o.childForFieldName("name"),c=o.childForFieldName("alias");s=l?l.text:o.text,a={local:c?c.text:s.split(".")[0],original:s,isDefault:false,isNamespace:false};}else s=o.text,a={local:s.split(".")[0],original:s,isDefault:false,isNamespace:false};await ie(s,i.startPosition.row,e,t,r,[a]);}function Ys(i,e){if(!e)return [];let t=[],r=i.childForFieldName("name");if(r){if(r.type==="aliased_import"){let s=r.childForFieldName("name"),a=r.childForFieldName("alias");s&&t.push({local:a?a.text:s.text,original:s.text,isDefault:false,isNamespace:false});}else t.push({local:r.text,original:r.text,isDefault:false,isNamespace:false});return t}let o=false;for(let s=0;s<i.childCount;s++){let a=i.child(s);if(a){if(a.type==="import"){o=true;continue}if(o){if(a.type==="dotted_name"||a.type==="identifier")t.push({local:a.text,original:a.text,isDefault:false,isNamespace:false});else if(a.type==="aliased_import"){let l=a.childForFieldName("name"),c=a.childForFieldName("alias");l&&t.push({local:c?c.text:l.text,original:l.text,isDefault:false,isNamespace:false});}}}}return t}async function qs(i,e,t,r){let o,s=i.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<i.childCount;c++){let u=i.child(c);if(u){if(u.type==="relative_import"){l=u.text;break}(u.type==="."||u.type==="import_prefix")&&(l+=u.text);}}o=l||".";}let a=Ys(i,!!s);await ie(o,i.startPosition.row,e,t,r,a);}async function Xs(i,e,t,r){await ie("__future__",i.startPosition.row,e,t,r,[]);}function rn(){return {language:"python",handlers:new Map([["import_statement",Vs],["import_from_statement",qs],["future_import_statement",Xs]]),classifyImportType:Js}}var Js,Ct=f(()=>{vt();ke();vt();Js=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let r=i.split(".")[0];return $e.has(r)?"builtin":"alias"};});var _t,Or=f(()=>{Ct();_t=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=P.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if($e.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let r=e.replace(/\./g,"/"),o=await this.tryResolveFile(P.resolve(this.projectRoot,r));return o?P.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let r=e.slice(t),o=t<=1?"":"../".repeat(t-1),s=r?o+r.replace(/\./g,"/"):o.slice(0,-1)||".",a=P.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?P.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,P.join(e,"__init__.py"),P.join(e,"__init__.pyi")];for(let r of t)try{return await qt.promises.access(r,qt.constants.F_OK),r}catch{continue}return null}};});var wt,Dr=f(()=>{ft();Or();wt=class extends re{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new _t(e,process.cwd())}};});function Ae(i){return ta[i]??i.charAt(0).toUpperCase()+i.slice(1)}var ta,je,xt,Et=f(()=>{xr();Er();Dr();ta={bash:"Bash",c:"C","c-sharp":"C#",cpp:"C++",go:"Go",java:"Java",javascript:"JavaScript",json:"JSON",php:"PHP",python:"Python",ruby:"Ruby",typescript:"TypeScript"};je={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},xt=class{constructor(e){this.config=e;this.registerPlugin(new yt),this.registerPlugin(new bt),this.registerPlugin(new wt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Qs,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??je.javascript};typescript={language:()=>ea.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??je.typescript};python={language:()=>Zs,fileExtensions:()=>this.config?.languages.python?.fileExtensions??je.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function be(i,e,t=32){let r=i.parent,o=0;for(;r!==null&&o<t;){if(e(r))return r;r=r.parent,o++;}return null}var Pt,on=f(()=>{Pt=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function sn(i,e){if(i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"||i.type==="jsx_closing_element"){let t=i.childForFieldName("name");t!==null&&na(t,e);}for(let t of i.namedChildren)t&&sn(t,e);}function na(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(ce(i.startPosition.row,i.startPosition.column),"call");return}if(i.type==="member_expression"||i.type==="nested_identifier"){let t=i.childForFieldName("property");t!==null&&e.set(ce(t.startPosition.row,t.startPosition.column),"call");}}var Mr=f(()=>{Le();});function ve(i,e){i.rootNode&&(Br(i.rootNode,e),sn(i.rootNode,e));}function Br(i,e){if(ra.has(i.type)){let t=ia(i);t!==null&&e.set(ce(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&Br(t,e);}function ia(i){if(sa(i))return "declaration";if(ha(i))return "read";if(ma(i))return "type";let e=be(i,t=>t.type==="decorator");return e!==null&&ca(i,e)?"call":la(i)?"instantiate":aa(i)?"call":pa(i)||ua(i)||da(i)||xa(i)||wa(i)?"write":ya(i)?"import-use":"read"}function sa(i){let e=i.parent;return e===null?false:!!(oa.has(e.type)&&(e.childForFieldName("name")===i||e.childForFieldName("property")===i)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===i||e.type==="import_specifier"&&(e.childForFieldName("name")===i||e.childForFieldName("alias")===i)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===i&&i.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===i||e.type==="enum_body")}function aa(i){let e=i.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function la(i){let e=i.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function ca(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call_expression"){let r=t.childForFieldName("function");if(r===i||r?.type==="member_expression"&&r.childForFieldName("property")===i)return true}return t.type==="member_expression"&&t.childForFieldName("property")===i}function pa(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="unary_expression")return t.child(0)?.type==="delete";if(t.type==="member_expression"&&t.childForFieldName("object")===e||Pt.has(t.type))return false;e=t;}return false}function ua(i){let e=i.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===i)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function da(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="assignment_expression"||t.type==="augmented_assignment_expression")&&t.childForFieldName("left")===e)return true;if(t.type==="member_expression"&&t.childForFieldName("object")===e||t.type==="subscript_expression"&&t.childForFieldName("object")!==e||Pt.has(t.type))return false;e=t;}return false}function ma(i){let e=i.parent,t=i;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let r=e.namedChild(1);return r===null?false:r===t||fa(r,i)}if(ga.has(e.type))return true;if(Pt.has(e.type))return false;t=e,e=e.parent;}return false}function fa(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function ha(i){return be(i,t=>t.type==="type_query")!==null}function ya(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,r=_a(i);return Sa(r,t)?!va(i,t):false}function va(i,e){let t=i.parent;for(;t!==null;){if(ba.has(t.type)&&Ca(t,e))return true;t=t.parent;}return false}function Ca(i,e){for(let t of i.namedChildren){if(t.type==="lexical_declaration"||t.type==="variable_declaration")for(let r of t.namedChildren){if(r.type!=="variable_declarator")continue;if(r.childForFieldName("name")?.text===e)return true}if(t.type==="formal_parameters")for(let r of t.namedChildren){if(r.type!=="required_parameter"&&r.type!=="optional_parameter")continue;let o=r.childForFieldName("pattern");if(o?.type==="identifier"&&o.text===e)return true}}return false}function _a(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function Sa(i,e){for(let t of i.descendantsOfType("namespace_import")){let r=t.namedChild(0);if(r!==null&&r.text===e)return true}return false}function wa(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function xa(i){let e=i.parent;if(e===null||!Ur.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===i||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==i)return false;let t=e;for(;t!==null;){let r=t.parent;if(r===null)return false;if(r.type==="variable_declarator"&&r.childForFieldName("name")===t||(r.type==="assignment_expression"||r.type==="augmented_assignment_expression")&&r.childForFieldName("left")===t||(r.type==="required_parameter"||r.type==="optional_parameter")&&r.childForFieldName("pattern")===t||r.type==="formal_parameters"||r.type==="for_in_statement"&&r.childForFieldName("left")===t)return true;if(!Ur.has(r.type))return false;t=r;}return false}var ra,oa,ga,ba,Ur,It=f(()=>{Le();on();Mr();ra=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));oa=Object.freeze(new Set(["variable_declarator","function_declaration","function_signature","generator_function_declaration","class_declaration","abstract_class_declaration","interface_declaration","type_alias_declaration","enum_declaration","enum_assignment","method_signature","abstract_method_signature","method_definition","public_field_definition","field_definition","property_signature"]));ga=Object.freeze(new Set(["type_annotation","type_arguments","type_parameter","type_parameters","type_alias_declaration","interface_declaration","generic_type","type_predicate","type_query","conditional_type","union_type","intersection_type","tuple_type","mapped_type_clause","implements_clause","extends_type_clause"]));ba=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Ur=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function Hr(i,e){ve(i,e);}var Gr=f(()=>{It();});function Wr(i,e){ve(i,e);}var zr=f(()=>{It();});function Kr(i,e){if(!i.rootNode)return;let t=za(i.rootNode);Jr(i.rootNode,e,t);}function Jr(i,e,t){if(Ea.has(i.type)){let r=Pa(i,t);r!==null&&e.set(ce(i.startPosition.row,i.startPosition.column),r);}for(let r of i.namedChildren)r&&Jr(r,e,t);}function Pa(i,e){if(Ia(i))return "declaration";if(Ta(i))return "read";if(Ra(i))return "declaration";if($a(i))return "type";let t=be(i,r=>r.type==="decorator");return t!==null&&ka(i,t)||ja(i)?"call":Aa(i)||La(i)||Fa(i)||Da(i)||Ua(i)?"write":Ba(i,e)?"import-use":"read"}function Ia(i){let e=i.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===i||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===i)return true;if(e.type==="list_splat_pattern"||e.type==="dictionary_splat_pattern"){let t=e.parent;if(t?.type==="parameters"||t?.type==="lambda_parameters")return true}return !!(e.type==="as_pattern_target"||Na(i))}function Na(i){let e=i.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function Ra(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(an.has(e.type))return false;e=e.parent;}return false}function Ta(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function $a(i){return be(i,t=>t.type==="type")!==null}function ka(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call"){let r=t.childForFieldName("function");if(r===i||r?.type==="attribute"&&r.childForFieldName("attribute")===i)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===i}function ja(i){let e=i.parent;if(e?.type==="call"&&e.childForFieldName("function")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function Aa(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="delete_statement")return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||an.has(t.type))return false;e=t;}return false}function La(i){let e=i.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function Fa(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function Da(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment"&&t.childForFieldName("left")===e)return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||t.type==="subscript"&&t.childForFieldName("value")!==e)return false;if(Oa.has(t.type)){e=t;continue}if(an.has(t.type))return false;e=t;}return false}function Ua(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="for_statement"||t.type==="for_in_clause")&&t.childForFieldName("left")===e)return true;if(!Ma.has(t.type))return false;e=t;}return false}function Ba(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let r=i.text;return e.has(r)?!Ga(i,r):false}function Ga(i,e){let t=i.parent;for(;t!==null;){if(Ha.has(t.type)&&Wa(t,e))return true;t=t.parent;}return false}function Wa(i,e){for(let t of i.namedChildren){if(t.type==="expression_statement"){let r=t.namedChild(0);if(r?.type==="assignment"){let o=r.childForFieldName("left");if(o?.type==="identifier"&&o.text===e)return true}}if(t.type==="parameters"){for(let r of t.namedChildren)if(r.type==="identifier"&&r.text===e||(r.type==="typed_parameter"||r.type==="typed_default_parameter"||r.type==="default_parameter")&&r.namedChild(0)?.type==="identifier"&&r.namedChild(0)?.text===e)return true}}return false}function za(i){let e=new Set;for(let t of i.descendantsOfType("import_statement"))for(let r of t.namedChildren)if(r.type==="dotted_name"&&e.add(r.text),r.type==="aliased_import"){let o=r.childForFieldName("alias");o&&e.add(o.text);}return e}var Ea,an,Oa,Ma,Ha,Vr=f(()=>{Le();on();Ea=Object.freeze(new Set(["identifier"])),an=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));Oa=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));Ma=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));Ha=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function qr(i,e){let t=new Map;switch(e){case "typescript":ve(i,t);break;case "tsx":Hr(i,t);break;case "javascript":Wr(i,t);break;case "python":Kr(i,t);break}return t}function ce(i,e){return `${i}:${e}`}var Yr,Le=f(()=>{It();Gr();zr();Vr();Yr=Object.freeze(new Set(["typescript","javascript","python"]));});function Va(i,e){return Yr.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function Ya(i){let e=[];for(let[t,r]of i.entries()){let o=t.indexOf(":");if(o<0)continue;let s=Number(t.slice(0,o)),a=Number(t.slice(o+1));!Number.isFinite(s)||!Number.isFinite(a)||e.push({line:s,column:a,referenceType:r});}return e.sort((t,r)=>t.line-r.line||t.column-r.column),e}var Nt,Zr=f(()=>{Le();K();Nt=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let r=this.langRegistry[t]?.language;if(!r)throw new Error(`Unsupported language: ${t}`);let o=await r();if(!o)throw new Error(`Failed to load language: ${t}`);t==="typescript"&&e.toLowerCase().endsWith(".tsx")&&(o=ea.tsx);let s=new Ka;s.setLanguage(o);let a=await _.getFileStats(e),l=10*1024*1024,c;if(a.size<=l){let m=await _.readFile(e),h={bufferSize:1024*1024};c=s.parse(m,void 0,h);}else c=await this.parseWithStream(s,e,a.size);let u=Va(t,e),g=u===null?[]:Ya(qr(c,u));return {tree:c,classificationMap:{filePath:e,entries:g}}}async parseWithStream(e,t,r){let o=null;try{o=await B.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(g=>{if(r>50*1024*1024){let m=Math.round(g/r*100);m>c+10&&(console.log(` Parsing large file: ${m}%...`),c=m);}let d=qt.readSync(s,l,0,a,g);return d===0?null:l.subarray(0,d).toString("utf-8")})}catch(s){if(o)try{await o.close();}catch(a){console.error(`Warning: Failed to close file handle for ${t}:`,a);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var Rt,ti=f(()=>{K();ae();D();Rt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=ei();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(s=>!t.ignores(s.relativePath)&&this.matchesLanguageExtension(s,e.languages))}async scanSpecificFiles(e,t){let r=[],o=null;t.exclude&&t.exclude.length>0&&(o=ei().add(t.exclude));let s=await B__default.realpath(this.rootPath);for(let a of e)try{let l=P__default.isAbsolute(a)?a:P__default.join(this.rootPath,a),c=await B__default.lstat(l);if(c.isSymbolicLink()){let u=await B__default.realpath(l);if(!u.startsWith(s+P__default.sep)&&u!==s){console.warn(`${b} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let g=await B__default.stat(l);if(!g.isFile())continue;let d=M(this.rootPath,l);if(o&&o.ignores(d))continue;let m=this.detectLanguage(d,t.languages);if(!m)continue;r.push({path:l,relativePath:d,language:m,size:g.size});}else if(c.isFile()){let u=M(this.rootPath,l);if(o&&o.ignores(u))continue;let g=this.detectLanguage(u,t.languages);if(!g)continue;r.push({path:l,relativePath:u,language:g,size:c.size});}}catch{console.warn(`${b} Skipping inaccessible file: ${a}`);}return r}async loadGitignoreRules(e,t){let r=[],o=t;for(;;){let s=P__default.join(o,".gitignore");await _.fileIsReadable(s)&&r.unshift(s);let a=P__default.dirname(o);if(a===o)break;o=a;let l=P__default.join(o,".git");if(await _.directoryExists(l)){let c=P__default.join(o,".gitignore");await _.fileIsReadable(c)&&!r.includes(c)&&r.unshift(c);break}}for(let s of r)try{let a=await _.readFile(s);e.add(a);}catch{console.warn(`${b} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,r,o){let s=[],a=t||e,l=r||await B__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=await B__default.readdir(e,{withFileTypes:!0});for(let g of u){let d=P__default.join(e,g.name),m=M(a,d);if(g.isDirectory()){if(g.name.startsWith("."))continue;let h=await this.walkDirectory(d,a,l,c);s.push(...h);}else if(g.isFile()){let h=await B__default.stat(d);s.push({path:d,relativePath:m,language:"",size:h.size});}else if(g.isSymbolicLink())try{let h=await B__default.realpath(d);if(!h.startsWith(l+P__default.sep)&&h!==l){console.warn(`${b} Skipping symlink pointing outside project: ${d} -> ${h}`);continue}let y=await B__default.stat(d);if(y.isDirectory()){if(g.name.startsWith(".")||c.has(h))continue;c.add(h);let S=await this.walkDirectory(d,a,l,c);s.push(...S);}else y.isFile()&&s.push({path:d,relativePath:m,language:"",size:y.size});}catch{console.warn(`${b} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${E} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let r=P__default.extname(e.path).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return e.language=o,true;return false}detectLanguage(e,t){let r=P__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return o;return null}};});var qa,Xa,Qa,ni,ri=f(()=>{vt();qa=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Xa=z.object({source:z.string().min(1,"Import source cannot be empty"),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:z.enum(["relative","workspace","alias","external","builtin"]),specifiers:z.array(qa).optional()}),Qa=z.record(z.string(),Xa),ni=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Qa.optional(),classificationMap:tn.optional()});});var el,Tt,si=f(()=>{el=promisify(ln__default.gunzip),Tt=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],r=ln__default.createGzip();r.on("data",a=>t.push(a));let o=new Promise((a,l)=>{r.on("end",a),r.on("error",l);}),s=Readable.from(e);return await pipeline(s,r),await o,Buffer.concat(t).toString("base64")}async compress(e){let t=[],r=ln__default.createGzip();r.on("data",a=>t.push(a));let o=new Promise((a,l)=>{r.on("end",a),r.on("error",l);}),s=Readable.from(this.serializeASTChunks(e));return await pipeline(s,r),await o,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),r=await el(t);return JSON.parse(r.toString("utf-8"))}};});var cn,$t=f(()=>{cn=new Set(["ACCESS_KEY_MISSING","AUTH_FAILURE","PROJECT_NOT_REGISTERED","PROJECT_INACTIVE","INVALID_PROJECT_ID","DIRTY_WORKTREE","CONCURRENT_INDEXING","GIT_SYNC_FAILURE","BRANCH_NOT_CONFIGURED","ENRICHMENT_FAILED"]);});function pn(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var Fe,ai=f(()=>{$t();Fe=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:p.unstyle(e.map(pn).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:p.unstyle(e.map(pn).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:p.unstyle(e.map(pn).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!cn.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!cn.has(e.code)))}capture(e,t,r){this.entries.push({level:e,message:p.unstyle(t),timestamp:new Date().toISOString(),code:r});let o=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?o.call(console,t):console[e==="info"?"log":e](t);}};});var jt,li=f(()=>{jt=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let r=new Map,o=0,s=0;for(;s<e.length&&r.size<this.concurrency;){let a=o++,l=this.processItem(e[s],s,t).then(c=>({result:c!==null?c.result:null,promiseId:a}));r.set(a,l),s++;}for(;r.size>0;){let a=await Promise.race(r.values());if(r.delete(a.promiseId),a.result!==null&&(yield a.result),s<e.length){let l=o++,c=this.processItem(e[s],s,t).then(u=>({result:u!==null?u.result:null,promiseId:l}));r.set(l,c),s++;}}}async processItem(e,t,r){try{return {result:await r(e,t),index:t}}catch{return null}}};});function tl(i){let e=[];for(let t=0;t<i.childCount;t++){let r=i.child(t);if(r){if(r.type==="identifier")e.push({local:r.text,original:"default",isDefault:true,isNamespace:false});else if(r.type==="namespace_import"){let o;for(let s=0;s<r.childCount;s++){let a=r.child(s);if(a?.type==="identifier"){o=a.text;break}}o!==void 0&&e.push({local:o,original:void 0,isDefault:false,isNamespace:true});}else if(r.type==="named_imports")for(let o=0;o<r.childCount;o++){let s=r.child(o);if(!s||s.type!=="import_specifier")continue;let a=s.childForFieldName("name"),l=s.childForFieldName("alias");if(!a)continue;let c=a.text,u=l?l.text:c,g=c==="default";e.push({local:u,original:c,isDefault:g,isNamespace:false});}}}return e}async function nl(i,e,t,r){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=i.childForFieldName("import_clause"),c=l?tl(l):[];await ie(a,s,e,t,r,c);}async function rl(i,e,t,r){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await ie(a,s,e,t,r,[]);}function At(){return {language:"javascript",handlers:new Map([["import_statement",nl],["export_statement",rl]])}}function un(){return {...At(),language:"typescript"}}var dn=f(()=>{ke();});var ci,pi=f(()=>{dn();Ct();ke();dn();Ct();ci=[At(),un(),rn()];});var ui={};Vn(ui,{ImportExtractor:()=>gn});var gn,di=f(()=>{pi();ke();gn=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??ci)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,r,o){if(!o)return {};let s=this.languageHandlers.get(r);if(!s)return {};let a=this.classifiers.get(r)??nn,l={};return await this.walkAST(e.rootNode,async c=>{let u=s.get(c.type);u&&await u(c,o,l,a);}),l}async walkAST(e,t){await t(e);for(let r=0;r<e.childCount;r++){let o=e.child(r);o&&await this.walkAST(o,t);}}};});var Oe,gi,mn,mi,fi,Lt=f(()=>{Oe=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),gi=new Set(["true","false","null","undefined","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type"]),mn={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},mi={language:"javascript",textIncludedTypes:gi,fieldNames:mn},fi={language:"typescript",textIncludedTypes:gi,fieldNames:mn};});var il,hi,yi,fn=f(()=>{il=new Set(["true","false","none","None","True","False","yield","pass","continue","break","ellipsis","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","type","subscript","attribute","list","tuple","binary_operator","union_type","generic_type"]),hi={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],list_splat_pattern:[],dictionary_splat_pattern:[],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]},yi={language:"python",textIncludedTypes:il,fieldNames:hi,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function bi(i){return De.get(i)}function vi(i){if(!i)return Oe;let e=De.get(i);if(!e)return Oe;let t=new Set(Oe);for(let r of e.textIncludedTypes)t.add(r);return t}function hn(i){if(!i){let t=Array.from(De.values()).map(r=>r.fieldNames);return Me(...t)}let e=De.get(i);if(!e){let t=Array.from(De.values()).map(r=>r.fieldNames);return Me(...t)}return e.fieldNames}var De,Ci=f(()=>{yn();Lt();fn();Lt();Lt();fn();De=new Map([["javascript",mi],["typescript",fi],["python",yi]]);});var Ei={};Vn(Ei,{COMMON_FIELD_NAMES:()=>Cn,JS_TS_FIELD_NAMES:()=>wi,PYTHON_FIELD_NAMES:()=>xi,TEXT_INCLUDED_TYPES:()=>_i,mergeFieldMaps:()=>Me,serializeAST:()=>sl,serializeASTStream:()=>ol});function*ol(i,e,t){yield*vn(i,e,t);}function*vn(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),Si(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?hn(t):Cn)[i.type]||[],s=new Set,a=true;for(let l of o){let c=i.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*vn(c,l,t));}for(let l=0;l<i.childCount;l++){let c=i.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*vn(c,void 0,t));}yield "]";}yield "}";}async function sl(i,e,t){let r=bn(i,e,t),o=t?hn(t):Cn,s=[{treeNode:i,serializedNode:r,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;s.length>0;){let a=s[s.length-1];if(a.childIndex===0&&a.treeNode.childCount>0){let l=o[a.treeNode.type]||[];for(let c of l){let u=a.treeNode.childForFieldName(c);if(u){a.fieldChildren.add(u);let g=bn(u,c,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(g),s.push({treeNode:u,serializedNode:g,fieldName:c,childIndex:0,fieldChildren:new Set});}}}if(a.childIndex<a.treeNode.childCount){let l=a.treeNode.child(a.childIndex);if(a.childIndex++,l&&!a.fieldChildren.has(l)){let c=bn(l,void 0,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(c),s.push({treeNode:l,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else s.pop();}return r}function bn(i,e,t){let r={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return Si(i,t)&&(r.text=i.text),r}function Si(i,e){if(e){let r=bi(e);if(r?.shouldIncludeText){let s=r.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return vi(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:_i.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function Me(...i){let e={};for(let t of i)for(let[r,o]of Object.entries(t)){let a=[...e[r]||[]];for(let l of o)a.includes(l)||a.push(l);e[r]=a;}return e}var _i,wi,xi,Cn,yn=f(()=>{Ci();_i=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","string_fragment","number","true","false","null","undefined","import_specifier","export_specifier","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","yield","pass","continue","break","None","none","True","False","ellipsis","type","string_content"]);wi={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},xi={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]};Cn=Me(wi,xi);});var Ue,Ii=f(()=>{it();fr();yr();_r();gt();Et();Zr();ti();ri();si();st();$t();ai();ae();li();D();at();Ue=class extends ne{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;logCollector=new Fe;discoveredFiles=[];constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new Rt(process.cwd()),this.parser=new Nt(this.langRegistry),this.compressor=new Tt;for(let t of Object.keys(this.config.languages)){let r=this.langRegistry.getPlugin(t);if(r?.getBuildConfigManager){let o=r.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false,r=false){this.logCollector=new Fe,this.logCollector.start();let o="failed";try{let s=await this.getAccessKey();this.apiClient=new nt(this.config,s),await this.validateProject(),this.logCollector.log(`${Q}Starting indexing procedure...
|
|
65
|
-
`)
|
|
66
|
-
|
|
67
|
-
${
|
|
64
|
+
`;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(i.HEADER_SEPARATOR);if(t===-1)break;let o=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!o){this.buffer=this.buffer.subarray(t+4);continue}let s=parseInt(o[1],10),a=t+4;if(this.buffer.length-a<s)break;let l=this.buffer.subarray(a,a+s).toString("utf-8");this.buffer=this.buffer.subarray(a+s);try{let c=JSON.parse(l);this.handleResponse(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,console.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var sr,ht,se,Oe=h(()=>{sr=P.join(Ie.homedir(),".constellation","lsp-servers"),ht=P.join(sr,"node_modules",".bin"),se=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});function On(i){return i.replace(/\\/g,"/")}function aa(i){let e=On(i);return P.posix.basename(e).toLowerCase().replace(/\.(exe|com|bat|cmd|ps1)$/i,"")}function Dn(i,e){if(!i||i.trim().length===0)return {classification:"denied",reason:"LSP command is empty"};let t=On(i);if(sa.test(t))return {classification:"denied",reason:"LSP command contains shell metacharacters"};for(let o of e){if(typeof o!="string")return {classification:"denied",reason:"LSP argument is not a string"};if(o.includes("\0"))return {classification:"denied",reason:"LSP argument contains a null byte"};if(o.includes(`
|
|
65
|
+
`)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let n=aa(i);if(oa.has(n))return {classification:"denied",reason:`LSP command resolves to a shell or interpreter ('${n}')`};for(let[,o]of se)if(n===o.command.toLowerCase())return {classification:"known-safe"};return {classification:"custom-untrusted"}}var oa,sa,Mn=h(()=>{Oe();oa=new Set(["sh","bash","zsh","zsh5","fish","dash","ash","ksh","csh","tcsh","rc","yash","cmd","command","powershell","pwsh","node","nodejs","deno","bun","python","python2","python3","pypy","pypy3","perl","ruby","php","lua","luajit","tclsh","wish","osascript","wscript","cscript","mshta","rundll32","sudo","su","doas","pkexec","runas","gsudo","env","xargs","exec","nohup","timeout","setsid"].map(i=>i.toLowerCase())),sa=/[;&|`$<>\n\r\0"']/;});function Un(i,e,t,n){return i.projectRoot===e&&i.command===t&&i.args.length===n.length&&i.args.every((o,s)=>o===n[s])}function la(i){if(!i||typeof i!="object")return false;let e=i;return typeof e.projectRoot=="string"&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var be,ar=h(()=>{be=class{constructor(e){this.trustFilePath=e;}async isTrusted(e,t,n){return (await this.load()).entries.some(s=>Un(s,e,t,n))}async recordTrust(e,t,n){let o=await this.load();if(o.entries.some(l=>Un(l,e,t,n)))return;o.entries.push({projectRoot:e,command:t,args:[...n],trustedAt:new Date().toISOString()}),await B.mkdir(P.dirname(this.trustFilePath),{recursive:true});let a=`${this.trustFilePath}.${process.pid}.tmp`;try{await B.writeFile(a,JSON.stringify(o,null,2)+`
|
|
66
|
+
`,"utf-8"),await B.rename(a,this.trustFilePath);}catch(l){throw await B.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await B.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(la)}:{entries:[]}}catch{return {entries:[]}}}static isCIEnvironment(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}};});var yt,Hn=h(()=>{Mn();ar();yt=class{projectRoot;logger;trustStore;prompt;isCI;constructor(e){this.projectRoot=e.projectRoot,this.logger=e.logger,this.trustStore=e.trustStore,this.prompt=e.prompt,this.isCI=e.isCI??be.isCIEnvironment;}async authorize(e,t,n){let{classification:o,reason:s}=Dn(t,n);if(o==="denied")return this.logger.error(`[LSP:${e}] Refusing unsafe LSP command '${t}': ${s??"denied"}.`),false;if(o==="known-safe"||await this.trustStore.isTrusted(this.projectRoot,t,n))return true;if(this.isCI())return this.logger.warn(`[LSP:${e}] Skipping untrusted custom LSP command '${t}' in CI. Run 'constellation index' interactively once to approve it, or set the 'lsp' field to a known binary.`),false;let a=n.length>0?` ${n.join(" ")}`:"",l=`Trust custom LSP command for this project?
|
|
67
|
+
${t}${a}
|
|
68
|
+
|
|
69
|
+
Only approve commands you recognize. Untrusted commands can execute arbitrary code.
|
|
70
|
+
Approve?`,c=false;try{c=await this.prompt(l);}catch{c=false;}return c?(await this.trustStore.recordTrust(this.projectRoot,t,n),this.logger.log(`[LSP:${e}] Trusted custom LSP command '${t}' for this project.`),true):(this.logger.warn(`[LSP:${e}] User declined to trust LSP command '${t}'. Skipping enrichment for this language.`),false)}};});var da,ma,bt,zn=h(()=>{J();An();Oe();Hn();ar();da={log:i=>console.log(i),warn:i=>console.warn(i),error:i=>console.error(i)},ma=P.join(Ie.homedir(),".constellation","lsp-trust.json"),bt=class{constructor(e,t,n){this.projectRoot=e;this.logger=t??da,this.policy=n??this.buildDefaultPolicy();}servers=new Map;unavailable=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new yt({projectRoot:this.projectRoot,logger:this.logger,trustStore:new be(ma),prompt:async e=>{let{confirm:t}=await import('@inquirer/prompts');try{return await t({message:e,default:!1})}catch{return false}}})}async startServer(e,t){if(t===false||this.unavailable.has(e))return null;let n=this.servers.get(e);if(n)return this.toConnection(n);let o=this.resolveCommand(e,t);if(!o)return this.unavailable.add(e),null;let{command:s,args:a}=o;if(!await this.policy.authorize(e,s,a))return this.unavailable.add(e),null;try{let c=spawn(s,a,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((g,f)=>{c.once("spawn",g),c.once("error",f);}),c.stderr?.on("data",g=>{let f=g.toString().trim();f.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${f}`);});let p=new ft(c.stdin,c.stdout,12e4),d=await p.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);p.sendNotification("initialized",{});let m={language:e,process:c,client:p};return this.servers.set(e,m),c.on("exit",g=>{let f=this.servers.get(e);f&&(f.client.dispose(),this.servers.delete(e)),g!==0&&g!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${g}`);}),this.toConnection(m)}catch(c){this.unavailable.add(e);let p=`[LSP:${e}] Failed to start: ${c instanceof Error?c.message:String(c)}`,d=c?.code;return d==="ENOENT"||d==="EACCES"?this.logger.warn(p):this.logger.error(p),null}}async shutdown(e){let t=this.servers.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(n=>{let o=setTimeout(()=>{t.process.kill("SIGKILL"),n();},3e3);t.process.on("exit",()=>{clearTimeout(o),n();});});}catch(n){this.logger.warn(`[LSP:${e}] Graceful shutdown failed, force killing: ${n instanceof Error?n.message:String(n)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.servers.delete(e);}}async shutdownAll(){let e=[...this.servers.keys()];await Promise.allSettled(e.map(t=>this.shutdown(t)));}destroyAll(){for(let e of this.servers.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.servers.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let n=se.get(e);if(!n)return null;let o=P.join(ht,n.command);return existsSync(o)?{command:o,args:n.args}:gt(n.command)?{command:n.command,args:n.args}:null}toConnection(e){let t=`lsp-${e.language}-${this.nextId++}`;return {language:e.language,process:e.process,id:t,sendRequest:(n,o,s)=>e.client.sendRequest(n,o,s),sendNotification:(n,o)=>e.client.sendNotification(n,o)}}};});var ae,vt=h(()=>{ae=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var ve,cr=h(()=>{D();ve=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${b} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}if(n){if(this.isJavaScriptEnabled)try{let o=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let s=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,s),s}throw o}if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let n=await find(e,{root:this.projectRoot,configName:t});return !n||this.failedConfigFiles.has(n)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let n=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(n&&!this.failedConfigFiles.has(n)){this.failedConfigFiles.add(n);let o=t instanceof Error?t.message:String(t);console.warn(`${b} Failed to parse ${n}: ${o}`),console.warn(`${b} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${b} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var Ct,Jn=h(()=>{pe();Ct=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),s=await this.resolveSubPath(n,o);if(s)return this.toProjectRelative(s)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?P.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,s]of Object.entries(t)){if(o.includes("*")||!Array.isArray(s))continue;let a=s[0];if(!a)continue;let l=P.resolve(n,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=P.join(this.projectRoot,"package.json"),n=await B.readFile(t,"utf-8"),s=JSON.parse(n).workspaces;if(!s)return e;let a=Array.isArray(s)?s:s.packages||[];for(let l of a){let c=await this.findWorkspaceDirs(l);for(let p of c){let d=await this.loadWorkspacePackage(p);d&&Object.assign(e,d);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),o=P.join(this.projectRoot,n);try{let s=await B.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(P.join(o,a.name));}catch{}}else {let n=P.join(this.projectRoot,e);try{(await B.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=P.join(e,"package.json"),n=await B.readFile(t,"utf-8"),o=JSON.parse(n),s=o.name;if(!s)return null;let a=await this.findPackageEntryPoint(e,o);return a?{[s]:a}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return P.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return P.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return P.join(e,a)}}}if(t.main)return P.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let o of n){let s=P.join(e,o);try{if((await B.stat(s)).isFile())return s}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let o=P.join(e,n);try{if((await B.stat(o)).isFile())return o}catch{}}try{if((await B.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?P.dirname(e):P.dirname(e),o=[P.join(n,t+".ts"),P.join(n,t+".tsx"),P.join(n,t+".js"),P.join(n,t+".jsx"),P.join(n,t+".d.ts"),P.join(n,t,"index.ts"),P.join(n,t,"index.tsx"),P.join(n,t,"index.js"),P.join(n,t,"index.jsx")];for(let s of o)try{if((await B.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=M(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var Ce,pr=h(()=>{pe();Jn();Ce=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=P.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Ct(this.projectRoot,t);let n=e.toLowerCase(),o=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),s=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:s?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=P.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=P.resolve(this.tsconfigDir,a.baseUrl)),a.paths&&typeof a.paths=="object"&&(this.paths=a.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=P.resolve(this.sourceDir,e),o=await this.findFileWithExtensions(n);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=M(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let s of n){let a=await this.trySubstitution(e,t,s,o);if(a)return a}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,o]=t.split("*");if(!e.startsWith(n)||o&&!e.endsWith(o))return null;let s=n.length,a=o?e.length-o.length:e.length;return e.substring(s,a)}async trySubstitution(e,t,n,o){let s=n.replaceAll("*",o),a=P.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=P.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(a=>e.endsWith(a));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],o=n.some(a=>e.endsWith(a)),s=e;if(o&&!t){for(let a of n)if(e.endsWith(a)){s=e.slice(0,-a.length);break}}if(!t)for(let a of this.extensions){let l=s+a;if(await this.fileExists(l))return await this.resolveSymlink(l)}for(let a of this.extensions){let l=P.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await B.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await B.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=P.join(t,"package.json");try{if((await B.stat(n)).isFile())return n}catch{}let o=P.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await B.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=P.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let o=this.matchPathPattern(e,t);if(o!==null){if(typeof n=="string"){let s=await this.tryPackageImportSubstitution(n,o);if(s)return s}if(Array.isArray(n)){for(let s of n)if(typeof s=="string"){let a=await this.tryPackageImportSubstitution(s,o);if(a)return a}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),o=P.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(o)}};});var wt,Kn=h(()=>{vt();cr();pr();wt=class extends ae{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new ve(e,t)}getImportResolver(e,t){return new Ce(e,t)}};});var _t,Vn=h(()=>{vt();cr();pr();_t=class extends ae{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new ve(e,t)}getImportResolver(e,t){return new Ce(e,t)}};});async function le(i,e,t,n,o,s=[]){let a=await t.resolve(i),l=qn(i,a),c=o(i,a,l),p=l?void 0:dt(a);n[e.toString()]={source:i,resolvedPath:p,isExternal:l,importType:c,specifiers:s};}function qn(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var ur,De=h(()=>{pe();ur=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function ya(i,e,t,n){let o=i.childForFieldName("name");if(!o)return;let s,a;if(o.type==="aliased_import"){let l=o.childForFieldName("name"),c=o.childForFieldName("alias");s=l?l.text:o.text,a={local:c?c.text:s.split(".")[0],original:s,isDefault:false,isNamespace:false};}else s=o.text,a={local:s.split(".")[0],original:s,isDefault:false,isNamespace:false};await le(s,i.startPosition.row,e,t,n,[a]);}function ba(i,e){if(!e)return [];let t=[],n=i.childForFieldName("name");if(n){if(n.type==="aliased_import"){let s=n.childForFieldName("name"),a=n.childForFieldName("alias");s&&t.push({local:a?a.text:s.text,original:s.text,isDefault:false,isNamespace:false});}else t.push({local:n.text,original:n.text,isDefault:false,isNamespace:false});return t}let o=false;for(let s=0;s<i.childCount;s++){let a=i.child(s);if(a){if(a.type==="import"){o=true;continue}if(o){if(a.type==="dotted_name"||a.type==="identifier")t.push({local:a.text,original:a.text,isDefault:false,isNamespace:false});else if(a.type==="aliased_import"){let l=a.childForFieldName("name"),c=a.childForFieldName("alias");l&&t.push({local:c?c.text:l.text,original:l.text,isDefault:false,isNamespace:false});}}}}return t}async function va(i,e,t,n){let o,s=i.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<i.childCount;c++){let p=i.child(c);if(p){if(p.type==="relative_import"){l=p.text;break}(p.type==="."||p.type==="import_prefix")&&(l+=p.text);}}o=l||".";}let a=ba(i,!!s);await le(o,i.startPosition.row,e,t,n,a);}async function Ca(i,e,t,n){await le("__future__",i.startPosition.row,e,t,n,[]);}function dr(){return {language:"python",handlers:new Map([["import_statement",ya],["import_from_statement",va],["future_import_statement",Ca]]),classifyImportType:ha}}var ha,St=h(()=>{ke();De();ke();ha=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return $e.has(n)?"builtin":"alias"};});var xt,Yn=h(()=>{St();xt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=P.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if($e.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),o=await this.tryResolveFile(P.resolve(this.projectRoot,n));return o?P.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),o=t<=1?"":"../".repeat(t-1),s=n?o+n.replace(/\./g,"/"):o.slice(0,-1)||".",a=P.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?P.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,P.join(e,"__init__.py"),P.join(e,"__init__.pyi")];for(let n of t)try{return await ir.promises.access(n,ir.constants.F_OK),n}catch{continue}return null}};});var Pt,Xn=h(()=>{vt();Yn();Pt=class extends ae{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new xt(e,process.cwd())}};});function Ue(i){return xa[i]??i.charAt(0).toUpperCase()+i.slice(1)}var xa,Me,It,Rt=h(()=>{Kn();Vn();Xn();xa={bash:"Bash",c:"C","c-sharp":"C#",cpp:"C++",go:"Go",java:"Java",javascript:"JavaScript",json:"JSON",php:"PHP",python:"Python",ruby:"Ruby",typescript:"TypeScript"};Me={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},It=class{constructor(e){this.config=e;this.registerPlugin(new wt),this.registerPlugin(new _t),this.registerPlugin(new Pt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>wa,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Me.javascript};typescript={language:()=>Sa.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Me.typescript};python={language:()=>_a,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Me.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function we(i,e,t=32){let n=i.parent,o=0;for(;n!==null&&o<t;){if(e(n))return n;n=n.parent,o++;}return null}var Nt,mr=h(()=>{Nt=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function gr(i,e){if(i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"||i.type==="jsx_closing_element"){let t=i.childForFieldName("name");t!==null&&Ea(t,e);}for(let t of i.namedChildren)t&&gr(t,e);}function Ea(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(de(i.startPosition.row,i.startPosition.column),"call");return}if(i.type==="member_expression"||i.type==="nested_identifier"){let t=i.childForFieldName("property");t!==null&&e.set(de(t.startPosition.row,t.startPosition.column),"call");}}var Qn=h(()=>{Be();});function _e(i,e){i.rootNode&&(ei(i.rootNode,e),gr(i.rootNode,e));}function ei(i,e){if(Pa.has(i.type)){let t=Ia(i);t!==null&&e.set(de(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&ei(t,e);}function Ia(i){if(Na(i))return "declaration";if(Ma(i))return "read";if(Oa(i))return "type";let e=we(i,t=>t.type==="decorator");return e!==null&&ja(i,e)?"call":$a(i)?"instantiate":Ta(i)?"call":ka(i)||Aa(i)||La(i)||Ka(i)||Ja(i)?"write":Ua(i)?"import-use":"read"}function Na(i){let e=i.parent;return e===null?false:!!(Ra.has(e.type)&&(e.childForFieldName("name")===i||e.childForFieldName("property")===i)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===i||e.type==="import_specifier"&&(e.childForFieldName("name")===i||e.childForFieldName("alias")===i)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===i&&i.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===i||e.type==="enum_body")}function Ta(i){let e=i.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function $a(i){let e=i.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function ja(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call_expression"){let n=t.childForFieldName("function");if(n===i||n?.type==="member_expression"&&n.childForFieldName("property")===i)return true}return t.type==="member_expression"&&t.childForFieldName("property")===i}function ka(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="unary_expression")return t.child(0)?.type==="delete";if(t.type==="member_expression"&&t.childForFieldName("object")===e||Nt.has(t.type))return false;e=t;}return false}function Aa(i){let e=i.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===i)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function La(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="assignment_expression"||t.type==="augmented_assignment_expression")&&t.childForFieldName("left")===e)return true;if(t.type==="member_expression"&&t.childForFieldName("object")===e||t.type==="subscript_expression"&&t.childForFieldName("object")!==e||Nt.has(t.type))return false;e=t;}return false}function Oa(i){let e=i.parent,t=i;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let n=e.namedChild(1);return n===null?false:n===t||Da(n,i)}if(Fa.has(e.type))return true;if(Nt.has(e.type))return false;t=e,e=e.parent;}return false}function Da(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function Ma(i){return we(i,t=>t.type==="type_query")!==null}function Ua(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,n=za(i);return Wa(n,t)?!Ha(i,t):false}function Ha(i,e){let t=i.parent;for(;t!==null;){if(Ba.has(t.type)&&Ga(t,e))return true;t=t.parent;}return false}function Ga(i,e){for(let t of i.namedChildren){if(t.type==="lexical_declaration"||t.type==="variable_declaration")for(let n of t.namedChildren){if(n.type!=="variable_declarator")continue;if(n.childForFieldName("name")?.text===e)return true}if(t.type==="formal_parameters")for(let n of t.namedChildren){if(n.type!=="required_parameter"&&n.type!=="optional_parameter")continue;let o=n.childForFieldName("pattern");if(o?.type==="identifier"&&o.text===e)return true}}return false}function za(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function Wa(i,e){for(let t of i.descendantsOfType("namespace_import")){let n=t.namedChild(0);if(n!==null&&n.text===e)return true}return false}function Ja(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function Ka(i){let e=i.parent;if(e===null||!Zn.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===i||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==i)return false;let t=e;for(;t!==null;){let n=t.parent;if(n===null)return false;if(n.type==="variable_declarator"&&n.childForFieldName("name")===t||(n.type==="assignment_expression"||n.type==="augmented_assignment_expression")&&n.childForFieldName("left")===t||(n.type==="required_parameter"||n.type==="optional_parameter")&&n.childForFieldName("pattern")===t||n.type==="formal_parameters"||n.type==="for_in_statement"&&n.childForFieldName("left")===t)return true;if(!Zn.has(n.type))return false;t=n;}return false}var Pa,Ra,Fa,Ba,Zn,Tt=h(()=>{Be();mr();Qn();Pa=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));Ra=Object.freeze(new Set(["variable_declarator","function_declaration","function_signature","generator_function_declaration","class_declaration","abstract_class_declaration","interface_declaration","type_alias_declaration","enum_declaration","enum_assignment","method_signature","abstract_method_signature","method_definition","public_field_definition","field_definition","property_signature"]));Fa=Object.freeze(new Set(["type_annotation","type_arguments","type_parameter","type_parameters","type_alias_declaration","interface_declaration","generic_type","type_predicate","type_query","conditional_type","union_type","intersection_type","tuple_type","mapped_type_clause","implements_clause","extends_type_clause"]));Ba=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Zn=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function ti(i,e){_e(i,e);}var ri=h(()=>{Tt();});function ni(i,e){_e(i,e);}var ii=h(()=>{Tt();});function oi(i,e){if(!i.rootNode)return;let t=gl(i.rootNode);si(i.rootNode,e,t);}function si(i,e,t){if(Va.has(i.type)){let n=qa(i,t);n!==null&&e.set(de(i.startPosition.row,i.startPosition.column),n);}for(let n of i.namedChildren)n&&si(n,e,t);}function qa(i,e){if(Ya(i))return "declaration";if(Za(i))return "read";if(Qa(i))return "declaration";if(el(i))return "type";let t=we(i,n=>n.type==="decorator");return t!==null&&tl(i,t)||rl(i)?"call":nl(i)||il(i)||ol(i)||al(i)||cl(i)?"write":pl(i,e)?"import-use":"read"}function Ya(i){let e=i.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===i||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===i)return true;if(e.type==="list_splat_pattern"||e.type==="dictionary_splat_pattern"){let t=e.parent;if(t?.type==="parameters"||t?.type==="lambda_parameters")return true}return !!(e.type==="as_pattern_target"||Xa(i))}function Xa(i){let e=i.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function Qa(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(fr.has(e.type))return false;e=e.parent;}return false}function Za(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function el(i){return we(i,t=>t.type==="type")!==null}function tl(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call"){let n=t.childForFieldName("function");if(n===i||n?.type==="attribute"&&n.childForFieldName("attribute")===i)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===i}function rl(i){let e=i.parent;if(e?.type==="call"&&e.childForFieldName("function")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function nl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="delete_statement")return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||fr.has(t.type))return false;e=t;}return false}function il(i){let e=i.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function ol(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function al(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment"&&t.childForFieldName("left")===e)return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||t.type==="subscript"&&t.childForFieldName("value")!==e)return false;if(sl.has(t.type)){e=t;continue}if(fr.has(t.type))return false;e=t;}return false}function cl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="for_statement"||t.type==="for_in_clause")&&t.childForFieldName("left")===e)return true;if(!ll.has(t.type))return false;e=t;}return false}function pl(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let n=i.text;return e.has(n)?!dl(i,n):false}function dl(i,e){let t=i.parent;for(;t!==null;){if(ul.has(t.type)&&ml(t,e))return true;t=t.parent;}return false}function ml(i,e){for(let t of i.namedChildren){if(t.type==="expression_statement"){let n=t.namedChild(0);if(n?.type==="assignment"){let o=n.childForFieldName("left");if(o?.type==="identifier"&&o.text===e)return true}}if(t.type==="parameters"){for(let n of t.namedChildren)if(n.type==="identifier"&&n.text===e||(n.type==="typed_parameter"||n.type==="typed_default_parameter"||n.type==="default_parameter")&&n.namedChild(0)?.type==="identifier"&&n.namedChild(0)?.text===e)return true}}return false}function gl(i){let e=new Set;for(let t of i.descendantsOfType("import_statement"))for(let n of t.namedChildren)if(n.type==="dotted_name"&&e.add(n.text),n.type==="aliased_import"){let o=n.childForFieldName("alias");o&&e.add(o.text);}return e}var Va,fr,sl,ll,ul,ai=h(()=>{Be();mr();Va=Object.freeze(new Set(["identifier"])),fr=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));sl=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));ll=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));ul=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function ci(i,e){let t=new Map;switch(e){case "typescript":_e(i,t);break;case "tsx":ti(i,t);break;case "javascript":ni(i,t);break;case "python":oi(i,t);break}return t}function de(i,e){return `${i}:${e}`}var li,Be=h(()=>{Tt();ri();ii();ai();li=Object.freeze(new Set(["typescript","javascript","python"]));});function yl(i,e){return li.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function bl(i){let e=[];for(let[t,n]of i.entries()){let o=t.indexOf(":");if(o<0)continue;let s=Number(t.slice(0,o)),a=Number(t.slice(o+1));!Number.isFinite(s)||!Number.isFinite(a)||e.push({line:s,column:a,referenceType:n});}return e.sort((t,n)=>t.line-n.line||t.column-n.column),e}var $t,di=h(()=>{Be();J();$t=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let o=await n();if(!o)throw new Error(`Failed to load language: ${t}`);t==="typescript"&&e.toLowerCase().endsWith(".tsx")&&(o=Sa.tsx);let s=new fl;s.setLanguage(o);let a=await w.getFileStats(e),l=10*1024*1024,c;if(a.size<=l){let g=await w.readFile(e),f={bufferSize:1024*1024};c=s.parse(g,void 0,f);}else c=await this.parseWithStream(s,e,a.size);let p=yl(t,e),d=p===null?[]:bl(ci(c,p));return {tree:c,classificationMap:{filePath:e,entries:d}}}async parseWithStream(e,t,n){let o=null;try{o=await B.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(d=>{if(n>50*1024*1024){let g=Math.round(d/n*100);g>c+10&&(console.log(` Parsing large file: ${g}%...`),c=g);}let m=ir.readSync(s,l,0,a,d);return m===0?null:l.subarray(0,m).toString("utf-8")})}catch(s){if(o)try{await o.close();}catch(a){console.error(`Warning: Failed to close file handle for ${t}:`,a);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var jt,gi=h(()=>{J();pe();D();jt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=mi();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(s=>!t.ignores(s.relativePath)&&this.matchesLanguageExtension(s,e.languages))}async scanSpecificFiles(e,t){let n=[],o=null;t.exclude&&t.exclude.length>0&&(o=mi().add(t.exclude));let s=await B__default.realpath(this.rootPath);for(let a of e)try{let l=P__default.isAbsolute(a)?a:P__default.join(this.rootPath,a),c=await B__default.lstat(l);if(c.isSymbolicLink()){let p=await B__default.realpath(l);if(!p.startsWith(s+P__default.sep)&&p!==s){console.warn(`${b} Skipping symlink pointing outside project: ${a} -> ${p}`);continue}let d=await B__default.stat(l);if(!d.isFile())continue;let m=M(this.rootPath,l);if(o&&o.ignores(m))continue;let g=this.detectLanguage(m,t.languages);if(!g)continue;n.push({path:l,relativePath:m,language:g,size:d.size});}else if(c.isFile()){let p=M(this.rootPath,l);if(o&&o.ignores(p))continue;let d=this.detectLanguage(p,t.languages);if(!d)continue;n.push({path:l,relativePath:p,language:d,size:c.size});}}catch{console.warn(`${b} Skipping inaccessible file: ${a}`);}return n}async loadGitignoreRules(e,t){let n=[],o=t;for(;;){let s=P__default.join(o,".gitignore");await w.fileIsReadable(s)&&n.unshift(s);let a=P__default.dirname(o);if(a===o)break;o=a;let l=P__default.join(o,".git");if(await w.directoryExists(l)){let c=P__default.join(o,".gitignore");await w.fileIsReadable(c)&&!n.includes(c)&&n.unshift(c);break}}for(let s of n)try{let a=await w.readFile(s);e.add(a);}catch{console.warn(`${b} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,n,o){let s=[],a=t||e,l=n||await B__default.realpath(this.rootPath),c=o||new Set([l]);try{let p=await B__default.readdir(e,{withFileTypes:!0});for(let d of p){let m=P__default.join(e,d.name),g=M(a,m);if(d.isDirectory()){if(d.name.startsWith("."))continue;let f=await this.walkDirectory(m,a,l,c);s.push(...f);}else if(d.isFile()){let f=await B__default.stat(m);s.push({path:m,relativePath:g,language:"",size:f.size});}else if(d.isSymbolicLink())try{let f=await B__default.realpath(m);if(!f.startsWith(l+P__default.sep)&&f!==l){console.warn(`${b} Skipping symlink pointing outside project: ${m} -> ${f}`);continue}let y=await B__default.stat(m);if(y.isDirectory()){if(d.name.startsWith(".")||c.has(f))continue;c.add(f);let x=await this.walkDirectory(m,a,l,c);s.push(...x);}else y.isFile()&&s.push({path:m,relativePath:g,language:"",size:y.size});}catch{console.warn(`${b} Skipping invalid symlink: ${m}`);}}}catch(p){console.error(`${E} Error walking directory ${e}:`,p);}return s}matchesLanguageExtension(e,t){let n=P__default.extname(e.path).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return e.language=o,true;return false}detectLanguage(e,t){let n=P__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return o;return null}};});var vl,Cl,wl,fi,hi=h(()=>{ke();vl=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Cl=z.object({source:z.string().min(1,"Import source cannot be empty"),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:z.enum(["relative","workspace","alias","external","builtin"]),specifiers:z.array(vl).optional()}),wl=z.record(z.string(),Cl),fi=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:wl.optional(),classificationMap:Yt.optional()});});var Sl,kt,vi=h(()=>{Sl=promisify(hr__default.gunzip),kt=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],n=hr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(e);return await pipeline(s,n),await o,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=hr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(this.serializeASTChunks(e));return await pipeline(s,n),await o,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await Sl(t);return JSON.parse(n.toString("utf-8"))}};});var yr,At=h(()=>{yr=new Set(["ACCESS_KEY_MISSING","AUTH_FAILURE","PROJECT_NOT_REGISTERED","PROJECT_INACTIVE","INVALID_PROJECT_ID","DIRTY_WORKTREE","CONCURRENT_INDEXING","GIT_SYNC_FAILURE","BRANCH_NOT_CONFIGURED","ENRICHMENT_FAILED"]);});function br(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var He,Ci=h(()=>{At();He=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:u.unstyle(e.map(br).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:u.unstyle(e.map(br).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:u.unstyle(e.map(br).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!yr.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!yr.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:u.unstyle(t),timestamp:new Date().toISOString(),code:n});let o=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?o.call(console,t):console[e==="info"?"log":e](t);}};});var Ft,wi=h(()=>{Ft=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let n=new Map,o=0,s=0;for(;s<e.length&&n.size<this.concurrency;){let a=o++,l=this.processItem(e[s],s,t).then(c=>({result:c!==null?c.result:null,promiseId:a}));n.set(a,l),s++;}for(;n.size>0;){let a=await Promise.race(n.values());if(n.delete(a.promiseId),a.result!==null&&(yield a.result),s<e.length){let l=o++,c=this.processItem(e[s],s,t).then(p=>({result:p!==null?p.result:null,promiseId:l}));n.set(l,c),s++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});function xl(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n){if(n.type==="identifier")e.push({local:n.text,original:"default",isDefault:true,isNamespace:false});else if(n.type==="namespace_import"){let o;for(let s=0;s<n.childCount;s++){let a=n.child(s);if(a?.type==="identifier"){o=a.text;break}}o!==void 0&&e.push({local:o,original:void 0,isDefault:false,isNamespace:true});}else if(n.type==="named_imports")for(let o=0;o<n.childCount;o++){let s=n.child(o);if(!s||s.type!=="import_specifier")continue;let a=s.childForFieldName("name"),l=s.childForFieldName("alias");if(!a)continue;let c=a.text,p=l?l.text:c,d=c==="default";e.push({local:p,original:c,isDefault:d,isNamespace:false});}}}return e}async function El(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=i.childForFieldName("import_clause"),c=l?xl(l):[];await le(a,s,e,t,n,c);}async function Pl(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await le(a,s,e,t,n,[]);}function Ot(){return {language:"javascript",handlers:new Map([["import_statement",El],["export_statement",Pl]])}}function vr(){return {...Ot(),language:"typescript"}}var Cr=h(()=>{De();});var _i,Si=h(()=>{Cr();St();De();Cr();St();_i=[Ot(),vr(),dr()];});var xi={};en(xi,{ImportExtractor:()=>wr});var wr,Ei=h(()=>{Si();De();wr=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??_i)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,o){if(!o)return {};let s=this.languageHandlers.get(n);if(!s)return {};let a=this.classifiers.get(n)??ur,l={};return await this.walkAST(e.rootNode,async c=>{let p=s.get(c.type);p&&await p(c,o,l,a);}),l}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let o=e.child(n);o&&await this.walkAST(o,t);}}};});var Ge,Pi,_r,Ii,Ri,Dt=h(()=>{Ge=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),Pi=new Set(["true","false","null","undefined","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type"]),_r={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},Ii={language:"javascript",textIncludedTypes:Pi,fieldNames:_r},Ri={language:"typescript",textIncludedTypes:Pi,fieldNames:_r};});var Il,Ni,Ti,Sr=h(()=>{Il=new Set(["true","false","none","None","True","False","yield","pass","continue","break","ellipsis","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","type","subscript","attribute","list","tuple","binary_operator","union_type","generic_type"]),Ni={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],list_splat_pattern:[],dictionary_splat_pattern:[],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]},Ti={language:"python",textIncludedTypes:Il,fieldNames:Ni,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function $i(i){return ze.get(i)}function ji(i){if(!i)return Ge;let e=ze.get(i);if(!e)return Ge;let t=new Set(Ge);for(let n of e.textIncludedTypes)t.add(n);return t}function xr(i){if(!i){let t=Array.from(ze.values()).map(n=>n.fieldNames);return We(...t)}let e=ze.get(i);if(!e){let t=Array.from(ze.values()).map(n=>n.fieldNames);return We(...t)}return e.fieldNames}var ze,ki=h(()=>{Er();Dt();Sr();Dt();Dt();Sr();ze=new Map([["javascript",Ii],["typescript",Ri],["python",Ti]]);});var Di={};en(Di,{COMMON_FIELD_NAMES:()=>Rr,JS_TS_FIELD_NAMES:()=>Fi,PYTHON_FIELD_NAMES:()=>Oi,TEXT_INCLUDED_TYPES:()=>Ai,mergeFieldMaps:()=>We,serializeAST:()=>Nl,serializeASTStream:()=>Rl});function*Rl(i,e,t){yield*Ir(i,e,t);}function*Ir(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),Li(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?xr(t):Rr)[i.type]||[],s=new Set,a=true;for(let l of o){let c=i.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*Ir(c,l,t));}for(let l=0;l<i.childCount;l++){let c=i.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*Ir(c,void 0,t));}yield "]";}yield "}";}async function Nl(i,e,t){let n=Pr(i,e,t),o=t?xr(t):Rr,s=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;s.length>0;){let a=s[s.length-1];if(a.childIndex===0&&a.treeNode.childCount>0){let l=o[a.treeNode.type]||[];for(let c of l){let p=a.treeNode.childForFieldName(c);if(p){a.fieldChildren.add(p);let d=Pr(p,c,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(d),s.push({treeNode:p,serializedNode:d,fieldName:c,childIndex:0,fieldChildren:new Set});}}}if(a.childIndex<a.treeNode.childCount){let l=a.treeNode.child(a.childIndex);if(a.childIndex++,l&&!a.fieldChildren.has(l)){let c=Pr(l,void 0,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(c),s.push({treeNode:l,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else s.pop();}return n}function Pr(i,e,t){let n={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return Li(i,t)&&(n.text=i.text),n}function Li(i,e){if(e){let n=$i(e);if(n?.shouldIncludeText){let s=n.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return ji(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Ai.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function We(...i){let e={};for(let t of i)for(let[n,o]of Object.entries(t)){let a=[...e[n]||[]];for(let l of o)a.includes(l)||a.push(l);e[n]=a;}return e}var Ai,Fi,Oi,Rr,Er=h(()=>{ki();Ai=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","string_fragment","number","true","false","null","undefined","import_specifier","export_specifier","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","yield","pass","continue","break","None","none","True","False","ellipsis","type","string_content"]);Fi={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},Oi={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]};Rr=We(Fi,Oi);});var Je,Ui=h(()=>{lt();$n();kn();zn();Oe();Rt();di();gi();hi();vi();pt();At();Ci();pe();wi();D();ut();Je=class extends oe{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;logCollector=new He;discoveredFiles=[];constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new jt(process.cwd()),this.parser=new $t(this.langRegistry),this.compressor=new kt;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let o=n.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false,n=false){this.logCollector=new He,this.logCollector.start();let o="failed";try{let s=await this.getAccessKey();this.apiClient=new st(this.config,s,t),await this.validateProject(),this.logCollector.log(`${te}Starting indexing procedure...
|
|
71
|
+
`);let a=performance.now();if(t?this.logCollector.log(`${b} Skipping git branch validation`):await this.validateGitBranch(),t?this.logCollector.log(`${b} Skipping git status validation`):await this.validateGitStatus(),t?this.logCollector.log(`${b} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){this.logCollector.log(`${v} Discovering language build configurations...`);let N=0;for(let[,A]of this.buildConfigManagers.entries()){let Z=await A.initialize();N+=Z.length;}N>0&&this.logCollector.log(`${C} Found ${N} configuration file(s)`);}let l=await this.determineIndexScope(e),c=await this.git.getLatestCommitHash(),p=await this.git.getCommitTimestamp();if(l.upToDate){this.logCollector.log(`
|
|
72
|
+
${C} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${c.substring(0,8)}`),o="succeeded";return}let d=await this.apiClient.claimAstLock(this.config.projectId,this.config.branch,l.isIncremental,c,p);switch(d.remapped===!0&&(d.effectiveBranchName?this.logCollector.log(`${b} --dirty: server is indexing as default branch "${d.effectiveBranchName}" (transmitted "${this.config.branch}").`):this.logCollector.log(`${b} --dirty: server reported a branch remap but did not include the effective branch name.`)),d.status){case "current":this.logCollector.log(`${C} Index already up to date for branch ${this.config.branch} at commit ${c?.substring(0,8)||"unknown"}`),o="succeeded";return;case "duplicate":this.logCollector.log("\u2713 Index for this commit is already in progress."),o="succeeded";return;case "superseded":this.logCollector.log("\u2713 A newer commit is already being indexed."),o="succeeded";return;case "queued":if(!d.queuedAttemptId)throw new Error("Server returned queued status without an attempt ID");await this.handleQueuedUpload(d.queuedAttemptId,l.isIncremental,c),o="succeeded";return;default:break}let m=!1,g=()=>{m||this.logCollector.log(`${v} Uploading metadata, processing, and indexing...`);},f,y,x=new Promise((N,A)=>{f=N,y=A;}),_=new AbortController,S=this.createIndexPipeline(l.isIncremental,g,f),I=null;try{let[,N]=await Promise.all([this.uploadToAPI(S,l.isIncremental,c,d.attemptId).then(A=>(m=!0,A)).catch(A=>{throw _.abort(A),y(A),m=!0,A}),x.then(A=>{let Z=this.getEnrichmentEligibleLanguages(n,A);return Z?(d.attemptId&&this.apiClient.startEnrichment(d.attemptId,this.config.projectId,this.config.branch),this.runLspEnrichment(A,Z,_.signal).catch(ee=>(_.signal.aborted||this.logCollector.warn(`${b} Index enrichment failed: ${ee instanceof Error?ee.message:String(ee)}`,{code:"ENRICHMENT_FAILED"}),null))):null}).catch(()=>null)]);I=N;}catch(N){throw m=!0,N}if(I&&I.length>0)try{let ee=this.discoveredFiles.length,Vt=Math.min(12e4+ee*1e3,9e5);if(this.logCollector.log(`${v} Waiting for server to finish syntax tree processing (${ee} files, timeout ${Math.round(Vt/1e3)}s)...`),await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,c,Vt)){this.logCollector.log(`${v} Uploading enrichment data (${I.length} files)...`);let vo=jn(I);await this.apiClient.uploadEnrichment(vo,this.config.projectId,this.config.branch,c)?this.logCollector.log(`${C} Enrichment data uploaded to Constellation Service, index enhancement in progress`):this.logCollector.log(`${b} Enrichment upload skipped (index state changed)`);}else this.logCollector.log(`${b} AST processing did not complete in time, enrichment skipped`);}catch(N){this.logCollector.warn(`${b} Enrichment upload failed: ${N instanceof Error?N.message:String(N)}`,{code:"ENRICHMENT_FAILED"});}let O=(performance.now()-a)/1e3,j=Math.floor(O/60),V=(O%60).toFixed(3),q=j>0?`${j}m ${V}s`:`${V}s`;this.logCollector.log(`
|
|
73
|
+
${C} Upload completed in ${q}! Server indexing in progress.`),o="succeeded";}catch(s){if(s instanceof U)throw s;if(s instanceof he){this.logIndexingInProgress(s.branchName||this.config?.branch),o="succeeded";return}if(s instanceof T)throw this.logCollector.error(`
|
|
68
74
|
${E} Authentication failed.`,{code:"AUTH_FAILURE"}),this.logCollector.log(`${v} Your access key may be invalid or expired. Run 'constellation auth'
|
|
69
|
-
to set or update your access key.`),s;if(s instanceof
|
|
70
|
-
${E} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),this.logCollector.log(`${v} Set the ${
|
|
71
|
-
'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){this.logCollector.log(`${v} Validating project access...`);try{await this.apiClient.getProjectState(),this.logCollector.log(`${C} Project validated successfully`);}catch(e){if(e instanceof U)throw this.displayProjectValidationError(e),e;if(e instanceof
|
|
72
|
-
Verify your network connection and that the API URL is correct.`):e}}displayProjectValidationError(e){let t=e.projectId||this.config.projectId,
|
|
75
|
+
to set or update your access key.`),s;if(s instanceof ne)throw this.logCollector.error(`${E} Indexing failed: ${s.message}`,{code:s.errorCode}),s;if(s instanceof Error&&s.message==="Access key not configured")throw s;let a=s instanceof Error?s.message:"An unexpected error occurred";throw this.logCollector.error(`${E} Indexing failed: ${a}`),s}finally{this.logCollector.stop();try{let a=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",l=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,c=this.logCollector.getReportableErrors();if(!a&&l&&c.length>0){let p=this.logCollector.getEntries(),d=c.map(S=>({type:"CLI_ERROR",message:S.message,phase:"indexing"})).slice(0,100),m=p.filter(S=>S.level==="warn").map(S=>({type:"CLI_WARNING",message:S.message,phase:"indexing"})).slice(0,100),g=d.length,f=m.length,y=[];g>0&&y.push(`${g} error${g!==1?"s":""}`),f>0&&y.push(`${f} warning${f!==1?"s":""}`);let x=y.join(", "),_=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:x,errorData:{errors:d,warnings:m},logEntries:p.slice(0,1e3),cliVersion:_,outcome:o,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(ie);if(!e)throw this.logCollector.error(`
|
|
76
|
+
${E} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),this.logCollector.log(`${v} Set the ${ie} environment variable or run
|
|
77
|
+
'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){this.logCollector.log(`${v} Validating project access...`);try{await this.apiClient.getProjectState(),this.logCollector.log(`${C} Project validated successfully`);}catch(e){if(e instanceof U)throw this.displayProjectValidationError(e),e;if(e instanceof re){this.logCollector.log(`${C} Project validated (first index)`);return}if(e instanceof T)throw e;let t=e instanceof Error?e.message:String(e);throw t==="fetch failed"||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("ETIMEDOUT")||t.includes("EHOSTUNREACH")||t.includes("ECONNRESET")?new Error(`Unable to connect to the Constellation service.
|
|
78
|
+
Verify your network connection and that the API URL is correct.`):e}}displayProjectValidationError(e){let t=e.projectId||this.config.projectId,n=t.length>40?t.substring(0,37)+"...":t;switch(e.code){case "PROJECT_NOT_REGISTERED":this.logCollector.error(`
|
|
73
79
|
${E} Project not registered
|
|
74
|
-
`,{code:"PROJECT_NOT_REGISTERED"}),this.logCollector.log(` The project ID "${
|
|
80
|
+
`,{code:"PROJECT_NOT_REGISTERED"}),this.logCollector.log(` The project ID "${n}" in constellation.json`),this.logCollector.log(` is not associated with your Constellation account.
|
|
75
81
|
`),this.logCollector.log(" To resolve this:"),this.logCollector.log(" 1. Verify the project exists at https://app.constellationdev.io"),this.logCollector.log(" 2. Check that the project ID in constellation.json is correct"),this.logCollector.log(` 3. Run 'constellation index' again
|
|
76
82
|
`);break;case "PROJECT_INACTIVE":this.logCollector.error(`
|
|
77
83
|
${E} Project is inactive
|
|
78
|
-
`,{code:"PROJECT_INACTIVE"}),this.logCollector.log(` The project "${
|
|
84
|
+
`,{code:"PROJECT_INACTIVE"}),this.logCollector.log(` The project "${n}" has been deactivated.
|
|
79
85
|
`),this.logCollector.log(" To resolve this:"),this.logCollector.log(" 1. Reactivate the project at https://app.constellationdev.io"),this.logCollector.log(` 2. Run 'constellation index' again
|
|
80
86
|
`);break;case "INVALID_PROJECT_ID":this.logCollector.error(`
|
|
81
87
|
${E} Invalid project ID
|
|
82
|
-
`,{code:"INVALID_PROJECT_ID"}),this.logCollector.log(` The project ID "${
|
|
88
|
+
`,{code:"INVALID_PROJECT_ID"}),this.logCollector.log(` The project ID "${n}" in constellation.json`),this.logCollector.log(` is not a valid Constellation project identifier.
|
|
83
89
|
`),this.logCollector.log(" To resolve this:"),this.logCollector.log(" 1. Get your project ID from https://app.constellationdev.io"),this.logCollector.log(" 2. Update the projectId field in constellation.json"),this.logCollector.log(` 3. Run 'constellation index' again
|
|
84
90
|
`);break;default:this.logCollector.error(`
|
|
85
91
|
${E} Project validation failed: ${e.message}
|
|
86
|
-
`,{code:"PROJECT_VALIDATION_FAILED"});}}logIndexingInProgress(e){this.logCollector.log(`${v} Another indexing operation is already in progress for branch ${e||"unknown"}. Your index is up to date with the current operation.`),this.logCollector.log(" Re-run this command after the current operation completes if you have newer changes.");}async validateGitBranch(){this.logCollector.log(`${v} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.logCollector.log(`${C} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.logCollector.log(`${v} Validating Git status...`),!(await this.git.status()).clean)throw new
|
|
92
|
+
`,{code:"PROJECT_VALIDATION_FAILED"});}}logIndexingInProgress(e){this.logCollector.log(`${v} Another indexing operation is already in progress for branch ${e||"unknown"}. Your index is up to date with the current operation.`),this.logCollector.log(" Re-run this command after the current operation completes if you have newer changes.");}async validateGitBranch(){this.logCollector.log(`${v} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.logCollector.log(`${C} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.logCollector.log(`${v} Validating Git status...`),!(await this.git.status()).clean)throw new ne(`Outstanding changes detected.
|
|
87
93
|
Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");this.logCollector.log(`${C} Working tree clean`);}async synchronizeChanges(){this.logCollector.log(`${v} Synchronizing latest changes...`);try{await this.git.pull()&&this.logCollector.log(`${C} Repository synchronized successfully`);}catch(e){throw this.logCollector.error(`${E} Failed to synchronize repository`,{code:"GIT_SYNC_FAILURE"}),e instanceof Error&&(e.message.includes("uncommitted changes")?(this.logCollector.log(`
|
|
88
94
|
To resolve:`),this.logCollector.log(' 1. Commit your changes: git add . && git commit -m "your message"'),this.logCollector.log(" 2. Or stash them: git stash"),this.logCollector.log(` 3. Then run the index command again
|
|
89
95
|
`)):e.message.includes("merge conflicts")?(this.logCollector.log(`
|
|
@@ -92,33 +98,7 @@ To resolve:`),this.logCollector.log(" 1. Fix the conflicted files manually"),th
|
|
|
92
98
|
Please check your internet connection and try again
|
|
93
99
|
`):e.message.includes("Authentication")&&this.logCollector.log(`
|
|
94
100
|
Please check your git credentials and try again
|
|
95
|
-
`)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.logCollector.log(`${v} Determining index scope...`);try{let
|
|
96
|
-
|
|
97
|
-
on:
|
|
98
|
-
push:
|
|
99
|
-
branches: ["${i}"]
|
|
100
|
-
|
|
101
|
-
permissions:
|
|
102
|
-
contents: read
|
|
103
|
-
|
|
104
|
-
jobs:
|
|
105
|
-
index:
|
|
106
|
-
runs-on: ubuntu-latest
|
|
107
|
-
steps:
|
|
108
|
-
- uses: actions/checkout@v4
|
|
109
|
-
|
|
110
|
-
- uses: ShiftinBits/constellation-github@v1
|
|
111
|
-
with:
|
|
112
|
-
access-key: \${{ secrets.CONSTELLATION_ACCESS_KEY }}
|
|
113
|
-
`}function Sn(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function Ft(i){return `include:
|
|
114
|
-
- component: gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1
|
|
115
|
-
inputs:
|
|
116
|
-
access_key: $CONSTELLATION_ACCESS_KEY
|
|
117
|
-
|
|
118
|
-
constellation-index:
|
|
119
|
-
rules:
|
|
120
|
-
- if: $CI_COMMIT_BRANCH == "${i}"
|
|
121
|
-
`}var wn=f(()=>{});var Be,Ri=f(()=>{K();wn();Be=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,r]=await Promise.all([_.directoryExists(P__default.join(this.gitRoot,".github","workflows")),_.fileIsReadable(P__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),r&&e.push("gitlab"),e}async githubWorkflowExists(){return _.fileIsReadable(P__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await _.fileIsReadable(e))return false;try{let r=await _.readFile(e),s=parseDocument(r).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=P__default.join(this.gitRoot,".github","workflows");await B__default.mkdir(t,{recursive:true});let r=P__default.join(t,"constellation-index.yml");return await _.writeFile(r,_n(e)),r}async createOrMergeGitLabCI(e){let t=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await _.fileIsReadable(t))return await _.writeFile(t,Ft(e)),t;let o=await _.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await _.writeFile(t,Ft(e)),t;let{includeEntry:a,job:l}=Sn(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await _.writeFile(t,s.toString()),t}mergeIncludeEntry(e,t){let r=e.get("include");if(!r){e.set("include",[t]);return}if(isSeq(r)){let o=r.items.filter(s=>{if(isMap(s)){let a=s.get("component");return typeof a!="string"||!a.includes("constellation-gitlab")}return true});r.items=o,r.items.push(e.createNode(t));return}e.set("include",[r,t]);}};});var Ti=f(()=>{Ri();wn();});function En(){return $i}var $i,ki=f(()=>{$i=[{event:"SessionStart",type:"prompt",content:`You have Constellation access. \`{MCP_TOOL_NAME}\` is your PRIMARY tool for understanding this codebase\u2014not an alternative, not a fallback, THE DEFAULT.
|
|
101
|
+
`)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.logCollector.log(`${v} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return this.logCollector.log(`${v} No previous index found, performing full index`),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return n===o?(this.logCollector.log(`${C} Already up to date`),{isIncremental:!0,upToDate:!0}):(this.logCollector.log(`${v} Last indexed commit: ${n.substring(0,8)}`),this.logCollector.log(`${v} Current commit: ${o.substring(0,8)}`),this.logCollector.log(`${v} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof T)throw t;return this.logCollector.log(`${b} Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){this.logCollector.log(`${v} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)this.logCollector.log(`${b} Cannot determine changes (no latestCommit in project state), falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let o=await this.git.getChangedFiles(n.latestCommit),s=[...o.added,...o.modified,...o.renamed.map(l=>l.to)];this.logCollector.log(`${v} Found ${s.length} changed files`),t=await this.scanner.scanSpecificFiles(s,this.config);let a=[...o.deleted,...o.renamed.map(l=>l.from)];if(a.length>0){let l=o.deleted.length,c=o.renamed.length,p=c>0?`${v} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${v} Removing ${l} deleted file(s) from graph`;this.logCollector.log(p),await this.apiClient.deleteFiles(a);}}}catch(n){if(n instanceof T)throw n;this.logCollector.log(`${b} Cannot determine changes (${n instanceof Error?n.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else this.logCollector.log(`${v} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return this.logCollector.log(`${C} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),o=e.length,s=0,a=0;this.logCollector.log(`${v} Processing ${o} files...`);let l=await this.git.getLatestCommitHash(),c=o>1e4?5:o>5e3?7:10;c<10&&this.logCollector.log(`${v} Large project detected, using concurrency of ${c} to optimize memory usage`);let d=new Ft(c).run(e,async(m,g)=>{let f=Math.round((g+1)/o*100);this.logCollector.log(`${v} Analyzing file ${m.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let{tree:y,classificationMap:x}=await this.parser.parseFile(m.path,m.language);x.entries.length>5e4&&this.logCollector.warn(`${b} Large classification map for ${m.relativePath}: ${x.entries.length} entries`);let S=this.langRegistry.getPlugin(m.language),I;if(S?.getImportResolver){let N=this.buildConfigManagers.get(m.language),A=N?await N.getConfigForFile(m.path):null,Z=S.getImportResolver(m.path,A);if(Z){let{ImportExtractor:ee}=await Promise.resolve().then(()=>(Ei(),xi));I=await new ee().extractImportResolutions(y,m.path,m.language,Z);}}let{serializeASTStream:L}=await Promise.resolve().then(()=>(Er(),Di)),R=L(y.rootNode,void 0,m.language),O=await this.compressor.compressStream(R),j=this.normalizePathToCanonical(m.relativePath),V={file:j,language:m.language,commit:l,timestamp:n,ast:O,importResolutions:I,classificationMap:{filePath:j,entries:x.entries}},q=fi.safeParse(V);if(!q.success)throw new Error(`AST validation failed: ${q.error.issues[0].message}`);return s++,q.data}catch(y){throw a++,this.logCollector.warn(` ${b} Failed to parse ${m.relativePath}: ${y.message}`,{code:"PARSE_FAILURE"}),y}});for await(let m of d)yield m;a>0?this.logCollector.log(`${b} Completed parsing with ${a} parsing errors`):this.logCollector.log(`${C} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n,o))throw new Error("Failed to upload data to Constellation Service");this.logCollector.log(`${C} Data uploaded to Constellation Service, indexing in progress`);}async*createIndexPipeline(e,t,n){let o=await this.discoverFiles(e);this.discoveredFiles=o,n(o),yield*this.generateASTs(o,t);}async handleQueuedUpload(e,t,n){this.logCollector.log("Generating AST data for queue upload...");let o=this.createIndexPipeline(t,()=>{},()=>{});await this.apiClient.uploadToQueue(o,this.config.projectId,this.config.branch,n,e),this.logCollector.log(`${C} Changes queued for indexing behind the current operation.`);}normalizePathToCanonical(e){return dt(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||se.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.logCollector.log(`${v} Index enrichment skipped (--no-enrich flag)`),null;if(this.config.lspEnrichment===false)return this.logCollector.log(`${v} Index enrichment disabled in constellation.json`),null;let o=[...new Set(t.map(s=>s.language))].filter(s=>this.isLanguageLspEligible(s));return o.length===0?null:(this.logCollector.log(`${v} Index enrichment enabled for: ${o.map(Ue).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,n){let o=new bt(process.cwd(),this.logCollector);try{if(n?.aborted)return null;this.logCollector.log(`${v} Starting index enrichment...`);let s=new Map,a=new Map;for(let g of e){if(!t.has(g.language))continue;let f=s.get(g.language)||[];if(f.push(this.normalizePathToCanonical(g.relativePath)),s.set(g.language,f),!a.has(g.language)){let x=this.config.languages[g.language]?.lsp,_=await o.startServer(g.language,x);_&&a.set(g.language,_);}}if(a.size===0)return this.logCollector.log(`${b} No language servers started, index enrichment skipped`),null;if(n?.aborted)return o.destroyAll(),null;this.logCollector.log(`${C} Language servers started: ${[...a.keys()].map(Ue).join(", ")}`);let l=new Map,c=new mt(process.cwd()),p=n?new Promise((g,f)=>{n.addEventListener("abort",()=>{o.destroyAll(),f(n.reason||new Error("Indexing aborted"));},{once:!0});}):null,d=await(p?Promise.race([c.enrich(s,l,a),p]):c.enrich(s,l,a)),m=d.reduce((g,f)=>g+f.symbols.length,0);return this.logCollector.log(`${C} Index enrichment analysis completed: ${m} symbols across ${d.length} files`),d.length>0?d:null}catch(s){return this.logCollector.warn(`${b} Index enrichment failed: ${s instanceof Error?s.message:String(s)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await o.shutdownAll();}}};});function Nr(i){return stringify({name:"Constellation Index",on:{push:{branches:[i]}},permissions:{contents:"read"},jobs:{index:{"runs-on":"ubuntu-latest",steps:[{uses:"actions/checkout@v4"},{uses:"ShiftinBits/constellation-github@v1",with:{"access-key":"${{ secrets.CONSTELLATION_ACCESS_KEY }}"}}]}}},{lineWidth:0})}function Mt(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function Ut(i){let{includeEntry:e,job:t}=Mt(i);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var Tr=h(()=>{});var Ke,Gi=h(()=>{J();Tr();Ke=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([w.directoryExists(P__default.join(this.gitRoot,".github","workflows")),w.fileIsReadable(P__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return w.fileIsReadable(P__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await w.fileIsReadable(e))return false;try{let n=await w.readFile(e),s=parseDocument(n).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=P__default.join(this.gitRoot,".github","workflows");await B__default.mkdir(t,{recursive:true});let n=P__default.join(t,"constellation-index.yml");return await w.writeFile(n,Nr(e)),n}async createOrMergeGitLabCI(e){let t=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await w.fileIsReadable(t))return await w.writeFile(t,Ut(e)),t;let o=await w.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await w.writeFile(t,Ut(e)),t;let{includeEntry:a,job:l}=Mt(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await w.writeFile(t,s.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let o=n.items.filter(s=>{if(isMap(s)){let a=s.get("component");return typeof a!="string"||!a.includes("constellation-gitlab")}return true});n.items=o,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var zi=h(()=>{Gi();Tr();});function jr(){return Wi}var Wi,Ji=h(()=>{Wi=[{event:"SessionStart",type:"prompt",content:`You have Constellation access. \`{MCP_TOOL_NAME}\` is your PRIMARY tool for understanding this codebase\u2014not an alternative, not a fallback, THE DEFAULT.
|
|
122
102
|
|
|
123
103
|
Mental model:
|
|
124
104
|
- "Where is X defined?" \u2192 {MCP_TOOL_NAME}
|
|
@@ -126,7 +106,7 @@ Mental model:
|
|
|
126
106
|
- "What would break?" \u2192 {MCP_TOOL_NAME}
|
|
127
107
|
- "Find the string 'ERROR_CODE_123'" \u2192 Grep
|
|
128
108
|
|
|
129
|
-
Grep is for literal text. Everything else starts with {MCP_TOOL_NAME}.`,matcher:".*"},{event:"SubagentStart",type:"prompt",content:"You have access to Constellation's {MCP_TOOL_NAME} MCP tool. For structural code questions\u2014symbol definitions, callers/callees, dependencies, dependents, impact analysis, architecture overview\u2014use {MCP_TOOL_NAME} instead of Grep/Glob. It answers in one call what would take 3-5 text searches. Use Grep/Glob only for literal string search, config values, or when the tool is unavailable.",matcher:"Explore|Plan|explore|shell"},{event:"PreCompact",type:"prompt",content:"Preserve: (1) The instruction that {MCP_TOOL_NAME} is the PRIMARY tool for code understanding\u2014Grep is only for literal text, (2) Any architectural insights, dependency relationships, or impact analysis results discovered via Constellation.",matcher:".*"}];});function
|
|
109
|
+
Grep is for literal text. Everything else starts with {MCP_TOOL_NAME}.`,matcher:".*"},{event:"SubagentStart",type:"prompt",content:"You have access to Constellation's {MCP_TOOL_NAME} MCP tool. For structural code questions\u2014symbol definitions, callers/callees, dependencies, dependents, impact analysis, architecture overview\u2014use {MCP_TOOL_NAME} instead of Grep/Glob. It answers in one call what would take 3-5 text searches. Use Grep/Glob only for literal string search, config values, or when the tool is unavailable.",matcher:"Explore|Plan|explore|shell"},{event:"PreCompact",type:"prompt",content:"Preserve: (1) The instruction that {MCP_TOOL_NAME} is the PRIMARY tool for code understanding\u2014Grep is only for literal text, (2) Any architectural insights, dependency relationships, or impact analysis results discovered via Constellation.",matcher:".*"}];});function Al(i){return Ki[i]}var Ki,kl,Ve,kr=h(()=>{Ki={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},kl="code_intel";Ve=class{id="cline";displayName="Cline";mapEventName(e){return Ki[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,kl)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){let o=Al(n.event);if(!o)continue;let s=`.clinerules/hooks/${o}`,a=this.generateScript(n);t.set(s,a);}return t.size>0?t:void 0}generateScript(e){let n=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return `#!/bin/bash
|
|
130
110
|
# Constellation ${e.event} Hook for Cline
|
|
131
111
|
# Generated by constellation-cli - DO NOT EDIT
|
|
132
112
|
#
|
|
@@ -136,64 +116,42 @@ Grep is for literal text. Everything else starts with {MCP_TOOL_NAME}.`,matcher:
|
|
|
136
116
|
cat << 'CONSTELLATION_EOF'
|
|
137
117
|
{
|
|
138
118
|
"cancel": false,
|
|
139
|
-
"contextModification": "${
|
|
140
|
-
}
|
|
141
|
-
CONSTELLATION_EOF
|
|
142
|
-
`}};});var dl,gl,Ce,In=f(()=>{dl={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},gl="constellation__code_intel",Ce=class{id="cursor";displayName="Cursor";mapEventName(e){return dl[e]}generateConfig(e){let t={};for(let r of e){let o=this.mapEventName(r.event);if(!o)continue;t[o]||(t[o]=[]);let s={type:r.type};r.type==="prompt"&&(s.prompt=this.customizePrompt(r)),r.matcher&&(s.matcher=r.matcher),t[o].push(s);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,gl)}};});function Ai(i){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[i]}.sh`}var ml,fl,hl,Ge,Nn=f(()=>{ml={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},fl={SessionStart:"startup",SubagentStart:"",PreCompact:""},hl="code_intel";Ge=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return ml[e]}generateConfig(e){let t={};for(let r of e){let o=this.mapEventName(r.event);if(!o)continue;t[o]||(t[o]=[]);let s=fl[r.event]??"",a=Ai(r.event),l=t[o].find(c=>c.matcher===s);l||(l={matcher:s,hooks:[]},t[o].push(l)),l.hooks.push({name:`constellation-${r.event.toLowerCase()}`,type:"command",command:`$GEMINI_PROJECT_DIR/.gemini/hooks/${a}`,timeout:5e3,description:`Constellation: ${this.getHookDescription(r.event)}`});}return {hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,hl)}generateAuxiliaryFiles(e){let t=new Map;for(let r of e){if(!this.mapEventName(r.event))continue;let a=`.gemini/hooks/${Ai(r.event)}`,l=this.generateScript(r);t.set(a,l);}return t.size>0?t:void 0}generateScript(e){let r=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return e.event==="PreCompact"?`#!/bin/bash
|
|
143
|
-
# Constellation ${e.event} Hook for Gemini CLI
|
|
144
|
-
# Generated by constellation-cli - DO NOT EDIT
|
|
145
|
-
#
|
|
146
|
-
# Note: PreCompress is advisory-only in Gemini CLI and cannot inject context.
|
|
147
|
-
# This hook outputs a systemMessage reminder instead.
|
|
148
|
-
|
|
149
|
-
cat << 'CONSTELLATION_EOF'
|
|
150
|
-
{
|
|
151
|
-
"systemMessage": "${r}"
|
|
152
|
-
}
|
|
153
|
-
CONSTELLATION_EOF
|
|
154
|
-
`:`#!/bin/bash
|
|
155
|
-
# Constellation ${e.event} Hook for Gemini CLI
|
|
156
|
-
# Generated by constellation-cli - DO NOT EDIT
|
|
157
|
-
|
|
158
|
-
cat << 'CONSTELLATION_EOF'
|
|
159
|
-
{
|
|
160
|
-
"hookSpecificOutput": {
|
|
161
|
-
"additionalContext": "${r}"
|
|
162
|
-
}
|
|
119
|
+
"contextModification": "${n}"
|
|
163
120
|
}
|
|
164
121
|
CONSTELLATION_EOF
|
|
165
|
-
`}
|
|
166
|
-
`),
|
|
167
|
-
`)||(
|
|
168
|
-
`),await
|
|
122
|
+
`}};});var Ll,Fl,Se,Ar=h(()=>{Ll={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},Fl="constellation__code_intel",Se=class{id="cursor";displayName="Cursor";mapEventName(e){return Ll[e]}generateConfig(e){let t={};for(let n of e){let o=this.mapEventName(n.event);if(!o)continue;t[o]||(t[o]=[]);let s={type:n.type};n.type==="prompt"&&(s.prompt=this.customizePrompt(n)),n.matcher&&(s.matcher=n.matcher),t[o].push(s);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,Fl)}};});function Lr(i){return Ol.get(i)}var Ol,Fr=h(()=>{kr();Ar();kr();Ar();Ol=new Map([["cline",new Ve],["cursor",new Se]]);});var qe,qi=h(()=>{J();Fr();qe=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureHooks(e,t){if(!e.hooksConfig)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:"Tool does not support hooks configuration"};let n=Lr(e.hooksConfig.adapterId);if(!n)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let o=P__default.join(this.cwd,e.hooksConfig.filePath),s=n.generateConfig(t),a=Object.keys(s).some(c=>{let p=s[c];return p!=null&&(typeof p!="object"||Object.keys(p).length>0)});if(a){await this.ensureDirectoryExists(o);let c=await this.readConfig(o),p=this.mergeHooksConfig(c,s);await this.writeConfig(o,p);}let l;if(n.generateAuxiliaryFiles){let c=n.generateAuxiliaryFiles(t);c&&(await this.writeAuxiliaryFiles(c),l=Array.from(c.keys()));}return {toolId:e.id,toolDisplayName:e.displayName,success:!0,configuredPath:a?o:void 0,auxiliaryPaths:l}}catch(o){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:o instanceof Error?o.message:String(o)}}}async ensureDirectoryExists(e){let t=P__default.dirname(e);await B__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await w.fileIsReadable(e))return {};let n=await w.readFile(e);return JSON.parse(n)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let n=e.hooks??{},o=t.hooks??{},s={...n,...o},a={...e,hooks:s};return t.version!==void 0&&(a.version=t.version),a}async writeConfig(e,t){let n=JSON.stringify(t,null," ");n=n.replace(/\r\n/g,`
|
|
123
|
+
`),n.endsWith(`
|
|
124
|
+
`)||(n+=`
|
|
125
|
+
`),await w.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let o=P__default.join(this.cwd,t);await this.ensureDirectoryExists(o);let s=n.replace(/\r\n/g,`
|
|
169
126
|
`);s.endsWith(`
|
|
170
127
|
`)||(s+=`
|
|
171
|
-
`),await
|
|
172
|
-
`;)t++;else if(i[t]==="/"&&t+1<
|
|
128
|
+
`),await w.writeFile(o,s),(t.endsWith(".sh")||s.startsWith("#!"))&&await B__default.chmod(o,493);}}};});var Yi=h(()=>{Ji();qi();Fr();});function Xi(i,e){let t=Ie__default.homedir(),n=process.platform,o=Ml[i];switch(n){case "darwin":return P__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return P__default.join(process.env.APPDATA||P__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return P__default.join(t,".config",o,"User/globalStorage",e)}}function Qi(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:P__default.join(Xi(t,i),"settings","cline_mcp_settings.json")}))}function Zi(){return P__default.join(Xi("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Ml,eo=h(()=>{Ml={stable:"Code",insiders:"Code - Insiders"};});function Mr(i){return Dr.find(e=>e.id===i)}var to,Ul,Dr,Ur=h(()=>{eo();to={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Ul={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},Dr=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",skipMcpServer:true,permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:Ul},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Zi(),isGlobalConfig:true,getGlobalConfigPaths:Qi,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false},hooksConfig:{filePath:".clinerules/hooks/placeholder",schemaVersion:1,adapterId:"cline"}},{id:"codex-cli",displayName:"Codex CLI",configPath:".codex/config.toml",format:"toml",mcpServersKeyPath:["mcp_servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"$CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{enabled_tools:["code_intel"]},envPolicyConfig:{includeOnlyKeyPath:["shell_environment_policy","include_only"],envVarsToAllow:["CONSTELLATION_ACCESS_KEY"],globalConfigPath:"~/.codex/config.toml"}},{id:"copilot-cli",displayName:"Copilot CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","marketplace","add","ShiftinBits/constellation-copilot"]},pluginPostInstallCommands:[{command:"copilot",args:["plugin","install","constellation@constellation-plugins"]}]},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"},hooksConfig:{filePath:".cursor/hooks.json",schemaVersion:1,adapterId:"cursor"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"gemini",args:["extensions","install","https://github.com/ShiftinBits/constellation-gemini"]},pluginUpdateCommand:{command:"gemini",args:["extensions","update","constellation"]},pluginPostInstallCommands:[{command:"gemini",args:["extensions","disable","--scope","user","constellation"]},{command:"gemini",args:["extensions","enable","--scope","workspace","constellation"]}]},{id:"jetbrains-ai",displayName:"JetBrains",configPath:".ai/mcp/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}},{id:"kilo-code",displayName:"Kilo Code",configPath:".kilocode/mcp.json",format:"json",permissionsConfig:{filePath:".kilocode/mcp.json",allowKeyPath:["mcpServers","constellation","alwaysAllow"],allowValue:"code_intel"},mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"opencode",displayName:"OpenCode",configPath:"opencode.jsonc",format:"jsonc",mcpServersKeyPath:["mcp"],skipMcpServer:true,pluginConfig:{pluginKeyPath:["plugin"],pluginValue:"@constellationdev/opencode"},configDefaults:{$schema:"https://opencode.ai/config.json"}},{id:"tabnine",displayName:"Tabnine",configPath:".tabnine/mcp_servers.json",format:"json",mcpServersKeyPath:["mcpServers"]},{id:"vscode-copilot",displayName:"VSCode",configPath:".vscode/mcp.json",format:"json",mcpServersKeyPath:["servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}}];});async function ro(){if(!Br)try{let i=await import('@iarna/toml');Br={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Br}function Gl(i){let e="",t=0,n=i.length;for(;t<n;)if(i[t]==='"'){for(e+='"',t++;t<n&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<n&&(e+=i[t++])):e+=i[t++];t<n&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<n&&i[t+1]==="/")for(t+=2;t<n&&i[t]!==`
|
|
129
|
+
`;)t++;else if(i[t]==="/"&&t+1<n&&i[t+1]==="*"){for(t+=2;t<n&&!(i[t]==="*"&&t+1<n&&i[t+1]==="/");)t++;t<n&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Br,Bt,no=h(()=>{J();Ur();Br=null;Bt=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=P__default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){await this.ensureDirectoryExists(t);let s=await this.readConfig(t,e.format);if(e.configDefaults)for(let[a,l]of Object.entries(e.configDefaults))a in s||(s[a]=l);e.pluginConfig&&(s=this.addPluginToArray(s,e.pluginConfig)),e.skipMcpServer||(s=this.addConstellationServer(s,e),await this.configureEnvPolicy(s,e)),await this.writeConfig(t,s,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let o;return n?o=t:e.permissionsConfig?o=P__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=P__default.join(this.cwd,e.marketplaceConfig.filePath):o=t,{tool:e,success:!0,configuredPath:o}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),n=[];for(let{displayName:o,settingsPath:s}of t)try{await this.ensureDirectoryExists(s);let a=await this.readConfig(s,e.format);a=this.addConstellationServer(a,e),await this.writeConfig(s,a,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:s});}catch(a){let l=a instanceof Error?a.message:String(a);l.includes("ENOENT")||l.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:l});}return n}async ensureDirectoryExists(e){let t=P__default.dirname(e);await B__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await w.fileIsReadable(e))return {};let o=await w.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(Gl(o)):(await ro()).parse(o)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let a=0;a<t.mcpServersKeyPath.length-1;a++){let l=t.mcpServersKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[o]||typeof n[o]!="object")&&(n[o]={});let s=n[o];if(!s.constellation){let a=t.mcpServerConfigOverride??to,l={...a};if(t.mcpServerExtras&&Object.assign(l,t.mcpServerExtras),t.mcpEnv){let c=t.mcpEnvKey??"env",p=a[c];l[c]={...p,...t.mcpEnv};}s.constellation=l;}return e}async writeConfig(e,t,n){let o;n==="json"||n==="jsonc"?o=JSON.stringify(t,null,2):o=(await ro()).stringify(t),o=o.replace(/\r\n/g,`
|
|
173
130
|
`),o.endsWith(`
|
|
174
131
|
`)||(o+=`
|
|
175
|
-
`),await
|
|
176
|
-
`);}async configureMarketplace(e){let t=P__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let
|
|
177
|
-
`);}deepMerge(e,t){let
|
|
132
|
+
`),await w.writeFile(e,o);}async configurePermissions(e){let t=P__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await w.fileIsReadable(t)){let c=await w.readFile(t);n=JSON.parse(c);}}catch{}let o=n;for(let l=0;l<e.allowKeyPath.length-1;l++){let c=e.allowKeyPath[l];(!o[c]||typeof o[c]!="object")&&(o[c]={}),o=o[c];}let s=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(o[s])||(o[s]=[]);let a=o[s];a.includes(e.allowValue)||a.push(e.allowValue),await w.writeFile(t,JSON.stringify(n,null," ")+`
|
|
133
|
+
`);}async configureMarketplace(e){let t=P__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await w.fileIsReadable(t)){let s=await w.readFile(t);n=JSON.parse(s);}}catch{}n=this.deepMerge(n,e.config),await w.writeFile(t,JSON.stringify(n,null," ")+`
|
|
134
|
+
`);}deepMerge(e,t){let n={...e};for(let o of Object.keys(t)){let s=t[o],a=e[o];s&&typeof s=="object"&&!Array.isArray(s)&&a&&typeof a=="object"&&!Array.isArray(a)?n[o]=this.deepMerge(a,s):n[o]=s;}return n}addPluginToArray(e,t){let n=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let s=n[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,o),s&&await this.updateGlobalEnvPolicy(s,n,o,t.format);}addToEnvPolicyWhitelist(e,t,n){let o=e;for(let l=0;l<t.length-1;l++){let c=t[l];if(!o[c]||typeof o[c]!="object")return;o=o[c];}let s=t[t.length-1];if(!Array.isArray(o[s]))return;let a=o[s];for(let l of n)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,n,o){let s=e.replace(/^~/,Ie__default.homedir()),a=await this.readConfig(s,o);if(Object.keys(a).length===0)return;let l=JSON.stringify(a);this.addToEnvPolicyWhitelist(a,t,n);let c=JSON.stringify(a);l!==c&&await this.writeConfig(s,a,o);}};});function Pe(i,e){let t=P__default.normalize(i),n=P__default.normalize(e);return t.startsWith(n+P__default.sep)?P__default.relative(e,i):i}var ql,Xe,so=h(()=>{zi();Oe();Yi();Rt();no();Ur();J();D();ut();ct();ql=promisify(execFile);Xe=class extends oe{async run(e={}){try{if(console.log(`${te}Initializing project configuration...
|
|
178
135
|
`),!await this.git.isGitAvailable())throw new Error(`${b} Could not find git client installation.
|
|
179
|
-
${v} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let
|
|
136
|
+
${v} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=P__default.join(process.cwd(),"constellation.json"),o=null,s=await w.fileIsReadable(n);if(s)try{let R=await w.readFile(n);o=JSON.parse(R),console.log(`${v} Found existing constellation.json, current values will be used as defaults.
|
|
180
137
|
`);}catch{console.log(`${b} Existing constellation.json is invalid, starting fresh.
|
|
181
138
|
`);}if(!await this.git.isGitRepository())throw new Error(`${b} Current directory is not a git repository.
|
|
182
|
-
${v} Please run this command from the root directory of a git repository.`);let l=await this.git.getRootDir(),[c,
|
|
183
|
-
${
|
|
184
|
-
${C} Plugin + MCP configuration complete: ${c} configured`),
|
|
185
|
-
${v} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let
|
|
186
|
-
${v} Configuring AI hooks...`);let a=[];for(let c of s){let
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
${
|
|
193
|
-
|
|
139
|
+
${v} Please run this command from the root directory of a git repository.`);let l=await this.git.getRootDir(),[c,p]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:d}=c,m=p.filter(R=>R!==d),g=d?[d,...m]:m,f=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:R=>R.trim().length>0||"Project ID is required",theme:k}),y=await select({message:"Branch to index:",choices:g.map(R=>({name:R,value:R})),default:o?.branch??g[0],theme:k}),_=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:k})).reduce((R,O)=>(R[O]={fileExtensions:Me[O]||[]},R),{});console.log(""),console.log(`${v} Checking for LSP servers...`);for(let[R,O]of Object.entries(_)){let j=se.get(R);if(!j)continue;let V=!1,q="";if(gt(j.command)&&(V=!0,q="system"),!V){let N=P__default.join(ht,j.command);existsSync(N)&&(V=!0,q="managed");}if(V)console.log(` ${C} ${R}: Found ${j.command} (${q})`),O.lsp={command:j.command,args:j.args};else if(await confirm({message:`${R}: ${j.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:k}))try{console.log(` ${v} Installing ${j.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",sr,...j.npmPackages],{stdio:"pipe"}),console.log(` ${C} ${R}: Installed ${j.command}`),O.lsp={command:j.command,args:j.args};}catch{console.log(` ${E} ${R}: Installation failed`),O.lspEnrichment=!1;}else O.lspEnrichment=!1;}let S=Object.entries(_).filter(([,R])=>R.lspEnrichment!==!1).map(([R])=>R);S.length>0?console.log(`${C} Index enrichment enabled for: ${S.map(Ue).join(", ")}`):console.log(`${b} No language servers configured. Index enrichment will be skipped.`);let I={projectId:f.trim(),branch:y,languages:{..._},...S.length>0&&{lspEnrichment:!0}},L=JSON.stringify(I,void 0,2);await w.writeFile(n,L),console.log(`${C} ${s?"Updated":"Initialized"} configuration file at ${Pe(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${C} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&l&&await this.configureCICD(y,l);}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred";console.error(`${E} Failed to initialize configuration file.
|
|
140
|
+
${n}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:k}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:Dr.map(d=>({name:d.displayName,value:d.id})),required:true,theme:k}),n=new Bt(process.cwd()),o=[];for(let d of t){let m=Mr(d);if(m)if(console.log(` ${v} Configuring ${m.displayName}...`),m.pluginInstallCommand){let g=await this.executePluginInstall(m);o.push(g),g.success?console.log(` ${C} ${m.displayName} plugin installed successfully`):console.log(` ${b} ${m.displayName}: ${g.error}`);}else if(m.isGlobalConfig&&m.getGlobalConfigPaths){let g=await n.configureGlobalTool(m),f=false;for(let y of g)o.push(y),y.success?(f=true,console.log(` ${C} ${y.tool.displayName} configured at ${Pe(y.configuredPath,process.cwd())}`)):y.error&&console.log(` ${b} ${y.tool.displayName}: ${y.error}`);if(f){let y=m.id==="cline"?"global VS Code settings":"global settings";console.log(` ${v} Note: ${m.displayName} uses ${y} (not project-level)`);}if(g.length===0){let y=m.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${b} ${m.displayName}: ${y}`);}}else {let g=await n.configureTool(m);o.push(g),g.success?(console.log(` ${C} ${m.displayName} configured at ${Pe(g.configuredPath,process.cwd())}`),m.permissionsConfig&&console.log(` ${C} ${m.displayName} permissions set in ${m.permissionsConfig.filePath}`)):console.log(` ${b} ${m.displayName}: ${g.error}`);}}if(o.find(d=>d.tool.id==="claude-code"&&d.success)){let d=P__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(d),console.log(` ${C} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${b} Could not stage .claude/settings.json in git`);}}if(o.find(d=>d.tool.id==="codex-cli"&&d.success)){let d=P__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(d),console.log(` ${C} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(d=>d.tool.id==="opencode"&&d.success)){let d=P__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(d),console.log(` ${C} Added opencode.jsonc to staged changes in git`);}catch{}}let c=o.filter(d=>d.success).length,p=o.filter(d=>!d.success).length;console.log(`
|
|
141
|
+
${C} Plugin + MCP configuration complete: ${c} configured`),p>0&&console.log(`${b} ${p} tool(s) could not be configured`),await this.configureHooks(t,o),console.log(`
|
|
142
|
+
${v} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new qe(process.cwd()),o=jr(),s=e.map(c=>Mr(c)).filter(c=>c!==void 0&&c.hooksConfig!==void 0&&t.some(p=>p.tool.id===c.id&&p.success));if(s.length===0)return;console.log(`
|
|
143
|
+
${v} Configuring AI hooks...`);let a=[];for(let c of s){let p=await n.configureHooks(c,o);if(a.push(p),p.success){let d=p.configuredPath?[p.configuredPath]:p.auxiliaryPaths??[];if(d.length>0){let m=p.configuredPath?Pe(p.configuredPath,process.cwd()):P__default.dirname(d[0]);console.log(` ${C} ${c.displayName} hooks configured at ${m}`);for(let g of d){let f=P__default.isAbsolute(g)?Pe(g,process.cwd()):g;try{await this.git.stageFile(g),console.log(` ${C} Added ${f} to staged changes in git`);}catch{console.log(` ${b} Could not stage ${f} in git`);}}}else console.log(` ${C} ${c.displayName} hooks configured`);}else console.log(` ${b} ${c.displayName}: ${p.error}`);}let l=a.filter(c=>c.success).length;l>0&&console.log(`${C} Hooks configuration complete: ${l} configured`);}async executePluginInstall(e){let t=e.pluginInstallCommand;try{await this.runPluginCommand(t);}catch(n){let o=n;if(e.pluginUpdateCommand&&this.isAlreadyInstalledError(o)){console.log(` ${v} ${e.displayName} extension already installed, attempting update...`);try{await this.runPluginCommand(e.pluginUpdateCommand);}catch(s){let a=s;return {tool:e,success:false,error:this.formatPluginCommandError(e.pluginUpdateCommand.command,a)}}}else if(this.isAlreadyInstalledError(o)&&(e.pluginPostInstallCommands?.length??0)>0)console.log(` ${v} ${e.displayName} plugin source already configured, continuing...`);else return {tool:e,success:false,error:this.formatPluginCommandError(t.command,o)}}for(let n of e.pluginPostInstallCommands??[])try{await this.runPluginCommand(n);}catch(o){let s=o;return {tool:e,success:false,error:this.formatPluginCommandError(n.command,s)}}return {tool:e,success:true}}async runPluginCommand(e){await ql(e.command,e.args,{timeout:3e4,env:process.env});}isAlreadyInstalledError(e){let t=`${e.message??""}
|
|
144
|
+
${e.stderr??""}`.toLowerCase();return t.includes("already installed")||t.includes("already exists")||t.includes("already registered")}formatPluginCommandError(e,t){return t.code==="ENOENT"?`${e} not found. Is ${e} installed and on your PATH?`:t.killed?"Plugin installation timed out after 30 seconds":t.stderr?`Plugin installation failed: ${t.stderr.trim()}`:`Plugin installation failed: ${t.message}`}async configureCICD(e,t){if(!await confirm({message:"Set up a CI/CD pipeline to automatically index your project?",default:true,theme:k}))return;let o=new Ke(t),s=await o.detectPlatforms(),a;if(s.length===1){let d=s[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${d}. Configure Constellation CI/CD for this platform?`,default:true,theme:k}))return;a=s[0];}else a=await select({message:"Select CI/CD platform:",choices:[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],theme:k});let l=a==="github"?await o.githubWorkflowExists():await o.gitlabJobExists();if(l&&!await confirm({message:"Constellation CI/CD configuration already exists. Overwrite?",default:false,theme:k})){console.log(`${v} Skipping CI/CD configuration`);return}let c;try{c=a==="github"?await o.createGitHubWorkflow(e):await o.createOrMergeGitLabCI(e);}catch(d){console.log(`${b} Failed to configure CI/CD pipeline: ${d.message}`);return}let p=Pe(c,process.cwd());console.log(a==="github"?`${C} Created ${p}`:`${C} ${l?"Updated":"Created"} ${p} with Constellation indexing`);try{await this.git.stageFile(c),console.log(`${C} Added ${p} to staged changes in git`);}catch{console.log(`${b} Could not stage ${p} in git`);}a==="github"?(console.log(`${v} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${v} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(n=>({...n,checked:t.includes(n.value)}))}};});var Ht,ao=h(()=>{lt();At();J();D();Ht=class i{constructor(e,t,n,o,s){this.branch=e;this.languages=t;this.projectId=n;this.exclude=o;this.lspEnrichment=s;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await w.fileIsReadable(e)){let n=await w.readFile(e),o=JSON.parse(n),s=new i(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${E} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let n of t.fileExtensions)if(!n.startsWith("."))throw new Error(`Invalid configuration: file extension "${n}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new ne("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new ne(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var Gt,Gr,zr,Wr,zt,co=h(()=>{J();Gt=class{getVariable(e){return Promise.resolve(process.env[e])}getSourceFile(){}isCIEnvironment(){return this.isCI()}isCI(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}validateInput(e,t){if(!e||typeof e!="string")throw new Error("Invalid key provided");if(t==null)throw new Error("Invalid value provided");if(!/^[A-Z_][A-Z0-9_]*$/i.test(e))throw new Error("Environment variable name must contain only letters, numbers, and underscores");if(t.includes("\0"))throw new Error("Value contains invalid characters");if(t.includes(`
|
|
145
|
+
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Gr=class extends Gt{async getVariable(e){try{let t=await this.queryRegistry("HKCU\\Environment",e);if(t)return process.env[e]=t,t;delete process.env[e];return}catch{return}}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
|
|
146
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,o)=>{let s=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0?n():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let o=(await new Promise((s,a)=>{let l=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",p="";l.stdout?.on("data",d=>{c+=d.toString();}),l.stderr?.on("data",d=>{p+=d.toString();}),l.on("close",d=>{d===0?s(c):a(new Error(`reg query failed: ${p}`));}),l.on("error",d=>{a(d);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},zr=class extends Gt{userConfigFiles;constructor(){super(),this.userConfigFiles=[P.join(Ie.homedir(),".zshenv"),P.join(Ie.homedir(),".profile")];}getSourceFile(){let e=process.env.SHELL??"";return e.endsWith("/zsh")||e.endsWith("/zsh5")?this.userConfigFiles.find(t=>t.endsWith(".zshenv")):this.userConfigFiles.find(t=>t.endsWith(".profile"))}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
|
|
147
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),o=`export ${e}="${n}"`;try{for(let s of this.userConfigFiles)await this.writeToConfigFile(s,e,o);process.env[e]=t;}catch(s){throw new Error(`Failed to set environment variable ${e}: ${s}`)}}async writeToConfigFile(e,t,n){let o="";try{o=await w.readFile(e,"utf-8");}catch{}let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^export ${s}=.*$`,"gm");a.test(o)?o=o.replace(a,n):o=o.trimEnd()+`
|
|
148
|
+
`+n+`
|
|
149
|
+
`,await w.writeFile(e,o);}},Wr=class{static create(){let e=Ie.platform();switch(e){case "win32":return new Gr;case "darwin":case "linux":return new zr;default:throw new Error(`Unsupported platform: ${e}`)}}},zt=class{manager;constructor(){this.manager=Wr.create();}async setKey(e,t){await this.manager.setVariable(e.toUpperCase(),t);}async getKey(e){return this.manager.getVariable(e.toUpperCase())}isCI(){return this.manager.isCIEnvironment()}getSourceFile(){return this.manager.getSourceFile()}};});var Wt,po=h(()=>{Wt=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let o of n.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=P__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function Xl(){let i=Ie.platform();if(i==="darwin")return P.join(Ie.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||P.join(Ie.homedir(),"AppData","Local");return P.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||P.join(Ie.homedir(),".cache");return P.join(e,"constellation")}}var Ql,Zl,ec,Ze,Jr=h(()=>{Ql=Xl(),Zl="update-state.json",ec=1440*60*1e3,Ze=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??Ql,this.stateFile=P.join(this.stateDir,Zl);}async load(){if(this.state)return this.state;try{let e=await B.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await B.mkdir(this.stateDir,{recursive:!0}),await B.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>ec}async recordCheck(){let e=await this.load();e.lastCheckTimestamp=Date.now(),await this.save(e);}async recordDecline(e){let t=await this.load();t.lastDeclinedVersion=e,t.lastDeclinedTimestamp=Date.now(),await this.save(t);}async wasVersionDeclined(e){return (await this.load()).lastDeclinedVersion===e}async clear(){try{await B.unlink(this.stateFile),this.state=null;}catch{}}};});var et,Kr=h(()=>{et=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...n]=this.getUpdateCommand(e);return new Promise(o=>{let s=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});s.on("close",a=>{o(a===0);}),s.on("error",()=>{o(false);});})}};});var tt,Vr=h(()=>{ct();D();tt=class{async promptForUpdate(e,t,n){console.log(""),console.log(u.cyan("\u2501".repeat(60))),console.log(`${te} ${u.bold("Update Available!")}`),console.log(""),console.log(` Current version: ${u.dim(e)}`),console.log(` Latest version: ${u.green.bold(t)}`),console.log(""),console.log(` ${u.dim(`Package manager: ${n}`)}`),console.log(u.cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:k})}catch{return false}}};});async function qr(i){return new Kt().check(i)}var nc,Jt,ic,Kt,uo=h(()=>{D();Jr();Kr();Vr();nc="https://registry.npmjs.org",Jt="@constellationdev/cli",ic=5e3,Kt=class{cache;packageManager;prompter;constructor(){this.cache=new Ze,this.packageManager=new et,this.prompter=new tt;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,n=setTimeout(()=>t.abort(),ic);try{let o=await fetch(`${nc}/${Jt}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let a=(await o.json()).version;return {current:e,latest:a,hasUpdate:this.isNewerVersion(a,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=a=>a.split("-")[0],o=n(e).split(".").map(Number),s=n(t).split(".").map(Number);for(let a=0;a<3;a++){let l=o[a]||0,c=s[a]||0;if(l>c)return true;if(l<c)return false}return false}async performUpdate(){return console.log(`
|
|
150
|
+
${v} Updating ${Jt}...
|
|
151
|
+
`),await this.packageManager.executeUpdate(Jt)?(console.log(`
|
|
194
152
|
${C} Update complete! Please re-run your command.
|
|
195
153
|
`),true):(console.log(`
|
|
196
|
-
${b} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(
|
|
197
|
-
`),false)}};});var
|
|
198
|
-
Modified: ${o.modified}, Created: ${o.created}, Deleted: ${o.deleted}, Conflicted: ${o.conflicted}, Staged: ${o.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let o=await this.git.status();if(o.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",o.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${o.conflicted.length} file(s): ${o.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let
|
|
199
|
-
${i?.message??String(i)}`),process.exit(1);});
|
|
154
|
+
${b} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Jt)}
|
|
155
|
+
`),false)}};});var mo=h(()=>{Jr();Kr();Vr();uo();});function sc(){return oc.some(i=>!!process.env[i])}function ac(){return !!process.stdout.isTTY}function go(){return !sc()&&ac()}var oc,fo=h(()=>{oc=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});var rt,ho=h(()=>{rt=class{git;constructor(e){let t={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(t);}async getLatestCommitHash(){let e=await this.git.log({maxCount:1});if(!e.latest)throw new Error("No commits found in repository");return e.latest.hash}async getCommitTimestamp(){let t=(await this.git.raw(["log","-1","--format=%aI"])).trim();if(!t)throw new Error("No commits found in repository");return t}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},o=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);for(let s of o){let a=s.split(" ");if(a.length<2)continue;let l=a[0];l==="A"?n.added.push(a[1]):l==="M"?n.modified.push(a[1]):l==="D"?n.deleted.push(a[1]):l.startsWith("R")&&a.length>=3&&n.renamed.push({from:a[1],to:a[2]});}return n}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(n=>n.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,n=e.current;return {clean:t,currentBranch:n}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let o={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw console.error("\u274C Cannot pull: Working directory has uncommitted changes"),console.error(" Details:",JSON.stringify(o,null,2)),e.conflicted.length>0&&console.error(" \u26A0\uFE0F Conflicted files:",e.conflicted.join(", ")),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
|
|
156
|
+
Modified: ${o.modified}, Created: ${o.created}, Deleted: ${o.deleted}, Conflicted: ${o.conflicted}, Staged: ${o.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let o=await this.git.status();if(o.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",o.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${o.conflicted.length} file(s): ${o.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",n.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(console.error("\u274C Pull failed due to merge conflicts"),console.error(' Run "git status" to see conflicted files'),console.error(' Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?console.error("\u274C Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?console.error("\u274C Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?console.error("\u274C Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&console.error("\u274C Pull failed: Uncommitted changes in working directory"),new Error(`Git pull operation failed: ${e.message}`,{cause:e})):new Error(`Git pull operation failed: ${String(e)}`)}}};});var dc={};var yo,Xr,Qr,nt,bo=h(async()=>{lt();In();Ui();so();ao();co();po();Rt();mo();qt();pt();fo();ho();D();process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${E} An unexpected error occurred during the index attempt:
|
|
157
|
+
${i?.message??String(i)}`),process.exit(1);});yo=globalThis.__constellationVersion??(()=>{let i=P__default.dirname(fileURLToPath(import.meta.url)),e=P__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})();if(go()){let i=process.argv[2];["auth","help","init","index"].includes(i)?er(i):er(),it.includes(i)||await qr(yo)&&process.exit(0);}Xr=process.cwd(),Qr=new zt,nt=new Command;nt.name("constellation").description("Connecting stars in your code into intelligent patterns").version(yo);nt.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async i=>{try{let t={GitClient:new rt(Xr)};await new Xe(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){console.error(`${E} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});nt.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async i=>{try{let e={Environment:Qr};await new Fe(e).run(i.manual);}catch(e){console.error(`${E} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});nt.command("index").description("Create or update the Constellation data indices for the current project").option("--full","Conduct a full project re-index").option("--incremental","Conduct an incremental project index update").option("--dirty","Skip git validation checks (branch and working tree status)").option("--no-enrich","Skip LSP enrichment (only perform parse tree indexing)").action(async i=>{try{let e=await Ht.loadFromFile(P__default.join(Xr,"constellation.json")),t=new rt(Xr),n=new It(e),o=new Wt(e),s={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:o,Environment:Qr},a=Qr.isCI(),l=i.full||!i.incremental&&a,c=i.dirty||!1,p=i.enrich===!1;!i.full&&!i.incremental&&a&&console.log(`${v} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new Je(s).run(l,c,p);}catch(e){!(e instanceof T)&&!(e instanceof U)&&console.error(`${E} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});nt.parse();});var wo=/^>=\s*\d+\.\d+\.\d+$/;function tn(i,e=process.version){if(!wo.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),n=e.replace(/^v/,""),o=t.split(".").map(Number),s=n.split(".").map(Number),a=true;for(let l=0;l<3;l++){let c=o[l]||0,p=s[l]||0;if(p>c)break;if(p<c){a=false;break}}return {compatible:a,current:e,required:i}}qt();var yc=dirname(fileURLToPath(import.meta.url)),bc=join(yc,"..","package.json"),Zr=JSON.parse(readFileSync(bc,"utf-8")),vc=process.argv[2];if(!it.includes(vc)&&Zr.engines?.node){let i=tn(Zr.engines.node);i.compatible||(console.error(`Error: Constellation CLI requires Node.js ${i.required} (current: ${i.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=Zr.version;await bo().then(()=>dc);
|