@constellationdev/cli 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/main.js +64 -61
- package/package.json +3 -2
package/dist/main.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {bold,blue,gray,green,red,dim,yellow,cyan}from'yoctocolors';import*as
|
|
2
|
+
import {bold,blue,gray,green,red,dim,yellow,blueBright,cyan}from'yoctocolors';import*as Oe from'os';import Oe__default from'os';import {execFile,execFileSync,spawn}from'child_process';import {promisify,stripVTControlCharacters}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import {confirm,password,input,select,checkbox}from'@inquirer/prompts';import {z as z$1}from'zod';import {Readable,Transform}from'stream';import {base32}from'@scure/base';import*as je from'fs';import {readFileSync,existsSync,realpathSync}from'fs';import {buffer}from'stream/consumers';import {pipeline}from'stream/promises';import*as _n from'zlib';import _n__default from'zlib';import {Agent,fetch as fetch$1}from'undici';import*as R from'path';import R__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as Q from'fs/promises';import Q__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import Hc from'tree-sitter-go';import zc from'tree-sitter-javascript';import Kc from'tree-sitter-python';import Vc from'tree-sitter-typescript';import Mp from'tree-sitter';import Ao from'ignore';import {performance}from'perf_hooks';import Vp from'yocto-spinner';import {parseDocument,isMap,isSeq,stringify}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var ua=Object.defineProperty;var g=(i,e)=>()=>(i&&(e=i(i=0)),e);var li=(i,e)=>{for(var t in e)ua(i,t,{get:e[t],enumerable:true});};var Dt,Vr=g(()=>{Dt=["help","--help","-h","--version","-V","-v"];});function ui(){let i=process.env;return i.FORCE_COLOR&&i.FORCE_COLOR!=="0"&&i.FORCE_COLOR!=="false"?true:i.NO_COLOR?false:!!process.stdout.isTTY}function di(){let i=process.env;if(i.NO_COLOR)return false;if(i.FORCE_COLOR==="3")return true;let e=i.COLORTERM?.toLowerCase();if(e==="truecolor"||e==="24bit"||i.WT_SESSION)return true;let t=i.TERM?.toLowerCase()??"";return !!(t.includes("truecolor")||t.includes("24bit")||t==="xterm-kitty"||t==="alacritty"||t==="wezterm")}function pi(i,e,t){return [Math.round(i[0]+(e[0]-i[0])*t),Math.round(i[1]+(e[1]-i[1])*t),Math.round(i[2]+(e[2]-i[2])*t)]}function se(i,e=0,t=false){if(ui()&&!di())return blueBright(i);let r=[],o=0;for(let p of i.matchAll(ha))p.index>o&&r.push({ansi:false,value:i.slice(o,p.index)}),r.push({ansi:true,value:p[0]}),o=p.index+p[0].length;o<i.length&&r.push({ansi:false,value:i.slice(o)});let a=[...r.filter(p=>!p.ansi).map(p=>p.value).join("")],l=mt.length,c=a.length,u=0;return r.map(p=>p.ansi?p.value:[...p.value].map(d=>{let m=u++;if(d===" ")return d;let f,h,S;if(t){let v=(m+e)%l/l*(l-1),y=Math.floor(v),C=Math.min(y+1,l-1),P=v-y;[f,h,S]=pi(mt[y],mt[C],P);}else {let v=(c>1?m/(c-1):0)*(l-1),y=Math.floor(v),C=Math.min(y+1,l-1),P=v-y;[f,h,S]=pi(mt[y],mt[C],P);}return fa(f,h,S,d)}).join("")).join("")}var X,mt,fa,ha,He=g(()=>{X={info:i=>blue(i),success:i=>green(i),warn:i=>yellow(i),error:i=>red(i),accent:i=>bold(blue(i)),muted:i=>gray(i),dim:i=>dim(i)},mt=[[142,68,173],[100,110,205],[74,144,226],[90,160,235],[110,180,245],[130,200,250],[110,180,245],[90,160,235],[74,144,226],[100,110,205],[142,68,173]];fa=(i,e,t,r)=>!ui()||!di()?r:`\x1B[38;2;${i};${e};${t}m${r}\x1B[0m`;ha=/\x1b\[[0-9;]*m/g;});function ya(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Oe.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 va,ba,Sa,wa,xa,Ca,Ea,_a,Pa,Ia,Ra,Na,ze,E,ae,O,de,xe,Yr,z=g(()=>{He();va="\u2714",ba="\u2717",Sa="\u26A0",wa="\u2139",xa="\u26A1",Ca="\u29D7",Ea="[OK]",_a="[ERR]",Pa="[WARN]",Ia="[INFO]",Ra="[>>]",Na="[WAIT]",ze=ya(),E=X.success(ze?va:Ea),ae=X.error(ze?ba:_a),O=X.warn(ze?Sa:Pa),de=X.info(ze?wa:Ia),xe=X.warn(ze?xa:Ra),Yr=X.info(ze?Ca:Na);});var M,Ut=g(()=>{He();z();M={prefix:{idle:blue("\u25C6"),done:E},style:{highlight:i=>blue(i),answer:i=>green(i),error:i=>red(`${ae} ${i}`),help:i=>gray(i)},icon:{checked:green("\u25FC"),unchecked:gray("\u25FB"),cursor:blue("\u276F")}};});async function gi(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await Xr("open",[i]),!0;case "linux":return await Xr("xdg-open",[i]),!0;case "win32":return await Xr("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var Xr,fi=g(()=>{Xr=promisify(execFile);});function Fa(i,e){if(!e)return false;let t,r;try{t=new URL(e),r=new URL(i);}catch{return false}return r.protocol!=="http:"&&r.protocol!=="https:"?false:r.origin===t.origin}function hi(i={}){let e=i.allowedOrigin;return new Promise((t,r)=>{let o=createServer(),s,a=false;o.listen(0,"127.0.0.1",()=>{let l=o.address();if(!l||typeof l=="string"){o.close(),r(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,u=3e5){return new Promise((p,d)=>{s=setTimeout(()=>{s=void 0,a=true,o.close(),o.closeAllConnections(),d(new Error("Authentication timed out"));},u),o.on("request",(m,f)=>{let h=new URL(m.url??"/",`http://127.0.0.1:${l.port}`);if(h.pathname!=="/callback"){f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not found");return}let S=h.searchParams.get("key");if(h.searchParams.get("state")!==c){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid state parameter");return}if(!S||!ja.test(S)){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid key format");return}if(a)return;a=true;let y=h.searchParams.get("return_url");y&&Fa(y,e)?(f.writeHead(302,{Location:y}),f.end()):(f.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),f.end(Aa)),s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections(),p(S);});})}});}),o.on("error",l=>{r(l);});})}var ja,Aa,yi=g(()=>{ja=/^ak:[0-9a-f]{32}$/i,Aa=`<!DOCTYPE html>
|
|
3
3
|
<html><head><title>Authentication Successful</title></head>
|
|
4
|
-
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function
|
|
5
|
-
`);}function
|
|
6
|
-
${
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
${
|
|
11
|
-
${
|
|
12
|
-
`):
|
|
4
|
+
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function Qr(i){process.stdout.write(i+`
|
|
5
|
+
`);}function Gt(i,e){let t=`${i} \u203A ${e}`;Qr(`${se("\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\u2500\u2500\u2500\u2500\u256E")}
|
|
6
|
+
${se("\u2502 \u2580\u2584 \u2588\u2580\u2580 \u2588\u2580\u2588 \u2588\u2580\u2588 \u2588\u2580\u2580 \u2580\u2588\u2580 \u2588\u2580\u2580 \u2588 \u2588 \u2588\u2580\u2588 \u2580\u2588\u2580 \u2580\u2588\u2580 \u2588\u2580\u2588 \u2588\u2580\u2588 \u2584 \u2584 \u2588\u2580\u2580 \u2588 \u2580\u2588\u2580 \u2502")}
|
|
7
|
+
${se("\u2502 \u2584\u2580 \u2588 \u2588 \u2588 \u2588 \u2588 \u2580\u2580\u2588 \u2588 \u2588\u2580 \u2588 \u2588 \u2588\u2580\u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2580 \u2584\u2580 \u2584\u2580 \u2588 \u2588 \u2588 \u2502")}
|
|
8
|
+
${se("\u2502 \u2580 \u2580\u2580\u2580 \u2580\u2580\u2580 \u2580\u2580\u2580 \u2580 \u2580 \u2580\u2580\u2580 \u2580 \u2580\u2580\u2580 \u2580\u2580\u2580 \u2580\u2580\u2580 \u2580 \u2580 \u2580 \u2580\u2580\u2580 \u2580\u2580\u2580 \u2580 \u2580 \u2580 \u2580 \u2580 \u2580\u2580\u2580 \u2580\u2580\u2580 \u2580\u2580\u2580 \u2502")}
|
|
9
|
+
${se("\u2502 CONSTELLATIONDEV.IO \u2502")}`),e&&e.length>0?Qr(`${se(`\u251C\u2500${"\u2500".repeat(t.length)}\u2500\u252C\u2500${"\u2500".repeat(78-t.length)}\u256F`)}
|
|
10
|
+
${se(`\u2502 ${bold(t)} \u2502${" ".repeat(80-t.length)}`)}
|
|
11
|
+
${se(`\u2570\u2500${"\u2500".repeat(t.length)}\u2500\u256F${" ".repeat(80-t.length)}`)}
|
|
12
|
+
`):Qr(se("\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\u2500\u2500\u2500\u2500\u256F"));}var vi=g(()=>{He();});var Ce,bi,Bt=g(()=>{vi();Ce="CONSTELLATION_ACCESS_KEY",bi="CONSTELLATION_WEB_URL";});var Ee,Wt=g(()=>{Ee=class{git;config;langRegistry;env;reporter;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment,this.reporter=e.Reporter;}};});function Ua(i){return Ma.test(i)}function Ga(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Ma,gt,wi=g(()=>{Ut();fi();yi();Bt();z();Wt();Ma=/^ak:[0-9a-f]{32}$/i;gt=class extends Ee{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(this.reporter.log(`${xe} Configuring access key authentication...
|
|
13
13
|
`),this.env.isCI()){this.reporter.error(`Cannot configure authentication in CI/CD environments
|
|
14
14
|
|
|
15
|
-
The ${
|
|
15
|
+
The ${Ce} environment variable must be configured
|
|
16
16
|
directly in your pipeline settings:
|
|
17
17
|
|
|
18
18
|
- GitHub Actions: Repository Settings -> Secrets and variables -> Actions
|
|
@@ -20,46 +20,49 @@ ${te(`\u2570\u2500${"\u2500".repeat(t.length)}\u2500\u256F${" ".repeat(80-t.leng
|
|
|
20
20
|
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
21
21
|
- Jenkins: Manage Jenkins -> Credentials
|
|
22
22
|
- CircleCI: Project Settings -> Environment Variables
|
|
23
|
-
`);return}if(await this.env.getKey(
|
|
24
|
-
${o}`);}}async manualAuthFlow(){let e,t=0,r=3;for(;t<r;){if(e=(await password({message:"Constellation Access Key:",theme:
|
|
23
|
+
`);return}if(await this.env.getKey(Ce)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:M})){this.reporter.log(`${E} Keeping existing Constellation access key`);return}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let r=t.message??"An unexpected error occurred",o=Ga(r);this.reporter.error(`Failed to store Constellation access key
|
|
24
|
+
${o}`);}}async manualAuthFlow(){let e,t=0,r=3;for(;t<r;){if(e=(await password({message:"Constellation Access Key:",theme:M})).trim(),!e){this.reporter.warn("Access key cannot be empty."),t++;continue}if(!Ua(e)){if(t++,t<r)this.reporter.warn(`Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
25
25
|
Attempts remaining: ${r-t}`);else {this.reporter.error(`Invalid access key format after ${r} attempts.
|
|
26
|
-
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[
|
|
26
|
+
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[bi]||"https://app.constellationdev.io",{port:r,waitForCallback:o}=await hi({allowedOrigin:t}),s=`${t}/auth/cli?callback_port=${r}&state=${e}`;this.reporter.info("Opening browser for authentication..."),await gi(s)||this.reporter.warn(`Could not open browser automatically.
|
|
27
27
|
Please open this URL manually:
|
|
28
28
|
|
|
29
29
|
${s}
|
|
30
|
-
`),this.reporter.info("Waiting for authentication... (press Ctrl+C to cancel)");try{let l=await o(e);await this.storeKey(l);}catch{this.reporter.error("Authentication timed out.\n Try again or use `constellation auth --manual` to paste your key directly.");}}async storeKey(e){await this.env.setKey(
|
|
30
|
+
`),this.reporter.info("Waiting for authentication... (press Ctrl+C to cancel)");try{let l=await o(e);await this.storeKey(l);}catch{this.reporter.error("Authentication timed out.\n Try again or use `constellation auth --manual` to paste your key directly.");}}async storeKey(e){await this.env.setKey(Ce,e),this.reporter.log(`${E} Stored access key in ${Ce} user environment variable`);let t=this.env.getSourceFile();t&&this.reporter.info(`To activate in this session, run:
|
|
31
31
|
|
|
32
32
|
source ${t}
|
|
33
33
|
|
|
34
|
-
New terminal sessions will load it automatically.`),Pe.platform()==="darwin"&&this.reporter.info("Already-running desktop apps (Claude Desktop, Codex, etc.) must be quit and relaunched to see the new value.");}};});var ea,oe,Xe,ta,Ae,Qe,ra,na,ia,Ze,oa,sa,aa,la,ca,pa,ua,da,ma,ga,fa,ha,ya,ba,va,Sa,wa,Kn,Ca,xa,Ea,_a,Pa,Ia,Na,Ra,Ta,La,ja,Aa,ka,Fa,$a,Da,Jn,Oa,Ma,Ir,Ua,Ga,Ba,Ha,et,Wa,za,Ka,Va,Ja,qn,qa,Ya,Pt,Yn,Vn,Xa,Qa,Za,Nr,Xn,el,tl,rl,nl,Rr,il,ol,sl,al,ll,cl,Qn,Zn,ei,ti,pl,ul,dl,ri,ni,tt=f(()=>{ea=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()}),oe=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"]),Xe=z.enum(["low","medium","high","critical"]),ta=z.enum(["low","moderate","high","very_high"]),Ae=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:ta}),Qe=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()}),Qe.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())}),ra=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),na=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),ia=z.object({nodes:z.array(ra),edges:z.array(na),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),Ze=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"]}),oa=Qe.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:Ae.optional(),languageMetadata:oe.optional()}),z.object({symbols:z.array(oa),pagination:ea.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()}),sa=Qe.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:Ae.optional(),languageMetadata:oe.optional()}),aa=Qe.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),la=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())}),ca=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Xe}),z.object({symbol:sa,references:z.array(aa).optional(),relationships:la.optional(),impactScore:ca.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)}),pa=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()}),ua=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),da=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(pa),transitiveDependencies:z.array(ua).optional(),packages:z.array(da).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)}),ma=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),ga=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:Xe}),z.object({file:z.string(),directDependents:z.array(ma),transitiveDependents:z.array(ga).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()}),fa=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Xe}),z.object({cycles:z.array(fa)}),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)}),ha=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:Ae.optional(),languageMetadata:oe.optional()}),ya=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()}),ba=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:ha,directUsages:z.array(ya),transitiveUsages:z.array(ba).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)}),va=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:Ae.optional(),languageMetadata:oe.optional()}),Sa=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:Ae.optional(),languageMetadata:oe.optional()}),wa=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:Ae.optional(),languageMetadata:oe.optional()}),z.object({root:va,callers:z.array(Sa).optional(),callees:z.array(wa).optional(),graph:ia.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)}),Kn=Qe.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:oe.optional()}),Ca=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()}))}),xa=z.object({riskLevel:Xe,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:oe.optional()}),directDependents:z.array(Kn).optional(),transitiveDependents:z.array(Kn).optional(),impactedFiles:z.array(Ca),breakingChangeRisk:xa.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()}),Ea=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:oe.optional()}),_a=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(Ea),orphanedFiles:z.array(_a)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),Pa=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),Ia=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),Na=z.object({languages:z.array(Pa),frameworks:z.array(Ia),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),Ra=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()})}),Ta=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()}))})}),La=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()}),ja=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),Aa=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),ka=z.object({nodes:z.array(ja),edges:z.array(Aa)}),z.object({metadata:Na,structure:Ra,dependencies:Ta,metrics:La.optional(),moduleGraph:ka.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),Fa=z.enum(["relative","workspace","alias","external","builtin"]),$a=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:Fa}),Da=z.record(z.string(),$a),Jn=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),Oa=Jn.exclude(["import-use","declaration"]),Ma=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:Jn}).strict(),Ir=z.object({filePath:z.string().min(1),entries:z.array(Ma).max(1e5)}).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:Da.optional(),classificationMap:Ir.optional()}).strict(),Ua=z.object({file:z.string(),error:z.string()}),Ga=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),Ba=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(Ga)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(Ua).optional(),relationships:Ba}),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())}),Ha=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(Ha),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:Oa,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"]),et={branchName:z.string().optional(),effectiveBranchName:z.string().optional(),remapped:z.boolean().optional()},Wa=z.object({status:z.literal("acquired"),attemptId:z.string().uuid(),...et}),za=z.object({status:z.literal("current"),...et}),Ka=z.object({status:z.literal("duplicate"),...et}),Va=z.object({status:z.literal("superseded"),activeCommit:z.string().optional(),...et}),Ja=z.object({status:z.literal("queued"),queuedAttemptId:z.string().uuid(),...et}),qn=z.discriminatedUnion("status",[Wa,za,Ka,Va,Ja]),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()}),qa=z.enum(["pass1","pass2","pass2b","pass3"]),Ya=z.object({phase:qa,durationMs:z.number().int().nonnegative(),fileCount:z.number().int().nonnegative(),symbolCount:z.number().int().nonnegative().optional(),relationshipCount:z.number().int().nonnegative().optional(),throughputPerSec:z.number().nonnegative(),deadlockRetryCount:z.number().int().nonnegative().optional()}),Pt=z.array(Ya),Yn=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),Vn=Yn.extend({name:z.string().min(1)}).strict(),Xa=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().max(16384).optional()}).strict(),Qa=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:Xa.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(Yn).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(Vn).max(200),outgoingCalls:z.array(Vn).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(Qa).max(1e4)}).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(),Za=z.enum(["pending","processing","completed","failed","skipped"]),Nr=z.object({status:Za,filesProcessed:z.number().int().nonnegative().nullable(),completedAt:z.union([z.string().datetime({offset:true}),z.date()]).nullable()}),z.enum(["current","processing","stale","failed"]),Xn=z.union([z.string().datetime({offset:true}),z.date()]),el=z.object({status:z.literal("processing"),commitHash:z.string().nullable().optional(),startedAt:Xn.optional(),phaseMetrics:Pt.optional()}).passthrough(),tl=z.object({status:z.literal("current"),commitHash:z.string().nullable().optional(),completedAt:Xn.nullable().optional(),enrichment:Nr.optional(),phaseMetrics:Pt.optional()}).passthrough(),rl=z.object({status:z.literal("stale"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:Nr.optional(),phaseMetrics:Pt.optional()}).passthrough(),nl=z.object({status:z.literal("failed"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:Nr.optional(),phaseMetrics:Pt.optional()}).passthrough(),Rr=z.discriminatedUnion("status",[el,tl,rl,nl]),il=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),ol=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),sl=z.object({id:z.string(),label:z.string(),type:il,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),al=z.object({id:z.string(),source:z.string(),target:z.string(),type:ol,label:z.string().optional()}),ll=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Xe.optional()}),cl=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(sl),edges:z.array(al),summary:ll,metadata:cl,features:z.record(z.string(),z.boolean()).optional()}),Qn=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(Qn)}),Qn.pick({projectId:true,projectName:true,defaultBranch:true}),Zn=z.enum(["unresolved","resolved","archived"]),ei=z.enum(["succeeded","failed"]),ti=z.enum(["full","incremental"]),pl=z.enum(["info","warn","error"]),ul=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),dl=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),ri=z.object({errors:z.array(ul),warnings:z.array(dl)}),ni=z.object({level:pl,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:ri,logEntries:z.array(ni),cliVersion:z.string(),outcome:ei,indexType:ti}),z.object({status:Zn.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:ti,status:Zn,outcome:ei,errorSummary:z.string(),errorData:ri,logEntries:z.array(ni),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 Tr(i){return i.length>It&&(i[It]=ii),i}function oi(){let i=false,e=0;return new Transform({transform(t,r,o){if(i){o(null,t);return}if(e+t.length>It){let s=It-e;t[s]=ii,i=true;}e+=t.length,o(null,t);}})}var It,ii,Lr=f(()=>{It=9,ii=255;});function si(i){return base32.encode(Buffer.from(i))}var ai=f(()=>{});function li(i,e,t){let r=`${i}:${e}${t?`:${t}`:""}`;return si(r)}var ci=f(()=>{ai();});var Nt,pi=f(()=>{Nt=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)+`
|
|
35
|
-
`,o=Buffer.from(r,"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),r=>t(e||r)):t(e);}};});function di(){return ui.some(i=>!!process.env[i])}function mi(){return !!process.stdout.isTTY}function gi(){let i=ui.find(e=>!!process.env[e]);return i?hl[i]:void 0}var ui,hl,jr=f(()=>{ui=["GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE","CI"],hl={GITHUB_ACTIONS:"github-actions",GITLAB_CI:"gitlab",JENKINS_URL:"jenkins",CIRCLECI:"circleci",TRAVIS:"travis",BUILDKITE:"buildkite",DRONE:"drone",CI:"unknown"};});function yl(i){switch(i){case "darwin":return "Macintosh";case "win32":return "Windows";case "linux":return "Linux";case "freebsd":return "FreeBSD";default:return i.charAt(0).toUpperCase()+i.slice(1)}}function bl(i,e){return i==="darwin"?`Darwin ${e}`:e}function vl(){let i=globalThis.__constellationVersion;return typeof i=="string"&&i.length>0?i:"unknown"}function Sl(i={}){let e=i.platform??process.platform,t=i.arch??process.arch,r=(i.nodeVersion??process.version).replace(/^v/,""),o=i.osRelease??Pe.release(),s=vl(),a=yl(e),l=bl(e,o),c=`constellation-cli/${s} (${a}; ${l}; ${t}) Node/${r}`,u=gi();return u&&(c+=` CI/${u}`),c}var rt,hi=f(()=>{jr();rt=Sl();});var Rt,Tt,k,fe,se,ke,he,Fr=f(()=>{tt();M();Lr();ci();pi();hi();Rt=class{constructor(e,t,r=false,o){this.config=e;this.accessKey=t;this.dirty=r;this.reporter=o;}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 r of t.split(",")){let[o,s]=r.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(),r=t?.code;switch(r){case "PROJECT_NOT_REGISTERED":throw new se(t?.message||"Project not registered",r,this.config.projectId);case "PROJECT_INACTIVE":throw new se(t?.message||"Project is inactive",r,this.config.projectId);case "INVALID_PROJECT_ID":throw new se(t?.message||"Invalid project ID format",r,this.config.projectId);case "PROJECT_NOT_FOUND":throw new fe("Project not found - no previous index exists");default:throw e.status===404?new fe("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof se||t instanceof fe?t:e.status===404?new fe("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let r=new URLSearchParams({branch:e});t&&r.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${r.toString()}`;try{let s=await this.sendRequest(o,null,"GET");if(!s||!s.ok)return null;let a=await s.json(),l=Rr.safeParse(a);return l.success?l.data:(this.reporter?.warn(`[constellation] getIndexStatus: unrecognized response shape \u2014 ${l.error.issues.map(c=>c.message).join("; ")}`),null)}catch(s){if(s instanceof k)throw s;return null}}async claimAstLock(e,t,r,o,s){let a=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":r?"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 k("Authentication failed");if(!a.ok){let u=await this.formatErrorBody(a);throw new Error(`Failed to claim indexing lock: ${a.status}${u?` \u2014 ${u}`:""}`)}let l=await a.json(),c=qn.safeParse(l);if(!c.success)throw new Error(`Invalid lock response from server: ${c.error.issues.map(u=>u.message).join("; ")}`);return c.data}async pollIndexStatus(e,t,r,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(r)}`,null,"GET",{"x-constellation-dirty":this.dirty?"true":"false"});if(!c)continue;if(c.status===401)throw new k("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let u=await c.json(),p=Rr.safeParse(u);if(p.success){if(p.data.status==="current")return !0;if(p.data.status==="stale"||p.data.status==="failed")return !1}}}catch(c){if(c instanceof k)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadToQueue(e,t,r,o,s){return this.streamToApi(e,"ast/queue",t,r,true,o,s)}async startEnrichment(e,t,r){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","User-Agent":rt,"x-project-id":t,"x-branch-name":r,"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 this.reporter?.warn(`Enrichment start heartbeat rejected: ${a}`),!1}catch(s){return this.reporter?.warn(`Enrichment start heartbeat failed: ${s instanceof Error?s.message:String(s)}`),false}finally{o.destroy().catch(()=>{});}}async uploadEnrichment(e,t,r,o){let s=[5e3,1e4,2e4],a=en.gzipSync(Buffer.from(e,"utf8")),l=new Agent({headersTimeout:0,bodyTimeout:0});try{for(let c=0;c<=s.length;c++)try{let u=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/x-ndjson; charset=utf-8","Content-Encoding":"gzip","User-Agent":rt,"x-project-id":t,"x-branch-name":r,"x-commit-hash":o,"x-constellation-dirty":this.dirty?"true":"false"},body:a,dispatcher:l});if(u.status===401)throw new k("Authentication failed during enrichment upload");if(u.status===409){if((await u.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return this.reporter?.warn("Enrichment skipped: index state changed since upload"),!1;if(c<s.length){await new Promise(d=>setTimeout(d,s[c]));continue}return this.reporter?.warn("Enrichment skipped: indexing still in progress after retries"),!1}return u.ok||u.status===202?!0:(this.reporter?.warn(`Enrichment upload failed with status ${u.status}`),!1)}catch(u){if(u instanceof k)throw u;if(c<s.length){this.reporter?.warn(`Enrichment upload network error (attempt ${c+1}/${s.length+1}): ${u instanceof Error?u.message:String(u)}`),await new Promise(p=>setTimeout(p,s[c]));continue}return this.reporter?.warn(`Enrichment upload error: ${u instanceof Error?u.message:String(u)}`),!1}return !1}finally{l.destroy().catch(()=>{});}}async deleteFiles(e){for(let t of e){let r=li(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${r}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",r;try{let o=await e.json();t=o?.message||t,r=o?.details?.branchName;}catch{}return new ke(t,r)}async formatErrorBody(e){try{let t=await e.json();if(typeof t?.message=="string"){let r=typeof t.code=="string"&&t.code.length>0?` [${t.code}]`:"";return `${t.message}${r}`}if(Array.isArray(t?.message))return t.message.join("; ");if(typeof t?.code=="string")return t.code}catch{}return ""}async streamToApi(e,t,r,o,s,a,l){try{let{Readable:c}=await import('stream'),u=new Nt(e),p=process.env.CAPTURE_PAYLOAD_PATH,d=null,m=c.toWeb(u);if(p){let[g,y]=m.tee(),b=zt.createWriteStream(p);d=pipeline(c.fromWeb(y),en.createGzip(),oi(),b).catch(v=>{this.reporter?.warn(`[constellation] capture tap failed: ${v instanceof Error?v.message:String(v)}`);}),m=g;}let h=new Agent({headersTimeout:0,bodyTimeout:0});try{let g=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","User-Agent":rt,"x-project-id":r,"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:m,duplex:"half",dispatcher:h});if(!g.ok&&typeof u.destroy=="function"&&u.destroy(),g.status===401)throw new k("Authentication failed");if(g.status===409)throw await this.parseIndexingConflict(g);if(g.status===200)try{let b=await g.json();if(b?.status==="current")return this.reporter?.summary(`${w} Index already up to date for ${o} at commit ${b.commitHash||"unknown"}`),!0}catch{}if(g.ok||g.status===202)return !0;let y=`Server returned ${g.status}`;try{let b=await g.json();b?.message&&(y=Array.isArray(b.message)?b.message.join("; "):b.message);}catch{}throw new Error(y)}finally{d&&await d;}}catch(c){if(c instanceof k||c instanceof ke)throw c;let u=c instanceof Error?c:new Error(String(c)),p="";if(u.message==="fetch failed"||c.code){let m=[],h=c.code||c.cause?.code;if(c.code&&m.push(`Error Code: ${c.code}`),c.cause){let g=c.cause;g.code&&m.push(`Cause Code: ${g.code}`),g.errno&&m.push(`Errno: ${g.errno}`),g.syscall&&m.push(`System Call: ${g.syscall}`),g.address&&m.push(`Address: ${g.address}`),g.port&&m.push(`Port: ${g.port}`);}h==="ERR_INVALID_ARG_VALUE"?p="Invalid argument value - check stream/body format and duplex option":h==="ECONNREFUSED"?p="Connection refused - service may be down or unreachable":h==="ENOTFOUND"?p="DNS lookup failed - check service URL":h==="ETIMEDOUT"?p="Connection timeout - service not responding":h==="ECONNRESET"?p="Connection reset by server":h==="EHOSTUNREACH"?p="Host unreachable - check network connectivity":p="Network failure",m.length>0&&(p+=` (${m.join(", ")})`);}else p=u.message;let d=new Error(`Failed to upload data to Constellation Service: ${p}`);throw d.cause=u,d.stack=`${d.stack}
|
|
36
|
-
Caused by: ${u.stack}`,d}}async sendRequest(e,t,r,o={},s=0,a=3,l=1e3,c=250){for(let u=1;u<=a;u++){let p;try{let d=new AbortController;s>0&&(p=setTimeout(()=>d.abort(),s));let m={...o,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8","User-Agent":rt,Authorization:`Bearer ${this.accessKey}`},h=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:r,headers:m,body:t?JSON.stringify(t):void 0,signal:d.signal});if(p&&clearTimeout(p),h.status===401)throw new k("Authentication failed");if(!h.ok&&this.retryableStatusCodes.includes(h.status))throw new Tt(`${h.statusText} (${h.status})`);return h}catch(d){if(p&&clearTimeout(p),!(d instanceof k)){let m=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);this.reporter?.warn(`HTTP request attempt ${u}/${a} failed: ${m}`);}if(u<a&&d instanceof Tt){let m=l+Math.floor(Math.random()*c);await new Promise(h=>setTimeout(h,m));}else throw d}}}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){this.reporter?.warn("Failed to upload error report: no response received");return}if(t.status===403){this.reporter?.warn("Error reporting is not available on your current plan");return}t.ok||this.reporter?.warn(`Failed to upload error report: ${t.statusText} (${t.status})`);}catch(t){this.reporter?.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"},r=await this.sendRequest(e,void 0,"DELETE",t);if(r&&!r.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Tt=class extends Error{constructor(e){super(e),this.name="RetryableError";}},k=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},fe=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},se=class extends Error{constructor(t,r,o){super(t);this.code=r;this.projectId=o;this.name="ProjectValidationError";}},ke=class extends Error{constructor(t,r){super(t);this.branchName=r;this.name="IndexingInProgressError";}},he=class extends Error{constructor(t,r){super(t);this.errorCode=r;this.name="GitValidationError";}};});function bi(i){return i.replace(/\\/g,"/")}function jt(i){return bi(i).replace(/^\.?\//,"")}function W(i,e){return bi(E.relative(i,e))}var we=f(()=>{});var Fe,Dr=f(()=>{Fe=class{constructor(e=10,t={}){this.concurrency=e;this.options=t;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,a=new Map,l=new Set,c=0;for(;s<e.length&&r.size<this.concurrency;){let u=o++,p=s,d=this.processItem(e[p],p,t).then(m=>({result:m!==null?m.result:null,index:p,promiseId:u}));r.set(u,d),s++;}for(;r.size>0;){let u=await Promise.race(r.values());if(r.delete(u.promiseId),this.options.preserveOrder)for(u.result!==null?a.set(u.index,u.result):l.add(u.index);c<e.length&&(a.has(c)||l.has(c));){if(a.has(c)){let p=a.get(c);a.delete(c),yield p;}else l.delete(c);c++;}else u.result!==null&&(yield u.result);if(s<e.length){let p=o++,d=s,m=this.processItem(e[d],d,t).then(h=>({result:h!==null?h.result:null,index:d,promiseId:p}));r.set(p,m),s++;}}}async processItem(e,t,r){try{return {result:await r(e,t),index:t}}catch{return null}}};});var El,_l,Or,Pl,At,Si=f(()=>{we();Dr();El={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}},_l={hover:true,references:true,callHierarchy:false},Or=1e4,Pl=1200*1e3,At=class{constructor(e,t){this.projectRoot=e;this.reporter=t;}async enrich(e,t,r,o,s){let a=[],l=Date.now(),c={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,lspProcessCrashes:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null,firstLspCrashLanguage:null},u=false,p=new Set,d=new Set;return await Promise.all([...e.entries()].map(async([m,h])=>{let g=r.get(m);if(!g)return;let y=h.length,b=y>1e4?8:y>5e3?10:16,v=new Fe(b),T=()=>{p.add(m),d.has(g.serverId)||(d.add(g.serverId),c.lspProcessCrashes++,c.firstLspCrashLanguage||(c.firstLspCrashLanguage=m)),this.reporter?.warn(`[LSP:${m}] Process exited mid-enrichment (concurrency=${b}); halting subsequent ${m} files.`);},N=g.onCrash(T),C=0,_=v.run(h,async x=>{try{if(u||Date.now()-l>Pl)return u=!0,null;if(p.has(m))return null;let G=await this.openFile(g,x,c,o?.get(x));if(!G)return null;let{uri:B}=G;try{let H=t.get(x)??[];if(H.length===0&&(H=await this.discoverSymbols(g,x,B,c),H.length===0))return c.filesNoSymbols++,null;let P=await this.enrichOpenFile(g,x,B,H,c);return P.length>0?{filePath:x,language:m,symbols:P}:null}finally{this.closeFile(g,B);}}finally{C++,s?.(m,C,y);}});try{for await(let x of _)x&&a.push(x);}finally{N();}})),u&&this.reporter?.info("Enrichment timeout reached. Uploading partial results."),this.logDiagnostics(c),a}async openFile(e,t,r,o){let s=E.resolve(this.projectRoot,t),a=pathToFileURL(s).href,l=o;if(l===void 0)try{l=await zt.promises.readFile(s,"utf-8");}catch(c){return r.filesUnreadable++,r.firstFileError||(r.firstFileError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(t),version:1,text:l}});}catch(c){return r.filesOpenFailed++,r.firstOpenError||(r.firstOpenError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}return {uri:a,content:l}}closeFile(e,t){try{e.sendNotification("textDocument/didClose",{textDocument:{uri:t}});}catch{}}async enrichOpenFile(e,t,r,o,s){let a=await Promise.allSettled(o.map(c=>this.querySymbol(e,r,c,s))),l=[];for(let c=0;c<a.length;c++){let u=a[c];if(u.status==="fulfilled")u.value&&l.push(u.value);else if(s.symbolQueryErrors++,!s.firstSymbolError){let p=o[c];s.firstSymbolError=`${p.name} in ${t}: ${u.reason instanceof Error?u.reason.message:String(u.reason)}`;}}return l}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.filesNoSymbols>0&&t.push(`${e.filesNoSymbols} files had no discoverable symbols`),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`),e.lspProcessCrashes>0&&t.push(`${e.lspProcessCrashes} LSP process crashes`);let r=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(r.length>0){let o=r.reduce((a,[,l])=>a+l,0),s=r.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(this.reporter?.warn(`Enrichment issues: ${t.join(", ")}`),e.firstFileError&&this.reporter?.warn(`First file read error: ${e.firstFileError}`),e.firstOpenError&&this.reporter?.warn(`First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&this.reporter?.warn(`First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&this.reporter?.warn(`First symbol query error: ${e.firstSymbolError}`));}async querySymbol(e,t,r,o){let s=r.kind.toLowerCase(),a=El[s]||_l,c=!r.isExported&&(s==="function"||s==="method")?{...a,callHierarchy:false}:a,u={line:r.line-1,character:r.column},p={textDocument:{uri:t},position:u},d={name:r.name,line:r.line,column:r.column,kind:r.kind},m=false,[h,g]=await Promise.allSettled([c.hover?e.sendRequest("textDocument/hover",p,Or):null,c.references?e.sendRequest("textDocument/references",{...p,context:{includeDeclaration:false}},Or):null]);for(let y of [h,g])y.status==="rejected"&&o.queryRejections++;if(h.status==="fulfilled"&&h.value?.contents){let y=h.value,b=typeof y.contents=="string"?y.contents:y.contents.value||"";b&&(d.typeInfo={resolvedType:b},m=true);}if(g.status==="fulfilled"&&g.value){let y=g.value;if(y.length>0){let b=y.slice(0,100).map(v=>({filePath:W(this.projectRoot,this.uriToPath(v.uri||"")),line:(v.range?.start?.line??0)+1,column:v.range?.start?.character??0}));d.references={count:y.length,locations:b},m=true;}}if(c.callHierarchy)try{let y=await e.sendRequest("textDocument/prepareCallHierarchy",p,Or);if(y&&y.length>0){let b=y[0],[v,T]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:b}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:b}).catch(()=>[])]),N=(v||[]).slice(0,200).map(_=>({name:_.from?.name||"",filePath:W(this.projectRoot,this.uriToPath(_.from?.uri||"")),line:(_.from?.range?.start?.line??0)+1,column:_.from?.selectionRange?.start?.character??_.from?.range?.start?.character??0})),C=(T||[]).slice(0,200).map(_=>({name:_.to?.name||"",filePath:W(this.projectRoot,this.uriToPath(_.to?.uri||"")),line:(_.to?.range?.start?.line??0)+1,column:_.to?.selectionRange?.start?.character??_.to?.range?.start?.character??0}));(N.length>0||C.length>0)&&(d.callHierarchy={incomingCalls:N,outgoingCalls:C},m=!0);}}catch{o.queryRejections++;}if(!m){let y=r.kind.toLowerCase();o.symbolsWithNoEnrichment[y]=(o.symbolsWithNoEnrichment[y]??0)+1;}return m?d:null}async discoverSymbols(e,t,r,o){try{let s=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:r}});return !s||!Array.isArray(s)?[]:this.flattenDocumentSymbols(s)}catch(s){return o.discoveryErrors++,o.firstDiscoveryError||(o.firstDiscoveryError=`${t}: ${s instanceof Error?s.message:String(s)}`),[]}}flattenDocumentSymbols(e){let t=[],r={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=r[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,isExported:true}),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=E.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function wi(i){return i.map(e=>JSON.stringify(e)).join(`
|
|
34
|
+
New terminal sessions will load it automatically.`),Oe.platform()==="darwin"&&this.reporter.info("Already-running desktop apps (Claude Desktop, Codex, etc.) must be quit and relaunched to see the new value.");}};});var Ba,me,ft,Wa,Ke,ht,Ha,za,Ka,yt,Va,Ja,qa,Ya,Xa,Qa,Za,el,tl,rl,nl,il,ol,sl,al,ll,cl,pl,ul,xi,dl,ml,gl,fl,hl,yl,vl,bl,Sl,wl,xl,Cl,El,_l,Pl,Il,Ei,Rl,Nl,en,Tl,Ll,kl,jl,vt,Al,Fl,$l,Dl,Ol,_i,Ml,Ul,Ht,Zr,Ci,Gl,Bl,Wl,tn,Pi,Hl,zl,Kl,Vl,rn,Jl,ql,Yl,Xl,Ql,Zl,Ii,Ri,Ni,Ti,ec,tc,rc,Li,ki,nc,ic,oc,sc,bt=g(()=>{Ba=z$1.object({total:z$1.number().int().nonnegative(),returned:z$1.number().int().nonnegative(),hasMore:z$1.boolean(),nextOffset:z$1.number().int().nonnegative().optional(),currentOffset:z$1.number().int().nonnegative().optional()}),z$1.object({overall:z$1.number().min(0).max(1),factors:z$1.object({dataFreshness:z$1.number().min(0).max(1).optional(),coverageComplete:z$1.number().min(0).max(1).optional(),heuristicAccuracy:z$1.number().min(0).max(1).optional(),semanticAnalysisDepth:z$1.number().min(0).max(1).optional(),patternMatchQuality:z$1.number().min(0).max(1).optional()}).optional(),warnings:z$1.array(z$1.string()).optional(),recommendations:z$1.array(z$1.string()).optional()}),z$1.object({qualityScore:z$1.number().min(0).max(100).optional(),lastUpdated:z$1.string().optional(),cached:z$1.boolean().optional(),executionTime:z$1.number().nonnegative().optional(),coveragePercentage:z$1.number().min(0).max(100).optional(),issues:z$1.array(z$1.string()).optional()}),me=z$1.object({language:z$1.string(),features:z$1.array(z$1.string()).optional(),visibility:z$1.string().optional(),decorators:z$1.array(z$1.string()).optional(),typeInfo:z$1.any().optional(),custom:z$1.record(z$1.string(),z$1.any()).optional()}),z$1.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),ft=z$1.enum(["low","medium","high","critical"]),Wa=z$1.enum(["low","moderate","high","very_high"]),Ke=z$1.object({cyclomaticComplexity:z$1.number().int().nonnegative(),complexityRisk:Wa}),ht=z$1.object({filePath:z$1.string(),line:z$1.number().int().positive().optional(),lineStart:z$1.number().int().positive().optional(),lineEnd:z$1.number().int().positive().optional(),column:z$1.number().int().nonnegative().optional()}),ht.extend({symbolId:z$1.string().optional(),symbolName:z$1.string().optional(),symbolKind:z$1.string().optional()}),z$1.object({outgoing:z$1.array(z$1.string()),incoming:z$1.array(z$1.string())}),Ha=z$1.object({id:z$1.string(),name:z$1.string(),type:z$1.string(),properties:z$1.record(z$1.string(),z$1.any()).optional()}),za=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string().optional(),weight:z$1.number().optional(),properties:z$1.record(z$1.string(),z$1.any()).optional()}),Ka=z$1.object({nodes:z$1.array(Ha),edges:z$1.array(za),metadata:z$1.object({nodeCount:z$1.number().int().nonnegative(),edgeCount:z$1.number().int().nonnegative(),directed:z$1.boolean(),hasCycles:z$1.boolean().optional()}).optional()}),yt=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$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.string(),message:z$1.string(),details:z$1.any().optional()})}),z$1.object({query:z$1.string().max(200),filterByKind:z$1.array(z$1.string()).optional(),filterByVisibility:z$1.array(z$1.string()).optional(),isExported:z$1.boolean().optional(),filterByFile:z$1.string().optional(),limit:z$1.number().int().positive().max(100).default(50),offset:z$1.number().int().nonnegative().default(0),includeUsageCount:z$1.boolean().optional(),includeDocumentation:z$1.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"]}),Va=ht.extend({id:z$1.string(),name:z$1.string(),qualifiedName:z$1.string(),kind:z$1.string(),signature:z$1.string().optional(),documentation:z$1.string().optional(),visibility:z$1.string().optional(),isExported:z$1.boolean(),usageCount:z$1.number().int().nonnegative().optional(),complexity:Ke.optional(),languageMetadata:me.optional()}),z$1.object({symbols:z$1.array(Va),pagination:Ba.optional()}),z$1.object({symbolId:z$1.string().optional(),symbolName:z$1.string().optional(),filePath:z$1.string().optional(),includeReferences:z$1.boolean().optional(),includeRelationships:z$1.boolean().optional(),includeImpactScore:z$1.boolean().optional()}),Ja=ht.extend({id:z$1.string(),name:z$1.string(),qualifiedName:z$1.string(),kind:z$1.string(),signature:z$1.string().optional(),documentation:z$1.string().optional(),visibility:z$1.string().optional(),modifiers:z$1.array(z$1.string()).optional(),typeInfo:z$1.any().optional(),decorators:z$1.array(z$1.string()).optional(),isExported:z$1.boolean(),isDeprecated:z$1.boolean(),complexity:Ke.optional(),languageMetadata:me.optional()}),qa=ht.extend({usageType:z$1.string(),context:z$1.string().optional(),aliasName:z$1.string().optional()}),Ya=z$1.object({calls:z$1.array(z$1.string()),calledBy:z$1.array(z$1.string()),inheritsFrom:z$1.array(z$1.string()),inheritedBy:z$1.array(z$1.string()),children:z$1.array(z$1.string())}),Xa=z$1.object({directUsage:z$1.number().int().nonnegative(),transitiveImpact:z$1.number().int().nonnegative(),riskScore:z$1.number().min(0).max(100),riskLevel:ft}),z$1.object({symbol:Ja,references:z$1.array(qa).optional(),relationships:Ya.optional(),impactScore:Xa.optional()}),z$1.object({filePath:z$1.string().min(1),depth:z$1.number().int().nonnegative().max(10).optional(),includePackages:z$1.boolean().optional(),includeSymbols:z$1.boolean().optional(),limit:z$1.number().int().positive().max(100).default(20),offset:z$1.number().int().nonnegative().default(0)}),Qa=z$1.object({type:z$1.enum(["file","module"]),filePath:z$1.string().nullable(),moduleName:z$1.string().nullable().optional(),importedSymbols:z$1.array(z$1.string()).optional(),isDefault:z$1.boolean(),isNamespace:z$1.boolean()}),Za=z$1.object({filePath:z$1.string(),distance:z$1.number().int().positive(),path:z$1.array(z$1.string())}),el=z$1.object({name:z$1.string(),version:z$1.string().optional(),type:z$1.string()}),z$1.object({totalFiles:z$1.number().int().nonnegative(),totalPackages:z$1.number().int().nonnegative(),maxDepth:z$1.number().int().nonnegative()}),z$1.object({file:z$1.string(),directDependencies:z$1.array(Qa),transitiveDependencies:z$1.array(Za).optional(),packages:z$1.array(el).optional()}),z$1.object({filePath:z$1.string().min(1),depth:z$1.number().int().nonnegative().max(10).optional(),includeSymbols:z$1.boolean().optional(),includeImpactMetrics:z$1.boolean().optional(),limit:z$1.number().int().positive().max(100).default(20),offset:z$1.number().int().nonnegative().default(0)}),tl=z$1.object({filePath:z$1.string(),usedSymbols:z$1.array(z$1.string()).optional()}),rl=z$1.object({filePath:z$1.string(),distance:z$1.number().int().positive(),path:z$1.array(z$1.string())}),z$1.object({totalFiles:z$1.number().int().nonnegative(),maxDepth:z$1.number().int().nonnegative(),riskLevel:ft}),z$1.object({file:z$1.string(),directDependents:z$1.array(tl),transitiveDependents:z$1.array(rl).optional(),detailedMetrics:z$1.object({byDepth:z$1.record(z$1.string(),z$1.number()),criticalPaths:z$1.array(z$1.array(z$1.string())),mostImpactedFiles:z$1.array(z$1.string())}).optional()}),z$1.object({filePath:z$1.string().min(1).optional(),minCycleLength:z$1.number().int().min(2).max(10).optional(),maxCycleLength:z$1.number().int().min(2).max(10).optional(),limit:z$1.number().int().positive().max(100).default(50),offset:z$1.number().int().nonnegative().default(0),includeImpactScore:z$1.boolean().optional(),includeConfidence:z$1.boolean().optional()}),nl=z$1.object({files:z$1.array(z$1.string()),length:z$1.number().int().positive(),impactScore:z$1.number().min(0).max(100).optional(),severity:ft}),z$1.object({cycles:z$1.array(nl)}),z$1.object({symbolId:z$1.string().optional(),symbolName:z$1.string().optional(),filePath:z$1.string().optional(),filterByUsageType:z$1.array(z$1.string()).optional(),filterByRelationshipType:z$1.array(z$1.string()).optional(),includeTransitive:z$1.boolean().optional(),includeContext:z$1.boolean().optional(),excludeTests:z$1.boolean().optional(),excludeGenerated:z$1.boolean().optional(),includeImportanceWeight:z$1.boolean().optional(),limit:z$1.number().int().positive().max(100).default(50),offset:z$1.number().int().nonnegative().default(0)}),il=z$1.object({name:z$1.string(),kind:z$1.string(),visibility:z$1.string().optional(),filePath:z$1.string(),lineEnd:z$1.number().int().positive().optional(),complexity:Ke.optional(),languageMetadata:me.optional()}),ol=z$1.object({filePath:z$1.string(),usageType:z$1.string(),relationshipType:z$1.string(),line:z$1.number().int().positive().optional(),column:z$1.number().int().nonnegative().optional(),enclosingSymbol:z$1.object({name:z$1.string(),kind:z$1.string()}).optional(),context:z$1.string().optional(),aliasName:z$1.string().optional(),isTest:z$1.boolean().optional(),isGenerated:z$1.boolean().optional(),importanceWeight:z$1.number().min(0).max(1).optional()}),sl=z$1.object({filePath:z$1.string(),distance:z$1.number().int().positive(),chain:z$1.array(z$1.string())}),al=z$1.object({limit:z$1.number().int().positive(),offset:z$1.number().int().nonnegative(),returned:z$1.number().int().nonnegative(),hasMore:z$1.boolean()}),ll=z$1.object({totalUsages:z$1.number().int().nonnegative(),usagesByType:z$1.record(z$1.string(),z$1.number().int().nonnegative()),filesAffected:z$1.number().int().nonnegative(),transitiveImpact:z$1.number().int().nonnegative(),pageInfo:al}),z$1.object({symbol:il,directUsages:z$1.array(ol),transitiveUsages:z$1.array(sl).optional(),summary:ll}),z$1.object({symbolId:z$1.string().optional(),symbolName:z$1.string().optional(),filePath:z$1.string().optional(),direction:z$1.enum(["callers","callees","both"]).default("both"),depth:z$1.number().int().positive().max(10).default(3),excludeExternal:z$1.boolean().optional(),includeGraph:z$1.boolean().optional(),limit:z$1.number().int().positive().max(100).default(25),offset:z$1.number().int().nonnegative().default(0)}),cl=z$1.object({symbolId:z$1.string(),name:z$1.string(),visibility:z$1.string().optional(),filePath:z$1.string(),line:z$1.number().int().positive(),lineEnd:z$1.number().int().positive().optional(),column:z$1.number().int().nonnegative(),complexity:Ke.optional(),languageMetadata:me.optional()}),pl=z$1.object({symbolId:z$1.string(),name:z$1.string(),visibility:z$1.string().optional(),filePath:z$1.string(),line:z$1.number().int().positive(),lineEnd:z$1.number().int().positive().optional(),column:z$1.number().int().nonnegative(),depth:z$1.number().int().nonnegative(),complexity:Ke.optional(),languageMetadata:me.optional()}),ul=z$1.object({symbolId:z$1.string(),name:z$1.string(),visibility:z$1.string().optional(),filePath:z$1.string(),line:z$1.number().int().positive(),lineEnd:z$1.number().int().positive().optional(),column:z$1.number().int().nonnegative(),isAsync:z$1.boolean(),depth:z$1.number().int().nonnegative(),complexity:Ke.optional(),languageMetadata:me.optional()}),z$1.object({root:cl,callers:z$1.array(pl).optional(),callees:z$1.array(ul).optional(),graph:Ka.optional()}),z$1.object({symbolId:z$1.string().optional(),qualifiedName:z$1.string().optional(),symbolName:z$1.string().optional(),filePath:z$1.string().optional(),includeDirectDependents:z$1.boolean().default(true),includeTransitiveDependents:z$1.boolean().default(true),depth:z$1.number().int().min(1).max(5).default(3),excludeTests:z$1.boolean().default(true),excludeGenerated:z$1.boolean().default(true),analyzeBreakingChanges:z$1.boolean().default(true)}),xi=ht.extend({id:z$1.string(),name:z$1.string(),qualifiedName:z$1.string(),kind:z$1.string(),visibility:z$1.string().optional(),relationshipType:z$1.string(),depth:z$1.number().int().positive(),isExported:z$1.boolean().optional(),transitiveImpactCount:z$1.number().int().nonnegative().optional(),languageMetadata:me.optional()}),dl=z$1.object({filePath:z$1.string(),symbolCount:z$1.number().int().positive(),isTest:z$1.boolean().optional(),isGenerated:z$1.boolean().optional(),symbols:z$1.array(z$1.object({id:z$1.string(),name:z$1.string(),kind:z$1.string(),line:z$1.number().int().positive()}))}),ml=z$1.object({riskLevel:ft,factors:z$1.array(z$1.object({factor:z$1.string(),severity:z$1.enum(["low","medium","high"]),description:z$1.string()})),recommendations:z$1.array(z$1.string())}),z$1.object({symbol:z$1.object({id:z$1.string(),name:z$1.string(),qualifiedName:z$1.string(),kind:z$1.string(),visibility:z$1.string().optional(),filePath:z$1.string(),line:z$1.number().int().positive(),lineEnd:z$1.number().int().positive().optional(),column:z$1.number().int().nonnegative(),isExported:z$1.boolean().optional(),languageMetadata:me.optional()}),directDependents:z$1.array(xi).optional(),transitiveDependents:z$1.array(xi).optional(),impactedFiles:z$1.array(dl),breakingChangeRisk:ml.optional(),summary:z$1.object({directDependentCount:z$1.number().int().nonnegative(),transitiveDependentCount:z$1.number().int().nonnegative(),impactedFileCount:z$1.number().int().nonnegative(),testFileCount:z$1.number().int().nonnegative(),productionFileCount:z$1.number().int().nonnegative(),maxDepth:z$1.number().int().nonnegative()})}),z$1.object({filePattern:z$1.string().optional(),filterByKind:z$1.array(z$1.string()).optional(),exportedOnly:z$1.boolean().optional(),excludeTests:z$1.boolean().default(true),limit:z$1.number().int().positive().max(100).default(50),offset:z$1.number().int().nonnegative().default(0),includeConfidence:z$1.boolean().optional()}),gl=z$1.object({symbolId:z$1.string(),name:z$1.string(),kind:z$1.string(),visibility:z$1.string().optional(),filePath:z$1.string(),lineEnd:z$1.number().int().positive().optional(),isExported:z$1.boolean(),reason:z$1.string(),confidence:z$1.number().min(0).max(1),languageMetadata:me.optional()}),fl=z$1.object({filePath:z$1.string(),reason:z$1.string(),lastUpdated:z$1.string(),confidence:z$1.number().min(0).max(1)}),z$1.object({orphanedSymbols:z$1.array(gl),orphanedFiles:z$1.array(fl)}),z$1.object({includeMetrics:z$1.boolean().default(false),includeModuleGraph:z$1.boolean().default(false),includePackages:z$1.boolean().default(true)}),hl=z$1.object({language:z$1.string(),fileCount:z$1.number().int().nonnegative(),percentage:z$1.number().min(0).max(100)}),yl=z$1.object({name:z$1.string(),version:z$1.string().optional(),confidence:z$1.enum(["high","medium","low"]),evidence:z$1.array(z$1.string())}),vl=z$1.object({languages:z$1.array(hl),frameworks:z$1.array(yl),primaryLanguage:z$1.string(),totalFiles:z$1.number().int().nonnegative(),totalLines:z$1.number().int().nonnegative().optional()}),bl=z$1.object({files:z$1.object({total:z$1.number().int().nonnegative(),byType:z$1.record(z$1.string(),z$1.number()),byParadigm:z$1.record(z$1.string(),z$1.number())}),symbols:z$1.object({total:z$1.number().int().nonnegative(),byKind:z$1.record(z$1.string(),z$1.number()),exported:z$1.number().int().nonnegative(),public:z$1.number().int().nonnegative()}),modules:z$1.object({total:z$1.number().int().nonnegative(),averageSize:z$1.number().nonnegative(),largest:z$1.string()})}),Sl=z$1.object({internal:z$1.object({totalConnections:z$1.number().int().nonnegative(),averagePerFile:z$1.number().nonnegative(),mostConnectedFiles:z$1.array(z$1.object({path:z$1.string(),incomingCount:z$1.number().int().nonnegative(),outgoingCount:z$1.number().int().nonnegative()}))}),external:z$1.object({totalPackages:z$1.number().int().nonnegative(),directDependencies:z$1.number().int().nonnegative(),topPackages:z$1.array(z$1.object({name:z$1.string(),usageCount:z$1.number().int().nonnegative()}))})}),wl=z$1.object({complexity:z$1.object({average:z$1.number().nonnegative(),high:z$1.number().int().nonnegative()}),maintainability:z$1.object({score:z$1.number().min(0).max(100),issues:z$1.array(z$1.string())}),testCoverage:z$1.object({percentage:z$1.number().min(0).max(100),testedFiles:z$1.number().int().nonnegative(),totalFiles:z$1.number().int().nonnegative()}).optional()}),xl=z$1.object({id:z$1.string(),name:z$1.string(),fileCount:z$1.number().int().nonnegative(),type:z$1.string()}),Cl=z$1.object({from:z$1.string(),to:z$1.string(),weight:z$1.number().int().nonnegative()}),El=z$1.object({nodes:z$1.array(xl),edges:z$1.array(Cl)}),z$1.object({metadata:vl,structure:bl,dependencies:Sl,metrics:wl.optional(),moduleGraph:El.optional()}),z$1.object({}).strict(),z$1.object({pong:z$1.literal(true)}),_l=z$1.enum(["relative","workspace","alias","external","builtin"]),Pl=z$1.object({source:z$1.string(),resolvedPath:z$1.string().optional(),isExternal:z$1.boolean(),importType:_l}),Il=z$1.record(z$1.string(),Pl),Ei=z$1.enum(["call","read","write","type","instantiate","import-use","declaration"]),Rl=Ei.exclude(["import-use","declaration"]),Nl=z$1.object({line:z$1.number().int().nonnegative(),column:z$1.number().int().nonnegative(),referenceType:Ei}).strict(),en=z$1.object({filePath:z$1.string().min(1),entries:z$1.array(Nl).max(1e5)}).strict(),z$1.object({file:z$1.string().min(1),language:z$1.string().min(1),commit:z$1.string().min(1),timestamp:z$1.string().datetime(),ast:z$1.string().min(1),importResolutions:Il.optional(),classificationMap:en.optional()}).strict(),Tl=z$1.object({file:z$1.string(),error:z$1.string()}),Ll=z$1.object({file:z$1.string(),failedCount:z$1.number().int().nonnegative(),createdCount:z$1.number().int().nonnegative(),isTransient:z$1.boolean()}),kl=z$1.object({totalCreated:z$1.number().int().nonnegative(),totalFailed:z$1.number().int().nonnegative(),filesWithFailures:z$1.array(Ll)}),z$1.object({processed:z$1.number().int().nonnegative(),failed:z$1.number().int().nonnegative(),projectId:z$1.string(),branchName:z$1.string(),failedFiles:z$1.array(Tl).optional(),relationships:kl}),z$1.object({projectId:z$1.string(),projectName:z$1.string(),branch:z$1.string(),latestCommit:z$1.string().nullable(),fileCount:z$1.number().int().nonnegative(),lastIndexedAt:z$1.string().nullable(),languages:z$1.array(z$1.string())}),jl=z$1.object({local:z$1.string(),original:z$1.string().optional(),isDefault:z$1.boolean(),isNamespace:z$1.boolean()}),z$1.object({source:z$1.string(),specifiers:z$1.array(jl),isType:z$1.boolean(),isDynamic:z$1.boolean(),isConditional:z$1.boolean().optional(),isLazy:z$1.boolean().optional(),isWildcard:z$1.boolean().optional(),line:z$1.number(),column:z$1.number()}),z$1.object({referencerId:z$1.string(),referencedName:z$1.string(),referenceType:Rl,line:z$1.number(),column:z$1.number(),scope:z$1.string().optional(),objectContext:z$1.string().optional(),language:z$1.string().optional()}),z$1.enum(["processing","completed","failed","cancelled","queued","superseded","cleaned_up"]),z$1.enum(["acquired","current","duplicate","superseded","queued"]),vt={branchName:z$1.string().optional(),effectiveBranchName:z$1.string().optional(),remapped:z$1.boolean().optional()},Al=z$1.object({status:z$1.literal("acquired"),attemptId:z$1.string().uuid(),...vt}),Fl=z$1.object({status:z$1.literal("current"),...vt}),$l=z$1.object({status:z$1.literal("duplicate"),...vt}),Dl=z$1.object({status:z$1.literal("superseded"),activeCommit:z$1.string().optional(),...vt}),Ol=z$1.object({status:z$1.literal("queued"),queuedAttemptId:z$1.string().uuid(),...vt}),_i=z$1.discriminatedUnion("status",[Al,Fl,$l,Dl,Ol]),z$1.object({"x-attempt-id":z$1.string().uuid(),"x-project-id":z$1.string(),"x-branch-name":z$1.string(),"x-commit-hash":z$1.string().length(40),"x-constellation-dirty":z$1.union([z$1.literal("true"),z$1.literal("false")]).optional()}),Ml=z$1.enum(["pass1","pass2","pass2b","pass3"]),Ul=z$1.object({phase:Ml,durationMs:z$1.number().int().nonnegative(),fileCount:z$1.number().int().nonnegative(),symbolCount:z$1.number().int().nonnegative().optional(),relationshipCount:z$1.number().int().nonnegative().optional(),throughputPerSec:z$1.number().nonnegative(),deadlockRetryCount:z$1.number().int().nonnegative().optional()}),Ht=z$1.array(Ul),Zr=z$1.object({filePath:z$1.string().min(1),line:z$1.number().int().positive(),column:z$1.number().int().nonnegative()}).strict(),Ci=Zr.extend({name:z$1.string().min(1)}).strict(),Gl=z$1.object({resolvedType:z$1.string().min(1),returnType:z$1.string().optional(),documentation:z$1.string().max(16384).optional()}).strict(),Bl=z$1.object({name:z$1.string().min(1),line:z$1.number().int().positive(),column:z$1.number().int().nonnegative(),kind:z$1.string().min(1),typeInfo:Gl.optional(),references:z$1.object({count:z$1.number().int().nonnegative(),locations:z$1.array(Zr).max(100)}).optional(),callHierarchy:z$1.object({incomingCalls:z$1.array(Ci).max(200),outgoingCalls:z$1.array(Ci).max(200)}).optional(),implementations:z$1.array(Zr).max(200).optional()}).strict(),z$1.object({filePath:z$1.string().min(1),language:z$1.string().min(1),symbols:z$1.array(Bl).max(1e4)}).strict(),z$1.object({projectId:z$1.string().min(1),branch:z$1.string().min(1),commit:z$1.string().regex(/^[0-9a-f]{40}$/),timestamp:z$1.string().datetime()}).strict(),Wl=z$1.enum(["pending","processing","completed","failed","skipped"]),tn=z$1.object({status:Wl,filesProcessed:z$1.number().int().nonnegative().nullable(),completedAt:z$1.union([z$1.string().datetime({offset:true}),z$1.date()]).nullable()}),z$1.enum(["current","processing","stale","failed"]),Pi=z$1.union([z$1.string().datetime({offset:true}),z$1.date()]),Hl=z$1.object({status:z$1.literal("processing"),commitHash:z$1.string().nullable().optional(),startedAt:Pi.optional(),phaseMetrics:Ht.optional()}).passthrough(),zl=z$1.object({status:z$1.literal("current"),commitHash:z$1.string().nullable().optional(),completedAt:Pi.nullable().optional(),enrichment:tn.optional(),phaseMetrics:Ht.optional()}).passthrough(),Kl=z$1.object({status:z$1.literal("stale"),currentCommit:z$1.string().nullable().optional(),requestedCommit:z$1.string().optional(),enrichment:tn.optional(),phaseMetrics:Ht.optional()}).passthrough(),Vl=z$1.object({status:z$1.literal("failed"),currentCommit:z$1.string().nullable().optional(),requestedCommit:z$1.string().optional(),enrichment:tn.optional(),phaseMetrics:Ht.optional()}).passthrough(),rn=z$1.discriminatedUnion("status",[Hl,zl,Kl,Vl]),Jl=z$1.enum(["function","class","variable","import","module","interface","type","constant","export"]),ql=z$1.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),Yl=z$1.object({id:z$1.string(),label:z$1.string(),type:Jl,data:z$1.object({filePath:z$1.string(),lineNumber:z$1.number().int().nonnegative(),module:z$1.string(),visibility:z$1.string(),isExported:z$1.boolean()})}),Xl=z$1.object({id:z$1.string(),source:z$1.string(),target:z$1.string(),type:ql,label:z$1.string().optional()}),Ql=z$1.object({totalNodes:z$1.number().int().nonnegative(),totalEdges:z$1.number().int().nonnegative(),toolName:z$1.string(),query:z$1.string(),riskLevel:ft.optional()}),Zl=z$1.object({projectName:z$1.string(),branch:z$1.string(),asOfCommit:z$1.string(),lastIndexedAt:z$1.string().datetime()}),z$1.object({nodes:z$1.array(Yl),edges:z$1.array(Xl),summary:Ql,metadata:Zl,features:z$1.record(z$1.string(),z$1.boolean()).optional()}),Ii=z$1.object({projectId:z$1.string(),projectName:z$1.string(),defaultBranch:z$1.string(),lastIndexedAt:z$1.string().datetime().optional(),fileCount:z$1.number().int().nonnegative().optional(),languages:z$1.array(z$1.string()).optional()}),z$1.object({projects:z$1.array(Ii)}),Ii.pick({projectId:true,projectName:true,defaultBranch:true}),Ri=z$1.enum(["unresolved","resolved","archived"]),Ni=z$1.enum(["succeeded","failed"]),Ti=z$1.enum(["full","incremental"]),ec=z$1.enum(["info","warn","error"]),tc=z$1.object({type:z$1.string(),message:z$1.string(),phase:z$1.string(),filePath:z$1.string().optional(),stack:z$1.string().optional()}),rc=z$1.object({type:z$1.string(),message:z$1.string(),phase:z$1.string(),filePath:z$1.string().optional()}),Li=z$1.object({errors:z$1.array(tc),warnings:z$1.array(rc)}),ki=z$1.object({level:ec,message:z$1.string(),timestamp:z$1.string().datetime()}),z$1.object({errorSummary:z$1.string().max(500),errorData:Li,logEntries:z$1.array(ki),cliVersion:z$1.string(),outcome:Ni,indexType:Ti}),z$1.object({status:Ri.exclude(["archived"])}),z$1.object({id:z$1.string(),organizationId:z$1.string(),userId:z$1.string(),projectId:z$1.string(),branchName:z$1.string(),commitHash:z$1.string().nullable(),indexType:Ti,status:Ri,outcome:Ni,errorSummary:z$1.string(),errorData:Li,logEntries:z$1.array(ki),cliVersion:z$1.string(),resolvedAt:z$1.string().nullable(),resolvedBy:z$1.string().nullable(),createdAt:z$1.string(),updatedAt:z$1.string(),organizationName:z$1.string().optional(),projectName:z$1.string().optional(),userEmail:z$1.string().optional(),resolvedByEmail:z$1.string().optional()}),z$1.object({unresolvedCount:z$1.number(),failedRunCount:z$1.number(),resolvedLast30d:z$1.number(),avgResolutionDays:z$1.number().nullable(),affectedOrgCount:z$1.number()}),nc=["org-admin-v1","developer-v1","constellation-admin-v1"],ic=z$1.enum(nc),oc=["eligible","completed","dismissed","ineligible"],sc=z$1.enum(oc),z$1.object({tourId:ic,status:sc,lastStepReached:z$1.string().max(64).optional()}),z$1.object({stepId:z$1.string().min(1).max(64)});});function nn(i){return i.length>zt&&(i[zt]=ji),i}function Ai(){let i=false,e=0;return new Transform({transform(t,r,o){if(i){o(null,t);return}if(e+t.length>zt){let s=zt-e;t[s]=ji,i=true;}e+=t.length,o(null,t);}})}var zt,ji,on=g(()=>{zt=9,ji=255;});function Fi(i){return base32.encode(Buffer.from(i))}var $i=g(()=>{});function Di(i,e,t){let r=`${i}:${e}${t?`:${t}`:""}`;return Fi(r)}var Oi=g(()=>{$i();});var Kt,Mi=g(()=>{Kt=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)+`
|
|
35
|
+
`,o=Buffer.from(r,"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),r=>t(e||r)):t(e);}};});function Gi(){return Ui.some(i=>!!process.env[i])}function Bi(){return !!process.stdout.isTTY}function Wi(){let i=Ui.find(e=>!!process.env[e]);return i?pc[i]:void 0}var Ui,pc,sn=g(()=>{Ui=["GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE","CI"],pc={GITHUB_ACTIONS:"github-actions",GITLAB_CI:"gitlab",JENKINS_URL:"jenkins",CIRCLECI:"circleci",TRAVIS:"travis",BUILDKITE:"buildkite",DRONE:"drone",CI:"unknown"};});function uc(i){switch(i){case "darwin":return "Macintosh";case "win32":return "Windows";case "linux":return "Linux";case "freebsd":return "FreeBSD";default:return i.charAt(0).toUpperCase()+i.slice(1)}}function dc(i,e){return i==="darwin"?`Darwin ${e}`:e}function mc(){let i=globalThis.__constellationVersion;return typeof i=="string"&&i.length>0?i:"unknown"}function gc(i={}){let e=i.platform??process.platform,t=i.arch??process.arch,r=(i.nodeVersion??process.version).replace(/^v/,""),o=i.osRelease??Oe.release(),s=mc(),a=uc(e),l=dc(e,o),c=`constellation-cli/${s} (${a}; ${l}; ${t}) Node/${r}`,u=Wi();return u&&(c+=` CI/${u}`),c}var St,zi=g(()=>{sn();St=gc();});var Vt,Jt,$,_e,ge,Le,Pe,cn=g(()=>{bt();z();on();Oi();Mi();zi();Vt=class i{constructor(e,t,r=false,o){this.config=e;this.accessKey=t;this.dirty=r;this.reporter=o;}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 r of t.split(",")){let[o,s]=r.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(),r=t?.code;switch(r){case "PROJECT_NOT_REGISTERED":throw new ge(t?.message||"Project not registered",r,this.config.projectId);case "PROJECT_INACTIVE":throw new ge(t?.message||"Project is inactive",r,this.config.projectId);case "INVALID_PROJECT_ID":throw new ge(t?.message||"Invalid project ID format",r,this.config.projectId);case "PROJECT_NOT_FOUND":throw new _e("Project not found - no previous index exists");default:throw e.status===404?new _e("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof ge||t instanceof _e?t:e.status===404?new _e("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let r=new URLSearchParams({branch:e});t&&r.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${r.toString()}`;try{let s=await this.sendRequest(o,null,"GET");if(!s||!s.ok)return null;let a=await s.json(),l=rn.safeParse(a);return l.success?l.data:(this.reporter?.warn(`[constellation] getIndexStatus: unrecognized response shape \u2014 ${l.error.issues.map(c=>c.message).join("; ")}`),null)}catch(s){if(s instanceof $)throw s;return null}}async claimAstLock(e,t,r,o,s){let a=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":r?"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 $("Authentication failed");if(!a.ok){let u=await this.formatErrorBody(a);throw new Error(`Failed to claim indexing lock: ${a.status}${u?` \u2014 ${u}`:""}`)}let l=await a.json(),c=_i.safeParse(l);if(!c.success)throw new Error(`Invalid lock response from server: ${c.error.issues.map(u=>u.message).join("; ")}`);return c.data}async pollIndexStatus(e,t,r,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(r)}`,null,"GET",{"x-constellation-dirty":this.dirty?"true":"false"});if(!c)continue;if(c.status===401)throw new $("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let u=await c.json(),p=rn.safeParse(u);if(p.success){if(p.data.status==="current")return !0;if(p.data.status==="stale"||p.data.status==="failed")return !1}}}catch(c){if(c instanceof $)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadToQueue(e,t,r,o,s){return this.streamToApi(e,"ast/queue",t,r,true,o,s)}async startEnrichment(e,t,r){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","User-Agent":St,"x-project-id":t,"x-branch-name":r,"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 this.reporter?.warn(`Enrichment start heartbeat rejected: ${a}`),!1}catch(s){return this.reporter?.warn(`Enrichment start heartbeat failed: ${s instanceof Error?s.message:String(s)}`),false}finally{o.destroy().catch(()=>{});}}async uploadEnrichment(e,t,r,o){let s=[5e3,1e4,2e4],a=_n.gzipSync(Buffer.from(e,"utf8")),l=new Agent({headersTimeout:0,bodyTimeout:0});try{for(let c=0;c<=s.length;c++)try{let u=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/x-ndjson; charset=utf-8","Content-Encoding":"gzip","User-Agent":St,"x-project-id":t,"x-branch-name":r,"x-commit-hash":o,"x-constellation-dirty":this.dirty?"true":"false"},body:a,dispatcher:l});if(u.status===401)throw new $("Authentication failed during enrichment upload");if(u.status===409){if((await u.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return this.reporter?.warn("Enrichment skipped: index state changed since upload"),!1;if(c<s.length){await new Promise(d=>setTimeout(d,s[c]));continue}return this.reporter?.warn("Enrichment skipped: indexing still in progress after retries"),!1}return u.ok||u.status===202?!0:(this.reporter?.warn(`Enrichment upload failed with status ${u.status}`),!1)}catch(u){if(u instanceof $)throw u;if(c<s.length){this.reporter?.warn(`Enrichment upload network error (attempt ${c+1}/${s.length+1}): ${u instanceof Error?u.message:String(u)}`),await new Promise(p=>setTimeout(p,s[c]));continue}return this.reporter?.warn(`Enrichment upload error: ${u instanceof Error?u.message:String(u)}`),!1}return !1}finally{l.destroy().catch(()=>{});}}async deleteFiles(e){for(let t of e){let r=Di(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${r}`);}}retryableStatusCodes=[500,502,503,504];static RETRYABLE_NETWORK_ERROR_CODES=new Set(["UND_ERR_SOCKET","UND_ERR_SOCKET_ERROR","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNRESET","EPIPE","ETIMEDOUT","EAI_AGAIN"]);isRetryableNetworkError(e){if(!e||typeof e!="object")return false;let t=e,r=typeof t.code=="string"?t.code:typeof t.cause?.code=="string"?t.cause.code:void 0;return r?i.RETRYABLE_NETWORK_ERROR_CODES.has(r):false}shortNetworkErrorReason(e){if(!e||typeof e!="object")return String(e);let t=e,r=typeof t.cause?.code=="string"?t.cause.code:typeof t.code=="string"?t.code:void 0,o=typeof t.message=="string"&&t.message.length>0?t.message:"network error";return r?`${o} (${r})`:o}async parseIndexingConflict(e){let t="Indexing already in progress",r;try{let o=await e.json();t=o?.message||t,r=o?.details?.branchName;}catch{}return new Le(t,r)}async formatErrorBody(e){try{let t=await e.json();if(typeof t?.message=="string"){let r=typeof t.code=="string"&&t.code.length>0?` [${t.code}]`:"";return `${t.message}${r}`}if(Array.isArray(t?.message))return t.message.join("; ");if(typeof t?.code=="string")return t.code}catch{}return ""}async streamToApi(e,t,r,o,s,a,l){try{let c=new Kt(e),u=await buffer(c),p=process.env.CAPTURE_PAYLOAD_PATH;if(p)try{await pipeline(Readable.from(u),_n.createGzip(),Ai(),je.createWriteStream(p));}catch(f){this.reporter?.warn(`[constellation] capture tap failed: ${f instanceof Error?f.message:String(f)}`);}let d=[1e3,2e3,4e3],m;for(let f=0;f<=d.length;f++){let h=new Agent({headersTimeout:0,bodyTimeout:0});try{let S=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","Content-Length":String(u.byteLength),"User-Agent":St,"x-project-id":r,"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:u,dispatcher:h});if(S.status===401)throw new $("Authentication failed");if(S.status===409)throw await this.parseIndexingConflict(S);if(S.status===200)try{let y=await S.json();if(y?.status==="current")return this.reporter?.summary(`${E} Index already up to date for ${o} at commit ${y.commitHash||"unknown"}`),!0}catch{}if(S.ok||S.status===202)return !0;let v=`Server returned ${S.status}`;try{let y=await S.json();y?.message&&(v=Array.isArray(y.message)?y.message.join("; "):y.message);}catch{}throw new Error(v)}catch(S){if(S instanceof $||S instanceof Le)throw S;if(this.isRetryableNetworkError(S)&&f<d.length){let v=Math.floor(Math.random()*250),y=d[f]+v;this.reporter?.warn(`Upload network error (attempt ${f+1}/${d.length+1}): ${this.shortNetworkErrorReason(S)} \u2014 retrying in ${y}ms`),m=S,await new Promise(C=>setTimeout(C,y));continue}throw S}finally{h.destroy().catch(()=>{});}}throw m??new Error("Upload failed after exhausting retry budget")}catch(c){if(c instanceof $||c instanceof Le)throw c;let u=c instanceof Error?c:new Error(String(c)),p="";if(u.message==="fetch failed"||c.code){let m=[],f=c.code||c.cause?.code;if(c.code&&m.push(`Error Code: ${c.code}`),c.cause){let h=c.cause;h.code&&m.push(`Cause Code: ${h.code}`),h.errno&&m.push(`Errno: ${h.errno}`),h.syscall&&m.push(`System Call: ${h.syscall}`),h.address&&m.push(`Address: ${h.address}`),h.port&&m.push(`Port: ${h.port}`);}f==="ERR_INVALID_ARG_VALUE"?p="Invalid argument value - check stream/body format and duplex option":f==="ECONNREFUSED"?p="Connection refused - service may be down or unreachable":f==="ENOTFOUND"?p="DNS lookup failed - check service URL":f==="ETIMEDOUT"?p="Connection timeout - service not responding":f==="ECONNRESET"?p="Connection reset by server":f==="EHOSTUNREACH"?p="Host unreachable - check network connectivity":p="Network failure",m.length>0&&(p+=` (${m.join(", ")})`);}else p=u.message;let d=new Error(`Failed to upload data to Constellation Service: ${p}`);throw d.cause=u,d.stack=`${d.stack}
|
|
36
|
+
Caused by: ${u.stack}`,d}}async sendRequest(e,t,r,o={},s=0,a=3,l=1e3,c=250){for(let u=1;u<=a;u++){let p;try{let d=new AbortController;s>0&&(p=setTimeout(()=>d.abort(),s));let m={...o,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8","User-Agent":St,Authorization:`Bearer ${this.accessKey}`},f=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:r,headers:m,body:t?JSON.stringify(t):void 0,signal:d.signal});if(p&&clearTimeout(p),f.status===401)throw new $("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new Jt(`${f.statusText} (${f.status})`);return f}catch(d){if(p&&clearTimeout(p),!(d instanceof $)){let m=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);this.reporter?.warn(`HTTP request attempt ${u}/${a} failed: ${m}`);}if(u<a&&d instanceof Jt){let m=l+Math.floor(Math.random()*c);await new Promise(f=>setTimeout(f,m));}else throw d}}}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){this.reporter?.warn("Failed to upload error report: no response received");return}if(t.status===403){this.reporter?.warn("Error reporting is not available on your current plan");return}t.ok||this.reporter?.warn(`Failed to upload error report: ${t.statusText} (${t.status})`);}catch(t){this.reporter?.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"},r=await this.sendRequest(e,void 0,"DELETE",t);if(r&&!r.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Jt=class extends Error{constructor(e){super(e),this.name="RetryableError";}},$=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},_e=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},ge=class extends Error{constructor(t,r,o){super(t);this.code=r;this.projectId=o;this.name="ProjectValidationError";}},Le=class extends Error{constructor(t,r){super(t);this.branchName=r;this.name="IndexingInProgressError";}},Pe=class extends Error{constructor(t,r){super(t);this.errorCode=r;this.name="GitValidationError";}};});function K(i){return i.replace(/\\/g,"/")}function Yt(i){return K(i).replace(/^\.?\//,"")}function V(i,e){return K(R.relative(i,e))}var fe=g(()=>{});var Ve,un=g(()=>{Ve=class{constructor(e=10,t={}){this.concurrency=e;this.options=t;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,a=new Map,l=new Set,c=0;for(;s<e.length&&r.size<this.concurrency;){let u=o++,p=s,d=this.processItem(e[p],p,t).then(m=>({result:m!==null?m.result:null,index:p,promiseId:u}));r.set(u,d),s++;}for(;r.size>0;){let u=await Promise.race(r.values());if(r.delete(u.promiseId),this.options.preserveOrder)for(u.result!==null?a.set(u.index,u.result):l.add(u.index);c<e.length&&(a.has(c)||l.has(c));){if(a.has(c)){let p=a.get(c);a.delete(c),yield p;}else l.delete(c);c++;}else u.result!==null&&(yield u.result);if(s<e.length){let p=o++,d=s,m=this.processItem(e[d],d,t).then(f=>({result:f!==null?f.result:null,index:d,promiseId:p}));r.set(p,m),s++;}}}async processItem(e,t,r){try{return {result:await r(e,t),index:t}}catch{return null}}};});var Sc,wc,Xt,xc,Qt,Ji=g(()=>{fe();un();Sc={function:{hover:true,references:true,callHierarchy:true,implementation:false},method:{hover:true,references:true,callHierarchy:true,implementation:true},class:{hover:false,references:true,callHierarchy:false,implementation:true},interface:{hover:false,references:true,callHierarchy:false,implementation:true},struct:{hover:false,references:true,callHierarchy:false,implementation:true},variable:{hover:true,references:true,callHierarchy:false,implementation:false},property:{hover:true,references:true,callHierarchy:false,implementation:false},import:{hover:true,references:false,callHierarchy:false,implementation:false}},wc={hover:true,references:true,callHierarchy:false,implementation:false},Xt=1e4,xc=1200*1e3,Qt=class{constructor(e,t){this.projectRoot=e;this.reporter=t;}async enrich(e,t,r,o,s){let a=[],l=Date.now(),c={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,lspProcessCrashes:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null,firstLspCrashLanguage:null},u=false,p=new Set,d=new Set;return await Promise.all([...e.entries()].map(async([m,f])=>{let h=r.get(m);if(!h)return;let S=f.length,v=S>1e4?8:S>5e3?10:16,y=new Ve(v),C=()=>{p.add(m),d.has(h.serverId)||(d.add(h.serverId),c.lspProcessCrashes++,c.firstLspCrashLanguage||(c.firstLspCrashLanguage=m)),this.reporter?.warn(`[LSP:${m}] Process exited mid-enrichment (concurrency=${v}); halting subsequent ${m} files.`);},P=h.onCrash(C),b=0,_=y.run(f,async w=>{try{if(u||Date.now()-l>xc)return u=!0,null;if(p.has(m))return null;let I=await this.openFile(h,w,c,o?.get(w));if(!I)return null;let{uri:A}=I;try{let j=t.get(w)??[];if(j.length===0&&(j=await this.discoverSymbols(h,w,A,c),j.length===0))return c.filesNoSymbols++,null;let W=await this.enrichOpenFile(h,w,A,j,c);return W.length>0?{filePath:w,language:m,symbols:W}:null}finally{this.closeFile(h,A);}}finally{b++,s?.(m,b,S);}});try{for await(let w of _)w&&a.push(w);}finally{P();}})),u&&this.reporter?.info("Enrichment timeout reached. Uploading partial results."),this.logDiagnostics(c),a}async openFile(e,t,r,o){let s=R.resolve(this.projectRoot,t),a=pathToFileURL(s).href,l=o;if(l===void 0)try{l=await je.promises.readFile(s,"utf-8");}catch(c){return r.filesUnreadable++,r.firstFileError||(r.firstFileError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(t),version:1,text:l}});}catch(c){return r.filesOpenFailed++,r.firstOpenError||(r.firstOpenError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}return {uri:a,content:l}}closeFile(e,t){try{e.sendNotification("textDocument/didClose",{textDocument:{uri:t}});}catch{}}async enrichOpenFile(e,t,r,o,s){let a=await Promise.allSettled(o.map(c=>this.querySymbol(e,r,c,s))),l=[];for(let c=0;c<a.length;c++){let u=a[c];if(u.status==="fulfilled")u.value&&l.push(u.value);else if(s.symbolQueryErrors++,!s.firstSymbolError){let p=o[c];s.firstSymbolError=`${p.name} in ${t}: ${u.reason instanceof Error?u.reason.message:String(u.reason)}`;}}return l}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.filesNoSymbols>0&&t.push(`${e.filesNoSymbols} files had no discoverable symbols`),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`),e.lspProcessCrashes>0&&t.push(`${e.lspProcessCrashes} LSP process crashes`);let r=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(r.length>0){let o=r.reduce((a,[,l])=>a+l,0),s=r.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(this.reporter?.warn(`Enrichment issues: ${t.join(", ")}`),e.firstFileError&&this.reporter?.warn(`First file read error: ${e.firstFileError}`),e.firstOpenError&&this.reporter?.warn(`First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&this.reporter?.warn(`First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&this.reporter?.warn(`First symbol query error: ${e.firstSymbolError}`));}async querySymbol(e,t,r,o){let s=r.kind.toLowerCase(),a=Sc[s]||wc,c=!r.isExported&&(s==="function"||s==="method")?{...a,callHierarchy:false}:a,u={line:r.line-1,character:r.column},p={textDocument:{uri:t},position:u},d={name:r.name,line:r.line,column:r.column,kind:r.kind},m=false,[f,h,S]=await Promise.allSettled([c.hover?e.sendRequest("textDocument/hover",p,Xt):null,c.references?e.sendRequest("textDocument/references",{...p,context:{includeDeclaration:false}},Xt):null,c.implementation?e.sendRequest("textDocument/implementation",p,Xt):null]);for(let v of [f,h])v.status==="rejected"&&o.queryRejections++;if(f.status==="fulfilled"&&f.value?.contents){let v=f.value,y=typeof v.contents=="string"?v.contents:v.contents.value||"";y&&(d.typeInfo={resolvedType:y},m=true);}if(h.status==="fulfilled"&&h.value){let v=h.value;if(v.length>0){let y=v.slice(0,100).map(C=>({filePath:V(this.projectRoot,this.uriToPath(C.uri||"")),line:(C.range?.start?.line??0)+1,column:C.range?.start?.character??0}));d.references={count:v.length,locations:y},m=true;}}if(c.implementation&&S.status==="fulfilled"){let v=S.value,C=(Array.isArray(v)?v:v?[v]:[]).slice(0,200).map(P=>{let b=P.targetUri??P.uri??"",_=P.targetSelectionRange??P.targetRange??P.range??null;return {filePath:V(this.projectRoot,this.uriToPath(b)),line:(_?.start?.line??0)+1,column:_?.start?.character??0}});d.implementations=C,C.length>0&&(m=true);}if(c.callHierarchy)try{let v=await e.sendRequest("textDocument/prepareCallHierarchy",p,Xt);if(v&&v.length>0){let y=v[0],[C,P]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:y}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:y}).catch(()=>[])]),b=200,_=[];for(let I of C||[]){let A=Array.isArray(I.fromRanges)?I.fromRanges:[];if(A.length===0)continue;let j=V(this.projectRoot,this.uriToPath(I.from?.uri||"")),W=I.from?.name||"";for(let T of A){if(_.length>=b)break;_.push({name:W,filePath:j,line:(T?.start?.line??0)+1,column:T?.start?.character??0});}if(_.length>=b)break}let w=[];for(let I of P||[]){let A=Array.isArray(I.fromRanges)?I.fromRanges:[];if(A.length===0)continue;let j=V(this.projectRoot,this.uriToPath(I.to?.uri||"")),W=I.to?.name||"";for(let T of A){if(w.length>=b)break;w.push({name:W,filePath:j,line:(T?.start?.line??0)+1,column:T?.start?.character??0});}if(w.length>=b)break}(_.length>0||w.length>0)&&(d.callHierarchy={incomingCalls:_,outgoingCalls:w},m=!0);}}catch{o.queryRejections++;}if(!m){let v=r.kind.toLowerCase();o.symbolsWithNoEnrichment[v]=(o.symbolsWithNoEnrichment[v]??0)+1;}return m?d:null}async discoverSymbols(e,t,r,o){try{let s=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:r}});return !s||!Array.isArray(s)?[]:this.flattenDocumentSymbols(s)}catch(s){return o.discoveryErrors++,o.firstDiscoveryError||(o.firstDiscoveryError=`${t}: ${s instanceof Error?s.message:String(s)}`),[]}}flattenDocumentSymbols(e){let t=[],r={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=r[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,isExported:true}),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=R.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function qi(i){return i.map(e=>JSON.stringify(e)).join(`
|
|
37
37
|
`)+`
|
|
38
|
-
`}var
|
|
38
|
+
`}var Yi=g(()=>{});function he(i){try{return execFileSync(process.platform==="win32"?"where":"which",[i],{stdio:"ignore"}),!0}catch{return false}}var x,le=g(()=>{x={async directoryExists(i){try{return (await Q__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await Q__default.access(i,Q__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await Q__default.readFile(i,{encoding:e,flag:Q__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let r=Buffer.from(e,t);await Q__default.writeFile(i,r,{encoding:t,flag:Q__default.constants.O_WRONLY|Q__default.constants.O_CREAT|Q__default.constants.O_TRUNC});},async getFileStats(i){return await Q__default.stat(i)},async getFileHandle(i,e,t){return await Q__default.open(i,e,t)}};});var er,Xi=g(()=>{er=class i{constructor(e,t,r=1e4,o){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=r;this.reporter=o;this.stdout.on("data",s=>this.handleData(s)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
|
|
39
39
|
\r
|
|
40
40
|
`);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,r){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 ${r??this.defaultTimeoutMs}ms`));},r??this.defaultTimeoutMs);this.pendingRequests.set(o,{resolve:a,reject:l,timer:c}),this.writeMessage(s);})}sendNotification(e,t){if(this.disposed)return;let r={jsonrpc:"2.0",method:e,...t!==void 0&&{params:t}};this.writeMessage(r);}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
|
|
41
41
|
\r
|
|
42
|
-
`;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,this.reporter?.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
|
|
43
|
-
`)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let r=
|
|
44
|
-
`,"utf-8"),await
|
|
42
|
+
`;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,this.reporter?.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 Je,rr,Ie,xt=g(()=>{Je=R.join(Oe.homedir(),".constellation","lsp-servers"),rr=R.join(Je,"node_modules",".bin"),Ie=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"]}],["go",{command:"gopls",args:["serve"],npmPackages:[],testCommand:["version"],manualInstall:{requires:"Go (https://go.dev/dl/)",command:"go install golang.org/x/tools/gopls@latest",pathNote:"After install, ensure $GOPATH/bin (or ~/go/bin) is on your PATH.",autoInstall:{prerequisite:"go",argv:["go","install","golang.org/x/tools/gopls@latest"],env:{GOBIN:R.join(Je,"bin")},installedBinaryPath:R.join(Je,"bin",Oe.platform()==="win32"?"gopls.exe":"gopls")}}}]]);});function Zi(i){return i.replace(/\\/g,"/")}function Pc(i){let e=Zi(i);return R.posix.basename(e).toLowerCase().replace(/\.(exe|com|bat|cmd|ps1)$/i,"")}function eo(i,e){if(!i||i.trim().length===0)return {classification:"denied",reason:"LSP command is empty"};let t=Zi(i);if(_c.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(`
|
|
43
|
+
`)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let r=Pc(i);if(Ec.has(r))return {classification:"denied",reason:`LSP command resolves to a shell or interpreter ('${r}')`};for(let[,o]of Ie)if(r===o.command.toLowerCase())return {classification:"known-safe"};return {classification:"custom-untrusted"}}var Ec,_c,to=g(()=>{xt();Ec=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())),_c=/[;&|`$<>\n\r\0"']/;});function ro(i,e,t,r){return i.projectRoot===e&&i.command===t&&i.args.length===r.length&&i.args.every((o,s)=>o===r[s])}function Ic(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 qe,dn=g(()=>{qe=class{constructor(e){this.trustFilePath=e;}async isTrusted(e,t,r){return (await this.load()).entries.some(s=>ro(s,e,t,r))}async recordTrust(e,t,r){let o=await this.load();if(o.entries.some(l=>ro(l,e,t,r)))return;o.entries.push({projectRoot:e,command:t,args:[...r],trustedAt:new Date().toISOString()}),await Q.mkdir(R.dirname(this.trustFilePath),{recursive:true});let a=`${this.trustFilePath}.${process.pid}.tmp`;try{await Q.writeFile(a,JSON.stringify(o,null,2)+`
|
|
44
|
+
`,"utf-8"),await Q.rename(a,this.trustFilePath);}catch(l){throw await Q.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await Q.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(Ic)}:{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 nr,io=g(()=>{to();dn();nr=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??qe.isCIEnvironment;}async authorize(e,t,r){let{classification:o,reason:s}=eo(t,r);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,r))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=r.length>0?` ${r.join(" ")}`:"",l=`Trust custom LSP command for this project?
|
|
45
45
|
${t}${a}
|
|
46
46
|
|
|
47
47
|
Only approve commands you recognize. Untrusted commands can execute arbitrary code.
|
|
48
|
-
Approve?`,c=false;try{c=await this.prompt(l);}catch{c=false;}return c?(await this.trustStore.recordTrust(this.projectRoot,t,r),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
|
|
48
|
+
Approve?`,c=false;try{c=await this.prompt(l);}catch{c=false;}return c?(await this.trustStore.recordTrust(this.projectRoot,t,r),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 Lc,kc,ir,so=g(()=>{le();Xi();xt();io();dn();Lc={log:i=>process.stderr.write(i+`
|
|
49
49
|
`),warn:i=>process.stderr.write(i+`
|
|
50
50
|
`),error:i=>process.stderr.write(i+`
|
|
51
|
-
`)},$l=E.join(Pe.homedir(),".constellation","lsp-trust.json"),Ot=class{constructor(e,t,r){this.projectRoot=e;this.logger=t??Fl,this.policy=r??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new Dt({projectRoot:this.projectRoot,logger:this.logger,trustStore:new De($l),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.unavailableLanguages.has(e))return null;let r=this.languageToServerKey.get(e),o=r?this.serversByKey.get(r):void 0;if(o)return this.toConnection(o,e);let s=this.resolveCommand(e,t);if(!s)return this.unavailableLanguages.add(e),null;let{command:a,args:l}=s,c=this.getServerKey(a,l);if(this.unavailableServerKeys.has(c))return this.unavailableLanguages.add(e),null;let u=this.serversByKey.get(c);if(u)return u.languages.add(e),this.languageToServerKey.set(e,c),this.toConnection(u,e);if(!await this.policy.authorize(e,a,l))return this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c),null;try{let d=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((y,b)=>{d.once("spawn",y),d.once("error",b);}),d.stderr?.on("data",y=>{let b=y.toString().trim();b.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${b}`);});let m=new Ft(d.stdin,d.stdout,12e4),h=await m.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);m.sendNotification("initialized",{});let g={key:c,language:e,languages:new Set([e]),process:d,client:m,crashHandlers:new Set,intentionalShutdown:!1};return this.serversByKey.set(c,g),this.languageToServerKey.set(e,c),d.on("exit",y=>{let b=this.serversByKey.get(c);if(b){if(b.intentionalShutdown)b.crashHandlers.clear();else {let v=[...b.crashHandlers];b.crashHandlers.clear();for(let T of v)try{T();}catch(N){this.logger.warn(`[LSP:${b.language}] crash handler threw: ${N instanceof Error?N.message:String(N)}`);}}b.client.dispose(),this.serversByKey.delete(c);for(let[v,T]of this.languageToServerKey.entries())T===c&&this.languageToServerKey.delete(v);}y!==0&&y!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${y}`);}),this.toConnection(g,e)}catch(d){this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let m=`[LSP:${e}] Failed to start: ${d instanceof Error?d.message:String(d)}`,h=d?.code;return h==="ENOENT"||h==="EACCES"?this.logger.warn(m):this.logger.error(m),null}}async shutdown(e){let t=this.languageToServerKey.get(e);if(!t)return;this.languageToServerKey.delete(e);let r=this.serversByKey.get(t);r&&(r.languages.delete(e),!(r.languages.size>0)&&await this.shutdownByKey(t));}async shutdownByKey(e){let t=this.serversByKey.get(e);if(t){t.intentionalShutdown=true;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:${t.language}] Graceful shutdown failed, force killing: ${r instanceof Error?r.message:String(r)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.serversByKey.delete(e);for(let[r,o]of this.languageToServerKey.entries())o===e&&this.languageToServerKey.delete(r);}}}async shutdownAll(){let e=[...this.serversByKey.keys()];await Promise.allSettled(e.map(t=>this.shutdownByKey(t)));}destroyAll(){for(let e of this.serversByKey.values()){e.intentionalShutdown=true;try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.serversByKey.clear(),this.languageToServerKey.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let r=ye.get(e);if(!r)return null;let o=E.join($t,r.command);return existsSync(o)?{command:o,args:r.args}:$e(r.command)?{command:r.command,args:r.args}:null}getServerKey(e,t){return `${e}\0${t.join("\0")}`}toConnection(e,t){let r=`lsp-${t}-${this.nextId++}`;return {language:t,process:e.process,id:r,serverId:e.key,sendRequest:(o,s,a)=>e.client.sendRequest(o,s,a),sendNotification:(o,s)=>e.client.sendNotification(o,s),onCrash:o=>(e.crashHandlers.add(o),()=>e.crashHandlers.delete(o))}}};});var be,Mt=f(()=>{be=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var Oe,Hr=f(()=>{M();Oe=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(`${A} 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(`${A} Failed to parse ${r}: ${o}`),console.warn(`${A} Path alias resolution will be skipped for files using this config`);}else r||console.warn(`${A} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var Ut,Fi=f(()=>{we();Ut=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?E.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=E.resolve(r,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=E.join(this.projectRoot,"package.json"),r=await J.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 p=await this.loadWorkspacePackage(u);p&&Object.assign(e,p);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let r=e.slice(0,-2),o=E.join(this.projectRoot,r);try{let s=await J.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(E.join(o,a.name));}catch{}}else {let r=E.join(this.projectRoot,e);try{(await J.stat(r)).isDirectory()&&t.push(r);}catch{}}return t}async loadWorkspacePackage(e){try{let t=E.join(e,"package.json"),r=await J.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 E.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return E.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return E.join(e,a)}}}if(t.main)return E.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=E.join(e,o);try{if((await J.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=E.join(e,r);try{if((await J.stat(o)).isFile())return o}catch{}}try{if((await J.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")?E.dirname(e):E.dirname(e),o=[E.join(r,t+".ts"),E.join(r,t+".tsx"),E.join(r,t+".js"),E.join(r,t+".jsx"),E.join(r,t+".d.ts"),E.join(r,t,"index.ts"),E.join(r,t,"index.tsx"),E.join(r,t,"index.js"),E.join(r,t,"index.jsx")];for(let s of o)try{if((await J.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=W(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var Me,Wr=f(()=>{we();Fi();Me=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=E.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Ut(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=E.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=E.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=E.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=W(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=E.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=E.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=E.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await J.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await J.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let r=E.join(t,"package.json");try{if((await J.stat(r)).isFile())return r}catch{}let o=E.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 J.readFile(e,"utf-8"),r=JSON.parse(t);this.packageJsonDir=E.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=E.resolve(this.packageJsonDir,r);return await this.findFileWithExtensions(o)}};});var Gt,$i=f(()=>{Mt();Hr();Wr();Gt=class extends be{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new Oe(e,t)}getImportResolver(e,t){return new Me(e,t)}};});var Bt,Di=f(()=>{Mt();Hr();Wr();Bt=class extends be{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new Oe(e,t)}getImportResolver(e,t){return new Me(e,t)}};});async function le(i,e,t,r,o,s=[]){let a=await t.resolve(i),l=Oi(i,a),c=o(i,a,l),u=l?void 0:jt(a);r[e.toString()]={source:i,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function Oi(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var zr,it=f(()=>{we();zr=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function Ul(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 le(s,i.startPosition.row,e,t,r,[a]);}function Gl(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 Bl(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=Gl(i,!!s);await le(o,i.startPosition.row,e,t,r,a);}async function Hl(i,e,t,r){await le("__future__",i.startPosition.row,e,t,r,[]);}function Kr(){return {language:"python",handlers:new Map([["import_statement",Ul],["import_from_statement",Bl],["future_import_statement",Hl]]),classifyImportType:Ml}}var Ml,Ht=f(()=>{tt();it();tt();Ml=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let r=i.split(".")[0];return Ze.has(r)?"builtin":"alias"};});var Wt,Mi=f(()=>{Ht();Wt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=E.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(Ze.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let r=e.replace(/\./g,"/"),o=await this.tryResolveFile(E.resolve(this.projectRoot,r));return o?E.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=E.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?E.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,E.join(e,"__init__.py"),E.join(e,"__init__.pyi")];for(let r of t)try{return await zt.promises.access(r,zt.constants.F_OK),r}catch{continue}return null}};});var Kt,Ui=f(()=>{Mt();Mi();Kt=class extends be{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new Wt(e,process.cwd())}};});function xe(i){return Vl[i]??i.charAt(0).toUpperCase()+i.slice(1)}var Vl,ot,Vt,Jt=f(()=>{$i();Di();Ui();Vl={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"};ot={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"]},Vt=class{constructor(e){this.config=e;this.registerPlugin(new Gt),this.registerPlugin(new Bt),this.registerPlugin(new Kt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Wl,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??ot.javascript};typescript={language:()=>Kl.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??ot.typescript};python={language:()=>zl,fileExtensions:()=>this.config?.languages.python?.fileExtensions??ot.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function Ue(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 qt,Vr=f(()=>{qt=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function Jr(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&&Jl(t,e);}for(let t of i.namedChildren)t&&Jr(t,e);}function Jl(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(Ee(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(Ee(t.startPosition.row,t.startPosition.column),"call");}}var Gi=f(()=>{st();});function Ge(i,e){i.rootNode&&(Hi(i.rootNode,e),Jr(i.rootNode,e));}function Hi(i,e){if(ql.has(i.type)){let t=Yl(i);t!==null&&e.set(Ee(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&Hi(t,e);}function Yl(i){if(Ql(i))return "declaration";if(lc(i))return "read";if(sc(i))return "type";let e=Ue(i,t=>t.type==="decorator");return e!==null&&tc(i,e)?"call":ec(i)?"instantiate":Zl(i)?"call":rc(i)||nc(i)||ic(i)||hc(i)||fc(i)?"write":cc(i)?"import-use":"read"}function Ql(i){let e=i.parent;return e===null?false:!!(Xl.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 Zl(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 ec(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 tc(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 rc(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||qt.has(t.type))return false;e=t;}return false}function nc(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 ic(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||qt.has(t.type))return false;e=t;}return false}function sc(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||ac(r,i)}if(oc.has(e.type))return true;if(qt.has(e.type))return false;t=e,e=e.parent;}return false}function ac(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function lc(i){return Ue(i,t=>t.type==="type_query")!==null}function cc(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,r=mc(i);return gc(r,t)?!uc(i,t):false}function uc(i,e){let t=i.parent;for(;t!==null;){if(pc.has(t.type)&&dc(t,e))return true;t=t.parent;}return false}function dc(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 mc(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function gc(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 fc(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function hc(i){let e=i.parent;if(e===null||!Bi.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(!Bi.has(r.type))return false;t=r;}return false}var ql,Xl,oc,pc,Bi,Yt=f(()=>{st();Vr();Gi();ql=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));Xl=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"]));oc=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"]));pc=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Bi=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function Wi(i,e){Ge(i,e);}var zi=f(()=>{Yt();});function Ki(i,e){Ge(i,e);}var Vi=f(()=>{Yt();});function Ji(i,e){if(!i.rootNode)return;let t=Dc(i.rootNode);qi(i.rootNode,e,t);}function qi(i,e,t){if(yc.has(i.type)){let r=bc(i,t);r!==null&&e.set(Ee(i.startPosition.row,i.startPosition.column),r);}for(let r of i.namedChildren)r&&qi(r,e,t);}function bc(i,e){if(vc(i))return "declaration";if(Cc(i))return "read";if(wc(i))return "declaration";if(xc(i))return "type";let t=Ue(i,r=>r.type==="decorator");return t!==null&&Ec(i,t)||_c(i)?"call":Pc(i)||Ic(i)||Nc(i)||Tc(i)||jc(i)?"write":Ac(i,e)?"import-use":"read"}function vc(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"||Sc(i))}function Sc(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 wc(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(qr.has(e.type))return false;e=e.parent;}return false}function Cc(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function xc(i){return Ue(i,t=>t.type==="type")!==null}function Ec(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 _c(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 Pc(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||qr.has(t.type))return false;e=t;}return false}function Ic(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 Nc(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function Tc(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(Rc.has(t.type)){e=t;continue}if(qr.has(t.type))return false;e=t;}return false}function jc(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(!Lc.has(t.type))return false;e=t;}return false}function Ac(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let r=i.text;return e.has(r)?!Fc(i,r):false}function Fc(i,e){let t=i.parent;for(;t!==null;){if(kc.has(t.type)&&$c(t,e))return true;t=t.parent;}return false}function $c(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 Dc(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 yc,qr,Rc,Lc,kc,Yi=f(()=>{st();Vr();yc=Object.freeze(new Set(["identifier"])),qr=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));Rc=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));Lc=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));kc=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function Qi(i,e){let t=new Map;switch(e){case "typescript":Ge(i,t);break;case "tsx":Wi(i,t);break;case "javascript":Ki(i,t);break;case "python":Ji(i,t);break}return t}function Ee(i,e){return `${i}:${e}`}var Xi,st=f(()=>{Yt();zi();Vi();Yi();Xi=Object.freeze(new Set(["typescript","javascript","python"]));});function Uc(i,e){return Xi.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function Gc(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 Xt,to=f(()=>{st();ae();Xt=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=Kl.tsx);let s=new Oc;s.setLanguage(o);let a=await S.getFileStats(e),l=25*1024*1024,c,u;if(a.size<=l){let h=await S.readFile(e);u=h;let g={bufferSize:1024*1024};c=s.parse(h,void 0,g);}else c=await this.parseWithStream(s,e,a.size);let p=Uc(t,e),d=p===null?[]:Gc(Qi(c,p));return {tree:c,classificationMap:{filePath:e,entries:d},content:u}}async parseWithStream(e,t,r){let o=null;try{o=await J.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(p=>{if(r>50*1024*1024){let m=Math.round(p/r*100);m>c+10&&(process.stderr.write(` Parsing large file: ${m}%...
|
|
52
|
-
`)
|
|
53
|
-
`);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var Qt,no=f(()=>{ae();we();M();Qt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=ro();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=ro().add(t.exclude));let s=await J__default.realpath(this.rootPath);for(let a of e)try{let l=E__default.isAbsolute(a)?a:E__default.join(this.rootPath,a),c=await J__default.lstat(l);if(c.isSymbolicLink()){let u=await J__default.realpath(l);if(!u.startsWith(s+E__default.sep)&&u!==s){console.warn(`${A} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let p=await J__default.stat(l);if(!p.isFile())continue;let d=W(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:p.size});}else if(c.isFile()){let u=W(this.rootPath,l);if(o&&o.ignores(u))continue;let p=this.detectLanguage(u,t.languages);if(!p)continue;r.push({path:l,relativePath:u,language:p,size:c.size});}}catch{console.warn(`${A} Skipping inaccessible file: ${a}`);}return r}async loadGitignoreRules(e,t){let r=[],o=t;for(;;){let s=E__default.join(o,".gitignore");await S.fileIsReadable(s)&&r.unshift(s);let a=E__default.dirname(o);if(a===o)break;o=a;let l=E__default.join(o,".git");if(await S.directoryExists(l)){let c=E__default.join(o,".gitignore");await S.fileIsReadable(c)&&!r.includes(c)&&r.unshift(c);break}}for(let s of r)try{let a=await S.readFile(s);e.add(a);}catch{console.warn(`${A} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,r,o){let s=[],a=t||e,l=r||await J__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=(await J__default.readdir(e,{withFileTypes:!0})).map(p=>(p.name=p.name.normalize("NFC"),p)).sort((p,d)=>p.name<d.name?-1:p.name>d.name?1:0);for(let p of u){let d=E__default.join(e,p.name),m=W(a,d);if(p.isDirectory()){if(p.name.startsWith("."))continue;let h=await this.walkDirectory(d,a,l,c);s.push(...h);}else if(p.isFile()){let h=await J__default.stat(d);s.push({path:d,relativePath:m,language:"",size:h.size});}else if(p.isSymbolicLink())try{let h=await J__default.realpath(d);if(!h.startsWith(l+E__default.sep)&&h!==l){console.warn(`${A} Skipping symlink pointing outside project: ${d} -> ${h}`);continue}let g=await J__default.stat(d);if(g.isDirectory()){if(p.name.startsWith(".")||c.has(h))continue;c.add(h);let y=await this.walkDirectory(d,a,l,c);s.push(...y);}else g.isFile()&&s.push({path:d,relativePath:m,language:"",size:g.size});}catch{console.warn(`${A} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${re} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let r=E__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=E__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return o;return null}};});var Bc,Hc,Wc,io,oo=f(()=>{tt();Bc=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Hc=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(Bc).optional()}),Wc=z.record(z.string(),Hc),io=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,"Index data cannot be empty").max(1e7,"Index data exceeds 10MB limit"),importResolutions:Wc.optional(),classificationMap:Ir.optional()});});function zc(i){let e=Math.max(0,i)/1e3;if(e<60)return `(${e.toFixed(1)}s)`;let t=Math.floor(e/60),r=Math.floor(e%60);return `(${t}m ${r}s)`}function so(){let i=performance.now();return {elapsed:()=>zc(performance.now()-i),reset:()=>{i=performance.now();},ms:()=>performance.now()-i}}var ao=f(()=>{});var Yr,er=f(()=>{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 Xr(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 tr,lo=f(()=>{er();tr=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:stripVTControlCharacters(e.map(Xr).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:stripVTControlCharacters(e.map(Xr).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:stripVTControlCharacters(e.map(Xr).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);}record(e,t,r){this.entries.push({level:e,message:stripVTControlCharacters(t),timestamp:new Date().toISOString(),code:r});}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,r){this.entries.push({level:e,message:stripVTControlCharacters(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);}};});function Be(i){if(i&&typeof i=="object")try{i.alreadyReported=!0;}catch{}}function pe(i){return !!(i&&typeof i=="object"&&i.alreadyReported)}function Qr(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 co,Vc,Jc,rr,Zr=f(()=>{Le();ao();lo();M();co=Math.floor(1e3/15),Vc={interval:100,frames:["\u280B","\u2819","\u281A","\u2813"]},Jc=new Set(["EPIPE","ENOTCONN","EBADF"]);rr=class i{static activeInstance=null;mode;stream;logCollector=new tr;spinner=null;currentPhaseLabel=null;currentPhaseTracker=null;lastUpdateAt=0;pendingUpdate=null;pendingUpdateTimer=null;paused=false;originalConsole=null;intercepting=false;warningBucket=new Map;stopped=false;constructor(e){if(i.activeInstance&&!i.activeInstance.stopped)throw new Error("Reporter is a singleton \u2014 only one instance may be active at a time. Call stop() on the existing Reporter before constructing another.");this.mode=e.mode,this.stream=e.stream??process.stderr,i.activeInstance=this,this.installConsoleInterception();}async phase(e,t,r){this.start(e);let o=this.makePhaseContext();try{let s=await t(o);return this.flushPendingUpdate(),this.flushAggregatedWarnings(),this.succeed(r?.successText??e),s}catch(s){this.flushPendingUpdate(),this.flushAggregatedWarnings();let a=r?.failText??`${e} failed: ${s instanceof Error?s.message:String(s)}`,l=s&&typeof s=="object"&&"errorCode"in s?s.errorCode:void 0;throw this.fail(a,l?{code:l}:void 0),Be(s),s}}start(e){this.currentPhaseLabel=e,this.currentPhaseTracker=so(),this.mode==="spinner"?(this.spinner?this.spinner.text=this.composeSpinnerText(e):this.spinner=Kc({text:this.composeSpinnerText(e),stream:this.stream,spinner:Vc}),this.paused||this.spinner.start()):(this.mode==="verbose"||this.mode==="plain")&&this.writeLine(`${ie} ${e}\u2026`);}update(e){if(!this.currentPhaseLabel)return;if(this.currentPhaseLabel=e,this.mode==="verbose"){this.writeLine(`${ie} ${e}`);return}if(this.mode!=="spinner")return;let t=Date.now();this.pendingUpdate=e;let r=t-this.lastUpdateAt;r>=co?this.flushPendingUpdate():this.pendingUpdateTimer||(this.pendingUpdateTimer=setTimeout(()=>this.flushPendingUpdate(),co-r),this.pendingUpdateTimer.unref?.());}succeed(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",r=`${w} ${t}`;this.terminatePhase(r,"info");}fail(e,t){this.flushPendingUpdate();let r=e??this.currentPhaseLabel??"",o=`${re} ${r}`;this.terminatePhase(o,"error",t?.code);}info(e){if(this.mode==="quiet"){this.logCollector.record("info",e);return}this.logCollector.record("info",e),this.writeLine(`${ie} ${e}`);}warn(e,t){if(this.logCollector.record("warn",e,t?.code),this.currentPhaseLabel&&t?.code){let r=this.warningBucket.get(t.code);r?(r.count+=1,r.samples.length<3&&r.samples.push(e)):this.warningBucket.set(t.code,{code:t.code,count:1,samples:[e]});return}this.writeLine(`${A} ${e}`);}error(e,t){this.logCollector.record("error",e,t?.code),this.writeLine(`${re} ${e}`);}detail(e){this.logCollector.record("info",e),this.mode==="verbose"&&this.writeLine(` ${V.muted(e)}`);}log(e){this.logCollector.record("info",e),this.mode!=="quiet"&&this.writeLine(e);}summary(e){this.logCollector.record("info",e),this.writeLine(e);}step(e){let t=this;return {ok(r){t.renderSubStep("ok",r??e);},fail(r,o){t.renderSubStep("fail",r??e,o?.code);},skip(r){t.renderSubStep("skip",r??e);}}}renderSubStep(e,t,r){let s=`${e==="ok"?w:e==="fail"?re:V.muted("-")} ${e==="skip"?V.muted(t):t}`,a=e==="fail"?"error":"info";this.logCollector.record(a,t,r),!(this.mode==="quiet"&&e!=="fail")&&this.writeLine(s);}pause(){this.paused||(this.paused=true,this.spinner?.isSpinning&&this.spinner.stop());}resume(){this.paused&&(this.paused=false,this.mode==="spinner"&&this.currentPhaseLabel&&this.spinner&&(this.spinner.text=this.composeSpinnerText(this.currentPhaseLabel),this.spinner.start()));}getEntries(){return this.logCollector.getEntries()}getReportableErrors(){return this.logCollector.getReportableErrors()}hasErrors(){return this.logCollector.hasErrors()}hasWarnings(){return this.logCollector.hasWarnings()}hasReportableErrors(){return this.logCollector.hasReportableErrors()}stop(){this.stopped||(this.stopped=true,this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.flushAggregatedWarnings(),this.spinner?.isSpinning&&this.spinner.stop(),this.spinner=null,this.uninstallConsoleInterception(),i.activeInstance===this&&(i.activeInstance=null));}composeSpinnerText(e){return e}flushPendingUpdate(){if(this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.pendingUpdate===null||!this.spinner){this.pendingUpdate=null;return}this.spinner.text=this.composeSpinnerText(this.pendingUpdate),this.pendingUpdate=null,this.lastUpdateAt=Date.now();}terminatePhase(e,t,r){this.logCollector.record(t,e,r),this.spinner?.isSpinning&&this.spinner.stop(),this.mode!=="quiet"&&this.writeLine(e),this.currentPhaseLabel=null,this.currentPhaseTracker=null;}flushAggregatedWarnings(){if(this.warningBucket.size!==0){for(let{code:e,count:t,samples:r}of this.warningBucket.values()){if(t===1){this.writeLine(`${A} ${r[0]}`);continue}let o=`${t} ${e} warnings (showing ${Math.min(r.length,3)}): ${r.slice(0,3).join(" | ")}. Use --verbose to see all.`;this.logCollector.record("warn",o,e),this.writeLine(`${A} ${o}`);}this.warningBucket.clear();}}makePhaseContext(){return {update:e=>this.update(e),detail:e=>this.detail(e),step:e=>this.step(e),warn:(e,t)=>this.warn(e,t),elapsed:()=>this.currentPhaseTracker?.elapsed()??"(0.0s)"}}writeLine(e){try{this.mode==="spinner"&&this.spinner?.isSpinning?(this.spinner.clear(),this.stream.write(e+`
|
|
51
|
+
`)},kc=R.join(Oe.homedir(),".constellation","lsp-trust.json"),ir=class{constructor(e,t,r){this.projectRoot=e;this.logger=t??Lc,this.policy=r??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new nr({projectRoot:this.projectRoot,logger:this.logger,trustStore:new qe(kc),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.unavailableLanguages.has(e))return null;let r=this.languageToServerKey.get(e),o=r?this.serversByKey.get(r):void 0;if(o)return this.toConnection(o,e);let s=this.resolveCommand(e,t);if(!s)return this.unavailableLanguages.add(e),null;let{command:a,args:l}=s,c=this.getServerKey(a,l);if(this.unavailableServerKeys.has(c))return this.unavailableLanguages.add(e),null;let u=this.serversByKey.get(c);if(u)return u.languages.add(e),this.languageToServerKey.set(e,c),this.toConnection(u,e);if(!await this.policy.authorize(e,a,l))return this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c),null;try{let d=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((S,v)=>{d.once("spawn",S),d.once("error",v);}),d.stderr?.on("data",S=>{let v=S.toString().trim();v.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${v}`);});let m=new er(d.stdin,d.stdout,12e4),f=await m.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);m.sendNotification("initialized",{});let h={key:c,language:e,languages:new Set([e]),process:d,client:m,crashHandlers:new Set,intentionalShutdown:!1};return this.serversByKey.set(c,h),this.languageToServerKey.set(e,c),d.on("exit",(S,v)=>{let y=this.serversByKey.get(c);if(y){if(y.intentionalShutdown)y.crashHandlers.clear();else {let C=[...y.crashHandlers];y.crashHandlers.clear();for(let P of C)try{P();}catch(b){this.logger.warn(`[LSP:${y.language}] crash handler threw: ${b instanceof Error?b.message:String(b)}`);}this.logUnexpectedExit(e,S,v);}y.client.dispose(),this.serversByKey.delete(c);for(let[C,P]of this.languageToServerKey.entries())P===c&&this.languageToServerKey.delete(C);}}),this.toConnection(h,e)}catch(d){this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let m=`[LSP:${e}] Failed to start: ${d instanceof Error?d.message:String(d)}`,f=d?.code;return f==="ENOENT"||f==="EACCES"?this.logger.warn(m):this.logger.error(m),null}}async shutdown(e){let t=this.languageToServerKey.get(e);if(!t)return;this.languageToServerKey.delete(e);let r=this.serversByKey.get(t);r&&(r.languages.delete(e),!(r.languages.size>0)&&await this.shutdownByKey(t));}async shutdownByKey(e){let t=this.serversByKey.get(e);if(t){t.intentionalShutdown=true;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:${t.language}] Graceful shutdown failed, force killing: ${r instanceof Error?r.message:String(r)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.serversByKey.delete(e);for(let[r,o]of this.languageToServerKey.entries())o===e&&this.languageToServerKey.delete(r);}}}async shutdownAll(){let e=[...this.serversByKey.keys()];await Promise.allSettled(e.map(t=>this.shutdownByKey(t)));}destroyAll(){for(let e of this.serversByKey.values()){e.intentionalShutdown=true;try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.serversByKey.clear(),this.languageToServerKey.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let r=Ie.get(e);if(!r)return null;let o=R.join(rr,r.command);return existsSync(o)?{command:o,args:r.args}:he(r.command)?{command:r.command,args:r.args}:null}getServerKey(e,t){return `${e}\0${t.join("\0")}`}logUnexpectedExit(e,t,r){if(t!==null&&t!==0){this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${t}`);return}if(t===0)return;if(r==="SIGKILL"){this.logger.warn(`[LSP:${e}] Server killed by SIGKILL (possibly OOM-killed \u2014 check \`dmesg | tail\` or system memory pressure)`);return}if(r!==null){this.logger.warn(`[LSP:${e}] Server exited unexpectedly via signal ${r}`);return}let o=process.platform==="win32"?"external termination (e.g. Task Manager / taskkill)":"unknown cause (no exit code or signal reported)";this.logger.warn(`[LSP:${e}] Server exited unexpectedly \u2014 ${o}`);}toConnection(e,t){let r=`lsp-${t}-${this.nextId++}`;return {language:t,process:e.process,id:r,serverId:e.key,sendRequest:(o,s,a)=>e.client.sendRequest(o,s,a),sendNotification:(o,s)=>e.client.sendNotification(o,s),onCrash:o=>(e.crashHandlers.add(o),()=>e.crashHandlers.delete(o))}}};});var pe,Ct=g(()=>{pe=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}preflightLsp(e){return Promise.resolve({skip:false})}};});var Ye,gn=g(()=>{z();Ye=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(`${O} 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(`${O} Failed to parse ${r}: ${o}`),console.warn(`${O} Path alias resolution will be skipped for files using this config`);}else r||console.warn(`${O} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var or,lo=g(()=>{fe();or=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?R.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=R.resolve(r,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=R.join(this.projectRoot,"package.json"),r=await Q.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 p=await this.loadWorkspacePackage(u);p&&Object.assign(e,p);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let r=e.slice(0,-2),o=R.join(this.projectRoot,r);try{let s=await Q.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(R.join(o,a.name));}catch{}}else {let r=R.join(this.projectRoot,e);try{(await Q.stat(r)).isDirectory()&&t.push(r);}catch{}}return t}async loadWorkspacePackage(e){try{let t=R.join(e,"package.json"),r=await Q.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 R.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return R.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return R.join(e,a)}}}if(t.main)return R.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=R.join(e,o);try{if((await Q.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=R.join(e,r);try{if((await Q.stat(o)).isFile())return o}catch{}}try{if((await Q.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")?R.dirname(e):R.dirname(e),o=[R.join(r,t+".ts"),R.join(r,t+".tsx"),R.join(r,t+".js"),R.join(r,t+".jsx"),R.join(r,t+".d.ts"),R.join(r,t,"index.ts"),R.join(r,t,"index.tsx"),R.join(r,t,"index.js"),R.join(r,t,"index.jsx")];for(let s of o)try{if((await Q.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=V(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var Xe,fn=g(()=>{fe();lo();Xe=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=R.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new or(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=R.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=R.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=R.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=V(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=R.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=R.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=R.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await Q.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await Q.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let r=R.join(t,"package.json");try{if((await Q.stat(r)).isFile())return r}catch{}let o=R.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 Q.readFile(e,"utf-8"),r=JSON.parse(t);this.packageJsonDir=R.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=R.resolve(this.packageJsonDir,r);return await this.findFileWithExtensions(o)}};});var sr,co=g(()=>{Ct();gn();fn();sr=class extends pe{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new Ye(e,t)}getImportResolver(e,t){return new Xe(e,t)}};});var ar,po=g(()=>{Ct();gn();fn();ar=class extends pe{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new Ye(e,t)}getImportResolver(e,t){return new Xe(e,t)}};});async function ee(i,e,t,r,o,s=[]){let a=await t.resolve(i),l=uo(i,a),c=o(i,a,l),u=l?void 0:Yt(a);r[e.toString()]={source:i,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function uo(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var hn,Qe=g(()=>{fe();hn=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function $c(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 ee(s,i.startPosition.row,e,t,r,[a]);}function Dc(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 Oc(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=Dc(i,!!s);await ee(o,i.startPosition.row,e,t,r,a);}async function Mc(i,e,t,r){await ee("__future__",i.startPosition.row,e,t,r,[]);}function yn(){return {language:"python",handlers:new Map([["import_statement",$c],["import_from_statement",Oc],["future_import_statement",Mc]]),classifyImportType:Fc}}var Fc,lr=g(()=>{bt();Qe();bt();Fc=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let r=i.split(".")[0];return yt.has(r)?"builtin":"alias"};});var cr,mo=g(()=>{lr();cr=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=R.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(yt.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let r=e.replace(/\./g,"/"),o=await this.tryResolveFile(R.resolve(this.projectRoot,r));return o?R.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=R.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?R.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,R.join(e,"__init__.py"),R.join(e,"__init__.pyi")];for(let r of t)try{return await je.promises.access(r,je.constants.F_OK),r}catch{continue}return null}};});var ur,go=g(()=>{Ct();mo();ur=class extends pe{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new cr(e,process.cwd())}};});function fo(i){return i.replace(/\/\/[^\n]*/g,"")}function Ze(i){return i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i}function Uc(i,e){let t=[],r=/^\s*replace\s*\(\s*([\s\S]*?)\)/gm,o=[];for(let l of i.matchAll(r))o.push(l[1]);let s=i.replace(r,l=>" ".repeat(l.length)),a=/^\s*replace\s+(?!\()(.+?)\s*$/gm;for(let l of s.matchAll(a))o.push(l[1]);for(let l of o)for(let c of l.split(`
|
|
52
|
+
`)){let u=c.trim();if(!u)continue;let p=Gc(u,e);p&&t.push(p);}return t}function Gc(i,e){let t=i.indexOf("=>");if(t===-1)return null;let r=i.slice(0,t).trim().split(/\s+/).filter(Boolean),o=i.slice(t+2).trim().split(/\s+/).filter(Boolean);if(r.length===0||o.length===0)return null;let s=Ze(r[0]),a=r.length>=2?Ze(r[1]):void 0,l=Ze(o[0]);if(!Bc(l))return null;let c=R.isAbsolute(l)?l:R.resolve(e,l);return {originalModulePath:s,originalVersion:a,localDir:c}}function Bc(i){return i==="."||i===".."||i.startsWith("./")||i.startsWith("../")||R.isAbsolute(i)}var Ae,ho=g(()=>{fe();Ae=class i{constructor(e,t=true){this.projectRoot=e;this.enabled=t;}cache=new Map;discovered=[];initialized=false;goWorkPath=null;warnings=[];isEnabled(){return this.enabled}clearCache(){this.cache.clear(),this.discovered=[],this.initialized=false,this.goWorkPath=null,this.warnings=[];}consumeWarnings(){let e=this.warnings;return this.warnings=[],e}async initialize(){if(this.initialized)return this.configFilesPaths();if(this.goWorkPath=i.findGoWorkAncestor(this.projectRoot),this.goWorkPath!==null){let e=await this.parseGoWork(this.goWorkPath),t=await Promise.all(e.map(async r=>{let o=R.join(r,"go.mod"),s=await this.parseGoMod(o);return {useDir:r,modPath:o,info:s}}));for(let{useDir:r,modPath:o,info:s}of t)s?(this.discovered.push(s),this.cache.set(K(s.rootDir),s)):this.warnings.push(`go.work: use directive ${K(r)} has no parseable go.mod at ${K(o)}`);}else {let e=await this.findGoModFiles(this.projectRoot,0,6),t=await Promise.all(e.map(r=>this.parseGoMod(r)));for(let r of t)r&&(this.discovered.push(r),this.cache.set(K(r.rootDir),r));}return this.initialized=true,this.configFilesPaths()}configFilesPaths(){let e=this.discovered.map(t=>K(R.join(t.rootDir,"go.mod")));return this.goWorkPath!==null&&e.unshift(K(this.goWorkPath)),e}async getConfigForFile(e){this.initialized||await this.initialize();let t=R.isAbsolute(e)?e:R.resolve(this.projectRoot,e),r=this.goWorkPath!==null?R.dirname(this.goWorkPath):this.projectRoot,o=R.dirname(t);for(;;){let s=this.cache.get(K(o));if(s!==void 0)return s;let a=R.dirname(o),l=o===r||o.startsWith(r+R.sep);if(a===o||!l)return null;o=a;}}getAllModules(){return this.discovered}static hasGoModAncestor(e){let t=R.resolve(e);for(;;){if(je.existsSync(R.join(t,"go.mod")))return true;let r=R.dirname(t);if(r===t)return false;t=r;}}static findGoWorkAncestor(e){let t=R.resolve(e);for(;;){let r=R.join(t,"go.work");if(je.existsSync(r))return r;let o=R.dirname(t);if(o===t)return null;t=o;}}async findGoModFiles(e,t,r){if(t>r)return [];let o=[],s;try{s=await je.promises.readdir(e,{withFileTypes:!0});}catch{return o}for(let a of s){if(a.name==="node_modules"||a.name==="vendor"||a.name.startsWith("."))continue;let l=R.join(e,a.name);if(a.isFile()&&a.name==="go.mod")o.push(l);else if(a.isDirectory()){let c=await this.findGoModFiles(l,t+1,r);o.push(...c);}}return o}async parseGoWork(e){let t;try{t=await je.promises.readFile(e,"utf8");}catch{return []}let r=R.dirname(e),o=[],s=fo(t),a=/^\s*use\s*\(\s*([\s\S]*?)\)/gm;for(let u of s.matchAll(a))for(let p of u[1].split(`
|
|
53
|
+
`)){let d=Ze(p.trim());d&&o.push(R.resolve(r,d));}let l=s.replace(a,u=>" ".repeat(u.length)),c=/^\s*use\s+(?!\()(\S.*?)\s*$/gm;for(let u of l.matchAll(c)){let p=Ze(u[1].trim());p&&o.push(R.resolve(r,p));}return o}async parseGoMod(e){let t;try{t=await je.promises.readFile(e,"utf8");}catch{return null}let r=fo(t),o=r.match(/^\s*module\s+(\S+)\s*$/m);if(!o)return null;let s=r.match(/^\s*go\s+(\d+\.\d+(?:\.\d+)?)\s*$/m),a=R.dirname(e);return {modulePath:Ze(o[1]),goVersion:s?.[1],rootDir:a,replaces:Uc(r,a)}}};});function Wc(i){let e=i.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}var mr,dr,gr=g(()=>{fe();mr=new Set(["archive","bufio","builtin","bytes","cmp","compress","container","context","crypto","database","debug","embed","encoding","errors","expvar","flag","fmt","go","hash","html","image","index","io","iter","log","maps","math","mime","net","os","path","plugin","reflect","regexp","runtime","slices","sort","strconv","strings","sync","syscall","testing","text","time","unicode","unique","unsafe"]),dr=class{constructor(e,t,r=[]){this.sourceFilePath=e;this.projectRoot=t;this.modules=r;}async resolve(e){let t=Wc(e);if(!t)return e;let r=t.split("/")[0];if(!r.includes(".")&&mr.has(r))return t;let o=this.findReplaceForSpecifier(t);if(o){let a=t.slice(o.originalModulePath.length),l=R.join(o.localDir,a.startsWith("/")?a.slice(1):a);if(await this.directoryHasGoFiles(l))return K(R.relative(this.projectRoot,l))}let s=this.findModuleForSpecifier(t);if(s){let a=t.slice(s.modulePath.length),l=R.join(s.rootDir,a.startsWith("/")?a.slice(1):a);if(await this.directoryHasGoFiles(l))return K(R.relative(this.projectRoot,l))}return t}findModuleForSpecifier(e){let t;for(let r of this.modules)(e===r.modulePath||e.startsWith(r.modulePath+"/"))&&(!t||r.modulePath.length>t.modulePath.length)&&(t=r);return t}findReplaceForSpecifier(e){let t;for(let r of this.modules)for(let o of r.replaces)(e===o.originalModulePath||e.startsWith(o.originalModulePath+"/"))&&(!t||o.originalModulePath.length>t.originalModulePath.length)&&(t=o);return t}async directoryHasGoFiles(e){try{return (await je.promises.readdir(e,{withFileTypes:!0})).some(r=>r.isFile()&&r.name.endsWith(".go")&&!r.name.endsWith("_test.go"))}catch{return false}}};});var fr,vo=g(()=>{Ct();ho();gr();fr=class extends pe{language="go";extensions=[".go"];manager=null;getBuildConfigManager(e,t){return this.manager=new Ae(e),this.manager}getImportResolver(e,t){let r;if(Array.isArray(t))r=t;else {let o=this.manager?.getAllModules()??[];o.length>0?r=o:t?r=[t]:r=[];}return new dr(e,process.cwd(),r)}async preflightLsp(e){return this.manager??=new Ae(e),await this.manager.initialize(),this.manager.getAllModules().length>0?{skip:false}:Ae.hasGoModAncestor(e)?{skip:false}:Ae.findGoWorkAncestor(e)!==null?{skip:false}:{skip:true,message:"No go.mod found within the project tree or any ancestor directory \u2014 Go files will be indexed without cross-file reference and interface edges. Run `go mod init <module-path>` in your project root (e.g. `go mod init github.com/your-org/your-repo`) to enable LSP enrichment for Go."}}};});function Re(i){return Jc[i]??i.charAt(0).toUpperCase()+i.slice(1)}var Jc,tt,hr,yr=g(()=>{co();po();go();vo();Jc={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"};tt={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"]},hr=class{constructor(e){this.config=e;this.registerPlugin(new sr),this.registerPlugin(new ar),this.registerPlugin(new ur),this.registerPlugin(new fr);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>zc,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??tt.javascript};typescript={language:()=>Vc.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??tt.typescript};python={language:()=>Kc,fileExtensions:()=>this.config?.languages.python?.fileExtensions??tt.python};php;json;java;go={language:()=>Hc,fileExtensions:()=>this.config?.languages.go?.fileExtensions??tt.go};cpp;"c-sharp";c;bash;ruby};});function rt(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 vr,vn=g(()=>{vr=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function bn(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&&qc(t,e);}for(let t of i.namedChildren)t&&bn(t,e);}function qc(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(Fe(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(Fe(t.startPosition.row,t.startPosition.column),"call");}}var bo=g(()=>{Et();});function nt(i,e){i.rootNode&&(wo(i.rootNode,e),bn(i.rootNode,e));}function wo(i,e){if(Yc.has(i.type)){let t=Xc(i);t!==null&&e.set(Fe(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&wo(t,e);}function Xc(i){if(Zc(i))return "declaration";if(cp(i))return "read";if(ap(i))return "type";let e=rt(i,t=>t.type==="decorator");return e!==null&&rp(i,e)?"call":tp(i)?"instantiate":ep(i)?"call":np(i)||ip(i)||op(i)||yp(i)||hp(i)?"write":pp(i)?"import-use":"read"}function Zc(i){let e=i.parent;return e===null?false:!!(Qc.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 ep(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 tp(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 rp(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 np(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||vr.has(t.type))return false;e=t;}return false}function ip(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 op(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||vr.has(t.type))return false;e=t;}return false}function ap(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||lp(r,i)}if(sp.has(e.type))return true;if(vr.has(e.type))return false;t=e,e=e.parent;}return false}function lp(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function cp(i){return rt(i,t=>t.type==="type_query")!==null}function pp(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,r=gp(i);return fp(r,t)?!dp(i,t):false}function dp(i,e){let t=i.parent;for(;t!==null;){if(up.has(t.type)&&mp(t,e))return true;t=t.parent;}return false}function mp(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 gp(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function fp(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 hp(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function yp(i){let e=i.parent;if(e===null||!So.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(!So.has(r.type))return false;t=r;}return false}var Yc,Qc,sp,up,So,br=g(()=>{Et();vn();bo();Yc=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));Qc=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"]));sp=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"]));up=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));So=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function xo(i,e){nt(i,e);}var Co=g(()=>{br();});function Eo(i,e){nt(i,e);}var _o=g(()=>{br();});function Po(i,e){if(!i.rootNode)return;let t=Op(i.rootNode);Io(i.rootNode,e,t);}function Io(i,e,t){if(vp.has(i.type)){let r=bp(i,t);r!==null&&e.set(Fe(i.startPosition.row,i.startPosition.column),r);}for(let r of i.namedChildren)r&&Io(r,e,t);}function bp(i,e){if(Sp(i))return "declaration";if(Cp(i))return "read";if(xp(i))return "declaration";if(Ep(i))return "type";let t=rt(i,r=>r.type==="decorator");return t!==null&&_p(i,t)||Pp(i)?"call":Ip(i)||Rp(i)||Np(i)||Lp(i)||jp(i)?"write":Ap(i,e)?"import-use":"read"}function Sp(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"||wp(i))}function wp(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 xp(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(Sn.has(e.type))return false;e=e.parent;}return false}function Cp(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function Ep(i){return rt(i,t=>t.type==="type")!==null}function _p(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 Pp(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 Ip(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||Sn.has(t.type))return false;e=t;}return false}function Rp(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 Np(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function Lp(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(Tp.has(t.type)){e=t;continue}if(Sn.has(t.type))return false;e=t;}return false}function jp(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(!kp.has(t.type))return false;e=t;}return false}function Ap(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let r=i.text;return e.has(r)?!$p(i,r):false}function $p(i,e){let t=i.parent;for(;t!==null;){if(Fp.has(t.type)&&Dp(t,e))return true;t=t.parent;}return false}function Dp(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 Op(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 vp,Sn,Tp,kp,Fp,Ro=g(()=>{Et();vn();vp=Object.freeze(new Set(["identifier"])),Sn=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));Tp=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));kp=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));Fp=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function To(i,e){let t=new Map;switch(e){case "typescript":nt(i,t);break;case "tsx":xo(i,t);break;case "javascript":Eo(i,t);break;case "python":Po(i,t);break}return t}function Fe(i,e){return `${i}:${e}`}var No,Et=g(()=>{br();Co();_o();Ro();No=Object.freeze(new Set(["typescript","javascript","python"]));});function Gp(i,e){return No.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function Bp(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 Sr,jo=g(()=>{Et();le();Sr=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=Vc.tsx);let s=new Mp;s.setLanguage(o);let a=await x.getFileStats(e),l=25*1024*1024,c,u;if(a.size<=l){let f=await x.readFile(e);u=f;let h={bufferSize:1024*1024};c=s.parse(f,void 0,h);}else c=await this.parseWithStream(s,e,a.size);let p=Gp(t,e),d=p===null?[]:Bp(To(c,p));return {tree:c,classificationMap:{filePath:e,entries:d},content:u}}async parseWithStream(e,t,r){let o=null;try{o=await Q.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(p=>{if(r>50*1024*1024){let m=Math.round(p/r*100);m>c+10&&(process.stderr.write(` Parsing large file: ${m}%...
|
|
54
|
+
`),c=m);}let d=je.readSync(s,l,0,a,p);return d===0?null:l.subarray(0,d).toString("utf-8")})}catch(s){if(o)try{await o.close();}catch(a){process.stderr.write(`Warning: Failed to close file handle for ${t}: ${String(a)}
|
|
55
|
+
`);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var wr,Fo=g(()=>{le();fe();z();wr=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Ao();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=Ao().add(t.exclude));let s=await Q__default.realpath(this.rootPath);for(let a of e)try{let l=R__default.isAbsolute(a)?a:R__default.join(this.rootPath,a),c=await Q__default.lstat(l);if(c.isSymbolicLink()){let u=await Q__default.realpath(l);if(!u.startsWith(s+R__default.sep)&&u!==s){console.warn(`${O} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let p=await Q__default.stat(l);if(!p.isFile())continue;let d=V(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:p.size});}else if(c.isFile()){let u=V(this.rootPath,l);if(o&&o.ignores(u))continue;let p=this.detectLanguage(u,t.languages);if(!p)continue;r.push({path:l,relativePath:u,language:p,size:c.size});}}catch{console.warn(`${O} Skipping inaccessible file: ${a}`);}return r}async loadGitignoreRules(e,t){let r=[],o=t;for(;;){let s=R__default.join(o,".gitignore");await x.fileIsReadable(s)&&r.unshift(s);let a=R__default.dirname(o);if(a===o)break;o=a;let l=R__default.join(o,".git");if(await x.directoryExists(l)){let c=R__default.join(o,".gitignore");await x.fileIsReadable(c)&&!r.includes(c)&&r.unshift(c);break}}for(let s of r)try{let a=await x.readFile(s);e.add(a);}catch{console.warn(`${O} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,r,o){let s=[],a=t||e,l=r||await Q__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=(await Q__default.readdir(e,{withFileTypes:!0})).map(p=>(p.name=p.name.normalize("NFC"),p)).sort((p,d)=>p.name<d.name?-1:p.name>d.name?1:0);for(let p of u){let d=R__default.join(e,p.name),m=V(a,d);if(p.isDirectory()){if(p.name.startsWith("."))continue;let f=await this.walkDirectory(d,a,l,c);s.push(...f);}else if(p.isFile()){let f=await Q__default.stat(d);s.push({path:d,relativePath:m,language:"",size:f.size});}else if(p.isSymbolicLink())try{let f=await Q__default.realpath(d);if(!f.startsWith(l+R__default.sep)&&f!==l){console.warn(`${O} Skipping symlink pointing outside project: ${d} -> ${f}`);continue}let h=await Q__default.stat(d);if(h.isDirectory()){if(p.name.startsWith(".")||c.has(f))continue;c.add(f);let S=await this.walkDirectory(d,a,l,c);s.push(...S);}else h.isFile()&&s.push({path:d,relativePath:m,language:"",size:h.size});}catch{console.warn(`${O} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${ae} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let r=R__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=R__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return o;return null}};});var Wp,Hp,zp,$o,Do=g(()=>{bt();Wp=z$1.object({local:z$1.string(),original:z$1.string().optional(),isDefault:z$1.boolean(),isNamespace:z$1.boolean()}),Hp=z$1.object({source:z$1.string().min(1,"Import source cannot be empty"),resolvedPath:z$1.string().optional(),isExternal:z$1.boolean(),importType:z$1.enum(["relative","workspace","alias","external","builtin"]),specifiers:z$1.array(Wp).optional()}),zp=z$1.record(z$1.string(),Hp),$o=z$1.object({file:z$1.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z$1.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z$1.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z$1.string().datetime({message:"Invalid ISO timestamp"}),ast:z$1.string().min(1,"Index data cannot be empty").max(1e7,"Index data exceeds 10MB limit"),importResolutions:zp.optional(),classificationMap:en.optional()});});function Kp(i){let e=Math.max(0,i)/1e3;if(e<60)return `(${e.toFixed(1)}s)`;let t=Math.floor(e/60),r=Math.floor(e%60);return `(${t}m ${r}s)`}function Oo(){let i=performance.now();return {elapsed:()=>Kp(performance.now()-i),reset:()=>{i=performance.now();},ms:()=>performance.now()-i}}var Mo=g(()=>{});var wn,Cr=g(()=>{wn=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 xn(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 Er,Uo=g(()=>{Cr();Er=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:stripVTControlCharacters(e.map(xn).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:stripVTControlCharacters(e.map(xn).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:stripVTControlCharacters(e.map(xn).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);}record(e,t,r){this.entries.push({level:e,message:stripVTControlCharacters(t),timestamp:new Date().toISOString(),code:r});}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||!wn.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!wn.has(e.code)))}capture(e,t,r){this.entries.push({level:e,message:stripVTControlCharacters(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);}};});function $e(i){if(i&&typeof i=="object")try{i.alreadyReported=!0;}catch{}}function ve(i){return !!(i&&typeof i=="object"&&i.alreadyReported)}function Cn(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 Go,Jp,qp,_r,En=g(()=>{He();Mo();Uo();z();Go=Math.floor(1e3/15),Jp={interval:100,frames:["\u280B","\u2819","\u281A","\u2813"]},qp=new Set(["EPIPE","ENOTCONN","EBADF"]);_r=class i{static activeInstance=null;mode;stream;logCollector=new Er;spinner=null;currentPhaseLabel=null;currentPhaseTracker=null;lastUpdateAt=0;pendingUpdate=null;pendingUpdateTimer=null;paused=false;originalConsole=null;intercepting=false;warningBucket=new Map;stopped=false;constructor(e){if(i.activeInstance&&!i.activeInstance.stopped)throw new Error("Reporter is a singleton \u2014 only one instance may be active at a time. Call stop() on the existing Reporter before constructing another.");this.mode=e.mode,this.stream=e.stream??process.stderr,i.activeInstance=this,this.installConsoleInterception();}async phase(e,t,r){this.start(e);let o=this.makePhaseContext();try{let s=await t(o);return this.flushPendingUpdate(),this.flushAggregatedWarnings(),this.succeed(r?.successText??e),s}catch(s){this.flushPendingUpdate(),this.flushAggregatedWarnings();let a=r?.failText??`${e} failed: ${s instanceof Error?s.message:String(s)}`,l=s&&typeof s=="object"&&"errorCode"in s?s.errorCode:void 0;throw this.fail(a,l?{code:l}:void 0),$e(s),s}}start(e){this.currentPhaseLabel=e,this.currentPhaseTracker=Oo(),this.mode==="spinner"?(this.spinner?this.spinner.text=this.composeSpinnerText(e):this.spinner=Vp({text:this.composeSpinnerText(e),stream:this.stream,spinner:Jp}),this.paused||this.spinner.start()):(this.mode==="verbose"||this.mode==="plain")&&this.writeLine(`${de} ${e}\u2026`);}update(e){if(!this.currentPhaseLabel)return;if(this.currentPhaseLabel=e,this.mode==="verbose"){this.writeLine(`${de} ${e}`);return}if(this.mode!=="spinner")return;let t=Date.now();this.pendingUpdate=e;let r=t-this.lastUpdateAt;r>=Go?this.flushPendingUpdate():this.pendingUpdateTimer||(this.pendingUpdateTimer=setTimeout(()=>this.flushPendingUpdate(),Go-r),this.pendingUpdateTimer.unref?.());}succeed(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",r=`${E} ${t}`;this.terminatePhase(r,"info");}fail(e,t){this.flushPendingUpdate();let r=e??this.currentPhaseLabel??"",o=`${ae} ${r}`;this.terminatePhase(o,"error",t?.code);}info(e){if(this.mode==="quiet"){this.logCollector.record("info",e);return}this.logCollector.record("info",e),this.writeLine(`${de} ${e}`);}warn(e,t){if(this.logCollector.record("warn",e,t?.code),this.currentPhaseLabel&&t?.code){let r=this.warningBucket.get(t.code);r?(r.count+=1,r.samples.length<3&&r.samples.push(e)):this.warningBucket.set(t.code,{code:t.code,count:1,samples:[e]});return}this.writeLine(`${O} ${e}`);}error(e,t){this.logCollector.record("error",e,t?.code),this.writeLine(`${ae} ${e}`);}detail(e){this.logCollector.record("info",e),this.mode==="verbose"&&this.writeLine(` ${X.muted(e)}`);}log(e){this.logCollector.record("info",e),this.mode!=="quiet"&&this.writeLine(e);}summary(e){this.logCollector.record("info",e),this.writeLine(e);}step(e){let t=this;return {ok(r){t.renderSubStep("ok",r??e);},fail(r,o){t.renderSubStep("fail",r??e,o?.code);},skip(r){t.renderSubStep("skip",r??e);}}}renderSubStep(e,t,r){let s=`${e==="ok"?E:e==="fail"?ae:X.muted("-")} ${e==="skip"?X.muted(t):t}`,a=e==="fail"?"error":"info";this.logCollector.record(a,t,r),!(this.mode==="quiet"&&e!=="fail")&&this.writeLine(s);}pause(){this.paused||(this.paused=true,this.spinner?.isSpinning&&this.spinner.stop());}resume(){this.paused&&(this.paused=false,this.mode==="spinner"&&this.currentPhaseLabel&&this.spinner&&(this.spinner.text=this.composeSpinnerText(this.currentPhaseLabel),this.spinner.start()));}getEntries(){return this.logCollector.getEntries()}getReportableErrors(){return this.logCollector.getReportableErrors()}hasErrors(){return this.logCollector.hasErrors()}hasWarnings(){return this.logCollector.hasWarnings()}hasReportableErrors(){return this.logCollector.hasReportableErrors()}stop(){this.stopped||(this.stopped=true,this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.flushAggregatedWarnings(),this.spinner?.isSpinning&&this.spinner.stop(),this.spinner=null,this.uninstallConsoleInterception(),i.activeInstance===this&&(i.activeInstance=null));}composeSpinnerText(e){return e}flushPendingUpdate(){if(this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.pendingUpdate===null||!this.spinner){this.pendingUpdate=null;return}this.spinner.text=this.composeSpinnerText(this.pendingUpdate),this.pendingUpdate=null,this.lastUpdateAt=Date.now();}terminatePhase(e,t,r){this.logCollector.record(t,e,r),this.spinner?.isSpinning&&this.spinner.stop(),this.mode!=="quiet"&&this.writeLine(e),this.currentPhaseLabel=null,this.currentPhaseTracker=null;}flushAggregatedWarnings(){if(this.warningBucket.size!==0){for(let{code:e,count:t,samples:r}of this.warningBucket.values()){if(t===1){this.writeLine(`${O} ${r[0]}`);continue}let o=`${t} ${e} warnings (showing ${Math.min(r.length,3)}): ${r.slice(0,3).join(" | ")}. Use --verbose to see all.`;this.logCollector.record("warn",o,e),this.writeLine(`${O} ${o}`);}this.warningBucket.clear();}}makePhaseContext(){return {update:e=>this.update(e),detail:e=>this.detail(e),step:e=>this.step(e),warn:(e,t)=>this.warn(e,t),elapsed:()=>this.currentPhaseTracker?.elapsed()??"(0.0s)"}}writeLine(e){try{this.mode==="spinner"&&this.spinner?.isSpinning?(this.spinner.clear(),this.stream.write(e+`
|
|
54
56
|
`),this.spinner.text=this.spinner.text):this.stream.write(e+`
|
|
55
|
-
`);}catch(t){let r=t?.code;if(r&&
|
|
56
|
-
`);}catch{}}}installConsoleInterception(){this.intercepting||(this.intercepting=true,this.originalConsole={log:console.log,warn:console.warn,error:console.error},console.log=(...e)=>{let t=e.map(
|
|
57
|
-
`),go=true);}return Math.min(12e4+i*1e3,s)}var go,ho=f(()=>{go=false;});function He(i,e){let t=e??i;return {line:t.startPosition.row+1,column:t.startPosition.column}}function We(i){return i?i.text:null}function ir(i,e,t){for(let r=i.parent;r;r=r.parent){if(r.type==="export_statement")return true;if(r.type==="internal_module")break}return t.exportedNames?.has(e)??false}function bo(i){let e=new Set,t=r=>{if(r.type==="export_statement"&&!Xc(r))for(let o=0;o<r.childCount;o++){let s=r.child(o);if(s)if(s.type==="export_clause")for(let a=0;a<s.childCount;a++){let l=s.child(a);if(l?.type!=="export_specifier")continue;let c=l.child(0);c?.type==="identifier"&&e.add(c.text);}else s.type==="identifier"&&e.add(s.text);}for(let o=0;o<r.childCount;o++){let s=r.child(o);s&&t(s);}};return t(i),e}function Xc(i){for(let e=0;e<i.childCount;e++){let t=i.child(e)?.type;if(t==="from"||t==="string")return true}return false}function Co(){return {language:"javascript",handlers:new Map(wo)}}function xo(){return {language:"typescript",handlers:new Map([...wo,["interface_declaration",Zc],["public_field_definition",yo],["property_signature",yo],["function_signature",vo],["method_signature",So]])}}var vo,Qc,Zc,So,yo,ep,wo,tn=f(()=>{vo=(i,e)=>{let t=i.childForFieldName("name"),r=We(t);r&&e.symbols.push({name:r,kind:"function",...He(i,t),isExported:ir(i,r,e)});},Qc=(i,e)=>{let t=i.childForFieldName("name"),r=We(t);if(!r)return;let o=ir(i,r,e);return e.symbols.push({name:r,kind:"class",...He(i,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},Zc=(i,e)=>{let t=i.childForFieldName("name"),r=We(t);if(!r)return;let o=ir(i,r,e);return e.symbols.push({name:r,kind:"interface",...He(i,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},So=(i,e)=>{let t=i.childForFieldName("name"),r=We(t);r&&e.symbols.push({name:r,kind:"method",...He(i,t),isExported:e.enclosingExported??false});},yo=(i,e)=>{let t=i.childForFieldName("name"),r=We(t);r&&e.symbols.push({name:r,kind:"property",...He(i,t),isExported:e.enclosingExported??false});},ep=(i,e)=>{let t=i.childForFieldName("name"),r=We(t);if(!r)return;let o=i.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:r,kind:s?"function":"variable",...He(i,t),isExported:ir(i,r,e)});},wo=[["function_declaration",vo],["class_declaration",Qc],["method_definition",So],["variable_declarator",ep]];});function rn(i){return {line:i.startPosition.row+1,column:i.startPosition.column}}function nn(i){return !i.startsWith("_")}function Eo(){return {language:"python",handlers:new Map([["function_definition",tp],["class_definition",rp],["assignment",np]])}}var tp,rp,np,_o=f(()=>{tp=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let r=t.text,o=e.enclosingType?"method":"function",s=nn(r),a=o==="method"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...rn(t),isExported:a});},rp=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let r=t.text,o=nn(r);return e.symbols.push({name:r,kind:"class",...rn(t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},np=(i,e)=>{let t=i.childForFieldName("left");if(!t||t.type!=="identifier")return;let r=t.text,o=e.enclosingType?"property":"variable",s=nn(r),a=o==="property"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...rn(t),isExported:a});};});var Po,Io=f(()=>{tn();_o();Po=[Co(),xo(),Eo()];});var or,No=f(()=>{Io();tn();or=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??Po)this.languageHandlers.set(t.language,t.handlers);}extract(e,t){let r=this.languageHandlers.get(t);if(!r)return [];let o=t==="typescript"||t==="javascript"?bo(e.rootNode):void 0,s={symbols:[],exportedNames:o};return this.walk(e.rootNode,s,r),s.symbols}walk(e,t,r){let s=r.get(e.type)?.(e,t)??t;for(let a=0;a<e.childCount;a++){let l=e.child(a);l&&this.walk(l,s,r);}}};});function ip(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,p=c==="default";e.push({local:u,original:c,isDefault:p,isNamespace:false});}}}return e}async function op(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?ip(l):[];await le(a,s,e,t,r,c);}async function sp(i,e,t,r){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await le(a,s,e,t,r,[]);}async function ap(i,e,t,r){let o=i.childForFieldName("function");if(!o||o.type!=="import")return;let s=i.childForFieldName("arguments");if(!s)return;let a=s.child(1);if(!a)return;let l;if(a.type==="string")l=a.text.slice(1,-1);else if(a.type==="template_string"){let u=a.child(1);l=u?.type==="string_fragment"&&u.text?u.text:"<dynamic>";}else l="<dynamic>";if(!l)return;let c=i.startPosition.row;await le(l,c,e,t,r,[]);}function sr(){return {language:"javascript",handlers:new Map([["import_statement",op],["export_statement",sp],["call_expression",ap]])}}function on(){let i=sr();return {language:"typescript",handlers:new Map(i.handlers)}}var sn=f(()=>{it();});var Ro,To=f(()=>{sn();Ht();it();sn();Ht();Ro=[sr(),on(),Kr()];});var Lo={};kn(Lo,{ImportExtractor:()=>an});var an,jo=f(()=>{To();it();an=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Ro)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)??zr,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 lt,Ao,ln,ko,Fo,ar=f(()=>{lt=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"]),Ao=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"]),ln={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"]},ko={language:"javascript",textIncludedTypes:Ao,fieldNames:ln},Fo={language:"typescript",textIncludedTypes:Ao,fieldNames:ln};});var lp,$o,Do,cn=f(()=>{lp=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"]),$o={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"]},Do={language:"python",textIncludedTypes:lp,fieldNames:$o,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function Oo(i){return ct.get(i)}function Mo(i){if(!i)return lt;let e=ct.get(i);if(!e)return lt;let t=new Set(lt);for(let r of e.textIncludedTypes)t.add(r);return t}function pn(i){if(!i){let t=Array.from(ct.values()).map(r=>r.fieldNames);return pt(...t)}let e=ct.get(i);if(!e){let t=Array.from(ct.values()).map(r=>r.fieldNames);return pt(...t)}return e.fieldNames}var ct,Uo=f(()=>{un();ar();cn();ar();ar();cn();ct=new Map([["javascript",ko],["typescript",Fo],["python",Do]]);});var zo={};kn(zo,{COMMON_FIELD_NAMES:()=>gn,JS_TS_FIELD_NAMES:()=>Ho,PYTHON_FIELD_NAMES:()=>Wo,TEXT_INCLUDED_TYPES:()=>Go,mergeFieldMaps:()=>pt,serializeAST:()=>pp,serializeASTStream:()=>cp});function*cp(i,e,t){yield*mn(i,e,t);}function*mn(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)}`),Bo(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?pn(t):gn)[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*mn(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*mn(c,void 0,t));}yield "]";}yield "}";}async function pp(i,e,t){let r=dn(i,e,t),o=t?pn(t):gn,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 p=dn(u,c,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(p),s.push({treeNode:u,serializedNode:p,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=dn(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 dn(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 Bo(i,t)&&(r.text=i.text),r}function Bo(i,e){if(e){let r=Oo(e);if(r?.shouldIncludeText){let s=r.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return Mo(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Go.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function pt(...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 Go,Ho,Wo,gn,un=f(()=>{Uo();Go=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"]);Ho={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"]},Wo={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"]};gn=pt(Ho,Wo);});var ut,Vo=f(()=>{Fr();Si();Ci();Ai();nt();Jt();to();no();oo();Zr();M();mo();ho();Et();er();we();Dr();No();_t();ut=class extends ge{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;discoveredFiles=[];parseSymbols=new Map;parseContent=new Map;symbolExtractor=new or;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new Qt(process.cwd()),this.parser=new Xt(this.langRegistry),this.compressor=new nr;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){if(!this.reporter)throw new Error("IndexCommand requires a Reporter dependency");let o="failed";try{let s=await this.getAccessKey();this.apiClient=new Rt(this.config,s,t,this.reporter),this.reporter.log(`${de} Starting indexing procedure...
|
|
58
|
-
`);let a=performance.now();await this.reporter.phase("Pre-flight checks",async P=>{let $=P.step("Project access");await this.validateProject(),$.ok("Project access validated");let L=P.step("Git branch");t?L.skip("Git branch validation skipped (--dirty)"):(await this.validateGitBranch(),L.ok("Git branch validated"));let ee=P.step("Git status");t?ee.skip("Git status validation skipped (--dirty)"):(await this.validateGitStatus(),ee.ok("Working tree clean"));let z=P.step("Repo sync");if(t?z.skip("Repository sync skipped (--dirty)"):(await this.synchronizeChanges(),z.ok("Repository synchronized")),this.buildConfigManagers.size>0){let K=P.step("Build configs"),I=0;for(let[,O]of this.buildConfigManagers.entries()){let j=await O.initialize();I+=j.length;}K.ok(I>0?`${I} build config(s) discovered`:"No build configs discovered");}},{successText:"Pre-flight checks complete"});let l=await this.reporter.phase("Determining index scope",()=>this.determineIndexScope(e),{successText:e?"Full index":"Index scope determined"}),c=await this.git.getLatestCommitHash(),u=await this.git.getCommitTimestamp();if(l.upToDate){this.reporter.summary(`${w} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${c.substring(0,8)}`),o="succeeded";return}let p=await this.reporter.phase("Claiming indexing lock",()=>this.apiClient.claimAstLock(this.config.projectId,this.config.branch,l.isIncremental,c,u),{successText:"Indexing lock claimed"});switch(p.remapped===!0&&(p.effectiveBranchName?this.reporter.warn(`--dirty: server is indexing as default branch "${p.effectiveBranchName}" (transmitted "${this.config.branch}").`):this.reporter.warn("--dirty: server reported a branch remap but did not include the effective branch name.")),p.status){case "current":this.reporter.summary(`${w} Index already up to date for branch ${this.config.branch} at commit ${c?.substring(0,8)||"unknown"}`),o="succeeded";return;case "duplicate":this.reporter.summary(`${w} Index for this commit is already in progress on the server.`),o="succeeded";return;case "superseded":this.reporter.summary(`${w} A newer commit is already being indexed; nothing to do.`),o="succeeded";return;case "queued":if(!p.queuedAttemptId)throw new Error("Server returned queued status without an attempt ID");await this.handleQueuedUpload(p.queuedAttemptId,l.isIncremental,c,u),o="succeeded";return;default:break}let d=!1,m=()=>{d||this.reporter.detail("Uploading metadata, processing, and indexing...");},h,g,y=new Promise((P,$)=>{h=P,g=$;}),b=new AbortController,v=()=>{},T=this.createIndexPipeline(l.isIncremental,u,m,h,(P,$)=>v(P,$)),N=null;try{let[,P]=await this.reporter.phase("Indexing files",async $=>{let L=null,ee=new Map,z=()=>{let I=[];if(L&&L.total>0){let O=ee?.size>0?`${Er} `:"",j=Math.min(100,Math.round(L.processed/L.total*100));I.push(`${O}Baseline index ${j}% (${L.processed}/${L.total})`);}else I.push(`${w} Baseline index complete (${L?.processed}/${L?.total})`);for(let[O,j]of ee){if(j.total<=0)continue;let An=Math.min(100,Math.round(j.processed/j.total*100));An===100?I.push(`${w} ${xe(O)} enrichment complete (${j.processed}/${j.total})`):I.push(`${Er} ${xe(O)} enrichment ${An}% (${j.processed}/${j.total})`);}$.update(I.join(`
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
57
|
+
`);}catch(t){let r=t?.code;if(r&&qp.has(r))return;try{process.stderr.write(`reporter write failed: ${String(t)}
|
|
58
|
+
`);}catch{}}}installConsoleInterception(){this.intercepting||(this.intercepting=true,this.originalConsole={log:console.log,warn:console.warn,error:console.error},console.log=(...e)=>{let t=e.map(Cn).join(" ");this.logCollector.record("info",t),this.writeLine(t);},console.warn=(...e)=>{let t=e.map(Cn).join(" ");this.logCollector.record("warn",t),this.writeLine(t);},console.error=(...e)=>{let t=e.map(Cn).join(" ");this.logCollector.record("error",t),this.writeLine(t);});}uninstallConsoleInterception(){!this.intercepting||!this.originalConsole||(this.intercepting=false,console.log=this.originalConsole.log,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null);}};});var Xp,Pr,Ho=g(()=>{on();Xp=promisify(_n__default.gunzip),Pr=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=_n__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,nn(Buffer.concat(t)).toString("base64")}async compress(e){let t=[],r=_n__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,nn(Buffer.concat(t)).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),r=await Xp(t);return JSON.parse(r.toString("utf-8"))}};});function Ko(i){let r=i>=5e4?27e5:i>=1e4?18e5:9e5,o=process.env.CONSTELLATION_AST_WAIT_MAX_MS,s=r;if(o!==void 0&&o!==""){let a=Number(o);Number.isFinite(a)&&Number.isInteger(a)&&a>0?s=a:zo||(process.stderr.write(`[constellation] Ignoring invalid CONSTELLATION_AST_WAIT_MAX_MS=${o}; using default tier cap.
|
|
59
|
+
`),zo=true);}return Math.min(12e4+i*1e3,s)}var zo,Vo=g(()=>{zo=false;});function Qp(i){try{return process.kill(i,0),!0}catch(e){return e.code==="EPERM"}}function Jo(i){let e=JSON.stringify(i);try{return je.writeFileSync(it,e,{flag:"wx",mode:384}),!0}catch(t){if(t.code==="EEXIST")return false;throw t}}function Pn(){let i;try{i=je.readFileSync(it,"utf8");}catch{return null}try{let e=JSON.parse(i);return typeof e.pid!="number"||typeof e.projectPath!="string"||typeof e.startTime!="string"?null:e}catch{return null}}function Qo(i){je.mkdirSync(Xo,{recursive:true,mode:448});let e={pid:process.pid,projectPath:R.resolve(i),startTime:new Date().toISOString()};if(Jo(e))return {ok:true,release:qo(e)};let t=Pn();if(t===null||!Qp(t.pid)){try{je.unlinkSync(it);}catch(o){if(o.code!=="ENOENT")throw o}if(Jo(e))return {ok:true,release:qo(e)};let r=Pn();return r!==null?{ok:false,reason:"held",holder:r}:{ok:false,reason:"indeterminate"}}return {ok:false,reason:"held",holder:t}}function qo(i){let e=false;return ()=>{if(e)return;e=true;let t=Pn();if(!(t?.pid!==i.pid||t?.startTime!==i.startTime))try{je.unlinkSync(it);}catch(r){if(r.code!=="ENOENT")throw r}}}function Zo(i){let e=Date.now()-new Date(i.startTime).getTime(),t=Zp(e);return `Another \`constellation index\` is already running (pid ${i.pid}, project ${i.projectPath}, started ${t} ago).
|
|
60
|
+
Wait for it to finish, or kill it, then retry.`}function Zp(i){let e=Math.max(0,i);if(e<1e3)return `${e}ms`;let t=Math.round(e/1e3);if(t<60)return `${t}s`;let r=Math.floor(t/60),o=t%60;if(r<60)return o===0?`${r}m`:`${r}m${o}s`;let s=Math.floor(r/60),a=r%60;return a===0?`${s}h`:`${s}h${a}m`}var Xo,it,es=g(()=>{Xo=R.join(Oe.homedir(),".constellation","locks"),it=R.join(Xo,"index.lock");});function ot(i,e){let t=e??i;return {line:t.startPosition.row+1,column:t.startPosition.column}}function st(i){return i?i.text:null}function Ir(i,e,t){for(let r=i.parent;r;r=r.parent){if(r.type==="export_statement")return true;if(r.type==="internal_module")break}return t.exportedNames?.has(e)??false}function rs(i){let e=new Set,t=r=>{if(r.type==="export_statement"&&!eu(r))for(let o=0;o<r.childCount;o++){let s=r.child(o);if(s)if(s.type==="export_clause")for(let a=0;a<s.childCount;a++){let l=s.child(a);if(l?.type!=="export_specifier")continue;let c=l.child(0);c?.type==="identifier"&&e.add(c.text);}else s.type==="identifier"&&e.add(s.text);}for(let o=0;o<r.childCount;o++){let s=r.child(o);s&&t(s);}};return t(i),e}function eu(i){for(let e=0;e<i.childCount;e++){let t=i.child(e)?.type;if(t==="from"||t==="string")return true}return false}function ss(){return {language:"javascript",handlers:new Map(os)}}function as(){return {language:"typescript",handlers:new Map([...os,["interface_declaration",ru],["public_field_definition",ts],["property_signature",ts],["function_signature",ns],["method_signature",is]])}}var ns,tu,ru,is,ts,nu,os,In=g(()=>{ns=(i,e)=>{let t=i.childForFieldName("name"),r=st(t);r&&e.symbols.push({name:r,kind:"function",...ot(i,t),isExported:Ir(i,r,e)});},tu=(i,e)=>{let t=i.childForFieldName("name"),r=st(t);if(!r)return;let o=Ir(i,r,e);return e.symbols.push({name:r,kind:"class",...ot(i,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},ru=(i,e)=>{let t=i.childForFieldName("name"),r=st(t);if(!r)return;let o=Ir(i,r,e);return e.symbols.push({name:r,kind:"interface",...ot(i,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},is=(i,e)=>{let t=i.childForFieldName("name"),r=st(t);r&&e.symbols.push({name:r,kind:"method",...ot(i,t),isExported:e.enclosingExported??false});},ts=(i,e)=>{let t=i.childForFieldName("name"),r=st(t);r&&e.symbols.push({name:r,kind:"property",...ot(i,t),isExported:e.enclosingExported??false});},nu=(i,e)=>{let t=i.childForFieldName("name"),r=st(t);if(!r)return;let o=i.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:r,kind:s?"function":"variable",...ot(i,t),isExported:Ir(i,r,e)});},os=[["function_declaration",ns],["class_declaration",tu],["method_definition",is],["variable_declarator",nu]];});function Rn(i){return {line:i.startPosition.row+1,column:i.startPosition.column}}function Nn(i){return !i.startsWith("_")}function ls(){return {language:"python",handlers:new Map([["function_definition",iu],["class_definition",ou],["assignment",su]])}}var iu,ou,su,cs=g(()=>{iu=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let r=t.text,o=e.enclosingType?"method":"function",s=Nn(r),a=o==="method"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...Rn(t),isExported:a});},ou=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let r=t.text,o=Nn(r);return e.symbols.push({name:r,kind:"class",...Rn(t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},su=(i,e)=>{let t=i.childForFieldName("left");if(!t||t.type!=="identifier")return;let r=t.text,o=e.enclosingType?"property":"variable",s=Nn(r),a=o==="property"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...Rn(t),isExported:a});};});var ps,us=g(()=>{In();cs();ps=[ss(),as(),ls()];});var Rr,ds=g(()=>{us();In();Rr=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??ps)this.languageHandlers.set(t.language,t.handlers);}extract(e,t){let r=this.languageHandlers.get(t);if(!r)return [];let o=t==="typescript"||t==="javascript"?rs(e.rootNode):void 0,s={symbols:[],exportedNames:o};return this.walk(e.rootNode,s,r),s.symbols}walk(e,t,r){let s=r.get(e.type)?.(e,t)??t;for(let a=0;a<e.childCount;a++){let l=e.child(a);l&&this.walk(l,s,r);}}};});function au(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,p=c==="default";e.push({local:u,original:c,isDefault:p,isNamespace:false});}}}return e}async function lu(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?au(l):[];await ee(a,s,e,t,r,c);}async function cu(i,e,t,r){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await ee(a,s,e,t,r,[]);}async function pu(i,e,t,r){let o=i.childForFieldName("function");if(!o||o.type!=="import")return;let s=i.childForFieldName("arguments");if(!s)return;let a=s.child(1);if(!a)return;let l;if(a.type==="string")l=a.text.slice(1,-1);else if(a.type==="template_string"){let u=a.child(1);l=u?.type==="string_fragment"&&u.text?u.text:"<dynamic>";}else l="<dynamic>";if(!l)return;let c=i.startPosition.row;await ee(l,c,e,t,r,[]);}function Nr(){return {language:"javascript",handlers:new Map([["import_statement",lu],["export_statement",cu],["call_expression",pu]])}}function Tn(){let i=Nr();return {language:"typescript",handlers:new Map(i.handlers)}}var Ln=g(()=>{Qe();});function du(i){let e=i.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function mu(i,e){let t=i.childForFieldName("name");if(t){let o=t.text,s=t.type==="dot"||o===".";return {local:o,original:e,isDefault:false,isNamespace:s}}return {local:e.split("/").pop()??e,original:e,isDefault:false,isNamespace:false}}async function ms(i,e,t,r){let o=i.childForFieldName("path");if(!o)return;let s=du(o.text);if(!s)return;let a=mu(i,s);await ee(s,i.startPosition.row,e,t,r,a?[a]:[]);}async function gu(i,e,t,r){for(let o=0;o<i.namedChildCount;o++){let s=i.namedChild(o);if(s){if(s.type==="import_spec")await ms(s,e,t,r);else if(s.type==="import_spec_list")for(let a=0;a<s.namedChildCount;a++){let l=s.namedChild(a);l&&l.type==="import_spec"&&await ms(l,e,t,r);}}}}function kn(){return {language:"go",handlers:new Map([["import_declaration",gu]]),classifyImportType:uu}}var uu,jn=g(()=>{gr();Qe();gr();uu=(i,e,t)=>{if(t){let r=i.split("/")[0];return !r.includes(".")&&mr.has(r)?"builtin":"external"}return "alias"};});var gs,fs=g(()=>{Ln();lr();jn();Qe();Ln();lr();jn();gs=[Nr(),Tn(),yn(),kn()];});var hs={};li(hs,{ImportExtractor:()=>An});var An,ys=g(()=>{fs();Qe();An=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??gs)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)??hn,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 It,vs,Fn,bs,Ss,Tr=g(()=>{It=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"]),vs=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"]),Fn={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"]},bs={language:"javascript",textIncludedTypes:vs,fieldNames:Fn},Ss={language:"typescript",textIncludedTypes:vs,fieldNames:Fn};});var fu,ws,xs,$n=g(()=>{fu=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"]),ws={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"]},xs={language:"python",textIncludedTypes:fu,fieldNames:ws,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});var hu,Lr,Cs,kr=g(()=>{hu=new Set(["package_identifier","field_identifier","type_identifier","predeclared_identifier","blank_identifier","label_name","nil","true","false","iota","dot"]),Lr={package_clause:[],import_declaration:[],import_spec:["name","path"],function_declaration:["name","parameters","result","body","type_parameters"],method_declaration:["receiver","name","parameters","result","body"],method_elem:["name","parameters","result"],type_declaration:[],type_spec:["name","type","type_parameters"],type_alias:["name","type"],struct_type:[],interface_type:[],field_declaration:["name","type","tag"],parameter_declaration:["name","type"],variadic_parameter_declaration:["name","type"],type_parameter_declaration:["name","type"],channel_type:["value"],pointer_type:[],slice_type:["element"],array_type:["length","element"],map_type:["key","value"],function_type:["parameters","result"],qualified_type:["package","name"],generic_type:["type","type_arguments"],var_declaration:[],const_declaration:[],var_spec:["name","type","value"],const_spec:["name","type","value"],short_var_declaration:["left","right"],assignment_statement:["left","right"],call_expression:["function","type_arguments","arguments"],selector_expression:["operand","field"],index_expression:["operand","index"],type_assertion_expression:["operand","type"],type_conversion_expression:["type","operand"],type_instantiation_expression:["type"],composite_literal:["type","body"],keyed_element:[],unary_expression:["operand"],binary_expression:["left","right"],parenthesized_expression:[],func_literal:["parameters","result","body"],if_statement:["initializer","condition","consequence","alternative"],for_statement:["body"],for_clause:["initializer","condition","update"],range_clause:["left","right"],expression_switch_statement:["initializer","value"],type_switch_statement:["initializer","alias","value"],expression_case:["value"],type_case:["type"],default_case:[],select_statement:[],communication_case:["communication"],send_statement:["channel","value"],receive_statement:["left","right"],return_statement:[],go_statement:[],defer_statement:[],break_statement:[],continue_statement:[],goto_statement:[],labeled_statement:["label"]},Cs={language:"go",textIncludedTypes:hu,fieldNames:Lr,shouldIncludeText:i=>{switch(i.type){case "interpreted_string_literal":case "raw_string_literal":case "rune_literal":case "int_literal":case "float_literal":case "imaginary_literal":case "comment":return false;default:return}}};});function Es(i){return Rt.get(i)}function _s(i){if(!i)return It;let e=Rt.get(i);if(!e)return It;let t=new Set(It);for(let r of e.textIncludedTypes)t.add(r);return t}function Dn(i){if(!i){let t=Array.from(Rt.values()).map(r=>r.fieldNames);return Nt(...t)}let e=Rt.get(i);if(!e){let t=Array.from(Rt.values()).map(r=>r.fieldNames);return Nt(...t)}return e.fieldNames}var Rt,Ps=g(()=>{On();Tr();$n();kr();Tr();Tr();$n();kr();Rt=new Map([["javascript",bs],["typescript",Ss],["python",xs],["go",Cs]]);});var Ls={};li(Ls,{COMMON_FIELD_NAMES:()=>Gn,JS_TS_FIELD_NAMES:()=>Ns,PYTHON_FIELD_NAMES:()=>Ts,TEXT_INCLUDED_TYPES:()=>Is,mergeFieldMaps:()=>Nt,serializeAST:()=>vu,serializeASTStream:()=>yu});function*yu(i,e,t){yield*Un(i,e,t);}function*Un(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)}`),Rs(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?Dn(t):Gn)[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*Un(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*Un(c,void 0,t));}yield "]";}yield "}";}async function vu(i,e,t){let r=Mn(i,e,t),o=t?Dn(t):Gn,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 p=Mn(u,c,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(p),s.push({treeNode:u,serializedNode:p,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=Mn(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 Mn(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 Rs(i,t)&&(r.text=i.text),r}function Rs(i,e){if(e){let r=Es(e);if(r?.shouldIncludeText){let s=r.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return _s(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Is.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function Nt(...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 Is,Ns,Ts,Gn,On=g(()=>{Ps();kr();Is=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"]);Ns={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"]},Ts={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"]};Gn=Nt(Ns,Ts,Lr);});var Tt,js=g(()=>{cn();Ji();Yi();so();xt();yr();jo();Fo();Do();En();z();Ho();Vo();Bt();Cr();es();fe();un();ds();Wt();Tt=class extends Ee{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;discoveredFiles=[];parseSymbols=new Map;parseContent=new Map;symbolExtractor=new Rr;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new wr(process.cwd()),this.parser=new Sr(this.langRegistry),this.compressor=new Pr;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){if(!this.reporter)throw new Error("IndexCommand requires a Reporter dependency");let o=Qo(process.cwd());if(!o.ok){let d=o.reason==="held"?Zo(o.holder):`Another \`constellation index\` may be running, but the lock file is in an indeterminate state. Re-run; if this persists, manually remove ${it} and retry.`;this.reporter.error(d);let m=new Error(d);throw $e(m),m}let s=o.release,a=()=>s(),l=d=>()=>{s(),process.exit(d==="SIGINT"?130:143);},c=l("SIGINT"),u=l("SIGTERM");process.on("exit",a),process.on("SIGINT",c),process.on("SIGTERM",u);let p="failed";try{let d=await this.getAccessKey();this.apiClient=new Vt(this.config,d,t,this.reporter),this.reporter.log(`${xe} Starting indexing procedure...
|
|
61
|
+
`);let m=performance.now();await this.reporter.phase("Pre-flight checks",async k=>{let oe=k.step("Project access");await this.validateProject(),oe.ok("Project access validated");let U=k.step("Git branch");t?U.skip("Git branch validation skipped (--dirty)"):(await this.validateGitBranch(),U.ok("Git branch validated"));let Se=k.step("Git status");t?Se.skip("Git status validation skipped (--dirty)"):(await this.validateGitStatus(),Se.ok("Working tree clean"));let we=k.step("Repo sync");if(t?we.skip("Repository sync skipped (--dirty)"):(await this.synchronizeChanges(),we.ok("Repository synchronized")),this.buildConfigManagers.size>0){let ue=k.step("Build configs"),L=0;for(let[,H]of this.buildConfigManagers.entries()){let D=await H.initialize();L+=D.length;}ue.ok(L>0?`${L} build config(s) discovered`:"No build configs discovered");}},{successText:"Pre-flight checks complete"});let f=await this.reporter.phase("Determining index scope",()=>this.determineIndexScope(e),{successText:e?"Full index":"Index scope determined"}),h=await this.git.getLatestCommitHash(),S=await this.git.getCommitTimestamp();if(f.upToDate){this.reporter.summary(`${E} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${h.substring(0,8)}`),p="succeeded";return}let v=await this.reporter.phase("Claiming indexing lock",()=>this.apiClient.claimAstLock(this.config.projectId,this.config.branch,f.isIncremental,h,S),{successText:"Indexing lock claimed"});switch(v.remapped===!0&&(v.effectiveBranchName?this.reporter.warn(`--dirty: server is indexing as default branch "${v.effectiveBranchName}" (transmitted "${this.config.branch}").`):this.reporter.warn("--dirty: server reported a branch remap but did not include the effective branch name.")),v.status){case "current":this.reporter.summary(`${E} Index already up to date for branch ${this.config.branch} at commit ${h?.substring(0,8)||"unknown"}`),p="succeeded";return;case "duplicate":this.reporter.summary(`${E} Index for this commit is already in progress on the server.`),p="succeeded";return;case "superseded":this.reporter.summary(`${E} A newer commit is already being indexed; nothing to do.`),p="succeeded";return;case "queued":if(!v.queuedAttemptId)throw new Error("Server returned queued status without an attempt ID");await this.handleQueuedUpload(v.queuedAttemptId,f.isIncremental,h,S),p="succeeded";return;default:break}let y=!1,C=()=>{y||this.reporter.detail("Uploading metadata, processing, and indexing...");},P,b,_=new Promise((k,oe)=>{P=k,b=oe;}),w=new AbortController,I=()=>{},A=this.createIndexPipeline(f.isIncremental,S,C,P,(k,oe)=>I(k,oe)),j=null;try{let[,k]=await this.reporter.phase("Indexing files",async oe=>{let U=null,Se=new Map,we=()=>{let L=[];if(U&&U.total>0){let H=Se?.size>0?`${Yr} `:"",D=Math.min(100,Math.round(U.processed/U.total*100));L.push(`${H}Baseline index ${D}% (${U.processed}/${U.total})`);}else L.push(`${E} Baseline index complete (${U?.processed}/${U?.total})`);for(let[H,D]of Se){if(D.total<=0)continue;let ai=Math.min(100,Math.round(D.processed/D.total*100));ai===100?L.push(`${E} ${Re(H)} enrichment complete (${D.processed}/${D.total})`):L.push(`${Yr} ${Re(H)} enrichment ${ai}% (${D.processed}/${D.total})`);}oe.update(L.join(`
|
|
62
|
+
`));};I=(L,H)=>{U={processed:L,total:H},we();};let ue=(L,H,D)=>{Se.set(L,{processed:H,total:D}),we();};return Promise.all([this.uploadToAPI(A,f.isIncremental,h,v.attemptId).then(L=>(y=!0,L)).catch(L=>{throw w.abort(L),b(L),y=!0,L}),_.then(L=>{let H=this.getEnrichmentEligibleLanguages(r,L);return H?(v.attemptId&&this.apiClient.startEnrichment(v.attemptId,this.config.projectId,this.config.branch),this.runLspEnrichment(L,H,this.parseSymbols,this.parseContent,w.signal,ue).catch(D=>(w.signal.aborted||this.reporter.warn(`Index enrichment failed: ${D instanceof Error?D.message:String(D)}`,{code:"ENRICHMENT_FAILED"}),null))):null}).catch(()=>null)])},{successText:"Index baseline data uploaded"});j=k;}catch(k){throw y=!0,k}j&&j.length>0&&await this.reporter.phase("Server processing & enrichment upload",async()=>{try{let k=this.discoveredFiles.length,oe=Ko(k),U=Math.round(oe/1e3);this.reporter.detail(`Waiting for server to finish syntax tree processing (${k} files, timeout ${U}s)...`);let Se=await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,h,oe),we=qi(j);if(Se){this.reporter.detail(`Uploading enrichment data (${j.length} files)...`);let ue=!1;try{ue=await this.apiClient.uploadEnrichment(we,this.config.projectId,this.config.branch,h);}catch{}ue?this.reporter.detail("Enrichment data uploaded to Constellation Service, index enhancement in progress"):this.reporter.warn("Enrichment upload failed \u2014 re-run 'constellation index --full' after the server finishes baseline index processing to retry.",{code:"ENRICHMENT_FAILED"});}else {this.reporter.warn(`Index processing not complete after ${U}s \u2014 attempting enrichment upload anyway.`);let ue=!1;try{ue=await this.apiClient.uploadEnrichment(we,this.config.projectId,this.config.branch,h);}catch{}ue?this.reporter.detail("Enrichment data uploaded to Constellation Service, index enhancement in progress"):this.reporter.warn("Enrichment upload failed \u2014 re-run 'constellation index --full' after the server finishes baseline index processing to retry.",{code:"ENRICHMENT_FAILED"});}}catch(k){this.reporter.warn(`Enrichment upload failed: ${k instanceof Error?k.message:String(k)}`,{code:"ENRICHMENT_FAILED"});}},{successText:"Index enrichment data uploaded"});let Ue=(performance.now()-m)/1e3,G=Math.floor(Ue/60),Y=(Ue%60).toFixed(3),Kr=G>0?`${G}m ${Y}s`:`${Y}s`;this.reporter.summary(`
|
|
63
|
+
${E} Upload completed in ${Kr}! Server indexing in progress.`),p="succeeded";}catch(d){if(d instanceof ge)throw d;if(d instanceof Le){this.logIndexingInProgress(d.branchName||this.config?.branch),p="succeeded";return}if(d instanceof $)throw ve(d)||(this.reporter.error("Authentication failed.",{code:"AUTH_FAILURE"}),this.reporter.info(`Your access key may be invalid or expired. Run 'constellation auth'
|
|
64
|
+
to set or update your access key.`),$e(d)),d;if(d instanceof Pe)throw d;if(d instanceof Error&&d.message==="Access key not configured")throw $e(d),d;if(ve(d))throw d;let m=d instanceof Error?d.message:"An unexpected error occurred";throw this.reporter.error(`Indexing failed: ${m}`),$e(d),d}finally{s(),process.removeListener("SIGINT",c),process.removeListener("SIGTERM",u),process.removeListener("exit",a),this.parseSymbols.clear(),this.parseContent.clear();try{let m=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",f=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,h=this.reporter.getReportableErrors();if(!m&&f&&h.length>0){let S=this.reporter.getEntries(),v=h.map(I=>({type:"CLI_ERROR",message:I.message,phase:"indexing"})).slice(0,100),y=S.filter(I=>I.level==="warn").map(I=>({type:"CLI_WARNING",message:I.message,phase:"indexing"})).slice(0,100),C=v.length,P=y.length,b=[];C>0&&b.push(`${C} error${C!==1?"s":""}`),P>0&&b.push(`${P} warning${P!==1?"s":""}`);let _=b.join(", "),w=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:_,errorData:{errors:v,warnings:y},logEntries:S.slice(0,1e3),cliVersion:w,outcome:p,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(Ce);if(!e)throw this.reporter.error("Access key not found.",{code:"ACCESS_KEY_MISSING"}),this.reporter.info(`Set the ${Ce} environment variable or run
|
|
65
|
+
'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){this.reporter.detail("Validating project access...");try{await this.apiClient.getProjectState(),this.reporter.detail("Project validated successfully");}catch(e){if(e instanceof ge)throw this.displayProjectValidationError(e),$e(e),e;if(e instanceof _e){this.reporter.detail("Project validated (first index)");return}if(e instanceof $)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.
|
|
63
66
|
Verify your network connection and that the API URL is correct.`):e}}displayProjectValidationError(e){let t=e.projectId||this.config.projectId,r=t.length>40?t.substring(0,37)+"...":t;switch(e.code){case "PROJECT_NOT_REGISTERED":this.reporter.error("Project not registered",{code:"PROJECT_NOT_REGISTERED"}),this.reporter.log(` The project ID "${r}" in constellation.json`),this.reporter.log(` is not associated with your Constellation account.
|
|
64
67
|
`),this.reporter.log(" To resolve this:"),this.reporter.log(" 1. Verify the project exists at https://app.constellationdev.io"),this.reporter.log(" 2. Check that the project ID in constellation.json is correct"),this.reporter.log(` 3. Run 'constellation index' again
|
|
65
68
|
`);break;case "PROJECT_INACTIVE":this.reporter.error("Project is inactive",{code:"PROJECT_INACTIVE"}),this.reporter.log(` The project "${r}" has been deactivated.
|
|
@@ -68,7 +71,7 @@ ${w} Upload completed in ${H}! Server indexing in progress.`),o="succeeded";}cat
|
|
|
68
71
|
`),this.reporter.log(" To resolve this:"),this.reporter.log(" 1. Get your project ID from https://app.constellationdev.io"),this.reporter.log(" 2. Update the projectId field in constellation.json"),this.reporter.log(` 3. Run 'constellation index' again
|
|
69
72
|
`);break;default:this.reporter.error(`Project validation failed: ${e.message}`,{code:"PROJECT_VALIDATION_FAILED"});}}logIndexingInProgress(e){this.reporter.info(`Another indexing operation is already in progress for branch ${e||"unknown"}.
|
|
70
73
|
Your index is up to date with the current operation.
|
|
71
|
-
Re-run this command after the current operation completes if you have newer changes.`);}async validateGitBranch(){this.reporter.detail("Validating Git repository and branch...");let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.reporter.detail(`Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.reporter.detail("Validating Git status..."),!(await this.git.status()).clean)throw new
|
|
74
|
+
Re-run this command after the current operation completes if you have newer changes.`);}async validateGitBranch(){this.reporter.detail("Validating Git repository and branch...");let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.reporter.detail(`Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.reporter.detail("Validating Git status..."),!(await this.git.status()).clean)throw new Pe(`Outstanding changes detected.
|
|
72
75
|
Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");this.reporter.detail("Working tree clean");}async synchronizeChanges(){this.reporter.detail("Synchronizing latest changes...");try{this.reporter.pause(),await this.git.pull()&&this.reporter.detail("Repository synchronized successfully");}catch(e){throw this.reporter.error("Failed to synchronize repository",{code:"GIT_SYNC_FAILURE"}),e instanceof Error&&(e.message.includes("uncommitted changes")?(this.reporter.log(`
|
|
73
76
|
To resolve:`),this.reporter.log(' 1. Commit your changes: git add . && git commit -m "your message"'),this.reporter.log(" 2. Or stash them: git stash"),this.reporter.log(` 3. Then run the index command again
|
|
74
77
|
`)):e.message.includes("merge conflicts")?(this.reporter.log(`
|
|
@@ -77,29 +80,29 @@ To resolve:`),this.reporter.log(" 1. Fix the conflicted files manually"),this.r
|
|
|
77
80
|
Please check your internet connection and try again
|
|
78
81
|
`):e.message.includes("Authentication")&&this.reporter.log(`
|
|
79
82
|
Please check your git credentials and try again
|
|
80
|
-
`)),e}finally{this.reporter.resume();}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.reporter.detail("Determining index scope...");try{let r=(await this.apiClient.getProjectState())?.latestCommit;if(!r)return this.reporter.detail("No previous index found, performing full index"),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return r===o?(this.reporter.detail("Already up to date"),{isIncremental:!0,upToDate:!0}):(this.reporter.detail(`Last indexed commit: ${r.substring(0,8)}`),this.reporter.detail(`Current commit: ${o.substring(0,8)}`),this.reporter.detail(`Performing incremental index starting from commit ${r.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof k)throw t;return this.reporter.warn(`Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){this.reporter.detail("Analyzing codebase...");let t;if(e)try{let r=await this.apiClient.getProjectState();if(!r?.latestCommit)this.reporter.warn("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(r.latestCommit),s=[...o.added,...o.modified,...o.renamed.map(l=>l.to)];this.reporter.detail(`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,u=c>0?`${ie} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${ie} Removing ${l} deleted file(s) from graph`;this.reporter.log(u),await this.apiClient.deleteFiles(a);}}}catch(r){if(r instanceof k)throw r;this.reporter.warn(`Cannot determine changes (${r instanceof Error?r.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else this.reporter.detail("Scanning all project files..."),t=await this.scanner.scanFiles(this.config);return this.reporter.detail(`Found ${t.length} files to index`),t}async*generateASTs(e,t,r,o){let s=e.length,a=0,l=0;o?.(0,s),this.reporter.detail(`Processing ${s} files...`);let c=await this.git.getLatestCommitHash(),u=s>1e4?5:s>5e3?7:10;u<10&&this.reporter.detail(`Large project detected, using concurrency of ${u} to optimize memory usage`);let d=new Fe(u,{preserveOrder:true}).run(e,async(m,h)=>{let g=Math.round((h+1)/s*100);this.reporter.detail(`Analyzing file ${m.path.replace(process.cwd()+"/","")} (${g}%)...`);try{let{tree:y,classificationMap:b,content:v}=await this.parser.parseFile(m.path,m.language),T=this.symbolExtractor.extract(y,m.language);T.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(m.relativePath),T),v!==void 0&&this.parseContent.set(this.normalizePathToCanonical(m.relativePath),v),b.entries.length>5e4&&this.reporter.warn(`Large classification map for ${m.relativePath}: ${b.entries.length} entries`);let C=this.langRegistry.getPlugin(m.language),_;if(C?.getImportResolver){let L=this.buildConfigManagers.get(m.language),ee=L?await L.getConfigForFile(m.path):null,z=C.getImportResolver(m.path,ee);if(z){let{ImportExtractor:K}=await Promise.resolve().then(()=>(jo(),Lo));_=await new K().extractImportResolutions(y,m.path,m.language,z);}}let{serializeASTStream:x}=await Promise.resolve().then(()=>(un(),zo)),G=x(y.rootNode,void 0,m.language),B=await this.compressor.compressStream(G),H=this.normalizePathToCanonical(m.relativePath),P={file:H,language:m.language,commit:c,timestamp:t,ast:B,importResolutions:_,classificationMap:{filePath:H,entries:b.entries}},$=io.safeParse(P);if(!$.success)throw new Error(`Index validation failed: ${$.error.issues[0].message}`);return a++,o?.(a,s),$.data}catch(y){throw l++,o?.(a+l,s),this.reporter.warn(`Failed to parse ${m.relativePath}: ${y.message}`,{code:"PARSE_FAILURE"}),y}});for await(let m of d)yield m;l>0?this.reporter.warn(`Completed parsing with ${l} parsing errors`):this.reporter.detail("All files analyzed successfully"),r&&r();}async uploadToAPI(e,t,r,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,r,o))throw new Error("Failed to upload data to Constellation Service");this.reporter.detail("Data uploaded to Constellation Service, indexing in progress");}async*createIndexPipeline(e,t,r,o,s){let a=await this.discoverFiles(e);this.discoveredFiles=a,o(a),yield*this.generateASTs(a,t,r,s);}async handleQueuedUpload(e,t,r,o){this.reporter.log("Generating index data for queue upload...");let s=this.createIndexPipeline(t,o,()=>{},()=>{});await this.apiClient.uploadToQueue(s,this.config.projectId,this.config.branch,r,e),this.reporter.detail("Changes queued for indexing behind the current operation.");}normalizePathToCanonical(e){return jt(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||ye.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.reporter.detail("Index enrichment skipped"),null;if(this.config.lspEnrichment===false)return this.reporter.detail("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.reporter.detail(`Index enrichment enabled for: ${o.map(xe).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,r,o,s,a){let l=new Ot(process.cwd(),this.reporter);try{if(s?.aborted)return null;this.reporter.detail("Starting index enrichment...");let c=new Map,u=new Map;for(let g of e){if(!t.has(g.language))continue;let y=c.get(g.language)||[];y.push(this.normalizePathToCanonical(g.relativePath)),c.set(g.language,y);}for(let g of c.keys()){if(u.has(g))continue;let b=this.config.languages[g]?.lsp,v=await l.startServer(g,b);v&&u.set(g,v);}if(u.size===0)return this.reporter.warn("No language servers started, index enrichment skipped"),null;if(s?.aborted)return l.destroyAll(),null;this.reporter.detail(`Language servers started: ${[...u.keys()].map(xe).join(", ")}`);let p=new At(process.cwd(),this.reporter),d=s?new Promise((g,y)=>{s.addEventListener("abort",()=>{l.destroyAll(),y(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,m=await(d?Promise.race([p.enrich(c,r,u,o,a),d]):p.enrich(c,r,u,o,a)),h=m.reduce((g,y)=>g+y.symbols.length,0);return this.reporter.detail(`Index enrichment analysis completed: ${h} symbols across ${m.length} files`),m.length>0?m:null}catch(c){return this.reporter.warn(`Index enrichment failed: ${c instanceof Error?c.message:String(c)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await l.shutdownAll();}}};});function fn(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 lr(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 cr(i){let{includeEntry:e,job:t}=lr(i);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var hn=f(()=>{});var dt,Yo=f(()=>{ae();hn();dt=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,r]=await Promise.all([S.directoryExists(E__default.join(this.gitRoot,".github","workflows")),S.fileIsReadable(E__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),r&&e.push("gitlab"),e}async githubWorkflowExists(){return S.fileIsReadable(E__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=E__default.join(this.gitRoot,".gitlab-ci.yml");if(!await S.fileIsReadable(e))return false;try{let r=await S.readFile(e),s=parseDocument(r).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=E__default.join(this.gitRoot,".github","workflows");await J__default.mkdir(t,{recursive:true});let r=E__default.join(t,"constellation-index.yml");return await S.writeFile(r,fn(e)),r}async createOrMergeGitLabCI(e){let t=E__default.join(this.gitRoot,".gitlab-ci.yml");if(!await S.fileIsReadable(t))return await S.writeFile(t,cr(e)),t;let o=await S.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await S.writeFile(t,cr(e)),t;let{includeEntry:a,job:l}=lr(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await S.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 Xo=f(()=>{Yo();hn();});function Qo(i,e){let t=Pe__default.homedir(),r=process.platform,o=fp[i];switch(r){case "darwin":return E__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return E__default.join(process.env.APPDATA||E__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return E__default.join(t,".config",o,"User/globalStorage",e)}}function Zo(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:E__default.join(Qo(t,i),"settings","cline_mcp_settings.json")}))}function es(){return E__default.join(Qo("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var fp,ts=f(()=>{fp={stable:"Code",insiders:"Code - Insiders"};});function ns(i){return bn.find(e=>e.id===i)}var rs,hp,bn,vn=f(()=>{ts();rs={command:"npx",args:["-y","@constellationdev/mcp@latest"]},hp={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"},autoUpdate:true}},enabledPlugins:{"constellation@constellation-plugins":true}},bn=[{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:hp},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:es(),isGlobalConfig:true,getGlobalConfigPaths:Zo,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false}},{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}"}},{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 is(){if(!Sn)try{let i=await import('@iarna/toml');Sn={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Sn}function vp(i){let e="",t=0,r=i.length;for(;t<r;)if(i[t]==='"'){for(e+='"',t++;t<r&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<r&&(e+=i[t++])):e+=i[t++];t<r&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<r&&i[t+1]==="/")for(t+=2;t<r&&i[t]!==`
|
|
81
|
-
`;)t++;else if(i[t]==="/"&&t+1<r&&i[t+1]==="*"){for(t+=2;t<r&&!(i[t]==="*"&&t+1<r&&i[t+1]==="/");)t++;t<r&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var
|
|
83
|
+
`)),e}finally{this.reporter.resume();}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.reporter.detail("Determining index scope...");try{let r=(await this.apiClient.getProjectState())?.latestCommit;if(!r)return this.reporter.detail("No previous index found, performing full index"),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return r===o?(this.reporter.detail("Already up to date"),{isIncremental:!0,upToDate:!0}):(this.reporter.detail(`Last indexed commit: ${r.substring(0,8)}`),this.reporter.detail(`Current commit: ${o.substring(0,8)}`),this.reporter.detail(`Performing incremental index starting from commit ${r.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof $)throw t;return this.reporter.warn(`Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){this.reporter.detail("Analyzing codebase...");let t;if(e)try{let r=await this.apiClient.getProjectState();if(!r?.latestCommit)this.reporter.warn("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(r.latestCommit),s=[...o.added,...o.modified,...o.renamed.map(l=>l.to)];this.reporter.detail(`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,u=c>0?`${de} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${de} Removing ${l} deleted file(s) from graph`;this.reporter.log(u),await this.apiClient.deleteFiles(a);}}}catch(r){if(r instanceof $)throw r;this.reporter.warn(`Cannot determine changes (${r instanceof Error?r.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else this.reporter.detail("Scanning all project files..."),t=await this.scanner.scanFiles(this.config);return this.reporter.detail(`Found ${t.length} files to index`),t}async*generateASTs(e,t,r,o){let s=e.length,a=0,l=0;o?.(0,s),this.reporter.detail(`Processing ${s} files...`);let c=await this.git.getLatestCommitHash(),u=s>1e4?5:s>5e3?7:10;u<10&&this.reporter.detail(`Large project detected, using concurrency of ${u} to optimize memory usage`);let d=new Ve(u,{preserveOrder:true}).run(e,async(m,f)=>{let h=Math.round((f+1)/s*100);this.reporter.detail(`Analyzing file ${m.path.replace(process.cwd()+"/","")} (${h}%)...`);try{let{tree:S,classificationMap:v,content:y}=await this.parser.parseFile(m.path,m.language),C=this.symbolExtractor.extract(S,m.language);C.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(m.relativePath),C),y!==void 0&&this.parseContent.set(this.normalizePathToCanonical(m.relativePath),y),v.entries.length>5e4&&this.reporter.warn(`Large classification map for ${m.relativePath}: ${v.entries.length} entries`);let b=this.langRegistry.getPlugin(m.language),_;if(b?.getImportResolver){let Ue=this.buildConfigManagers.get(m.language),G=Ue?await Ue.getConfigForFile(m.path):null,Y=b.getImportResolver(m.path,G);if(Y){let{ImportExtractor:Kr}=await Promise.resolve().then(()=>(ys(),hs));_=await new Kr().extractImportResolutions(S,m.path,m.language,Y);}}let{serializeASTStream:w}=await Promise.resolve().then(()=>(On(),Ls)),I=w(S.rootNode,void 0,m.language),A=await this.compressor.compressStream(I),j=this.normalizePathToCanonical(m.relativePath),W={file:j,language:m.language,commit:c,timestamp:t,ast:A,importResolutions:_,classificationMap:{filePath:j,entries:v.entries}},T=$o.safeParse(W);if(!T.success)throw new Error(`Index validation failed: ${T.error.issues[0].message}`);return a++,o?.(a,s),T.data}catch(S){throw l++,o?.(a+l,s),this.reporter.warn(`Failed to parse ${m.relativePath}: ${S.message}`,{code:"PARSE_FAILURE"}),S}});for await(let m of d)yield m;l>0?this.reporter.warn(`Completed parsing with ${l} parsing errors`):this.reporter.detail("All files analyzed successfully"),r&&r();}async uploadToAPI(e,t,r,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,r,o))throw new Error("Failed to upload data to Constellation Service");this.reporter.detail("Data uploaded to Constellation Service, indexing in progress");}async*createIndexPipeline(e,t,r,o,s){let a=await this.discoverFiles(e);this.discoveredFiles=a,o(a),yield*this.generateASTs(a,t,r,s);}async handleQueuedUpload(e,t,r,o){this.reporter.log("Generating index data for queue upload...");let s=this.createIndexPipeline(t,o,()=>{},()=>{});await this.apiClient.uploadToQueue(s,this.config.projectId,this.config.branch,r,e),this.reporter.detail("Changes queued for indexing behind the current operation.");}normalizePathToCanonical(e){return Yt(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||Ie.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.reporter.detail("Index enrichment skipped"),null;if(this.config.lspEnrichment===false)return this.reporter.detail("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.reporter.detail(`Index enrichment enabled for: ${o.map(Re).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,r,o,s,a){let l=new ir(process.cwd(),this.reporter);try{if(s?.aborted)return null;this.reporter.detail("Starting index enrichment...");let c=new Map,u=new Map;for(let y of e){if(!t.has(y.language))continue;let C=c.get(y.language)||[];C.push(this.normalizePathToCanonical(y.relativePath)),c.set(y.language,C);}let p=c.size,d=!1;for(let y of [...c.keys()]){if(s?.aborted)return null;let C=this.langRegistry?.getPlugin(y);if(!C?.preflightLsp)continue;let P;try{P=await C.preflightLsp(process.cwd());}catch(b){let _=b instanceof Error?b.message:String(b);this.reporter.warn(`LSP pre-flight failed for ${Re(y)} (${_}); proceeding without skip.`);continue}P.skip&&(this.reporter.warn(P.message),c.delete(y),d=!0);}let m=d&&c.size===0&&p>0;for(let y of c.keys()){if(u.has(y))continue;let P=this.config.languages[y]?.lsp,b=await l.startServer(y,P);b&&u.set(y,b);}if(u.size===0)return m||this.reporter.warn("No language servers started, index enrichment skipped"),null;if(s?.aborted)return l.destroyAll(),null;this.reporter.detail(`Language servers started: ${[...u.keys()].map(Re).join(", ")}`);let f=new Qt(process.cwd(),this.reporter),h=s?new Promise((y,C)=>{s.addEventListener("abort",()=>{l.destroyAll(),C(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,S=await(h?Promise.race([f.enrich(c,r,u,o,a),h]):f.enrich(c,r,u,o,a)),v=S.reduce((y,C)=>y+C.symbols.length,0);return this.reporter.detail(`Index enrichment analysis completed: ${v} symbols across ${S.length} files`),S.length>0?S:null}catch(c){return this.reporter.warn(`Index enrichment failed: ${c instanceof Error?c.message:String(c)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await l.shutdownAll();}}};});function Bn(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 jr(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 Ar(i){let{includeEntry:e,job:t}=jr(i);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var Wn=g(()=>{});var Lt,$s=g(()=>{le();Wn();Lt=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,r]=await Promise.all([x.directoryExists(R__default.join(this.gitRoot,".github","workflows")),x.fileIsReadable(R__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),r&&e.push("gitlab"),e}async githubWorkflowExists(){return x.fileIsReadable(R__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=R__default.join(this.gitRoot,".gitlab-ci.yml");if(!await x.fileIsReadable(e))return false;try{let r=await x.readFile(e),s=parseDocument(r).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=R__default.join(this.gitRoot,".github","workflows");await Q__default.mkdir(t,{recursive:true});let r=R__default.join(t,"constellation-index.yml");return await x.writeFile(r,Bn(e)),r}async createOrMergeGitLabCI(e){let t=R__default.join(this.gitRoot,".gitlab-ci.yml");if(!await x.fileIsReadable(t))return await x.writeFile(t,Ar(e)),t;let o=await x.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await x.writeFile(t,Ar(e)),t;let{includeEntry:a,job:l}=jr(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await x.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 Ds=g(()=>{$s();Wn();});function zn(i){if(i.installedBinaryPath!==void 0)return existsSync(i.installedBinaryPath)?{ok:true,path:i.installedBinaryPath}:{ok:false,reason:"not-installed"};if(!he(i.prerequisite))return {ok:false,reason:"not-installed"};let e;try{e=execFileSync(i.verifyCommand[0],[...i.verifyCommand.slice(1)],{stdio:["ignore","pipe","pipe"],timeout:Pu,maxBuffer:_u}).toString();}catch{return {ok:false,reason:"not-installed"}}let t=e.trim().split(/\r?\n/)[0]?.trim()??"";if(!t||!R.isAbsolute(t))return {ok:false,reason:"invalid-stdout"};let r=R.resolve(i.allowedRootPrefix),o;try{o=realpathSync(t);}catch{return {ok:false,reason:"not-installed"}}return o!==r&&!o.startsWith(r+R.sep)?{ok:false,reason:"untrusted-path"}:{ok:true,path:o}}var _u,Pu,Os=g(()=>{le();_u=4096,Pu=1e4;});function Ms(i,e){let t=Oe__default.homedir(),r=process.platform,o=Ru[i];switch(r){case "darwin":return R__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return R__default.join(process.env.APPDATA||R__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return R__default.join(t,".config",o,"User/globalStorage",e)}}function Us(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:R__default.join(Ms(t,i),"settings","cline_mcp_settings.json")}))}function Gs(){return R__default.join(Ms("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Ru,Bs=g(()=>{Ru={stable:"Code",insiders:"Code - Insiders"};});function Hs(i){return Kn.find(e=>e.id===i)}var Ws,Nu,Kn,Vn=g(()=>{Bs();Ws={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Nu={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"},autoUpdate:true}},enabledPlugins:{"constellation@constellation-plugins":true}},Kn=[{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:Nu},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Gs(),isGlobalConfig:true,getGlobalConfigPaths:Us,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false}},{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}"}},{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 zs(){if(!Jn)try{let i=await import('@iarna/toml');Jn={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Jn}function ku(i){let e="",t=0,r=i.length;for(;t<r;)if(i[t]==='"'){for(e+='"',t++;t<r&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<r&&(e+=i[t++])):e+=i[t++];t<r&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<r&&i[t+1]==="/")for(t+=2;t<r&&i[t]!==`
|
|
84
|
+
`;)t++;else if(i[t]==="/"&&t+1<r&&i[t+1]==="*"){for(t+=2;t<r&&!(i[t]==="*"&&t+1<r&&i[t+1]==="/");)t++;t<r&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Jn,Fr,Ks=g(()=>{le();Vn();Jn=null;Fr=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=R__default.join(this.cwd,e.configPath),r=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(r){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 r?o=t:e.permissionsConfig?o=R__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=R__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(),r=[];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),r.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")||r.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:l});}return r}async ensureDirectoryExists(e){let t=R__default.dirname(e);await Q__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await x.fileIsReadable(e))return {};let o=await x.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(ku(o)):(await zs()).parse(o)}catch{return {}}}addConstellationServer(e,t){let r=e;for(let a=0;a<t.mcpServersKeyPath.length-1;a++){let l=t.mcpServersKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!r[o]||typeof r[o]!="object")&&(r[o]={});let s=r[o];if(!s.constellation){let a=t.mcpServerConfigOverride??Ws,l={...a};if(t.mcpServerExtras&&Object.assign(l,t.mcpServerExtras),t.mcpEnv){let c=t.mcpEnvKey??"env",u=a[c];l[c]={...u,...t.mcpEnv};}s.constellation=l;}return e}async writeConfig(e,t,r){let o;r==="json"||r==="jsonc"?o=JSON.stringify(t,null,2):o=(await zs()).stringify(t),o=o.replace(/\r\n/g,`
|
|
82
85
|
`),o.endsWith(`
|
|
83
86
|
`)||(o+=`
|
|
84
|
-
`),await
|
|
85
|
-
`);}async configureMarketplace(e){let t=
|
|
86
|
-
`);}deepMerge(e,t){let r={...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)?r[o]=this.deepMerge(a,s):r[o]=s;}return r}addPluginToArray(e,t){let r=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(r[o])||(r[o]=[]);let s=r[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:r,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,r,o),s&&await this.updateGlobalEnvPolicy(s,r,o,t.format);}addToEnvPolicyWhitelist(e,t,r){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 r)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,r,o){let s=e.replace(/^~/,
|
|
87
|
-
`),!await this.git.isGitAvailable())throw new Error("Could not find git client installation. Constellation requires git \u2014 install it from https://git-scm.com/downloads and try again.");let r=
|
|
88
|
-
${r}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:
|
|
89
|
-
${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:
|
|
87
|
+
`),await x.writeFile(e,o);}async configurePermissions(e){let t=R__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await x.fileIsReadable(t)){let c=await x.readFile(t);r=JSON.parse(c);}}catch{}let o=r;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 x.writeFile(t,JSON.stringify(r,null," ")+`
|
|
88
|
+
`);}async configureMarketplace(e){let t=R__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await x.fileIsReadable(t)){let s=await x.readFile(t);r=JSON.parse(s);}}catch{}r=this.deepMerge(r,e.config),await x.writeFile(t,JSON.stringify(r,null," ")+`
|
|
89
|
+
`);}deepMerge(e,t){let r={...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)?r[o]=this.deepMerge(a,s):r[o]=s;}return r}addPluginToArray(e,t){let r=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(r[o])||(r[o]=[]);let s=r[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:r,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,r,o),s&&await this.updateGlobalEnvPolicy(s,r,o,t.format);}addToEnvPolicyWhitelist(e,t,r){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 r)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,r,o){let s=e.replace(/^~/,Oe__default.homedir()),a=await this.readConfig(s,o);if(Object.keys(a).length===0)return;let l=JSON.stringify(a);this.addToEnvPolicyWhitelist(a,t,r);let c=JSON.stringify(a);l!==c&&await this.writeConfig(s,a,o);}};});function $r(i,e){let t=R__default.normalize(i),r=R__default.normalize(e);return t.startsWith(r+R__default.sep)?R__default.relative(e,i):i}var Du,kt,Ys=g(()=>{Ds();xt();Os();yr();Ks();Vn();le();z();Wt();Ut();Du=promisify(execFile);kt=class extends Ee{async run(e={}){try{if(this.reporter.log(`${xe} Initializing project configuration...
|
|
90
|
+
`),!await this.git.isGitAvailable())throw new Error("Could not find git client installation. Constellation requires git \u2014 install it from https://git-scm.com/downloads and try again.");let r=R__default.join(process.cwd(),"constellation.json"),o=null,s=await x.fileIsReadable(r);if(s)try{let b=await x.readFile(r);o=JSON.parse(b),this.reporter.info("Found existing constellation.json, current values will be used as defaults.");}catch{this.reporter.warn("Existing constellation.json is invalid, starting fresh.");}if(!await this.git.isGitRepository())throw new Error("Current directory is not a git repository. Run this command from the root directory of a git repository.");let l=await this.git.getRootDir(),[c,u]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:p}=c,d=u.filter(b=>b!==p),m=p?[p,...d]:d,f=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:b=>b.trim().length>0||"Project ID is required",theme:M}),h=await select({message:"Branch to index:",choices:m.map(b=>({name:b,value:b})),default:o?.branch??m[0],theme:M}),v=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:M})).reduce((b,_)=>(b[_]={fileExtensions:tt[_]||[]},b),{});this.reporter.log(""),this.reporter.info("Checking for LSP servers...");for(let[b,_]of Object.entries(v)){let w=Ie.get(b);if(!w)continue;let I=!1,A="";if(he(w.command)&&(I=!0,A="system"),!I){let T=R__default.join(rr,w.command);existsSync(T)&&(I=!0,A="managed");}let j=w.manualInstall?.autoInstall,W;if(!I&&j){let T=zn(j);T.ok&&(W=T.path,I=!0,A="managed");}if(I)this.reporter.log(`${E} ${b}: Found ${w.command} (${A})`),_.lsp={command:A==="managed"&&W!==void 0?W:w.command,args:w.args};else if(w.npmPackages.length===0&&w.manualInstall){let T=w.manualInstall.autoInstall;if(T&&he(T.prerequisite)){if(T.installedBinaryPath!==void 0){let G=R__default.resolve(Je),Y=R__default.resolve(T.installedBinaryPath);if(!Y.startsWith(G+R__default.sep)){this.reporter.error(`${b}: installedBinaryPath (${Y}) is outside the managed directory; refusing to install. Report this as a bug.`),_.lspEnrichment=!1;continue}}if(await confirm({message:`${b}: ${w.command} not found. Install via \`${w.manualInstall.command}\`?`,default:!0,theme:M}))try{this.reporter.info(`${b}: Installing ${w.command} via \`${T.argv.join(" ")}\` (this may take a minute)...`),execFileSync(T.argv[0],[...T.argv.slice(1)],{stdio:"pipe",env:{...process.env,...T.env??{}}});let G=zn(T);G.ok?(this.reporter.log(`${E} ${b}: Installed ${w.command} (${G.path})`),_.lsp={command:G.path,args:w.args}):G.reason==="untrusted-path"?(this.reporter.error(`${b}: Install completed but the resolved binary path is outside the allowed prefix; refusing to wire it. Report this as a bug.`),_.lspEnrichment=!1):G.reason==="invalid-stdout"?(this.reporter.error(`${b}: Install completed but the verify command produced no usable absolute path. Try running manually: \`${w.manualInstall.command}\`.`),_.lspEnrichment=!1):(this.reporter.error(`${b}: Install command exited 0 but ${w.command} wasn't found afterwards. Try running manually: \`${w.manualInstall.command}\`.`),_.lspEnrichment=!1);}catch(G){let Y=G.stderr?.toString().trim();this.reporter.error(`${b}: Installation failed${Y?`: ${Y}`:""}`),_.lspEnrichment=!1;}else this.reporter.info(`${b}: To install manually: \`${w.manualInstall.command}\``),this.reporter.info(`${b}: Indexing will continue without LSP enrichment.`),_.lspEnrichment=!1;}else this.reporter.info(`${b}: ${w.command} not found. Requires ${w.manualInstall.requires}. Install with: ${w.manualInstall.command}`),w.manualInstall.pathNote&&this.reporter.info(`${b}: ${w.manualInstall.pathNote}`),this.reporter.info(`${b}: Indexing will continue without LSP enrichment.`),_.lspEnrichment=!1;}else if(await confirm({message:`${b}: ${w.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:M}))try{this.reporter.info(`Installing ${w.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",Je,...w.npmPackages],{stdio:"pipe"}),this.reporter.log(`${E} ${b}: Installed ${w.command}`),_.lsp={command:w.command,args:w.args};}catch{this.reporter.error(`${b}: Installation failed`),_.lspEnrichment=!1;}else _.lspEnrichment=!1;}let y=Object.entries(v).filter(([,b])=>b.lspEnrichment!==!1).map(([b])=>b);y.length>0?this.reporter.log(`${E} Index enrichment enabled for: ${y.map(Re).join(", ")}`):this.reporter.warn("No language servers configured. Index enrichment will be skipped.");let C={projectId:f.trim(),branch:h,languages:{...v},...y.length>0&&{lspEnrichment:!0}},P=JSON.stringify(C,void 0,2);await x.writeFile(r,P),this.reporter.log(`${E} ${s?"Updated":"Initialized"} configuration file at ${$r(r,process.cwd())}`),await this.git.stageFile(r),this.reporter.log(`${E} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&l&&await this.configureCICD(h,l);}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let r=t.message??"An unexpected error occurred";this.reporter.error(`Failed to initialize configuration file.
|
|
91
|
+
${r}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:M}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:Kn.map(p=>({name:p.displayName,value:p.id})),required:true,theme:M}),r=new Fr(process.cwd()),o=[];for(let p of t){let d=Hs(p);if(d)if(this.reporter.info(`Configuring ${d.displayName}...`),d.pluginInstallCommand){let m=await this.executePluginInstall(d);o.push(m),m.success?this.reporter.log(`${E} ${d.displayName} plugin installed successfully`):this.reporter.warn(`${d.displayName}: ${m.error}`);}else if(d.isGlobalConfig&&d.getGlobalConfigPaths){let m=await r.configureGlobalTool(d),f=false;for(let h of m)o.push(h),h.success?(f=true,this.reporter.log(`${E} ${h.tool.displayName} configured at ${$r(h.configuredPath,process.cwd())}`)):h.error&&this.reporter.warn(`${h.tool.displayName}: ${h.error}`);if(f){let h=d.id==="cline"?"global VS Code settings":"global settings";this.reporter.info(`Note: ${d.displayName} uses ${h} (not project-level)`);}if(m.length===0){let h=d.id==="cline"?"No VS Code installations found":"Configuration directory not found";this.reporter.warn(`${d.displayName}: ${h}`);}}else {let m=await r.configureTool(d);o.push(m),m.success?(this.reporter.log(`${E} ${d.displayName} configured at ${$r(m.configuredPath,process.cwd())}`),d.permissionsConfig&&this.reporter.log(`${E} ${d.displayName} permissions set in ${d.permissionsConfig.filePath}`)):this.reporter.warn(`${d.displayName}: ${m.error}`);}}if(o.find(p=>p.tool.id==="claude-code"&&p.success)){let p=R__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),this.reporter.log(`${E} Added .claude/settings.json to staged changes in git`);}catch{this.reporter.warn("Could not stage .claude/settings.json in git");}}if(o.find(p=>p.tool.id==="codex-cli"&&p.success)){let p=R__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),this.reporter.log(`${E} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=R__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),this.reporter.log(`${E} Added opencode.jsonc to staged changes in git`);}catch{}}let c=o.filter(p=>p.success).length,u=o.filter(p=>!p.success).length;this.reporter.log(`${E} Plugin + MCP configuration complete: ${c} configured`),u>0&&this.reporter.warn(`${u} tool(s) could not be configured`),this.reporter.info("Some tools may require restart to pick up new configuration.");}async executePluginInstall(e){let t=e.pluginInstallCommand;try{await this.runPluginCommand(t);}catch(r){let o=r;if(e.pluginUpdateCommand&&this.isAlreadyInstalledError(o)){this.reporter.info(`${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)this.reporter.info(`${e.displayName} plugin source already configured, continuing...`);else return {tool:e,success:false,error:this.formatPluginCommandError(t.command,o)}}for(let r of e.pluginPostInstallCommands??[])try{await this.runPluginCommand(r);}catch(o){let s=o;return {tool:e,success:false,error:this.formatPluginCommandError(r.command,s)}}return {tool:e,success:true}}async runPluginCommand(e){await Du(e.command,e.args,{timeout:3e4,env:process.env});}isAlreadyInstalledError(e){let t=`${e.message??""}
|
|
92
|
+
${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:M}))return;let o=new Lt(t),s=await o.detectPlatforms(),a;if(s.length===1){let p=s[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${p}. Configure Constellation CI/CD for this platform?`,default:true,theme:M}))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:M});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:M})){this.reporter.info("Skipping CI/CD configuration");return}let c;try{c=a==="github"?await o.createGitHubWorkflow(e):await o.createOrMergeGitLabCI(e);}catch(p){this.reporter.warn(`Failed to configure CI/CD pipeline: ${p.message}`);return}let u=$r(c,process.cwd());a==="github"?this.reporter.log(`${E} Created ${u}`):this.reporter.log(`${E} ${l?"Updated":"Created"} ${u} with Constellation indexing`);try{await this.git.stageFile(c),this.reporter.log(`${E} Added ${u} to staged changes in git`);}catch{this.reporter.warn(`Could not stage ${u} in git`);}a==="github"?this.reporter.info(`Add your access key as a repository secret:
|
|
90
93
|
Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret
|
|
91
94
|
Name: CONSTELLATION_ACCESS_KEY`):this.reporter.info(`Add your access key as a CI/CD variable:
|
|
92
95
|
Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable
|
|
93
|
-
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(r=>({...r,checked:t.includes(r.value)}))}};});var
|
|
94
|
-
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},
|
|
95
|
-
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((r,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?r():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(r){throw new Error(`Failed to set environment variable ${e}: ${r}`)}}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="",u="";l.stdout?.on("data",p=>{c+=p.toString();}),l.stderr?.on("data",p=>{u+=p.toString();}),l.on("close",p=>{p===0?s(c):a(new Error(`reg query failed: ${u}`));}),l.on("error",p=>{a(p);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},
|
|
96
|
-
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let r=this.escapeShellValue(t),o=`export ${e}="${r}"`;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,r){let o="";try{o=await
|
|
96
|
+
Key: CONSTELLATION_ACCESS_KEY`);}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"Go",value:"go"},{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(r=>({...r,checked:t.includes(r.value)}))}};});var Dr,Xs=g(()=>{cn();Cr();le();z();Dr=class i{constructor(e,t,r,o,s){this.branch=e;this.languages=t;this.projectId=r;this.exclude=o;this.lspEnrichment=s;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await x.fileIsReadable(e)){let r=await x.readFile(e),o=JSON.parse(r),s=new i(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${ae} 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 r of t.fileExtensions)if(!r.startsWith("."))throw new Error(`Invalid configuration: file extension "${r}" 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 Pe("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new Pe(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var Mr,qn,Ur,Yn,Xn,Qn,Gr,Qs=g(()=>{le();Mr=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(`
|
|
97
|
+
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},qn=class extends Mr{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.
|
|
98
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((r,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?r():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(r){throw new Error(`Failed to set environment variable ${e}: ${r}`)}}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="",u="";l.stdout?.on("data",p=>{c+=p.toString();}),l.stderr?.on("data",p=>{u+=p.toString();}),l.on("close",p=>{p===0?s(c):a(new Error(`reg query failed: ${u}`));}),l.on("error",p=>{a(p);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},Ur=class extends Mr{userConfigFiles;constructor(){super(),this.userConfigFiles=[R.join(Oe.homedir(),".zshenv"),R.join(Oe.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.
|
|
99
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let r=this.escapeShellValue(t),o=`export ${e}="${r}"`;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,r){let o="";try{o=await x.readFile(e,"utf-8");}catch{}let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^export ${s}=.*$`,"gm");a.test(o)?o=o.replace(a,r):o=o.trimEnd()+`
|
|
97
100
|
`+r+`
|
|
98
|
-
`,await
|
|
101
|
+
`,await x.writeFile(e,o);}async assertSafeWriteTarget(e){try{let t=await Q__default.lstat(e);if(!t.isFile()){let o=t.isSymbolicLink()?"symlink":"special file";throw new Error(`refusing to overwrite ${e}: existing path is a ${o}`)}let r=process.getuid?.();if(r!==void 0&&t.uid!==r)throw new Error(`refusing to overwrite ${e}: file is owned by uid ${t.uid}, not the current user`)}catch(t){if(t.code==="ENOENT")return;throw t}}},Yn=class i extends Ur{static LAUNCH_AGENT_LABEL="io.constellationdev.env";launchAgentDir;launchAgentScriptDir;launchAgentLogDir;launchAgentPlistPath;launchAgentScriptPath;launchAgentStderrPath;constructor(){super();let e=Oe.homedir();this.launchAgentDir=R.join(e,"Library","LaunchAgents"),this.launchAgentScriptDir=R.join(e,"Library","Application Support","Constellation"),this.launchAgentLogDir=R.join(e,"Library","Logs","Constellation"),this.launchAgentPlistPath=R.join(this.launchAgentDir,`${i.LAUNCH_AGENT_LABEL}.plist`),this.launchAgentScriptPath=R.join(this.launchAgentScriptDir,"launchd-env.sh"),this.launchAgentStderrPath=R.join(this.launchAgentLogDir,"launchd-env.err");}async setVariable(e,t){await super.setVariable(e,t);try{await this.ensureLaunchAgentDirs();}catch(r){this.warnLaunchd("create LaunchAgent directories",r);return}try{await this.updateLaunchAgentScript(e,t);}catch(r){this.warnLaunchd("write launchd-env.sh wrapper script",r);return}try{await this.ensureLaunchAgentPlist();}catch(r){this.warnLaunchd("write LaunchAgent plist",r);return}await this.reloadLaunchAgent(),await this.setLaunchctlEnv(e,t);}async ensureLaunchAgentDirs(){await Q__default.mkdir(this.launchAgentDir,{recursive:true}),await Q__default.mkdir(this.launchAgentScriptDir,{recursive:true}),await Q__default.mkdir(this.launchAgentLogDir,{recursive:true}),await Q__default.chmod(this.launchAgentScriptDir,448);}static escapeXml(e){return e.replace(/[&<>"']/g,t=>{switch(t){case "&":return "&";case "<":return "<";case ">":return ">";case '"':return """;case "'":return "'";default:return t}})}async updateLaunchAgentScript(e,t){let r=this.escapeShellValue(t),o=`launchctl setenv ${e} "${r}"`,s="";try{s=await x.readFile(this.launchAgentScriptPath,"utf-8");}catch{}s||(s=`#!/bin/bash
|
|
99
102
|
# Managed by Constellation CLI - do not edit manually
|
|
100
103
|
`);let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^launchctl setenv ${a} .*$`,"gm");l.test(s)?s=s.replace(l,o):s=s.trimEnd()+`
|
|
101
104
|
`+o+`
|
|
102
|
-
`,await this.assertSafeWriteTarget(this.launchAgentScriptPath),await
|
|
105
|
+
`,await this.assertSafeWriteTarget(this.launchAgentScriptPath),await Q__default.writeFile(this.launchAgentScriptPath,s,{mode:448}),await Q__default.chmod(this.launchAgentScriptPath,448);}async ensureLaunchAgentPlist(){let e=i.escapeXml(this.launchAgentScriptPath),t=i.escapeXml(this.launchAgentStderrPath),o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
103
106
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
104
107
|
<plist version="1.0">
|
|
105
108
|
<dict>
|
|
@@ -118,18 +121,18 @@ ${e.stderr??""}`.toLowerCase();return t.includes("already installed")||t.include
|
|
|
118
121
|
<string>${t}</string>
|
|
119
122
|
</dict>
|
|
120
123
|
</plist>
|
|
121
|
-
`;await this.assertSafeWriteTarget(this.launchAgentPlistPath),await
|
|
122
|
-
Shell environments still updated; log out and back in if GUI apps don't see the value.`);}runLaunchctl(e,t){return new Promise((r,o)=>{let s=spawn("/bin/launchctl",e,{shell:false}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0||t?r():o(new Error(`launchctl ${e[0]} failed (code ${l}): ${a.trim()}`));}),s.on("error",l=>{t?r():o(l);});})}async reloadLaunchAgent(){let e=process.getuid?.();if(e!==void 0)try{await this.runLaunchctl(["bootout",`gui/${e}/${i.LAUNCH_AGENT_LABEL}`],!0),await this.runLaunchctl(["bootstrap",`gui/${e}`,this.launchAgentPlistPath],!1);}catch(t){this.warnLaunchd("register LaunchAgent for next login",t);}}async setLaunchctlEnv(e,t){try{await this.runLaunchctl(["setenv",e,t],!0);}catch(r){this.warnLaunchd("run launchctl setenv",r);}}},
|
|
124
|
+
`;await this.assertSafeWriteTarget(this.launchAgentPlistPath),await x.writeFile(this.launchAgentPlistPath,o),await Q__default.chmod(this.launchAgentPlistPath,384);}warnLaunchd(e,t){let r=t instanceof Error?t.message:String(t);console.warn(`Warning: failed to ${e} for GUI apps: ${r}
|
|
125
|
+
Shell environments still updated; log out and back in if GUI apps don't see the value.`);}runLaunchctl(e,t){return new Promise((r,o)=>{let s=spawn("/bin/launchctl",e,{shell:false}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0||t?r():o(new Error(`launchctl ${e[0]} failed (code ${l}): ${a.trim()}`));}),s.on("error",l=>{t?r():o(l);});})}async reloadLaunchAgent(){let e=process.getuid?.();if(e!==void 0)try{await this.runLaunchctl(["bootout",`gui/${e}/${i.LAUNCH_AGENT_LABEL}`],!0),await this.runLaunchctl(["bootstrap",`gui/${e}`,this.launchAgentPlistPath],!1);}catch(t){this.warnLaunchd("register LaunchAgent for next login",t);}}async setLaunchctlEnv(e,t){try{await this.runLaunchctl(["setenv",e,t],!0);}catch(r){this.warnLaunchd("run launchctl setenv",r);}}},Xn=class i extends Ur{static ENV_D_FILENAME="io.constellationdev.env.conf";envDDir;envDFilePath;constructor(){super(),this.envDDir=R.join(Oe.homedir(),".config","environment.d"),this.envDFilePath=R.join(this.envDDir,i.ENV_D_FILENAME);}async setVariable(e,t){await super.setVariable(e,t);try{await this.ensureEnvironmentDDir();}catch(r){this.warnSystemd("create environment.d directory",r);return}try{await this.updateEnvironmentDFile(e,t);}catch(r){this.warnSystemd("write environment.d conf file",r);return}await this.importToSystemdUser(e,t);}async ensureEnvironmentDDir(){await Q__default.mkdir(this.envDDir,{recursive:true});}async updateEnvironmentDFile(e,t){let r=i.escapeEnvironmentDValue(t),o=`${e}=${r}`,s="";try{s=await x.readFile(this.envDFilePath,"utf-8");}catch{}s||(s=`# Managed by Constellation CLI - do not edit manually
|
|
123
126
|
`);let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^${a}=.*$`,"gm");l.test(s)?s=s.replace(l,o):s=s.trimEnd()+`
|
|
124
127
|
`+o+`
|
|
125
|
-
`,await this.assertSafeWriteTarget(this.envDFilePath),await
|
|
126
|
-
Shell environments still updated; log out and back in if systemd-launched apps don't see the value.`);}},
|
|
127
|
-
`);}catch{}return "verbose"}if(t)return "verbose";if(r)return "quiet";if(e.CONSTELLATION_REPORTER_MODE){let a=e.CONSTELLATION_REPORTER_MODE;if(a==="spinner"||a==="verbose"||a==="quiet"||a==="plain")return a}let o=
|
|
128
|
-
${
|
|
129
|
-
`),await this.packageManager.executeUpdate(
|
|
130
|
-
${
|
|
128
|
+
`,await this.assertSafeWriteTarget(this.envDFilePath),await Q__default.writeFile(this.envDFilePath,s,{mode:384}),await Q__default.chmod(this.envDFilePath,384);}async importToSystemdUser(e,t){if(he("systemctl")&&process.env.XDG_RUNTIME_DIR)try{await this.runSystemctl(["--user","set-environment",`${e}=${t}`],!1);}catch(r){this.warnSystemd("run systemctl --user set-environment",r);}}runSystemctl(e,t){return new Promise((r,o)=>{let s=spawn("systemctl",e,{shell:false}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0||t?r():o(new Error(`systemctl ${e.slice(0,2).join(" ")} failed (code ${l}): ${a.trim()}`));}),s.on("error",l=>{t?r():o(l);});})}static escapeEnvironmentDValue(e){return e.replace(/\\/g,"\\\\").replace(/\$/g,"$$$$")}warnSystemd(e,t){let r=t instanceof Error?t.message:String(t);console.warn(`Warning: failed to ${e} for systemd user services: ${r}
|
|
129
|
+
Shell environments still updated; log out and back in if systemd-launched apps don't see the value.`);}},Qn=class{static create(){let e=Oe.platform();switch(e){case "win32":return new qn;case "darwin":return new Yn;case "linux":return new Xn;default:throw new Error(`Unsupported platform: ${e}`)}}},Gr=class{manager;constructor(){this.manager=Qn.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 Br,Zs=g(()=>{Br=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,r]of Object.entries(e.languages))for(let o of r.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=R__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function ea(i=process.argv,e=process.env){let t=i.includes("--verbose"),r=i.includes("--quiet")||i.includes("-q")||i.includes("-Q");if(t&&r){try{process.stderr.write(`note: --verbose and --quiet are mutually exclusive; --verbose wins.
|
|
130
|
+
`);}catch{}return "verbose"}if(t)return "verbose";if(r)return "quiet";if(e.CONSTELLATION_REPORTER_MODE){let a=e.CONSTELLATION_REPORTER_MODE;if(a==="spinner"||a==="verbose"||a==="quiet"||a==="plain")return a}let o=Gi(),s=Bi();return o||!s?"plain":"spinner"}var ta=g(()=>{sn();});function Mu(){let i=Oe.platform();if(i==="darwin")return R.join(Oe.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||R.join(Oe.homedir(),"AppData","Local");return R.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||R.join(Oe.homedir(),".cache");return R.join(e,"constellation")}}var Uu,Gu,Bu,jt,Zn=g(()=>{Uu=Mu(),Gu="update-state.json",Bu=1440*60*1e3,jt=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??Uu,this.stateFile=R.join(this.stateDir,Gu);}async load(){if(this.state)return this.state;try{let e=await Q.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await Q.mkdir(this.stateDir,{recursive:!0}),await Q.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>Bu}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 Q.unlink(this.stateFile),this.state=null;}catch{}}};});var At,ei=g(()=>{At=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,...r]=this.getUpdateCommand(e);return new Promise(o=>{let s=spawn(t,r,{stdio:"inherit",shell:process.platform==="win32"});s.on("close",a=>{o(a===0);}),s.on("error",()=>{o(false);});})}};});var Ft,ti=g(()=>{He();z();Ut();Ft=class{async promptForUpdate(e,t,r){console.log(""),console.log(cyan("\u2501".repeat(60))),console.log(`${xe} ${bold("Update Available!")}`),console.log(""),console.log(` Current version: ${dim(e)}`),console.log(` Latest version: ${bold(green(t))}`),console.log(""),console.log(` ${dim(`Package manager: ${r}`)}`),console.log(cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:M})}catch{return false}}};});async function ri(i){return new Hr().check(i)}var zu,Wr,Ku,Hr,ra=g(()=>{z();Zn();ei();ti();zu="https://registry.npmjs.org",Wr="@constellationdev/cli",Ku=5e3,Hr=class{cache;packageManager;prompter;constructor(){this.cache=new jt,this.packageManager=new At,this.prompter=new Ft;}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,r=setTimeout(()=>t.abort(),Ku);try{let o=await fetch(`${zu}/${Wr}/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(r);}}isNewerVersion(e,t){let r=a=>a.split("-")[0],o=r(e).split(".").map(Number),s=r(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(`
|
|
131
|
+
${de} Updating ${Wr}...
|
|
132
|
+
`),await this.packageManager.executeUpdate(Wr)?(console.log(`
|
|
133
|
+
${E} Update complete! Please re-run your command.
|
|
131
134
|
`),true):(console.log(`
|
|
132
|
-
${
|
|
133
|
-
`),false)}};});var
|
|
134
|
-
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 this.reporter?.error("Pull failed: Merge conflicts detected"),this.reporter?.detail(`Conflicted files: ${o.conflicted.join(", ")}`),this.reporter?.detail("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&&this.reporter?.log(`${
|
|
135
|
-
`);}catch(i){
|
|
135
|
+
${O} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Wr)}
|
|
136
|
+
`),false)}};});var na=g(()=>{Zn();ei();ti();ra();});var $t,ia=g(()=>{z();$t=class{constructor(e,t){this.reporter=t;let r={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(r);}git;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");let r=new Date(t);if(Number.isNaN(r.getTime()))throw new Error(`Could not parse commit timestamp: ${t}`);return r.toISOString()}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),r={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"?r.added.push(a[1]):l==="M"?r.modified.push(a[1]):l==="D"?r.deleted.push(a[1]):l.startsWith("R")&&a.length>=3&&r.renamed.push({from:a[1],to:a[2]});}return r}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(r=>r.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,r=e.current;return {clean:t,currentBranch:r}}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 this.reporter?.error("Cannot pull: Working directory has uncommitted changes"),this.reporter?.detail(`Details: ${JSON.stringify(o,null,2)}`),e.conflicted.length>0&&this.reporter?.warn(`Conflicted files: ${e.conflicted.join(", ")}`),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
|
|
137
|
+
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 this.reporter?.error("Pull failed: Merge conflicts detected"),this.reporter?.detail(`Conflicted files: ${o.conflicted.join(", ")}`),this.reporter?.detail("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&&this.reporter?.log(`${E} Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let r=await this.git.status();if(r.conflicted.length>0)throw this.reporter?.error("Unexpected conflicts after pull:"),this.reporter?.detail(`Conflicted files: ${r.conflicted.join(", ")}`),new Error(`Unexpected merge conflicts detected after pull: ${r.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(this.reporter?.error("Pull failed due to merge conflicts"),this.reporter?.detail('Run "git status" to see conflicted files'),this.reporter?.detail('Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?this.reporter?.error("Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?this.reporter?.error("Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?this.reporter?.error("Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&this.reporter?.error("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 sa,oa=g(()=>{sa={"tree-sitter":"0.21.1","tree-sitter-typescript":"0.21.2","tree-sitter-javascript":"0.21.4","tree-sitter-python":"0.21.0"};});function aa(){let i={};for(let e of qu){let t=sa[e];if(typeof t!="string"||t.length===0)throw new Error(`grammar-versions.json missing entry for ${e}`);i[e]=t;}return i}var qu,la=g(()=>{oa();qu=["tree-sitter","tree-sitter-typescript","tree-sitter-javascript","tree-sitter-python"];});var td={};var J,Te,ca,ni,Zu,ed,ii,oi,dt,pa=g(async()=>{wi();js();Ys();Xs();Qs();Zs();yr();ta();En();na();Vr();Bt();ia();la();J=new _r({mode:ea(process.argv)}),Te=()=>{try{J.stop();}catch{}};process.on("exit",Te);process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&(Te(),process.exit(0)),ve(i)||J.error(i?.message??String(i)),Te(),process.exit(1);});ca=globalThis.__constellationVersion??(()=>{let i=R__default.dirname(fileURLToPath(import.meta.url)),e=R__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})(),ni=(()=>{let i=process.argv[1];return i&&R__default.basename(i).replace(/\.(c|m)?js$/i,"")==="const"?"const":"constellation"})(),Zu=new Set(["print-grammar-versions"]),ed=Zu.has(process.argv[2]);if(J.mode!=="quiet"&&!ed){let i=process.argv[2];["auth","help","init","index"].includes(i)?Gt(ni,i):Gt(ni),Dt.includes(i)||await ri(ca)&&(Te(),process.exit(0));}ii=process.cwd(),oi=new Gr,dt=new Command;dt.name(ni).description("Connecting stars in your code into intelligent patterns").version(ca).option("--verbose","Print every step (no spinner). Useful for CI logs and debugging.").option("-q, --quiet","Suppress phase output. Print only warnings, errors, and a final summary.");dt.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 $t(ii,J),Reporter:J};await new kt(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){ve(e)||J.error(e instanceof Error?e.message:String(e)),Te(),process.exit(1);}});dt.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:oi,Reporter:J};await new gt(e).run(i.manual);}catch(e){ve(e)||J.error(e instanceof Error?e.message:String(e)),Te(),process.exit(1);}});dt.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 Dr.loadFromFile(R__default.join(ii,"constellation.json")),t=new $t(ii,J),r=new hr(e),o=new Br(e),s={GitClient:t,Config:e,LanguageRegistry:r,LanguageDetector:o,Environment:oi,Reporter:J},a=oi.isCI(),l=i.full||!i.incremental&&a,c=i.dirty||!1,u=!0;!i.full&&!i.incremental&&a&&J.info("CI environment detected \u2014 defaulting to full index. Use --incremental to override."),await new Tt(s).run(l,c,u);}catch(e){ve(e)||J.error(e instanceof Error?e.message:String(e)),Te(),process.exit(1);}});dt.command("print-grammar-versions",{hidden:true}).description("Emit installed tree-sitter grammar versions as JSON").action(()=>{try{process.stdout.write(JSON.stringify(aa())+`
|
|
138
|
+
`);}catch(i){ve(i)||J.error(i instanceof Error?i.message:String(i)),Te(),process.exit(1);}});dt.parse();});var da=/^>=\s*\d+\.\d+\.\d+$/;function ci(i,e=process.version){if(!da.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),r=e.replace(/^v/,""),o=t.split(".").map(Number),s=r.split(".").map(Number),a=true;for(let l=0;l<3;l++){let c=o[l]||0,u=s[l]||0;if(u>c)break;if(u<c){a=false;break}}return {compatible:a,current:e,required:i}}Vr();var sd=dirname(fileURLToPath(import.meta.url)),ad=join(sd,"..","package.json"),si=JSON.parse(readFileSync(ad,"utf-8")),ld=process.argv[2];if(!Dt.includes(ld)&&si.engines?.node){let i=ci(si.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=si.version;await pa().then(()=>td);
|