@constellationdev/cli 1.3.1 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +49 -49
- package/package.json +4 -2
- package/third_party/tree-sitter-swift/LICENSE +21 -0
- package/third_party/tree-sitter-swift/README.md +34 -0
- package/third_party/tree-sitter-swift/binding.gyp +25 -0
- package/third_party/tree-sitter-swift/bindings/node/binding.cc +20 -0
- package/third_party/tree-sitter-swift/bindings/node/index.d.ts +28 -0
- package/third_party/tree-sitter-swift/bindings/node/index.js +7 -0
- package/third_party/tree-sitter-swift/package.json +17 -0
- package/third_party/tree-sitter-swift/src/node-types.json +31727 -0
- package/third_party/tree-sitter-swift/src/parser.c +484485 -0
- package/third_party/tree-sitter-swift/src/scanner.c +856 -0
- package/third_party/tree-sitter-swift/src/tree_sitter/alloc.h +54 -0
- package/third_party/tree-sitter-swift/src/tree_sitter/array.h +290 -0
- package/third_party/tree-sitter-swift/src/tree_sitter/parser.h +266 -0
package/dist/main.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {bold,blue,gray,green,red,dim,yellow,blueBright,cyan}from'yoctocolors';import*as
|
|
2
|
+
import {bold,blue,gray,green,red,dim,yellow,blueBright,cyan}from'yoctocolors';import*as We from'os';import We__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}from'zod';import {Readable,Transform}from'stream';import {base32}from'@scure/base';import*as Oe from'fs';import {readFileSync,existsSync,realpathSync}from'fs';import {buffer}from'stream/consumers';import {pipeline}from'stream/promises';import*as Vn from'zlib';import Vn__default from'zlib';import {Agent,fetch as fetch$1}from'undici';import*as k from'path';import k__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as se from'fs/promises';import se__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import Xp from'tree-sitter-c-sharp';import Qp from'tree-sitter-go';import Zp from'tree-sitter-javascript';import eu from'tree-sitter-python';import tu from'tree-sitter-swift';import ru from'tree-sitter-typescript';import od from'tree-sitter';import Ps from'ignore';import {performance}from'perf_hooks';import md from'yocto-spinner';import {parseDocument,isMap,isSeq,stringify}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var il=Object.defineProperty;var f=(n,e)=>()=>(n&&(e=n(n=0)),e);var $i=(n,e)=>{for(var t in e)il(n,t,{get:e[t],enumerable:true});};var Vt,an=f(()=>{Vt=["help","--help","-h","--version","-V","-v"];});function Oi(){let n=process.env;return n.FORCE_COLOR&&n.FORCE_COLOR!=="0"&&n.FORCE_COLOR!=="false"?true:n.NO_COLOR?false:!!process.stdout.isTTY}function Ui(){let n=process.env;if(n.NO_COLOR)return false;if(n.FORCE_COLOR==="3")return true;let e=n.COLORTERM?.toLowerCase();if(e==="truecolor"||e==="24bit"||n.WT_SESSION)return true;let t=n.TERM?.toLowerCase()??"";return !!(t.includes("truecolor")||t.includes("24bit")||t==="xterm-kitty"||t==="alacritty"||t==="wezterm")}function Mi(n,e,t){return [Math.round(n[0]+(e[0]-n[0])*t),Math.round(n[1]+(e[1]-n[1])*t),Math.round(n[2]+(e[2]-n[2])*t)]}function fe(n,e=0,t=false){if(Oi()&&!Ui())return blueBright(n);let r=[],o=0;for(let p of n.matchAll(cl))p.index>o&&r.push({ansi:false,value:n.slice(o,p.index)}),r.push({ansi:true,value:p[0]}),o=p.index+p[0].length;o<n.length&&r.push({ansi:false,value:n.slice(o)});let a=[...r.filter(p=>!p.ansi).map(p=>p.value).join("")],l=xt.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 g,h,b;if(t){let y=(m+e)%l/l*(l-1),S=Math.floor(y),E=Math.min(S+1,l-1),T=y-S;[g,h,b]=Mi(xt[S],xt[E],T);}else {let y=(c>1?m/(c-1):0)*(l-1),S=Math.floor(y),E=Math.min(S+1,l-1),T=y-S;[g,h,b]=Mi(xt[S],xt[E],T);}return ll(g,h,b,d)}).join("")).join("")}var oe,xt,ll,cl,Ye=f(()=>{oe={info:n=>blue(n),success:n=>green(n),warn:n=>yellow(n),error:n=>red(n),accent:n=>bold(blue(n)),muted:n=>gray(n),dim:n=>dim(n)},xt=[[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]];ll=(n,e,t,r)=>!Oi()||!Ui()?r:`\x1B[38;2;${n};${e};${t}m${r}\x1B[0m`;cl=/\x1b\[[0-9;]*m/g;});function pl(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:We.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 ul,dl,ml,fl,gl,hl,yl,vl,bl,Sl,wl,_l,Xe,x,ge,W,ve,Ee,Yt,X=f(()=>{Ye();ul="\u2714",dl="\u2717",ml="\u26A0",fl="\u2139",gl="\u26A1",hl="\u29D7",yl="[OK]",vl="[ERR]",bl="[WARN]",Sl="[INFO]",wl="[>>]",_l="[WAIT]",Xe=pl(),x=oe.success(Xe?ul:yl),ge=oe.error(Xe?dl:vl),W=oe.warn(Xe?ml:bl),ve=oe.info(Xe?fl:Sl),Ee=oe.warn(Xe?gl:wl),Yt=oe.info(Xe?hl:_l);});var B,Xt=f(()=>{Ye();X();B={prefix:{idle:blue("\u25C6"),done:x},style:{highlight:n=>blue(n),answer:n=>green(n),error:n=>red(`${ge} ${n}`),help:n=>gray(n)},icon:{checked:green("\u25FC"),unchecked:gray("\u25FB"),cursor:blue("\u276F")}};});async function Bi(n){if(!n.startsWith("http://")&&!n.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await pn("open",[n]),!0;case "linux":return await pn("xdg-open",[n]),!0;case "win32":return await pn("cmd",["/c","start","",n]),!0;default:return !1}}catch{return false}}var pn,Hi=f(()=>{pn=promisify(execFile);});function Rl(n,e){if(!e)return false;let t,r;try{t=new URL(e),r=new URL(n);}catch{return false}return r.protocol!=="http:"&&r.protocol!=="https:"?false:r.origin===t.origin}function Wi(n={}){let e=n.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,g)=>{let h=new URL(m.url??"/",`http://127.0.0.1:${l.port}`);if(h.pathname!=="/callback"){g.writeHead(404,{"Content-Type":"text/plain"}),g.end("Not found");return}let b=h.searchParams.get("key");if(h.searchParams.get("state")!==c){g.writeHead(400,{"Content-Type":"text/plain"}),g.end("Invalid state parameter");return}if(!b||!Pl.test(b)){g.writeHead(400,{"Content-Type":"text/plain"}),g.end("Invalid key format");return}if(a)return;a=true;let S=h.searchParams.get("return_url");S&&Rl(S,e)?(g.writeHead(302,{Location:S}),g.end()):(g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(Il)),s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections(),p(b);});})}});}),o.on("error",l=>{r(l);});})}var Pl,Il,zi=f(()=>{Pl=/^ak:[0-9a-f]{32}$/i,Il=`<!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 Qt(n,e){let t=`${n} \u203A ${e}`;
|
|
4
|
+
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function un(n){process.stdout.write(n+`
|
|
5
|
+
`);}function Qt(n,e){let t=`${n} \u203A ${e}`;un(`${fe("\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
6
|
${fe("\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
7
|
${fe("\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
8
|
${fe("\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
|
-
${fe("\u2502 CONSTELLATIONDEV.IO \u2502")}`),e&&e.length>0?
|
|
9
|
+
${fe("\u2502 CONSTELLATIONDEV.IO \u2502")}`),e&&e.length>0?un(`${fe(`\u251C\u2500${"\u2500".repeat(t.length)}\u2500\u252C\u2500${"\u2500".repeat(78-t.length)}\u256F`)}
|
|
10
10
|
${fe(`\u2502 ${bold(t)} \u2502${" ".repeat(80-t.length)}`)}
|
|
11
11
|
${fe(`\u2570\u2500${"\u2500".repeat(t.length)}\u2500\u256F${" ".repeat(80-t.length)}`)}
|
|
12
|
-
`):
|
|
12
|
+
`):un(fe("\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 Ki=f(()=>{Ye();});var Pe,Vi,Zt=f(()=>{Ki();Pe="CONSTELLATION_ACCESS_KEY",Vi="CONSTELLATION_WEB_URL";});var Ie,er=f(()=>{Ie=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 jl(n){return kl.test(n)}function Al(n){return n.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var kl,Ct,qi=f(()=>{Xt();Hi();zi();Zt();X();er();kl=/^ak:[0-9a-f]{32}$/i;Ct=class extends Ie{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(this.reporter.log(`${Ee} Configuring access key authentication...
|
|
13
13
|
`),this.env.isCI()){this.reporter.error(`Cannot configure authentication in CI/CD environments
|
|
14
14
|
|
|
15
15
|
The ${Pe} environment variable must be configured
|
|
@@ -20,10 +20,10 @@ ${fe(`\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(Pe)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:B})){this.reporter.log(`${x} 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=
|
|
24
|
-
${o}`);}}async manualAuthFlow(){let e,t=0,r=3;for(;t<r;){if(e=(await password({message:"Constellation Access Key:",theme:B})).trim(),!e){this.reporter.warn("Access key cannot be empty."),t++;continue}if(!
|
|
23
|
+
`);return}if(await this.env.getKey(Pe)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:B})){this.reporter.log(`${x} 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=Al(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:B})).trim(),!e){this.reporter.warn("Access key cannot be empty."),t++;continue}if(!jl(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[Vi]||"https://app.constellationdev.io",{port:r,waitForCallback:o}=await Wi({allowedOrigin:t}),s=`${t}/auth/cli?callback_port=${r}&state=${e}`;this.reporter.info("Opening browser for authentication..."),await Bi(s)||this.reporter.warn(`Could not open browser automatically.
|
|
27
27
|
Please open this URL manually:
|
|
28
28
|
|
|
29
29
|
${s}
|
|
@@ -31,38 +31,38 @@ ${fe(`\u2570\u2500${"\u2500".repeat(t.length)}\u2500\u256F${" ".repeat(80-t.leng
|
|
|
31
31
|
|
|
32
32
|
source ${t}
|
|
33
33
|
|
|
34
|
-
New terminal sessions will load it automatically.`),He.platform()==="darwin"&&this.reporter.info("Already-running desktop apps (Claude Desktop, Codex, etc.) must be quit and relaunched to see the new value.");}};});var Hi,be,Et,xl,Xe,Pt,Cl,El,Pl,It,Il,Rl,Nl,Tl,Ll,kl,jl,Al,Fl,$l,Dl,Ol,Ml,Ul,Gl,Bl,Hl,zl,Wl,Kl,Gi,Vl,Jl,ql,Yl,Xl,Ql,Zl,ec,tc,rc,nc,ic,oc,sc,ac,lc,cc,zi,pc,uc,pn,dc,mc,fc,gc,Rt,hc,yc,vc,bc,Sc,Wi,wc,_c,tr,cn,Bi,xc,Cc,Ec,un,Ki,Pc,Ic,Rc,Nc,dn,Tc,Lc,kc,jc,Ac,Fc,Vi,Ji,qi,Yi,$c,Dc,Oc,Xi,Qi,Mc,Uc,Gc,Bc,Nt=f(()=>{Hi=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()}),be=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","record","delegate","event","indexer","operator","destructor","local_function","attribute","generic_type_parameter","macro","unknown"]),Et=z$1.enum(["low","medium","high","critical"]),xl=z$1.enum(["low","moderate","high","very_high"]),Xe=z$1.object({cyclomaticComplexity:z$1.number().int().nonnegative(),complexityRisk:xl}),Pt=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()}),Pt.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())}),Cl=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()}),El=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()}),Pl=z$1.object({nodes:z$1.array(Cl),edges:z$1.array(El),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()}),It=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(n=>n.query.length>0||n.filterByKind&&n.filterByKind.length>0||n.filterByVisibility&&n.filterByVisibility.length>0||n.isExported!==void 0||n.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),Il=Pt.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:Xe.optional(),languageMetadata:be.optional()}),z$1.object({symbols:z$1.array(Il),pagination:Hi.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()}),Rl=Pt.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:Xe.optional(),languageMetadata:be.optional()}),Nl=Pt.extend({usageType:z$1.string(),context:z$1.string().optional(),aliasName:z$1.string().optional()}),Tl=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())}),Ll=z$1.object({directUsage:z$1.number().int().nonnegative(),transitiveImpact:z$1.number().int().nonnegative(),riskScore:z$1.number().min(0).max(100),riskLevel:Et}),z$1.object({symbol:Rl,references:z$1.array(Nl).optional(),relationships:Tl.optional(),impactScore:Ll.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)}),kl=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()}),jl=z$1.object({filePath:z$1.string(),distance:z$1.number().int().positive(),path:z$1.array(z$1.string())}),Al=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(kl),transitiveDependencies:z$1.array(jl).optional(),packages:z$1.array(Al).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)}),Fl=z$1.object({filePath:z$1.string(),usedSymbols:z$1.array(z$1.string()).optional()}),$l=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:Et}),z$1.object({file:z$1.string(),directDependents:z$1.array(Fl),transitiveDependents:z$1.array($l).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()}),Dl=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:Et}),z$1.object({cycles:z$1.array(Dl)}),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)}),Ol=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:Xe.optional(),languageMetadata:be.optional()}),Ml=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()}),Ul=z$1.object({filePath:z$1.string(),distance:z$1.number().int().positive(),chain:z$1.array(z$1.string())}),Gl=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()}),Bl=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:Gl}),z$1.object({symbol:Ol,directUsages:z$1.array(Ml),transitiveUsages:z$1.array(Ul).optional(),summary:Bl}),Hl=z$1.preprocess(n=>n==="callers"?"incoming":n==="callees"?"outgoing":n,z$1.enum(["incoming","outgoing","both"])).describe("Direction of traversal for getCallGraph. Use 'incoming' | 'outgoing' | 'both'. Legacy aliases 'callers' (\u2192 'incoming') and 'callees' (\u2192 'outgoing') are deprecated and will be removed in a future release."),z$1.object({symbolId:z$1.string().optional(),symbolName:z$1.string().optional(),filePath:z$1.string().optional(),direction:Hl.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)}),zl=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:Xe.optional(),languageMetadata:be.optional()}),Wl=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:Xe.optional(),languageMetadata:be.optional()}),Kl=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:Xe.optional(),languageMetadata:be.optional()}),z$1.object({root:zl,callers:z$1.array(Wl).optional(),callees:z$1.array(Kl).optional(),graph:Pl.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(2),excludeTests:z$1.boolean().default(true),excludeGenerated:z$1.boolean().default(true),analyzeBreakingChanges:z$1.boolean().default(true)}),Gi=Pt.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:be.optional()}),Vl=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()}))}),Jl=z$1.object({riskLevel:Et,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:be.optional()}),directDependents:z$1.array(Gi).optional(),transitiveDependents:z$1.array(Gi).optional(),impactedFiles:z$1.array(Vl),breakingChangeRisk:Jl.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()}),ql=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:be.optional()}),Yl=z$1.object({filePath:z$1.string(),reason:z$1.string(),lastUpdated:z$1.string().optional(),confidence:z$1.number().min(0).max(1)}),Xl=z$1.object({totalOrphanedSymbols:z$1.number().int().nonnegative(),totalOrphanedFiles:z$1.number().int().nonnegative(),potentialDeletions:z$1.number().int().nonnegative(),filesTruncated:z$1.boolean().optional()}),z$1.object({orphanedSymbols:z$1.array(ql),orphanedFiles:z$1.array(Yl),summary:Xl.optional(),pagination:Hi.optional()}),z$1.object({includeMetrics:z$1.boolean().default(false),includeModuleGraph:z$1.boolean().default(false),includePackages:z$1.boolean().default(true)}),Ql=z$1.object({language:z$1.string(),fileCount:z$1.number().int().nonnegative(),percentage:z$1.number().min(0).max(100)}),Zl=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())}),ec=z$1.object({languages:z$1.array(Ql),frameworks:z$1.array(Zl),primaryLanguage:z$1.string(),totalFiles:z$1.number().int().nonnegative(),totalLines:z$1.number().int().nonnegative().optional()}),tc=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()})}),rc=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()}))})}),nc=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()}),ic=z$1.object({id:z$1.string(),name:z$1.string(),fileCount:z$1.number().int().nonnegative(),type:z$1.string()}),oc=z$1.object({from:z$1.string(),to:z$1.string(),weight:z$1.number().int().nonnegative()}),sc=z$1.object({nodes:z$1.array(ic),edges:z$1.array(oc)}),z$1.object({metadata:ec,structure:tc,dependencies:rc,metrics:nc.optional(),moduleGraph:sc.optional()}),z$1.object({}).strict(),z$1.object({pong:z$1.literal(true)}),ac=z$1.enum(["relative","workspace","alias","external","builtin"]),lc=z$1.object({source:z$1.string(),resolvedPath:z$1.string().optional(),isExternal:z$1.boolean(),importType:ac}),cc=z$1.record(z$1.string(),lc),zi=z$1.enum(["call","read","write","type","instantiate","import-use","declaration"]),pc=zi.exclude(["import-use","declaration"]),uc=z$1.object({line:z$1.number().int().nonnegative(),column:z$1.number().int().nonnegative(),referenceType:zi}).strict(),pn=z$1.object({filePath:z$1.string().min(1),entries:z$1.array(uc).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:cc.optional(),classificationMap:pn.optional()}).strict(),dc=z$1.object({file:z$1.string(),error:z$1.string()}),mc=z$1.object({file:z$1.string(),failedCount:z$1.number().int().nonnegative(),createdCount:z$1.number().int().nonnegative(),isTransient:z$1.boolean()}),fc=z$1.object({totalCreated:z$1.number().int().nonnegative(),totalFailed:z$1.number().int().nonnegative(),filesWithFailures:z$1.array(mc)}),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(dc).optional(),relationships:fc}),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())}),gc=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(gc),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:pc,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"]),Rt={branchName:z$1.string().optional(),effectiveBranchName:z$1.string().optional(),remapped:z$1.boolean().optional()},hc=z$1.object({status:z$1.literal("acquired"),attemptId:z$1.string().uuid(),...Rt}),yc=z$1.object({status:z$1.literal("current"),...Rt}),vc=z$1.object({status:z$1.literal("duplicate"),...Rt}),bc=z$1.object({status:z$1.literal("superseded"),activeCommit:z$1.string().optional(),...Rt}),Sc=z$1.object({status:z$1.literal("queued"),queuedAttemptId:z$1.string().uuid(),...Rt}),Wi=z$1.discriminatedUnion("status",[hc,yc,vc,bc,Sc]),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()}),wc=z$1.enum(["pass1","pass2","pass2b","pass3"]),_c=z$1.object({phase:wc,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()}),tr=z$1.array(_c),cn=z$1.object({filePath:z$1.string().min(1),line:z$1.number().int().positive(),column:z$1.number().int().nonnegative()}).strict(),Bi=cn.extend({name:z$1.string().min(1)}).strict(),xc=z$1.object({resolvedType:z$1.string().min(1),returnType:z$1.string().optional(),documentation:z$1.string().max(16384).optional()}).strict(),Cc=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:xc.optional(),references:z$1.object({count:z$1.number().int().nonnegative(),locations:z$1.array(cn).max(100)}).optional(),callHierarchy:z$1.object({incomingCalls:z$1.array(Bi).max(200),outgoingCalls:z$1.array(Bi).max(200)}).optional(),implementations:z$1.array(cn).max(200).optional()}).strict(),z$1.object({filePath:z$1.string().min(1),language:z$1.string().min(1),symbols:z$1.array(Cc).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(),Ec=z$1.enum(["pending","processing","completed","failed","skipped"]),un=z$1.object({status:Ec,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"]),Ki=z$1.union([z$1.string().datetime({offset:true}),z$1.date()]),Pc=z$1.object({status:z$1.literal("processing"),commitHash:z$1.string().nullable().optional(),startedAt:Ki.optional(),phaseMetrics:tr.optional()}).passthrough(),Ic=z$1.object({status:z$1.literal("current"),commitHash:z$1.string().nullable().optional(),completedAt:Ki.nullable().optional(),enrichment:un.optional(),phaseMetrics:tr.optional()}).passthrough(),Rc=z$1.object({status:z$1.literal("stale"),currentCommit:z$1.string().nullable().optional(),requestedCommit:z$1.string().optional(),enrichment:un.optional(),phaseMetrics:tr.optional()}).passthrough(),Nc=z$1.object({status:z$1.literal("failed"),currentCommit:z$1.string().nullable().optional(),requestedCommit:z$1.string().optional(),enrichment:un.optional(),phaseMetrics:tr.optional()}).passthrough(),dn=z$1.discriminatedUnion("status",[Pc,Ic,Rc,Nc]),Tc=z$1.enum(["function","class","variable","import","module","interface","type","constant","export"]),Lc=z$1.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),kc=z$1.object({id:z$1.string(),label:z$1.string(),type:Tc,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()})}),jc=z$1.object({id:z$1.string(),source:z$1.string(),target:z$1.string(),type:Lc,label:z$1.string().optional()}),Ac=z$1.object({totalNodes:z$1.number().int().nonnegative(),totalEdges:z$1.number().int().nonnegative(),toolName:z$1.string(),query:z$1.string(),riskLevel:Et.optional()}),Fc=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(kc),edges:z$1.array(jc),summary:Ac,metadata:Fc,features:z$1.record(z$1.string(),z$1.boolean()).optional()}),Vi=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(Vi)}),Vi.pick({projectId:true,projectName:true,defaultBranch:true}),Ji=z$1.enum(["unresolved","resolved","archived"]),qi=z$1.enum(["succeeded","failed"]),Yi=z$1.enum(["full","incremental"]),$c=z$1.enum(["info","warn","error"]),Dc=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()}),Oc=z$1.object({type:z$1.string(),message:z$1.string(),phase:z$1.string(),filePath:z$1.string().optional()}),Xi=z$1.object({errors:z$1.array(Dc),warnings:z$1.array(Oc)}),Qi=z$1.object({level:$c,message:z$1.string(),timestamp:z$1.string().datetime()}),z$1.object({errorSummary:z$1.string().max(500),errorData:Xi,logEntries:z$1.array(Qi),cliVersion:z$1.string(),outcome:qi,indexType:Yi}),z$1.object({status:Ji.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:Yi,status:Ji,outcome:qi,errorSummary:z$1.string(),errorData:Xi,logEntries:z$1.array(Qi),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()}),Mc=["org-admin-v1","developer-v1","constellation-admin-v1"],Uc=z$1.enum(Mc),Gc=["eligible","completed","dismissed","ineligible"],Bc=z$1.enum(Gc),z$1.object({tourId:Uc,status:Bc,lastStepReached:z$1.string().max(64).optional()}),z$1.object({stepId:z$1.string().min(1).max(64)});});var mn,Tt=f(()=>{mn=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 fn(n){return n.length>rr&&(n[rr]=Zi),n}function eo(){let n=false,e=0;return new Transform({transform(t,r,o){if(n){o(null,t);return}if(e+t.length>rr){let s=rr-e;t[s]=Zi,n=true;}e+=t.length,o(null,t);}})}var rr,Zi,gn=f(()=>{rr=9,Zi=255;});function to(n){return base32.encode(Buffer.from(n))}var ro=f(()=>{});function no(n,e,t){let r=`${n}:${e}${t?`:${t}`:""}`;return to(r)}var io=f(()=>{ro();});var nr,oo=f(()=>{nr=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 ao(){return so.some(n=>!!process.env[n])}function lo(){return !!process.stdout.isTTY}function co(){let n=so.find(e=>!!process.env[e]);return n?Kc[n]:void 0}var so,Kc,hn=f(()=>{so=["GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE","CI"],Kc={GITHUB_ACTIONS:"github-actions",GITLAB_CI:"gitlab",JENKINS_URL:"jenkins",CIRCLECI:"circleci",TRAVIS:"travis",BUILDKITE:"buildkite",DRONE:"drone",CI:"unknown"};});function Vc(n){switch(n){case "darwin":return "Macintosh";case "win32":return "Windows";case "linux":return "Linux";case "freebsd":return "FreeBSD";default:return n.charAt(0).toUpperCase()+n.slice(1)}}function Jc(n,e){return n==="darwin"?`Darwin ${e}`:e}function qc(){let n=globalThis.__constellationVersion;return typeof n=="string"&&n.length>0?n:"unknown"}function Yc(n={}){let e=n.platform??process.platform,t=n.arch??process.arch,r=(n.nodeVersion??process.version).replace(/^v/,""),o=n.osRelease??He.release(),s=qc(),a=Vc(e),l=Jc(e,o),c=`constellation-cli/${s} (${a}; ${l}; ${t}) Node/${r}`,u=co();return u&&(c+=` CI/${u}`),c}var Lt,uo=f(()=>{hn();Lt=Yc();});function ep(n){switch(n){case "PROJECT_NOT_REGISTERED":return "PROJECT_NOT_REGISTERED";case "PROJECT_INACTIVE":return "PROJECT_INACTIVE";case "INVALID_PROJECT_ID":return "INVALID_PROJECT_ID";default:return "PROJECT_VALIDATION_FAILED"}}var ir,or,H,Re,Se,je,Ne,bn=f(()=>{Nt();q();Tt();gn();io();oo();uo();ir=class n{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 Re("Project not found - no previous index exists");default:throw e.status===404?new Re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof Se||t instanceof Re?t:e.status===404?new Re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let 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=dn.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 H)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 H("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=Wi.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 H("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let u=await c.json(),p=dn.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 H)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":Lt,"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=Gn.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":Lt,"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 H("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 H)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=no(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?n.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 je(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 nr(e),u=await buffer(c),p=process.env.CAPTURE_PAYLOAD_PATH;if(p)try{await pipeline(Readable.from(u),Gn.createGzip(),eo(),De.createWriteStream(p));}catch(g){this.reporter?.warn(`[constellation] capture tap failed: ${g instanceof Error?g.message:String(g)}`);}let d=[1e3,2e3,4e3],m;for(let g=0;g<=d.length;g++){let h=new Agent({headersTimeout:0,bodyTimeout:0});try{let b=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":Lt,"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(b.status===401)throw new H("Authentication failed");if(b.status===409)throw await this.parseIndexingConflict(b);if(b.status===200)try{let S=await b.json();if(S?.status==="current")return this.reporter?.summary(`${x} Index already up to date for ${o} at commit ${S.commitHash||"unknown"}`),!0}catch{}if(b.ok||b.status===202)return !0;let y=`Server returned ${b.status}`;try{let S=await b.json();S?.message&&(y=Array.isArray(S.message)?S.message.join("; "):S.message);}catch{}throw new Error(y)}catch(b){if(b instanceof H||b instanceof je)throw b;if(this.isRetryableNetworkError(b)&&g<d.length){let y=Math.floor(Math.random()*250),S=d[g]+y;this.reporter?.warn(`Upload network error (attempt ${g+1}/${d.length+1}): ${this.shortNetworkErrorReason(b)} \u2014 retrying in ${S}ms`),m=b,await new Promise(E=>setTimeout(E,S));continue}throw b}finally{h.destroy().catch(()=>{});}}throw m??new Error("Upload failed after exhausting retry budget")}catch(c){if(c instanceof H||c instanceof je)throw c;let u=c instanceof Error?c:new Error(String(c)),p="";if(u.message==="fetch failed"||c.code){let m=[],g=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}`);}g==="ERR_INVALID_ARG_VALUE"?p="Invalid argument value - check stream/body format and duplex option":g==="ECONNREFUSED"?p="Connection refused - service may be down or unreachable":g==="ENOTFOUND"?p="DNS lookup failed - check service URL":g==="ETIMEDOUT"?p="Connection timeout - service not responding":g==="ECONNRESET"?p="Connection reset by server":g==="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":Lt,Authorization:`Bearer ${this.accessKey}`},g=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),g.status===401)throw new H("Authentication failed");if(!g.ok&&this.retryableStatusCodes.includes(g.status))throw new or(`${g.statusText} (${g.status})`);return g}catch(d){if(p&&clearTimeout(p),!(d instanceof H)){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 or){let m=l+Math.floor(Math.random()*c);await new Promise(g=>setTimeout(g,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}`)}},or=class extends Error{constructor(e){super(e),this.name="RetryableError";}},H=class extends Error{errorCode="AUTH_FAILURE";constructor(e){super(e),this.name="AuthenticationError";}},Re=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",this.errorCode=
|
|
37
|
-
`):y&&typeof y=="object"&&(S=y.value||""),S&&(d.typeInfo={resolvedType:S},m=true);}if(h.status==="fulfilled"&&h.value){let y=h.value.filter(S=>{let E=this.uriToPath(S.uri||"");return !
|
|
34
|
+
New terminal sessions will load it automatically.`),We.platform()==="darwin"&&this.reporter.info("Already-running desktop apps (Claude Desktop, Codex, etc.) must be quit and relaunched to see the new value.");}};});var Qi,be,Et,Fl,Qe,Pt,$l,Dl,Ml,It,Ol,Ul,Gl,Bl,Hl,Wl,zl,Kl,Vl,Jl,ql,Yl,Xl,Ql,Zl,ec,tc,rc,nc,ic,Yi,oc,sc,ac,lc,cc,pc,uc,dc,mc,fc,gc,hc,yc,vc,bc,Sc,wc,Zi,_c,xc,mn,Cc,Ec,Pc,Ic,Rt,Rc,Nc,Tc,Lc,kc,eo,jc,Ac,tr,dn,Xi,Fc,$c,Dc,fn,to,Mc,Oc,Uc,Gc,gn,Bc,Hc,Wc,zc,Kc,Vc,ro,no,io,oo,Jc,qc,Yc,so,ao,Xc,Qc,Zc,ep,Nt=f(()=>{Qi=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()}),be=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","record","delegate","event","indexer","operator","destructor","local_function","attribute","generic_type_parameter","macro","unknown"]),Et=z.enum(["low","medium","high","critical"]),Fl=z.enum(["low","moderate","high","very_high"]),Qe=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:Fl}),Pt=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()}),Pt.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())}),$l=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),Dl=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),Ml=z.object({nodes:z.array($l),edges:z.array(Dl),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),It=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(n=>n.query.length>0||n.filterByKind&&n.filterByKind.length>0||n.filterByVisibility&&n.filterByVisibility.length>0||n.isExported!==void 0||n.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),Ol=Pt.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:Qe.optional(),languageMetadata:be.optional()}),z.object({symbols:z.array(Ol),pagination:Qi.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()}),Ul=Pt.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:Qe.optional(),languageMetadata:be.optional()}),Gl=Pt.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),Bl=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())}),Hl=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Et}),z.object({symbol:Ul,references:z.array(Gl).optional(),relationships:Bl.optional(),impactScore:Hl.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)}),Wl=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()}),zl=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),Kl=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(Wl),transitiveDependencies:z.array(zl).optional(),packages:z.array(Kl).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)}),Vl=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),Jl=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:Et}),z.object({file:z.string(),directDependents:z.array(Vl),transitiveDependents:z.array(Jl).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()}),ql=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Et}),z.object({cycles:z.array(ql)}),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)}),Yl=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:Qe.optional(),languageMetadata:be.optional()}),Xl=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()}),Ql=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),Zl=z.object({limit:z.number().int().positive(),offset:z.number().int().nonnegative(),returned:z.number().int().nonnegative(),hasMore:z.boolean()}),ec=z.object({totalUsages:z.number().int().nonnegative(),usagesByType:z.record(z.string(),z.number().int().nonnegative()),filesAffected:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),pageInfo:Zl}),z.object({symbol:Yl,directUsages:z.array(Xl),transitiveUsages:z.array(Ql).optional(),summary:ec}),tc=z.preprocess(n=>n==="callers"?"incoming":n==="callees"?"outgoing":n,z.enum(["incoming","outgoing","both"])).describe("Direction of traversal for getCallGraph. Use 'incoming' | 'outgoing' | 'both'. Legacy aliases 'callers' (\u2192 'incoming') and 'callees' (\u2192 'outgoing') are deprecated and will be removed in a future release."),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:tc.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)}),rc=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:Qe.optional(),languageMetadata:be.optional()}),nc=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:Qe.optional(),languageMetadata:be.optional()}),ic=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:Qe.optional(),languageMetadata:be.optional()}),z.object({root:rc,callers:z.array(nc).optional(),callees:z.array(ic).optional(),graph:Ml.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(2),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),Yi=Pt.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:be.optional()}),oc=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()}))}),sc=z.object({riskLevel:Et,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:be.optional()}),directDependents:z.array(Yi).optional(),transitiveDependents:z.array(Yi).optional(),impactedFiles:z.array(oc),breakingChangeRisk:sc.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()}),ac=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:be.optional()}),lc=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string().optional(),confidence:z.number().min(0).max(1)}),cc=z.object({totalOrphanedSymbols:z.number().int().nonnegative(),totalOrphanedFiles:z.number().int().nonnegative(),potentialDeletions:z.number().int().nonnegative(),filesTruncated:z.boolean().optional()}),z.object({orphanedSymbols:z.array(ac),orphanedFiles:z.array(lc),summary:cc.optional(),pagination:Qi.optional()}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),pc=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),uc=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),dc=z.object({languages:z.array(pc),frameworks:z.array(uc),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),mc=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()})}),fc=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()}))})}),gc=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()}),hc=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),yc=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),vc=z.object({nodes:z.array(hc),edges:z.array(yc)}),z.object({metadata:dc,structure:mc,dependencies:fc,metrics:gc.optional(),moduleGraph:vc.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),bc=z.enum(["relative","workspace","alias","external","builtin"]),Sc=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:bc}),wc=z.record(z.string(),Sc),Zi=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),_c=Zi.exclude(["import-use","declaration"]),xc=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:Zi}).strict(),mn=z.object({filePath:z.string().min(1),entries:z.array(xc).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:wc.optional(),classificationMap:mn.optional()}).strict(),Cc=z.object({file:z.string(),error:z.string()}),Ec=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),Pc=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(Ec)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(Cc).optional(),relationships:Pc}),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())}),Ic=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(Ic),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:_c,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"]),Rt={branchName:z.string().optional(),effectiveBranchName:z.string().optional(),remapped:z.boolean().optional()},Rc=z.object({status:z.literal("acquired"),attemptId:z.string().uuid(),...Rt}),Nc=z.object({status:z.literal("current"),...Rt}),Tc=z.object({status:z.literal("duplicate"),...Rt}),Lc=z.object({status:z.literal("superseded"),activeCommit:z.string().optional(),...Rt}),kc=z.object({status:z.literal("queued"),queuedAttemptId:z.string().uuid(),...Rt}),eo=z.discriminatedUnion("status",[Rc,Nc,Tc,Lc,kc]),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()}),jc=z.enum(["pass1","pass2","pass2b","pass3"]),Ac=z.object({phase:jc,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()}),tr=z.array(Ac),dn=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),Xi=dn.extend({name:z.string().min(1)}).strict(),Fc=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().max(16384).optional()}).strict(),$c=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:Fc.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(dn).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(Xi).max(200),outgoingCalls:z.array(Xi).max(200)}).optional(),implementations:z.array(dn).max(200).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array($c).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(),Dc=z.enum(["pending","processing","completed","failed","skipped"]),fn=z.object({status:Dc,filesProcessed:z.number().int().nonnegative().nullable(),completedAt:z.union([z.string().datetime({offset:true}),z.date()]).nullable()}),z.enum(["current","processing","stale","failed"]),to=z.union([z.string().datetime({offset:true}),z.date()]),Mc=z.object({status:z.literal("processing"),commitHash:z.string().nullable().optional(),startedAt:to.optional(),phaseMetrics:tr.optional()}).passthrough(),Oc=z.object({status:z.literal("current"),commitHash:z.string().nullable().optional(),completedAt:to.nullable().optional(),enrichment:fn.optional(),phaseMetrics:tr.optional()}).passthrough(),Uc=z.object({status:z.literal("stale"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:fn.optional(),phaseMetrics:tr.optional()}).passthrough(),Gc=z.object({status:z.literal("failed"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:fn.optional(),phaseMetrics:tr.optional()}).passthrough(),gn=z.discriminatedUnion("status",[Mc,Oc,Uc,Gc]),Bc=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),Hc=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),Wc=z.object({id:z.string(),label:z.string(),type:Bc,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),zc=z.object({id:z.string(),source:z.string(),target:z.string(),type:Hc,label:z.string().optional()}),Kc=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Et.optional()}),Vc=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(Wc),edges:z.array(zc),summary:Kc,metadata:Vc,features:z.record(z.string(),z.boolean()).optional()}),ro=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(ro)}),ro.pick({projectId:true,projectName:true,defaultBranch:true}),no=z.enum(["unresolved","resolved","archived"]),io=z.enum(["succeeded","failed"]),oo=z.enum(["full","incremental"]),Jc=z.enum(["info","warn","error"]),qc=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),Yc=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),so=z.object({errors:z.array(qc),warnings:z.array(Yc)}),ao=z.object({level:Jc,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:so,logEntries:z.array(ao),cliVersion:z.string(),outcome:io,indexType:oo}),z.object({status:no.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:oo,status:no,outcome:io,errorSummary:z.string(),errorData:so,logEntries:z.array(ao),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()}),Xc=["org-admin-v1","developer-v1","constellation-admin-v1"],Qc=z.enum(Xc),Zc=["eligible","completed","dismissed","ineligible"],ep=z.enum(Zc),z.object({tourId:Qc,status:ep,lastStepReached:z.string().max(64).optional()}),z.object({stepId:z.string().min(1).max(64)});});var hn,Tt=f(()=>{hn=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 yn(n){return n.length>rr&&(n[rr]=lo),n}function co(){let n=false,e=0;return new Transform({transform(t,r,o){if(n){o(null,t);return}if(e+t.length>rr){let s=rr-e;t[s]=lo,n=true;}e+=t.length,o(null,t);}})}var rr,lo,vn=f(()=>{rr=9,lo=255;});function po(n){return base32.encode(Buffer.from(n))}var uo=f(()=>{});function mo(n,e,t){let r=`${n}:${e}${t?`:${t}`:""}`;return po(r)}var fo=f(()=>{uo();});var nr,go=f(()=>{nr=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 yo(){return ho.some(n=>!!process.env[n])}function vo(){return !!process.stdout.isTTY}function bo(){let n=ho.find(e=>!!process.env[e]);return n?ip[n]:void 0}var ho,ip,bn=f(()=>{ho=["GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE","CI"],ip={GITHUB_ACTIONS:"github-actions",GITLAB_CI:"gitlab",JENKINS_URL:"jenkins",CIRCLECI:"circleci",TRAVIS:"travis",BUILDKITE:"buildkite",DRONE:"drone",CI:"unknown"};});function op(n){switch(n){case "darwin":return "Macintosh";case "win32":return "Windows";case "linux":return "Linux";case "freebsd":return "FreeBSD";default:return n.charAt(0).toUpperCase()+n.slice(1)}}function sp(n,e){return n==="darwin"?`Darwin ${e}`:e}function ap(){let n=globalThis.__constellationVersion;return typeof n=="string"&&n.length>0?n:"unknown"}function lp(n={}){let e=n.platform??process.platform,t=n.arch??process.arch,r=(n.nodeVersion??process.version).replace(/^v/,""),o=n.osRelease??We.release(),s=ap(),a=op(e),l=sp(e,o),c=`constellation-cli/${s} (${a}; ${l}; ${t}) Node/${r}`,u=bo();return u&&(c+=` CI/${u}`),c}var Lt,wo=f(()=>{bn();Lt=lp();});function dp(n){switch(n){case "PROJECT_NOT_REGISTERED":return "PROJECT_NOT_REGISTERED";case "PROJECT_INACTIVE":return "PROJECT_INACTIVE";case "INVALID_PROJECT_ID":return "INVALID_PROJECT_ID";default:return "PROJECT_VALIDATION_FAILED"}}var ir,or,H,Re,Se,Fe,Ne,_n=f(()=>{Nt();X();Tt();vn();fo();go();wo();ir=class n{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 Re("Project not found - no previous index exists");default:throw e.status===404?new Re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof Se||t instanceof Re?t:e.status===404?new Re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let 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=gn.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 H)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 H("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=eo.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 H("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let u=await c.json(),p=gn.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 H)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":Lt,"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=Vn.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":Lt,"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 H("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 H)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=mo(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?n.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 Fe(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 nr(e),u=await buffer(c),p=process.env.CAPTURE_PAYLOAD_PATH;if(p)try{await pipeline(Readable.from(u),Vn.createGzip(),co(),Oe.createWriteStream(p));}catch(g){this.reporter?.warn(`[constellation] capture tap failed: ${g instanceof Error?g.message:String(g)}`);}let d=[1e3,2e3,4e3],m;for(let g=0;g<=d.length;g++){let h=new Agent({headersTimeout:0,bodyTimeout:0});try{let b=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":Lt,"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(b.status===401)throw new H("Authentication failed");if(b.status===409)throw await this.parseIndexingConflict(b);if(b.status===200)try{let S=await b.json();if(S?.status==="current")return this.reporter?.summary(`${x} Index already up to date for ${o} at commit ${S.commitHash||"unknown"}`),!0}catch{}if(b.ok||b.status===202)return !0;let y=`Server returned ${b.status}`;try{let S=await b.json();S?.message&&(y=Array.isArray(S.message)?S.message.join("; "):S.message);}catch{}throw new Error(y)}catch(b){if(b instanceof H||b instanceof Fe)throw b;if(this.isRetryableNetworkError(b)&&g<d.length){let y=Math.floor(Math.random()*250),S=d[g]+y;this.reporter?.warn(`Upload network error (attempt ${g+1}/${d.length+1}): ${this.shortNetworkErrorReason(b)} \u2014 retrying in ${S}ms`),m=b,await new Promise(E=>setTimeout(E,S));continue}throw b}finally{h.destroy().catch(()=>{});}}throw m??new Error("Upload failed after exhausting retry budget")}catch(c){if(c instanceof H||c instanceof Fe)throw c;let u=c instanceof Error?c:new Error(String(c)),p="";if(u.message==="fetch failed"||c.code){let m=[],g=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}`);}g==="ERR_INVALID_ARG_VALUE"?p="Invalid argument value - check stream/body format and duplex option":g==="ECONNREFUSED"?p="Connection refused - service may be down or unreachable":g==="ENOTFOUND"?p="DNS lookup failed - check service URL":g==="ETIMEDOUT"?p="Connection timeout - service not responding":g==="ECONNRESET"?p="Connection reset by server":g==="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":Lt,Authorization:`Bearer ${this.accessKey}`},g=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),g.status===401)throw new H("Authentication failed");if(!g.ok&&this.retryableStatusCodes.includes(g.status))throw new or(`${g.statusText} (${g.status})`);return g}catch(d){if(p&&clearTimeout(p),!(d instanceof H)){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 or){let m=l+Math.floor(Math.random()*c);await new Promise(g=>setTimeout(g,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}`)}},or=class extends Error{constructor(e){super(e),this.name="RetryableError";}},H=class extends Error{errorCode="AUTH_FAILURE";constructor(e){super(e),this.name="AuthenticationError";}},Re=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",this.errorCode=dp(r);}errorCode};Fe=class extends Error{constructor(t,r){super(t);this.branchName=r;this.name="IndexingInProgressError";}errorCode="CONCURRENT_INDEXING"},Ne=class extends Error{constructor(t,r){super(t);this.errorCode=r;this.name="GitValidationError";}};});function F(n){return n.replace(/\\/g,"/")}function ar(n){return F(n).replace(/^\.?\//,"")}function Q(n,e){return F(k.relative(n,e))}var ee=f(()=>{});var Ze,Cn=f(()=>{Ze=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(g=>({result:g!==null?g.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}}};});function gp(n){if(!n)return false;let e=k.sep;return n.includes(`${e}obj${e}`)||n.includes(`${e}bin${e}`)||n.includes("/obj/")||n.includes("/bin/")}var hp,yp,et,vp,lr,Eo=f(()=>{ee();Cn();hp={function:{hover:true,references:true,callHierarchy:true,implementation:false},method:{hover:true,references:true,callHierarchy:true,implementation:true},constructor:{hover:true,references:true,callHierarchy:true,implementation:false},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}},yp={hover:true,references:true,callHierarchy:false,implementation:false},et=1e4,vp=1200*1e3,lr=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,g])=>{let h=r.get(m);if(!h)return;let b=g.length,y=b>1e4?8:b>5e3?10:16,S=new Ze(y),E=()=>{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=${y}); halting subsequent ${m} files.`,{verboseOnly:true});},T=h.onCrash(E),w=0,P=S.run(g,async N=>{try{if(u||Date.now()-l>vp)return u=!0,null;if(p.has(m))return null;let I=await this.openFile(h,N,c,o?.get(N));if(!I)return null;let{uri:v}=I;try{let R=t.get(N)??[];if(R.length===0&&(R=await this.discoverSymbols(h,N,v,c),R.length===0))return c.filesNoSymbols++,null;let _=await this.enrichOpenFile(h,N,v,R,c);return _.length>0?{filePath:N,language:m,symbols:_}:null}finally{this.closeFile(h,v);}}finally{w++,s?.(m,w,b);}});try{for await(let N of P)N&&a.push(N);}finally{T();}})),u&&this.reporter?.info("Enrichment timeout reached. Uploading partial results."),this.logDiagnostics(c),a}async openFile(e,t,r,o){let s=k.resolve(this.projectRoot,t),a=pathToFileURL(s).href,l=o;if(l===void 0)try{l=await Oe.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=hp[s]||yp,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,[g,h,b]=await Promise.allSettled([c.hover?e.sendRequest("textDocument/hover",p,et):null,c.references?e.sendRequest("textDocument/references",{...p,context:{includeDeclaration:false}},et):null,c.implementation?e.sendRequest("textDocument/implementation",p,et):null]);for(let y of [g,h])y.status==="rejected"&&o.queryRejections++;if(g.status==="fulfilled"&&g.value?.contents){let y=g.value.contents,S="";typeof y=="string"?S=y:Array.isArray(y)?S=y.map(E=>typeof E=="string"?E:E?.value??"").filter(Boolean).join(`
|
|
37
|
+
`):y&&typeof y=="object"&&(S=y.value||""),S&&(d.typeInfo={resolvedType:S},m=true);}if(h.status==="fulfilled"&&h.value){let y=h.value.filter(S=>{let E=this.uriToPath(S.uri||"");return !gp(E)});if(y.length>0){let S=y.slice(0,100).map(E=>({filePath:Q(this.projectRoot,this.uriToPath(E.uri||"")),line:(E.range?.start?.line??0)+1,column:E.range?.start?.character??0}));d.references={count:y.length,locations:S},m=true;}}if(c.implementation&&b.status==="fulfilled"){let y=b.value,E=(Array.isArray(y)?y:y?[y]:[]).slice(0,200).map(T=>{let w=T.targetUri??T.uri??"",P=T.targetSelectionRange??T.targetRange??T.range??null;return {filePath:Q(this.projectRoot,this.uriToPath(w)),line:(P?.start?.line??0)+1,column:P?.start?.character??0}});d.implementations=E,E.length>0&&(m=true);}if(c.callHierarchy)try{let y=await e.sendRequest("textDocument/prepareCallHierarchy",p,et);if(y&&y.length>0){let S=y[0],[E,T]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:S},et).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:S},et).catch(()=>[])]),w=200,P=[];for(let I of E||[]){let v=Array.isArray(I.fromRanges)?I.fromRanges:[];if(v.length===0)continue;let R=Q(this.projectRoot,this.uriToPath(I.from?.uri||"")),_=I.from?.name||"";for(let M of v){if(P.length>=w)break;P.push({name:_,filePath:R,line:(M?.start?.line??0)+1,column:M?.start?.character??0});}if(P.length>=w)break}let N=[];for(let I of T||[]){let v=Array.isArray(I.fromRanges)?I.fromRanges:[];if(v.length===0)continue;let R=Q(this.projectRoot,this.uriToPath(I.to?.uri||"")),_=I.to?.name||"";for(let M of v){if(N.length>=w)break;N.push({name:_,filePath:R,line:(M?.start?.line??0)+1,column:M?.start?.character??0});}if(N.length>=w)break}(P.length>0||N.length>0)&&(d.callHierarchy={incomingCalls:P,outgoingCalls:N},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,t=null){let r=[],o={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"},s=new Set([null,2,3,5,6,9,10,11,12,23]),a=new Set([2,3,5,6,9,10,11,12,23,26]);for(let l of e){let c=o[l.kind]||"variable",u=l.selectionRange||l.range||l.location?.range,p=l.kind;u!=null&&(p!==void 0&&a.has(p)||s.has(t))&&r.push({name:l.name,line:(u.start?.line??0)+1,column:u.start?.character??0,kind:c,isExported:true}),l.children&&Array.isArray(l.children)&&r.push(...this.flattenDocumentSymbols(l.children,l.kind??null));}return r}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=k.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python",".cs":"csharp",".csx":"csharp",".swift":"swift"}[t]||"plaintext"}};});function Po(n){return n.map(e=>JSON.stringify(e)).join(`
|
|
38
38
|
`)+`
|
|
39
|
-
`}var
|
|
39
|
+
`}var Io=f(()=>{});function ae(n){try{return execFileSync(process.platform==="win32"?"where":"which",[n],{stdio:"ignore"}),!0}catch{return false}}var C,le=f(()=>{C={async directoryExists(n){try{return (await se__default.stat(n)).isDirectory()}catch{return false}},async fileIsReadable(n){try{return await se__default.access(n,se__default.constants.R_OK),!0}catch{return false}},async readFile(n,e="utf-8"){let t=await se__default.readFile(n,{encoding:e,flag:se__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(n,e,t="utf-8"){let r=Buffer.from(e,t);await se__default.writeFile(n,r,{encoding:t,flag:se__default.constants.O_WRONLY|se__default.constants.O_CREAT|se__default.constants.O_TRUNC});},async getFileStats(n){return await se__default.stat(n)},async getFileHandle(n,e,t){return await se__default.open(n,e,t)}};});var cr,Ro=f(()=>{cr=class n{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
|
|
40
40
|
\r
|
|
41
41
|
`);nextId=1;pendingRequests=new Map;notificationHandlers=new Map;pendingNotifications=new Set;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);}onNotification(e,t){if(this.disposed)return ()=>{};let r=this.notificationHandlers.get(e);return r||(r=new Set,this.notificationHandlers.set(e,r)),r.add(t),()=>{r.delete(t),r.size===0&&this.notificationHandlers.delete(e);}}waitForNotification(e,t){return this.disposed?Promise.reject(new Error("LspClient disposed")):new Promise((r,o)=>{let s,a={timer:setTimeout(()=>{this.pendingNotifications.delete(a),s?.(),o(new Error(`Timed out waiting for notification '${e}' after ${t}ms`));},t),reject:o};this.pendingNotifications.add(a),s=this.onNotification(e,l=>{clearTimeout(a.timer),this.pendingNotifications.delete(a),s?.(),r(l);});})}dispose(){this.disposed=true;for(let[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("LspClient disposed"));this.pendingRequests.clear();for(let e of this.pendingNotifications)clearTimeout(e.timer),e.reject(new Error("LspClient disposed"));this.pendingNotifications.clear(),this.notificationHandlers.clear(),this.stdout.removeAllListeners("data");}writeMessage(e){let t=JSON.stringify(e),o=`Content-Length: ${Buffer.byteLength(t,"utf-8")}\r
|
|
42
42
|
\r
|
|
43
|
-
`;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(n.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.handleMessage(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,this.reporter?.error("[LSP] Received malformed JSON from language server",{verboseOnly:true}));}}}handleMessage(e){"id"in e&&e.id!==void 0&&e.id!==null?this.handleResponse(e):"method"in e&&this.handleNotification(e);}handleResponse(e){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));}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t)for(let r of t)try{let o=r(e.params);o&&typeof o.catch=="function"&&o.catch(()=>{});}catch{}}};});function
|
|
44
|
-
`)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let r=
|
|
45
|
-
`,"utf-8"),await se.rename(a,this.trustFilePath);}catch(l){throw await se.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await se.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(
|
|
43
|
+
`;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(n.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.handleMessage(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,this.reporter?.error("[LSP] Received malformed JSON from language server",{verboseOnly:true}));}}}handleMessage(e){"id"in e&&e.id!==void 0&&e.id!==null?this.handleResponse(e):"method"in e&&this.handleNotification(e);}handleResponse(e){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));}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t)for(let r of t)try{let o=r(e.params);o&&typeof o.catch=="function"&&o.catch(()=>{});}catch{}}};});function En(n){return n.includes("roslyn-language-server")}var rt,nt,Te,it=f(()=>{rt=k.join(We.homedir(),".constellation","lsp-servers"),nt=k.join(rt,"node_modules",".bin"),Te=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"]}],["c-sharp",{command:"roslyn-language-server",args:["--stdio","--autoLoadProjects"],npmPackages:[],testCommand:["--version"],manualInstall:{requires:".NET 10 SDK or later (https://dotnet.microsoft.com/download)",command:"dotnet tool install --global roslyn-language-server --prerelease",pathNote:We.platform()==="win32"?"After install, ensure %USERPROFILE%\\.dotnet\\tools is on your PATH.":"After install, ensure ~/.dotnet/tools is on your PATH.",verifyToolchain:{command:"dotnet",versionArgs:["--version"],minVersion:"10.0"}}}],["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:k.join(rt,"bin")},installedBinaryPath:k.join(rt,"bin",We.platform()==="win32"?"gopls.exe":"gopls")}}}],["swift",{command:"sourcekit-lsp",args:[],npmPackages:[],testCommand:["--help"],manualInstall:{requires:"Swift toolchain (https://www.swift.org/install/) \u2014 sourcekit-lsp ships with it",command:"Install the Swift toolchain from https://www.swift.org/install/ (sourcekit-lsp is included with Xcode / the swift.org toolchain).",pathNote:"After install, ensure the Swift toolchain bin directory (containing sourcekit-lsp) is on your PATH."}}]]);});function In(n){let e=We.homedir();if(!e)return null;let t=process.platform==="win32"?`${n}.exe`:n,r=k.join(e,".dotnet","tools",t);try{let o=realpathSync(r),s=k.resolve(e);return o!==s&&!o.startsWith(s+k.sep)?null:o}catch{return null}}function Rn(n){if(ae(n.command))return n.command;let e=k.join(nt,n.command);return existsSync(e)?e:In(n.command)}function No(n){let e=/(\d+)(?:\.(\d+))?/.exec(n);return e?[Number(e[1]),e[2]?Number(e[2]):0]:null}function Ep(n,e){let t=No(e);if(!t)return true;let r=No(n);return r?r[0]!==t[0]?r[0]>t[0]:r[1]>=t[1]:true}function Lo(n){let e;try{e=execFileSync(n.command,[...n.versionArgs],{stdio:["ignore","pipe","pipe"],timeout:_p,maxBuffer:xp,cwd:We.homedir()||void 0}).toString();}catch{return {ok:false,reason:"missing"}}let t=e.trim().split(/\r?\n/)[0]?.trim()??"";return n.minVersion&&!Ep(t,n.minVersion)?{ok:false,reason:"too-old",detected:t||"unknown",required:n.minVersion}:{ok:true,version:t}}function ko(n){let e=n.manualInstall?.command;if(!e)return {ok:false,spawnError:"no manualInstall.command configured"};let[t,...r]=e.split(/\s+/).filter(Boolean);if(!t)return {ok:false,spawnError:"empty manualInstall.command"};try{return execFileSync(t,r,{stdio:"pipe",timeout:Cp}),{ok:!0}}catch(o){let s=o,a=s.stderr?.toString().trim()??"";return typeof s.status=="number"||s.signal?{ok:false,exitCode:s.status??null,stderr:a}:{ok:false,spawnError:s.message??String(o)}}}var _p,xp,Cp,Nn=f(()=>{le();it();_p=5e3,xp=4096,Cp=300*1e3;});function Ao(n){return n.replace(/\\/g,"/")}function Rp(n){let e=Ao(n);return k.posix.basename(e).toLowerCase().replace(/\.(exe|com|bat|cmd|ps1)$/i,"")}function Fo(n,e){if(!n||n.trim().length===0)return {classification:"denied",reason:"LSP command is empty"};let t=Ao(n);if(Ip.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(`
|
|
44
|
+
`)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let r=Rp(n);if(Pp.has(r))return {classification:"denied",reason:`LSP command resolves to a shell or interpreter ('${r}')`};for(let[,o]of Te)if(r===o.command.toLowerCase())return {classification:"known-safe"};return {classification:"custom-untrusted"}}var Pp,Ip,$o=f(()=>{it();Pp=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(n=>n.toLowerCase())),Ip=/[;&|`$<>\n\r\0"']/;});function Do(n,e,t,r){return n.projectRoot===e&&n.command===t&&n.args.length===r.length&&n.args.every((o,s)=>o===r[s])}function Np(n){if(!n||typeof n!="object")return false;let e=n;return typeof e.projectRoot=="string"&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var ot,Tn=f(()=>{ot=class{constructor(e){this.trustFilePath=e;}async isTrusted(e,t,r){return (await this.load()).entries.some(s=>Do(s,e,t,r))}async recordTrust(e,t,r){let o=await this.load();if(o.entries.some(l=>Do(l,e,t,r)))return;o.entries.push({projectRoot:e,command:t,args:[...r],trustedAt:new Date().toISOString()}),await se.mkdir(k.dirname(this.trustFilePath),{recursive:true});let a=`${this.trustFilePath}.${process.pid}.tmp`;try{await se.writeFile(a,JSON.stringify(o,null,2)+`
|
|
45
|
+
`,"utf-8"),await se.rename(a,this.trustFilePath);}catch(l){throw await se.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await se.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(Np)}:{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 pr,Oo=f(()=>{$o();Tn();pr=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??ot.isCIEnvironment;}async authorize(e,t,r){let{classification:o,reason:s}=Fo(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?
|
|
46
46
|
${t}${a}
|
|
47
47
|
|
|
48
48
|
Only approve commands you recognize. Untrusted commands can execute arbitrary code.
|
|
49
|
-
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
|
|
49
|
+
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 jp,Ap,ur,Go=f(()=>{le();Ro();it();Nn();Oo();Tn();jp={log:n=>process.stderr.write(n+`
|
|
50
50
|
`),warn:n=>process.stderr.write(n+`
|
|
51
51
|
`),error:n=>process.stderr.write(n+`
|
|
52
|
-
`)},_p=k.join(He.homedir(),".constellation","lsp-trust.json"),ur=class{constructor(e,t,r){this.projectRoot=e;this.logger=t??wp,this.policy=r??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new pr({projectRoot:this.projectRoot,logger:this.logger,trustStore:new it(_p),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;let d,m;try{d=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});let g=d;await new Promise((T,w)=>{g.once("spawn",T),g.once("error",w);}),g.stderr?.on("data",T=>{this.handleServerDiagnostics(e,T.toString());}),m=new cr(g.stdin,g.stdout,12e4);let h=m,b=_n(a)?{background_analysis:{dotnet_analyzer_diagnostics_scope:"none",dotnet_compiler_diagnostics_scope:"openFiles"}}:void 0,y=pathToFileURL(this.projectRoot).href,S=await h.sendRequest("initialize",{processId:process.pid,rootUri:y,workspaceFolders:[{uri:y,name:k.basename(this.projectRoot)}],capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}},...b&&{initializationOptions:b}},12e4);if(h.sendNotification("initialized",{}),_n(a)){this.logger.log(`[LSP:${e}] Roslyn: waiting for project initialization (auto-load)\u2026`);let T=h.waitForNotification("workspace/projectInitializationComplete",18e4),w=new Promise((P,N)=>{let I=(v,R)=>{N(new Error(`Roslyn server exited during project initialization (code=${v}, signal=${R})`));};g.once("exit",I),T.finally(()=>g.removeListener("exit",I));});await Promise.race([T,w]),T.catch(()=>{}),w.catch(()=>{}),this.logger.log(`[LSP:${e}] Roslyn project initialization complete`);}let E={key:c,language:e,languages:new Set([e]),process:g,client:h,crashHandlers:new Set,intentionalShutdown:!1};return this.serversByKey.set(c,E),this.languageToServerKey.set(e,c),g.on("exit",(T,w)=>{let P=this.serversByKey.get(c);if(P){if(P.intentionalShutdown)P.crashHandlers.clear();else {let N=[...P.crashHandlers];P.crashHandlers.clear();for(let I of N)try{I();}catch(v){this.logger.warn(`[LSP:${P.language}] crash handler threw: ${v instanceof Error?v.message:String(v)}`);}this.logUnexpectedExit(e,T,w);}P.client.dispose(),this.serversByKey.delete(c);for(let[N,I]of this.languageToServerKey.entries())I===c&&this.languageToServerKey.delete(N);}}),this.toConnection(E,e)}catch(g){try{m?.dispose();}catch{}try{d?.kill();}catch{}this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let h=`[LSP:${e}] Failed to start: ${g instanceof Error?g.message:String(g)}`,b=g?.code;return b==="ENOENT"||b==="EACCES"?this.logger.warn(h):this.logger.error(h),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();}handleServerDiagnostics(e,t){}resolveCommand(e,t){if(t?.command)return {command:t.command,args:[...t.args||[]]};let r=Te.get(e);if(!r)return null;let o=k.join(rt,r.command);if(existsSync(o))return {command:o,args:[...r.args]};if(ae(r.command))return {command:r.command,args:[...r.args]};let s=Cn(r.command);return s?{command:s,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),onNotification:(o,s)=>e.client.onNotification(o,s),onCrash:o=>(e.crashHandlers.add(o),()=>e.crashHandlers.delete(o))}}};});var Z,ot=f(()=>{Z=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}preflightLsp(e){return Promise.resolve({skip:false})}};});var st,Rn=f(()=>{q();st=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(`${z} 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(`${z} Failed to parse ${r}: ${o}`),console.warn(`${z} Path alias resolution will be skipped for files using this config`);}else r||console.warn(`${z} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var dr,Ao=f(()=>{oe();dr=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?k.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=k.resolve(r,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=k.join(this.projectRoot,"package.json"),r=await se.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=k.join(this.projectRoot,r);try{let s=await se.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(k.join(o,a.name));}catch{}}else {let r=k.join(this.projectRoot,e);try{(await se.stat(r)).isDirectory()&&t.push(r);}catch{}}return t}async loadWorkspacePackage(e){try{let t=k.join(e,"package.json"),r=await se.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 k.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return k.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return k.join(e,a)}}}if(t.main)return k.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=k.join(e,o);try{if((await se.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=k.join(e,r);try{if((await se.stat(o)).isFile())return o}catch{}}try{if((await se.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")?k.dirname(e):k.dirname(e),o=[k.join(r,t+".ts"),k.join(r,t+".tsx"),k.join(r,t+".js"),k.join(r,t+".jsx"),k.join(r,t+".d.ts"),k.join(r,t,"index.ts"),k.join(r,t,"index.tsx"),k.join(r,t,"index.js"),k.join(r,t,"index.jsx")];for(let s of o)try{if((await se.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=Y(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var at,Nn=f(()=>{oe();Ao();at=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=k.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new dr(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=k.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=k.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=k.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=Y(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=k.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=k.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=k.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await se.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await se.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let r=k.join(t,"package.json");try{if((await se.stat(r)).isFile())return r}catch{}let o=k.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 se.readFile(e,"utf-8"),r=JSON.parse(t);this.packageJsonDir=k.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=k.resolve(this.packageJsonDir,r);return await this.findFileWithExtensions(o)}};});var mr,Fo=f(()=>{ot();Rn();Nn();mr=class extends Z{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new st(e,t)}getImportResolver(e,t){return new at(e,t)}};});var fr,$o=f(()=>{ot();Rn();Nn();fr=class extends Z{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new st(e,t)}getImportResolver(e,t){return new at(e,t)}};});async function X(n,e,t,r,o,s=[]){let a=await t.resolve(n),l=Do(n,a),c=o(n,a,l),u=l?void 0:ar(a);r[e.toString()]={source:n,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function Do(n,e){return n===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var Tn,$e=f(()=>{oe();Tn=(n,e,t)=>t?n.startsWith("node:")?"builtin":"external":n.startsWith("./")||n.startsWith("../")?"relative":n.startsWith("@")?"workspace":"alias";});async function Pp(n,e,t,r){let o=n.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 X(s,n.startPosition.row,e,t,r,[a]);}function Ip(n,e){if(!e)return [];let t=[],r=n.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<n.childCount;s++){let a=n.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 Rp(n,e,t,r){let o,s=n.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<n.childCount;c++){let u=n.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=Ip(n,!!s);await X(o,n.startPosition.row,e,t,r,a);}async function Np(n,e,t,r){await X("__future__",n.startPosition.row,e,t,r,[]);}function Ln(){return {language:"python",handlers:new Map([["import_statement",Pp],["import_from_statement",Rp],["future_import_statement",Np]]),classifyImportType:Ep}}var Ep,gr=f(()=>{Nt();$e();Nt();Ep=(n,e,t)=>{if(t)return "external";if(/^\.+/.test(n))return "relative";let r=n.split(".")[0];return It.has(r)?"builtin":"alias"};});var hr,Oo=f(()=>{gr();hr=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=k.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(It.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let r=e.replace(/\./g,"/"),o=await this.tryResolveFile(k.resolve(this.projectRoot,r));return o?k.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=k.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?k.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,k.join(e,"__init__.py"),k.join(e,"__init__.pyi")];for(let r of t)try{return await De.promises.access(r,De.constants.F_OK),r}catch{continue}return null}};});var vr,Mo=f(()=>{ot();Oo();vr=class extends Z{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new hr(e,process.cwd())}};});function Uo(n){return n.replace(/\/\/[^\n]*/g,"")}function lt(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}function Tp(n,e){let t=[],r=/^\s*replace\s*\(\s*([\s\S]*?)\)/gm,o=[];for(let l of n.matchAll(r))o.push(l[1]);let s=n.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(`
|
|
53
|
-
`)){let u=c.trim();if(!u)continue;let p=
|
|
54
|
-
`)){let d=lt(p.trim());d&&o.push(k.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=lt(u[1].trim());p&&o.push(k.resolve(r,p));}return o}async parseGoMod(e){let t;try{t=await De.promises.readFile(e,"utf8");}catch{return null}let r=Uo(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=k.dirname(e);return {modulePath:lt(o[1]),goVersion:s?.[1],rootDir:a,replaces:Tp(r,a)}}};});function jp(n){let e=n.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}var Sr,br,wr=f(()=>{oe();Sr=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"]),br=class{constructor(e,t,r=[]){this.sourceFilePath=e;this.projectRoot=t;this.modules=r;}async resolve(e){let t=jp(e);if(!t)return e;let r=t.split("/")[0];if(!r.includes(".")&&Sr.has(r))return t;let o=this.findReplaceForSpecifier(t);if(o){let a=t.slice(o.originalModulePath.length),l=k.join(o.localDir,a.startsWith("/")?a.slice(1):a);if(await this.directoryHasGoFiles(l))return F(k.relative(this.projectRoot,l))}let s=this.findModuleForSpecifier(t);if(s){let a=t.slice(s.modulePath.length),l=k.join(s.rootDir,a.startsWith("/")?a.slice(1):a);if(await this.directoryHasGoFiles(l))return F(k.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 De.promises.readdir(e,{withFileTypes:!0})).some(r=>r.isFile()&&r.name.endsWith(".go")&&!r.name.endsWith("_test.go"))}catch{return false}}};});var _r,Ho=f(()=>{ot();Go();wr();_r=class extends Z{language="go";extensions=[".go"];manager=null;getBuildConfigManager(e,t){return this.manager=new Oe(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 br(e,process.cwd(),r)}async preflightLsp(e){return this.manager??=new Oe(e),await this.manager.initialize(),this.manager.getAllModules().length>0?{skip:false}:Oe.hasGoModAncestor(e)?{skip:false}:Oe.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."}}};});async function Ko(n){let e=false,t=false,r=async o=>{if(e&&t)return;let s;try{s=await De.promises.readdir(o,{withFileTypes:!0});}catch{return}for(let a of s){if(e&&t)return;if(a.isFile())!e&&(a.name.endsWith(".sln")||a.name.endsWith(".csproj"))?e=true:!t&&a.name==="project.assets.json"&&(t=true);else if(a.isDirectory()){if(Ap.has(a.name)||a.name.startsWith("."))continue;await r(k.join(o,a.name));}}};return await r(n),{hasProjects:e,restored:t}}var Ap,Vo=f(()=>{Ap=new Set(["node_modules",".git","bin"]);});function jn(n,e){let t=new RegExp(`<${e}[^>]*>([^<]+)<\\/${e}>`,"i"),r=n.match(t);return r?r[1].trim():void 0}function Fp(n){let e=jn(n,"ImplicitUsings");return e?e.toLowerCase()==="enable"||e.toLowerCase()==="true":false}function $p(n){let e=[],t=/<PackageReference\s[^>]*Include\s*=\s*"([^"]+)"/gi;for(let r of n.matchAll(t))e.push(r[1].trim());return e}function Dp(n,e,t){let r=n.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,""),o=/\bnamespace\s+([a-zA-Z_][\w]*(?:\.[a-zA-Z_][\w]*)*)\s*(?:[{;])/g;for(let a of r.matchAll(o)){let l=a[1].trim();l&&kn(t,l,e,false);}let s=/\busing\s+([a-zA-Z_][\w]*)\s*=\s*([a-zA-Z_][\w]*(?:\.[a-zA-Z_][\w]*)*)\s*;/g;for(let a of r.matchAll(s)){let l=a[1].trim(),c=a[2].trim();l&&kn(t,l,e,true),c&&kn(t,c,e,false);}}function kn(n,e,t,r){let o=n.get(e);(!o||F(t)<F(o.filePath))&&n.set(e,{filePath:t,isAlias:r});}var Cr,Jo=f(()=>{oe();Cr=class{constructor(e,t=true){this.projectRoot=e;this.enabled=t;}cache=new Map;discovered=[];initialized=false;namespaceIndex=new Map;isEnabled(){return this.enabled}clearCache(){this.cache.clear(),this.discovered=[],this.initialized=false,this.namespaceIndex=new Map;}async initialize(){if(this.initialized)return this.configFilePaths();let{projectFiles:e,csFiles:t}=await this.findBuildArtifacts(this.projectRoot),r=await Promise.all(e.map(o=>this.parseProjectFile(o)));for(let o of r){if(!o)continue;this.discovered.push(o);let s=F(o.rootDir),a=this.cache.get(s),l=o.configFilePath.endsWith(".csproj"),c=a?.configFilePath.endsWith(".csproj")??false;(!a||l&&!c)&&this.cache.set(s,o);}return await Promise.all(t.map(async o=>{let s;try{s=await De.promises.readFile(o,"utf8");}catch{return}Dp(s,o,this.namespaceIndex);})),this.initialized=true,this.configFilePaths()}getNamespaceIndex(){return this.namespaceIndex}configFilePaths(){return this.discovered.map(e=>F(e.configFilePath))}async getConfigForFile(e){this.initialized||await this.initialize();let t=k.isAbsolute(e)?e:k.resolve(this.projectRoot,e),r=k.dirname(t);for(;;){let o=this.cache.get(F(r));if(o!==void 0)return o;let s=k.dirname(r),a=r===this.projectRoot||r.startsWith(this.projectRoot+k.sep);if(s===r||!a)return null;r=s;}}getAllProjects(){return this.discovered}getAllPackageReferences(){let e=new Set;for(let t of this.discovered)for(let r of t.packageReferences)e.add(r);return e}async findBuildArtifacts(e){let t=[],r=[],o;try{o=await De.promises.readdir(e,{withFileTypes:!0});}catch{return {projectFiles:t,csFiles:r}}for(let s of o){if(s.name==="node_modules"||s.name==="bin"||s.name==="obj"||s.name.startsWith("."))continue;let a=k.join(e,s.name);if(s.isFile())s.name.endsWith(".csproj")||s.name==="Directory.Build.props"?t.push(a):(s.name.endsWith(".cs")||s.name.endsWith(".csx"))&&r.push(a);else if(s.isDirectory()){let l=await this.findBuildArtifacts(a);t.push(...l.projectFiles),r.push(...l.csFiles);}}return {projectFiles:t,csFiles:r}}async parseProjectFile(e){let t;try{t=await De.promises.readFile(e,"utf8");}catch{return null}let r=k.dirname(e);return {configFilePath:e,rootDir:r,langVersion:jn(t,"LangVersion"),nullable:jn(t,"Nullable"),implicitUsings:Fp(t),packageReferences:$p(t)}}};});function Op(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];(r==="."||r===":"&&n[t+1]===":")&&e.push(n.slice(0,t));}return e}var Er,qo=f(()=>{oe();Er=class{constructor(e,t){this.projectRoot=e;this.index=t;}index;async resolve(e){if(!e)return e;let t=this.index.get(e);if(t)return F(k.relative(this.projectRoot,t.filePath));let r=Op(e);for(let o=r.length-1;o>=0;o--){let s=this.index.get(r[o]);if(s)return F(k.relative(this.projectRoot,s.filePath))}return e}};});var Pr,Yo=f(()=>{ot();Vo();Jo();qo();Pr=class extends Z{language="c-sharp";extensions=[".cs",".csx"];manager=null;getBuildConfigManager(e,t){return this.manager=new Cr(e),this.manager}getImportResolver(e,t){let r=this.manager?t?.rootDir??this.manager.getAllProjects()[0]?.rootDir??process.cwd():process.cwd(),o=this.manager?.getNamespaceIndex()??new Map;return new Er(r,o)}async preflightLsp(e){let t;try{t=await Ko(e);}catch{return {skip:false}}return !t.hasProjects||t.restored?{skip:false}:{skip:true,message:"C# enrichment skipped: the solution is not restored (no project.assets.json found). Run `dotnet restore` in the project root, then re-index. Skipping avoids empty results caused by unresolved analyzer references."}}};});function te(n){return zp[n]??n.charAt(0).toUpperCase()+n.slice(1)}var zp,Me,Ir,Rr=f(()=>{Fo();$o();Mo();Ho();Yo();zp={bash:"Bash",c:"C","c-sharp":"C#",cpp:"C++",go:"Go",java:"Java",javascript:"JavaScript",json:"JSON",php:"PHP",python:"Python",ruby:"Ruby",typescript:"TypeScript"};Me={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs",".csx"],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"]},Ir=class{constructor(e){this.config=e;this.registerPlugin(new mr),this.registerPlugin(new fr),this.registerPlugin(new vr),this.registerPlugin(new _r),this.registerPlugin(new Pr);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Gp,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Me.javascript};typescript={language:()=>Hp.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Me.typescript};python={language:()=>Bp,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Me.python};php;json;java;go={language:()=>Up,fileExtensions:()=>this.config?.languages.go?.fileExtensions??Me.go};cpp;"c-sharp"={language:()=>Mp,fileExtensions:()=>this.config?.languages["c-sharp"]?.fileExtensions??Me["c-sharp"]};c;bash;ruby};});function pt(n,e,t=32){let r=n.parent,o=0;for(;r!==null&&o<t;){if(e(r))return r;r=r.parent,o++;}return null}var Nr,Fn=f(()=>{Nr=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function $n(n,e){if(n.type==="jsx_opening_element"||n.type==="jsx_self_closing_element"||n.type==="jsx_closing_element"){let t=n.childForFieldName("name");t!==null&&Wp(t,e);}for(let t of n.namedChildren)t&&$n(t,e);}function Wp(n,e){if(n.type==="identifier"||n.type==="type_identifier"){e.set(we(n.startPosition.row,n.startPosition.column),"call");return}if(n.type==="member_expression"||n.type==="nested_identifier"){let t=n.childForFieldName("property");t!==null&&e.set(we(t.startPosition.row,t.startPosition.column),"call");}}var Xo=f(()=>{ut();});function dt(n,e){n.rootNode&&(Zo(n.rootNode,e),$n(n.rootNode,e));}function Zo(n,e){if(Kp.has(n.type)){let t=Vp(n);t!==null&&e.set(we(n.startPosition.row,n.startPosition.column),t);}for(let t of n.namedChildren)t&&Zo(t,e);}function Vp(n){if(qp(n))return "declaration";if(ou(n))return "read";if(nu(n))return "type";let e=pt(n,t=>t.type==="decorator");return e!==null&&Qp(n,e)?"call":Xp(n)?"instantiate":Yp(n)?"call":Zp(n)||eu(n)||tu(n)||mu(n)||du(n)?"write":su(n)?"import-use":"read"}function qp(n){let e=n.parent;return e===null?false:!!(Jp.has(e.type)&&(e.childForFieldName("name")===n||e.childForFieldName("property")===n)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===n||e.type==="import_specifier"&&(e.childForFieldName("name")===n||e.childForFieldName("alias")===n)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===n&&n.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===n||e.type==="enum_body")}function Yp(n){let e=n.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===n)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===n){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function Xp(n){let e=n.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===n)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===n){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function Qp(n,e){let t=e.namedChild(0);if(t===null)return false;if(t===n)return true;if(t.type==="call_expression"){let r=t.childForFieldName("function");if(r===n||r?.type==="member_expression"&&r.childForFieldName("property")===n)return true}return t.type==="member_expression"&&t.childForFieldName("property")===n}function Zp(n){let e=n;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||Nr.has(t.type))return false;e=t;}return false}function eu(n){let e=n.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===n)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===n){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function tu(n){let e=n;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||Nr.has(t.type))return false;e=t;}return false}function nu(n){let e=n.parent,t=n;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let r=e.namedChild(1);return r===null?false:r===t||iu(r,n)}if(ru.has(e.type))return true;if(Nr.has(e.type))return false;t=e,e=e.parent;}return false}function iu(n,e){let t=e;for(;t!==null;){if(t===n)return true;t=t.parent;}return false}function ou(n){return pt(n,t=>t.type==="type_query")!==null}function su(n){let e=n.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==n)return false;let t=n.text,r=pu(n);return uu(r,t)?!lu(n,t):false}function lu(n,e){let t=n.parent;for(;t!==null;){if(au.has(t.type)&&cu(t,e))return true;t=t.parent;}return false}function cu(n,e){for(let t of n.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 pu(n){let e=n;for(;e.parent!==null;)e=e.parent;return e}function uu(n,e){for(let t of n.descendantsOfType("namespace_import")){let r=t.namedChild(0);if(r!==null&&r.text===e)return true}return false}function du(n){let e=n.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===n}function mu(n){let e=n.parent;if(e===null||!Qo.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===n||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==n)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(!Qo.has(r.type))return false;t=r;}return false}var Kp,Jp,ru,au,Qo,Tr=f(()=>{ut();Fn();Xo();Kp=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));Jp=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"]));ru=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"]));au=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Qo=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function es(n,e){dt(n,e);}var ts=f(()=>{Tr();});function rs(n,e){dt(n,e);}var ns=f(()=>{Tr();});function is(n,e){if(!n.rootNode)return;let t=Au(n.rootNode);os(n.rootNode,e,t);}function os(n,e,t){if(fu.has(n.type)){let r=gu(n,t);r!==null&&e.set(we(n.startPosition.row,n.startPosition.column),r);}for(let r of n.namedChildren)r&&os(r,e,t);}function gu(n,e){if(hu(n))return "declaration";if(bu(n))return "read";if(vu(n))return "declaration";if(Su(n))return "type";let t=pt(n,r=>r.type==="decorator");return t!==null&&wu(n,t)||_u(n)?"call":xu(n)||Cu(n)||Eu(n)||Iu(n)||Nu(n)?"write":Tu(n,e)?"import-use":"read"}function hu(n){let e=n.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===n||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===n)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"||yu(n))}function yu(n){let e=n.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function vu(n){let e=n.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(Dn.has(e.type))return false;e=e.parent;}return false}function bu(n){let e=n.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function Su(n){return pt(n,t=>t.type==="type")!==null}function wu(n,e){let t=e.namedChild(0);if(t===null)return false;if(t===n)return true;if(t.type==="call"){let r=t.childForFieldName("function");if(r===n||r?.type==="attribute"&&r.childForFieldName("attribute")===n)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===n}function _u(n){let e=n.parent;if(e?.type==="call"&&e.childForFieldName("function")===n)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===n){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function xu(n){let e=n;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||Dn.has(t.type))return false;e=t;}return false}function Cu(n){let e=n.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===n)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===n){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function Eu(n){let e=n.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===n}function Iu(n){let e=n;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(Pu.has(t.type)){e=t;continue}if(Dn.has(t.type))return false;e=t;}return false}function Nu(n){let e=n;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(!Ru.has(t.type))return false;e=t;}return false}function Tu(n,e){let t=n.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==n)return false;let r=n.text;return e.has(r)?!ku(n,r):false}function ku(n,e){let t=n.parent;for(;t!==null;){if(Lu.has(t.type)&&ju(t,e))return true;t=t.parent;}return false}function ju(n,e){for(let t of n.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 Au(n){let e=new Set;for(let t of n.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 fu,Dn,Pu,Ru,Lu,ss=f(()=>{ut();Fn();fu=Object.freeze(new Set(["identifier"])),Dn=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));Pu=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));Ru=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));Lu=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function ls(n,e){n.rootNode&&cs(n.rootNode,e);}function cs(n,e){if(Fu.has(n.type)){let t=Ou(n);t!==null&&e.set(we(n.startPosition.row,n.startPosition.column),t);}for(let t of n.namedChildren)t&&cs(t,e);}function Ou(n){return Mu(n)?"declaration":Uu(n)?"type":Gu(n)?"call":Bu(n)?"instantiate":Hu(n)?"call":zu(n)||Wu(n)?"write":"read"}function Mu(n){let e=n.parent;return e===null?false:!!($u.has(e.type)&&e.childForFieldName("name")===n||e.type==="foreach_statement"&&e.childForFieldName("left")===n||e.type==="declaration_pattern"&&e.childForFieldName("name")===n)}function Uu(n){let e=n,t=n.parent;for(;t!==null;){if(Du.has(t.type)||t.type==="variable_declaration"&&t.childForFieldName("type")===e||t.type==="parameter"&&t.childForFieldName("type")===e||t.type==="method_declaration"&&t.childForFieldName("returns")===e||t.type==="property_declaration"&&t.childForFieldName("type")===e||t.type==="cast_expression"&&t.childForFieldName("type")===e||t.type==="as_expression"&&t.childForFieldName("right")===e||t.type==="is_expression"&&t.childForFieldName("right")===e||t.type==="typeof_expression"&&t.childForFieldName("type")===e||t.type==="default_expression"&&t.childForFieldName("type")===e||t.type==="foreach_statement"&&t.childForFieldName("type")===e||t.type==="catch_declaration"&&t.childForFieldName("type")===e||t.type==="local_function_statement"&&t.childForFieldName("type")===e||t.type==="delegate_declaration"&&t.childForFieldName("type")===e||t.type==="declaration_pattern"&&t.childForFieldName("type")===e)return true;if(t.type==="is_pattern_expression")return t.namedChild(0)!==e;if(as.has(t.type))return false;e=t,t=t.parent;}return false}function Gu(n){let e=n.parent;return e!==null&&e.type==="attribute"&&e.childForFieldName("name")===n}function Bu(n){let e=n.parent;return e===null?false:e.type==="object_creation_expression"&&e.childForFieldName("type")===n}function Hu(n){let e=n.parent;if(e===null)return false;if(e.type==="invocation_expression"&&e.childForFieldName("function")===n)return true;if(e.type==="member_access_expression"&&e.childForFieldName("name")===n){let t=e.parent;if(t!==null&&t.type==="invocation_expression"&&t.childForFieldName("function")===e)return true}return false}function zu(n){let e=n;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment_expression"&&t.childForFieldName("left")===e)return true;if(t.type==="member_access_expression"&&t.childForFieldName("expression")===e||as.has(t.type))return false;e=t;}return false}function Wu(n){let e=n.parent;if(e===null)return false;if(e.type==="postfix_unary_expression"||e.type==="prefix_unary_expression"){let t=e.text;if(t.startsWith("++")||t.startsWith("--")||t.endsWith("++")||t.endsWith("--"))return true}return false}var Fu,as,$u,Du,ps=f(()=>{ut();Fu=Object.freeze(new Set(["identifier","generic_name"])),as=Object.freeze(new Set(["compilation_unit","namespace_declaration","file_scoped_namespace_declaration","class_declaration","struct_declaration","interface_declaration","record_declaration","enum_declaration","method_declaration","constructor_declaration","block"])),$u=Object.freeze(new Set(["class_declaration","interface_declaration","struct_declaration","record_declaration","enum_declaration","delegate_declaration","method_declaration","constructor_declaration","property_declaration","event_declaration","local_function_statement","namespace_declaration","enum_member_declaration","variable_declarator","parameter","catch_declaration"])),Du=Object.freeze(new Set(["base_list","type_argument_list","type_parameter","type_parameter_list","type_parameter_constraints_clause","type_constraint"]));});function ds(n,e){let t=new Map;switch(e){case "typescript":dt(n,t);break;case "tsx":es(n,t);break;case "javascript":rs(n,t);break;case "python":is(n,t);break;case "c-sharp":ls(n,t);break}return t}function we(n,e){return `${n}:${e}`}var us,ut=f(()=>{Tr();ts();ns();ss();ps();us=Object.freeze(new Set(["typescript","javascript","python","c-sharp"]));});function Ju(n,e){return us.has(n)?n==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":n:null}function qu(n){let e=[];for(let[t,r]of n.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 Lr,gs=f(()=>{ut();le();Lr=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=Hp.tsx);let s=new Ku;s.setLanguage(o);let a=await C.getFileStats(e),l=25*1024*1024,c,u;if(a.size<=l){let g=await C.readFile(e);u=g;let h={bufferSize:1024*1024};c=s.parse(g,void 0,h);}else c=await this.parseWithStream(s,e,a.size);let p=Ju(t,e),d=p===null?[]:qu(ds(c,p));return {tree:c,classificationMap:{filePath:e,entries:d},content:u}}async parseWithStream(e,t,r){let o=null;try{o=await se.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}%...
|
|
55
|
-
`),c=m);}let d=
|
|
56
|
-
`);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var kr,ys=f(()=>{le();oe();q();kr=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=hs();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=hs().add(t.exclude));let s=await se__default.realpath(this.rootPath);for(let a of e)try{let l=k__default.isAbsolute(a)?a:k__default.join(this.rootPath,a),c=await se__default.lstat(l);if(c.isSymbolicLink()){let u=await se__default.realpath(l);if(!u.startsWith(s+k__default.sep)&&u!==s){console.warn(`${z} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let p=await se__default.stat(l);if(!p.isFile())continue;let d=Y(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=Y(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(`${z} Skipping inaccessible file: ${a}`);}return r}async loadGitignoreRules(e,t){let r=[],o=t;for(;;){let s=k__default.join(o,".gitignore");await C.fileIsReadable(s)&&r.unshift(s);let a=k__default.dirname(o);if(a===o)break;o=a;let l=k__default.join(o,".git");if(await C.directoryExists(l)){let c=k__default.join(o,".gitignore");await C.fileIsReadable(c)&&!r.includes(c)&&r.unshift(c);break}}for(let s of r)try{let a=await C.readFile(s);e.add(a);}catch{console.warn(`${z} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,r,o){let s=[],a=t||e,l=r||await se__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=(await se__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=k__default.join(e,p.name),m=Y(a,d);if(p.isDirectory()){if(p.name.startsWith("."))continue;let g=await this.walkDirectory(d,a,l,c);s.push(...g);}else if(p.isFile()){let g=await se__default.stat(d);s.push({path:d,relativePath:m,language:"",size:g.size});}else if(p.isSymbolicLink())try{let g=await se__default.realpath(d);if(!g.startsWith(l+k__default.sep)&&g!==l){console.warn(`${z} Skipping symlink pointing outside project: ${d} -> ${g}`);continue}let h=await se__default.stat(d);if(h.isDirectory()){if(p.name.startsWith(".")||c.has(g))continue;c.add(g);let b=await this.walkDirectory(d,a,l,c);s.push(...b);}else h.isFile()&&s.push({path:d,relativePath:m,language:"",size:h.size});}catch{console.warn(`${z} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${ge} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let r=k__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=k__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return o;return null}};});var Yu,Xu,Qu,vs,bs=f(()=>{Nt();Yu=z$1.object({local:z$1.string(),original:z$1.string().optional(),isDefault:z$1.boolean(),isNamespace:z$1.boolean()}),Xu=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(Yu).optional()}),Qu=z$1.record(z$1.string(),Xu),vs=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:Qu.optional(),classificationMap:pn.optional()});});function Zu(n){let e=Math.max(0,n)/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 Ss(){let n=performance.now();return {elapsed:()=>Zu(performance.now()-n),reset:()=>{n=performance.now();},ms:()=>performance.now()-n}}var ws=f(()=>{});function On(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(typeof n=="object"&&n!==null)try{return JSON.stringify(n)}catch{return String(n)}return String(n)}var Ar,_s=f(()=>{Tt();Ar=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(On).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:stripVTControlCharacters(e.map(On).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:stripVTControlCharacters(e.map(On).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||!mn.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!mn.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 Ue(n){if(n&&typeof n=="object")try{n.alreadyReported=!0;}catch{}}function xe(n){return !!(n&&typeof n=="object"&&n.alreadyReported)}function Mn(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(typeof n=="object"&&n!==null)try{return JSON.stringify(n)}catch{return String(n)}return String(n)}var xs,td,rd,Fr,Un=f(()=>{qe();ws();_s();q();xs=Math.floor(1e3/15),td={interval:100,frames:["\u280B","\u2819","\u281A","\u2813"]},rd=new Set(["EPIPE","ENOTCONN","EBADF"]);Fr=class n{static activeInstance=null;mode;stream;logCollector=new Ar;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(n.activeInstance&&!n.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,n.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),Ue(s),s}}start(e){this.currentPhaseLabel=e,this.currentPhaseTracker=Ss(),this.mode==="spinner"?(this.spinner?this.spinner.text=this.composeSpinnerText(e):this.spinner=ed({text:this.composeSpinnerText(e),stream:this.stream,spinner:td}),this.paused||this.spinner.start()):(this.mode==="verbose"||this.mode==="plain")&&this.writeLine(`${ve} ${e}\u2026`);}update(e){if(!this.currentPhaseLabel)return;if(this.currentPhaseLabel=e,this.mode==="verbose"){this.writeLine(`${ve} ${e}`);return}if(this.mode!=="spinner")return;let t=Date.now();this.pendingUpdate=e;let r=t-this.lastUpdateAt;r>=xs?this.flushPendingUpdate():this.pendingUpdateTimer||(this.pendingUpdateTimer=setTimeout(()=>this.flushPendingUpdate(),xs-r),this.pendingUpdateTimer.unref?.());}succeed(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",r=`${x} ${t}`;this.terminatePhase(r,"info");}fail(e,t){this.flushPendingUpdate();let r=e??this.currentPhaseLabel??"",o=`${ge} ${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(`${ve} ${e}`);}warn(e,t){if(this.logCollector.record("warn",e,t?.code),!(t?.verboseOnly&&this.mode!=="verbose")){if(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(`${z} ${e}`);}}error(e,t){this.logCollector.record("error",e,t?.code),!(t?.verboseOnly&&this.mode!=="verbose")&&this.writeLine(`${ge} ${e}`);}detail(e){this.logCollector.record("info",e),this.mode==="verbose"&&this.writeLine(` ${ie.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"?x:e==="fail"?ge:ie.muted("-")} ${e==="skip"?ie.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(),n.activeInstance===this&&(n.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(`${z} ${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(`${z} ${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+`
|
|
52
|
+
`)},Ap=k.join(We.homedir(),".constellation","lsp-trust.json"),ur=class{constructor(e,t,r){this.projectRoot=e;this.logger=t??jp,this.policy=r??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new pr({projectRoot:this.projectRoot,logger:this.logger,trustStore:new ot(Ap),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;let d,m;try{d=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});let g=d;await new Promise((T,w)=>{g.once("spawn",T),g.once("error",w);}),g.stderr?.on("data",T=>{this.handleServerDiagnostics(e,T.toString());}),m=new cr(g.stdin,g.stdout,12e4);let h=m,b=En(a)?{background_analysis:{dotnet_analyzer_diagnostics_scope:"none",dotnet_compiler_diagnostics_scope:"openFiles"}}:void 0,y=pathToFileURL(this.projectRoot).href,S=await h.sendRequest("initialize",{processId:process.pid,rootUri:y,workspaceFolders:[{uri:y,name:k.basename(this.projectRoot)}],capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}},...b&&{initializationOptions:b}},12e4);if(h.sendNotification("initialized",{}),En(a)){this.logger.log(`[LSP:${e}] Roslyn: waiting for project initialization (auto-load)\u2026`);let T=h.waitForNotification("workspace/projectInitializationComplete",18e4),w=new Promise((P,N)=>{let I=(v,R)=>{N(new Error(`Roslyn server exited during project initialization (code=${v}, signal=${R})`));};g.once("exit",I),T.finally(()=>g.removeListener("exit",I));});await Promise.race([T,w]),T.catch(()=>{}),w.catch(()=>{}),this.logger.log(`[LSP:${e}] Roslyn project initialization complete`);}let E={key:c,language:e,languages:new Set([e]),process:g,client:h,crashHandlers:new Set,intentionalShutdown:!1};return this.serversByKey.set(c,E),this.languageToServerKey.set(e,c),g.on("exit",(T,w)=>{let P=this.serversByKey.get(c);if(P){if(P.intentionalShutdown)P.crashHandlers.clear();else {let N=[...P.crashHandlers];P.crashHandlers.clear();for(let I of N)try{I();}catch(v){this.logger.warn(`[LSP:${P.language}] crash handler threw: ${v instanceof Error?v.message:String(v)}`);}this.logUnexpectedExit(e,T,w);}P.client.dispose(),this.serversByKey.delete(c);for(let[N,I]of this.languageToServerKey.entries())I===c&&this.languageToServerKey.delete(N);}}),this.toConnection(E,e)}catch(g){try{m?.dispose();}catch{}try{d?.kill();}catch{}this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let h=`[LSP:${e}] Failed to start: ${g instanceof Error?g.message:String(g)}`,b=g?.code;return b==="ENOENT"||b==="EACCES"?this.logger.warn(h):this.logger.error(h),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();}handleServerDiagnostics(e,t){}resolveCommand(e,t){if(t?.command)return {command:t.command,args:[...t.args||[]]};let r=Te.get(e);if(!r)return null;let o=k.join(nt,r.command);if(existsSync(o))return {command:o,args:[...r.args]};if(ae(r.command))return {command:r.command,args:[...r.args]};let s=In(r.command);return s?{command:s,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),onNotification:(o,s)=>e.client.onNotification(o,s),onCrash:o=>(e.crashHandlers.add(o),()=>e.crashHandlers.delete(o))}}};});var J,De=f(()=>{J=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}preflightLsp(e){return Promise.resolve({skip:false})}};});var st,Ln=f(()=>{X();st=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(`${W} 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(`${W} Failed to parse ${r}: ${o}`),console.warn(`${W} Path alias resolution will be skipped for files using this config`);}else r||console.warn(`${W} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var dr,Ho=f(()=>{ee();dr=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?k.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=k.resolve(r,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=k.join(this.projectRoot,"package.json"),r=await se.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=k.join(this.projectRoot,r);try{let s=await se.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(k.join(o,a.name));}catch{}}else {let r=k.join(this.projectRoot,e);try{(await se.stat(r)).isDirectory()&&t.push(r);}catch{}}return t}async loadWorkspacePackage(e){try{let t=k.join(e,"package.json"),r=await se.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 k.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return k.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return k.join(e,a)}}}if(t.main)return k.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=k.join(e,o);try{if((await se.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=k.join(e,r);try{if((await se.stat(o)).isFile())return o}catch{}}try{if((await se.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")?k.dirname(e):k.dirname(e),o=[k.join(r,t+".ts"),k.join(r,t+".tsx"),k.join(r,t+".js"),k.join(r,t+".jsx"),k.join(r,t+".d.ts"),k.join(r,t,"index.ts"),k.join(r,t,"index.tsx"),k.join(r,t,"index.js"),k.join(r,t,"index.jsx")];for(let s of o)try{if((await se.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=Q(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var at,kn=f(()=>{ee();Ho();at=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=k.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new dr(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=k.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=k.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=k.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=Q(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=k.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=k.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=k.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await se.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await se.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let r=k.join(t,"package.json");try{if((await se.stat(r)).isFile())return r}catch{}let o=k.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 se.readFile(e,"utf-8"),r=JSON.parse(t);this.packageJsonDir=k.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=k.resolve(this.packageJsonDir,r);return await this.findFileWithExtensions(o)}};});var mr,Wo=f(()=>{De();Ln();kn();mr=class extends J{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new st(e,t)}getImportResolver(e,t){return new at(e,t)}};});var fr,zo=f(()=>{De();Ln();kn();fr=class extends J{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new st(e,t)}getImportResolver(e,t){return new at(e,t)}};});async function K(n,e,t,r,o,s=[]){let a=await t.resolve(n),l=Ko(n,a),c=o(n,a,l),u=l?void 0:ar(a);r[e.toString()]={source:n,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function Ko(n,e){return n===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var jn,Le=f(()=>{ee();jn=(n,e,t)=>t?n.startsWith("node:")?"builtin":"external":n.startsWith("./")||n.startsWith("../")?"relative":n.startsWith("@")?"workspace":"alias";});async function Mp(n,e,t,r){let o=n.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 K(s,n.startPosition.row,e,t,r,[a]);}function Op(n,e){if(!e)return [];let t=[],r=n.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<n.childCount;s++){let a=n.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 Up(n,e,t,r){let o,s=n.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<n.childCount;c++){let u=n.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=Op(n,!!s);await K(o,n.startPosition.row,e,t,r,a);}async function Gp(n,e,t,r){await K("__future__",n.startPosition.row,e,t,r,[]);}function An(){return {language:"python",handlers:new Map([["import_statement",Mp],["import_from_statement",Up],["future_import_statement",Gp]]),classifyImportType:Dp}}var Dp,gr=f(()=>{Nt();Le();Nt();Dp=(n,e,t)=>{if(t)return "external";if(/^\.+/.test(n))return "relative";let r=n.split(".")[0];return It.has(r)?"builtin":"alias"};});var hr,Vo=f(()=>{gr();hr=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=k.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(It.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let r=e.replace(/\./g,"/"),o=await this.tryResolveFile(k.resolve(this.projectRoot,r));return o?k.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=k.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?k.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,k.join(e,"__init__.py"),k.join(e,"__init__.pyi")];for(let r of t)try{return await Oe.promises.access(r,Oe.constants.F_OK),r}catch{continue}return null}};});var vr,Jo=f(()=>{De();Vo();vr=class extends J{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new hr(e,process.cwd())}};});function qo(n){return n.replace(/\/\/[^\n]*/g,"")}function lt(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}function Bp(n,e){let t=[],r=/^\s*replace\s*\(\s*([\s\S]*?)\)/gm,o=[];for(let l of n.matchAll(r))o.push(l[1]);let s=n.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(`
|
|
53
|
+
`)){let u=c.trim();if(!u)continue;let p=Hp(u,e);p&&t.push(p);}return t}function Hp(n,e){let t=n.indexOf("=>");if(t===-1)return null;let r=n.slice(0,t).trim().split(/\s+/).filter(Boolean),o=n.slice(t+2).trim().split(/\s+/).filter(Boolean);if(r.length===0||o.length===0)return null;let s=lt(r[0]),a=r.length>=2?lt(r[1]):void 0,l=lt(o[0]);if(!Wp(l))return null;let c=k.isAbsolute(l)?l:k.resolve(e,l);return {originalModulePath:s,originalVersion:a,localDir:c}}function Wp(n){return n==="."||n===".."||n.startsWith("./")||n.startsWith("../")||k.isAbsolute(n)}var Ue,Yo=f(()=>{ee();Ue=class n{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=n.findGoWorkAncestor(this.projectRoot),this.goWorkPath!==null){let e=await this.parseGoWork(this.goWorkPath),t=await Promise.all(e.map(async r=>{let o=k.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(F(s.rootDir),s)):this.warnings.push(`go.work: use directive ${F(r)} has no parseable go.mod at ${F(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(F(r.rootDir),r));}return this.initialized=true,this.configFilesPaths()}configFilesPaths(){let e=this.discovered.map(t=>F(k.join(t.rootDir,"go.mod")));return this.goWorkPath!==null&&e.unshift(F(this.goWorkPath)),e}async getConfigForFile(e){this.initialized||await this.initialize();let t=k.isAbsolute(e)?e:k.resolve(this.projectRoot,e),r=this.goWorkPath!==null?k.dirname(this.goWorkPath):this.projectRoot,o=k.dirname(t);for(;;){let s=this.cache.get(F(o));if(s!==void 0)return s;let a=k.dirname(o),l=o===r||o.startsWith(r+k.sep);if(a===o||!l)return null;o=a;}}getAllModules(){return this.discovered}static hasGoModAncestor(e){let t=k.resolve(e);for(;;){if(Oe.existsSync(k.join(t,"go.mod")))return true;let r=k.dirname(t);if(r===t)return false;t=r;}}static findGoWorkAncestor(e){let t=k.resolve(e);for(;;){let r=k.join(t,"go.work");if(Oe.existsSync(r))return r;let o=k.dirname(t);if(o===t)return null;t=o;}}async findGoModFiles(e,t,r){if(t>r)return [];let o=[],s;try{s=await Oe.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=k.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 Oe.promises.readFile(e,"utf8");}catch{return []}let r=k.dirname(e),o=[],s=qo(t),a=/^\s*use\s*\(\s*([\s\S]*?)\)/gm;for(let u of s.matchAll(a))for(let p of u[1].split(`
|
|
54
|
+
`)){let d=lt(p.trim());d&&o.push(k.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=lt(u[1].trim());p&&o.push(k.resolve(r,p));}return o}async parseGoMod(e){let t;try{t=await Oe.promises.readFile(e,"utf8");}catch{return null}let r=qo(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=k.dirname(e);return {modulePath:lt(o[1]),goVersion:s?.[1],rootDir:a,replaces:Bp(r,a)}}};});function zp(n){let e=n.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}var Sr,br,wr=f(()=>{ee();Sr=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"]),br=class{constructor(e,t,r=[]){this.sourceFilePath=e;this.projectRoot=t;this.modules=r;}async resolve(e){let t=zp(e);if(!t)return e;let r=t.split("/")[0];if(!r.includes(".")&&Sr.has(r))return t;let o=this.findReplaceForSpecifier(t);if(o){let a=t.slice(o.originalModulePath.length),l=k.join(o.localDir,a.startsWith("/")?a.slice(1):a);if(await this.directoryHasGoFiles(l))return F(k.relative(this.projectRoot,l))}let s=this.findModuleForSpecifier(t);if(s){let a=t.slice(s.modulePath.length),l=k.join(s.rootDir,a.startsWith("/")?a.slice(1):a);if(await this.directoryHasGoFiles(l))return F(k.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 Oe.promises.readdir(e,{withFileTypes:!0})).some(r=>r.isFile()&&r.name.endsWith(".go")&&!r.name.endsWith("_test.go"))}catch{return false}}};});var _r,Qo=f(()=>{De();Yo();wr();_r=class extends J{language="go";extensions=[".go"];manager=null;getBuildConfigManager(e,t){return this.manager=new Ue(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 br(e,process.cwd(),r)}async preflightLsp(e){return this.manager??=new Ue(e),await this.manager.initialize(),this.manager.getAllModules().length>0?{skip:false}:Ue.hasGoModAncestor(e)?{skip:false}:Ue.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."}}};});async function ts(n){let e=false,t=false,r=async o=>{if(e&&t)return;let s;try{s=await Oe.promises.readdir(o,{withFileTypes:!0});}catch{return}for(let a of s){if(e&&t)return;if(a.isFile())!e&&(a.name.endsWith(".sln")||a.name.endsWith(".csproj"))?e=true:!t&&a.name==="project.assets.json"&&(t=true);else if(a.isDirectory()){if(Kp.has(a.name)||a.name.startsWith("."))continue;await r(k.join(o,a.name));}}};return await r(n),{hasProjects:e,restored:t}}var Kp,rs=f(()=>{Kp=new Set(["node_modules",".git","bin"]);});function $n(n,e){let t=new RegExp(`<${e}[^>]*>([^<]+)<\\/${e}>`,"i"),r=n.match(t);return r?r[1].trim():void 0}function Vp(n){let e=$n(n,"ImplicitUsings");return e?e.toLowerCase()==="enable"||e.toLowerCase()==="true":false}function Jp(n){let e=[],t=/<PackageReference\s[^>]*Include\s*=\s*"([^"]+)"/gi;for(let r of n.matchAll(t))e.push(r[1].trim());return e}function qp(n,e,t){let r=n.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,""),o=/\bnamespace\s+([a-zA-Z_][\w]*(?:\.[a-zA-Z_][\w]*)*)\s*(?:[{;])/g;for(let a of r.matchAll(o)){let l=a[1].trim();l&&Fn(t,l,e,false);}let s=/\busing\s+([a-zA-Z_][\w]*)\s*=\s*([a-zA-Z_][\w]*(?:\.[a-zA-Z_][\w]*)*)\s*;/g;for(let a of r.matchAll(s)){let l=a[1].trim(),c=a[2].trim();l&&Fn(t,l,e,true),c&&Fn(t,c,e,false);}}function Fn(n,e,t,r){let o=n.get(e);(!o||F(t)<F(o.filePath))&&n.set(e,{filePath:t,isAlias:r});}var Cr,ns=f(()=>{ee();Cr=class{constructor(e,t=true){this.projectRoot=e;this.enabled=t;}cache=new Map;discovered=[];initialized=false;namespaceIndex=new Map;isEnabled(){return this.enabled}clearCache(){this.cache.clear(),this.discovered=[],this.initialized=false,this.namespaceIndex=new Map;}async initialize(){if(this.initialized)return this.configFilePaths();let{projectFiles:e,csFiles:t}=await this.findBuildArtifacts(this.projectRoot),r=await Promise.all(e.map(o=>this.parseProjectFile(o)));for(let o of r){if(!o)continue;this.discovered.push(o);let s=F(o.rootDir),a=this.cache.get(s),l=o.configFilePath.endsWith(".csproj"),c=a?.configFilePath.endsWith(".csproj")??false;(!a||l&&!c)&&this.cache.set(s,o);}return await Promise.all(t.map(async o=>{let s;try{s=await Oe.promises.readFile(o,"utf8");}catch{return}qp(s,o,this.namespaceIndex);})),this.initialized=true,this.configFilePaths()}getNamespaceIndex(){return this.namespaceIndex}configFilePaths(){return this.discovered.map(e=>F(e.configFilePath))}async getConfigForFile(e){this.initialized||await this.initialize();let t=k.isAbsolute(e)?e:k.resolve(this.projectRoot,e),r=k.dirname(t);for(;;){let o=this.cache.get(F(r));if(o!==void 0)return o;let s=k.dirname(r),a=r===this.projectRoot||r.startsWith(this.projectRoot+k.sep);if(s===r||!a)return null;r=s;}}getAllProjects(){return this.discovered}getAllPackageReferences(){let e=new Set;for(let t of this.discovered)for(let r of t.packageReferences)e.add(r);return e}async findBuildArtifacts(e){let t=[],r=[],o;try{o=await Oe.promises.readdir(e,{withFileTypes:!0});}catch{return {projectFiles:t,csFiles:r}}for(let s of o){if(s.name==="node_modules"||s.name==="bin"||s.name==="obj"||s.name.startsWith("."))continue;let a=k.join(e,s.name);if(s.isFile())s.name.endsWith(".csproj")||s.name==="Directory.Build.props"?t.push(a):(s.name.endsWith(".cs")||s.name.endsWith(".csx"))&&r.push(a);else if(s.isDirectory()){let l=await this.findBuildArtifacts(a);t.push(...l.projectFiles),r.push(...l.csFiles);}}return {projectFiles:t,csFiles:r}}async parseProjectFile(e){let t;try{t=await Oe.promises.readFile(e,"utf8");}catch{return null}let r=k.dirname(e);return {configFilePath:e,rootDir:r,langVersion:$n(t,"LangVersion"),nullable:$n(t,"Nullable"),implicitUsings:Vp(t),packageReferences:Jp(t)}}};});function Yp(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];(r==="."||r===":"&&n[t+1]===":")&&e.push(n.slice(0,t));}return e}var Er,is=f(()=>{ee();Er=class{constructor(e,t){this.projectRoot=e;this.index=t;}index;async resolve(e){if(!e)return e;let t=this.index.get(e);if(t)return F(k.relative(this.projectRoot,t.filePath));let r=Yp(e);for(let o=r.length-1;o>=0;o--){let s=this.index.get(r[o]);if(s)return F(k.relative(this.projectRoot,s.filePath))}return e}};});var Pr,os=f(()=>{De();rs();ns();is();Pr=class extends J{language="c-sharp";extensions=[".cs",".csx"];manager=null;getBuildConfigManager(e,t){return this.manager=new Cr(e),this.manager}getImportResolver(e,t){let r=this.manager?t?.rootDir??this.manager.getAllProjects()[0]?.rootDir??process.cwd():process.cwd(),o=this.manager?.getNamespaceIndex()??new Map;return new Er(r,o)}async preflightLsp(e){let t;try{t=await ts(e);}catch{return {skip:false}}return !t.hasProjects||t.restored?{skip:false}:{skip:true,message:"C# enrichment skipped: the solution is not restored (no project.assets.json found). Run `dotnet restore` in the project root, then re-index. Skipping avoids empty results caused by unresolved analyzer references."}}};});var On,Ir,Un=f(()=>{ee();On=new Set(["Foundation","Dispatch","ObjectiveC","Darwin","Glibc","Observation","OSLog","os","simd","Accelerate","SwiftUI","UIKit","AppKit","WidgetKit","Charts","WebKit","PDFKit","Combine","CoreData","SwiftData","CloudKit","CoreGraphics","CoreImage","CoreAnimation","AVFoundation","Photos","Metal","MetalKit","SpriteKit","SceneKit","ARKit","RealityKit","CoreLocation","MapKit","Contacts","EventKit","HealthKit","HomeKit","StoreKit","GameKit","Network","Security","CryptoKit","CoreML","Vision","NaturalLanguage","XCTest","Testing"]),Ir=class{projectRoot;localTargetCache=new Map;constructor(e){this.projectRoot=e;}resolve(e){let t=e.trim();return !t||On.has(t)?Promise.resolve(e):this.isLocalTarget(t)?Promise.resolve(F(k.join("Sources",t))):Promise.resolve(e)}isLocalTarget(e){let t=this.localTargetCache.get(e);if(t!==void 0)return t;let r=false;try{let o=k.join(this.projectRoot,"Sources",e);r=Oe.existsSync(o)&&Oe.statSync(o).isDirectory();}catch{r=false;}return this.localTargetCache.set(e,r),r}};});var Nr,ss=f(()=>{De();Un();Nr=class extends J{language="swift";extensions=[".swift"];getImportResolver(e,t){return new Ir(process.cwd())}};});function re(n){return nu[n]??n.charAt(0).toUpperCase()+n.slice(1)}var nu,ke,Tr,Lr=f(()=>{Wo();zo();Jo();Qo();os();ss();nu={bash:"Bash",c:"C","c-sharp":"C#",cpp:"C++",go:"Go",java:"Java",javascript:"JavaScript",json:"JSON",php:"PHP",python:"Python",ruby:"Ruby",swift:"Swift",typescript:"TypeScript"};ke={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs",".csx"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],swift:[".swift"],typescript:[".ts",".tsx"]},Tr=class{constructor(e){this.config=e;this.registerPlugin(new mr),this.registerPlugin(new fr),this.registerPlugin(new vr),this.registerPlugin(new _r),this.registerPlugin(new Pr),this.registerPlugin(new Nr);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Zp,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??ke.javascript};typescript={language:()=>ru.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??ke.typescript};python={language:()=>eu,fileExtensions:()=>this.config?.languages.python?.fileExtensions??ke.python};php;json;java;go={language:()=>Qp,fileExtensions:()=>this.config?.languages.go?.fileExtensions??ke.go};cpp;"c-sharp"={language:()=>Xp,fileExtensions:()=>this.config?.languages["c-sharp"]?.fileExtensions??ke["c-sharp"]};c;bash;ruby;swift={language:()=>tu,fileExtensions:()=>this.config?.languages.swift?.fileExtensions??ke.swift}};});function pt(n,e,t=32){let r=n.parent,o=0;for(;r!==null&&o<t;){if(e(r))return r;r=r.parent,o++;}return null}var kr,Gn=f(()=>{kr=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function Bn(n,e){if(n.type==="jsx_opening_element"||n.type==="jsx_self_closing_element"||n.type==="jsx_closing_element"){let t=n.childForFieldName("name");t!==null&&iu(t,e);}for(let t of n.namedChildren)t&&Bn(t,e);}function iu(n,e){if(n.type==="identifier"||n.type==="type_identifier"){e.set(we(n.startPosition.row,n.startPosition.column),"call");return}if(n.type==="member_expression"||n.type==="nested_identifier"){let t=n.childForFieldName("property");t!==null&&e.set(we(t.startPosition.row,t.startPosition.column),"call");}}var as=f(()=>{ut();});function dt(n,e){n.rootNode&&(cs(n.rootNode,e),Bn(n.rootNode,e));}function cs(n,e){if(ou.has(n.type)){let t=su(n);t!==null&&e.set(we(n.startPosition.row,n.startPosition.column),t);}for(let t of n.namedChildren)t&&cs(t,e);}function su(n){if(lu(n))return "declaration";if(vu(n))return "read";if(hu(n))return "type";let e=pt(n,t=>t.type==="decorator");return e!==null&&uu(n,e)?"call":pu(n)?"instantiate":cu(n)?"call":du(n)||mu(n)||fu(n)||Pu(n)||Eu(n)?"write":bu(n)?"import-use":"read"}function lu(n){let e=n.parent;return e===null?false:!!(au.has(e.type)&&(e.childForFieldName("name")===n||e.childForFieldName("property")===n)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===n||e.type==="import_specifier"&&(e.childForFieldName("name")===n||e.childForFieldName("alias")===n)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===n&&n.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===n||e.type==="enum_body")}function cu(n){let e=n.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===n)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===n){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function pu(n){let e=n.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===n)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===n){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function uu(n,e){let t=e.namedChild(0);if(t===null)return false;if(t===n)return true;if(t.type==="call_expression"){let r=t.childForFieldName("function");if(r===n||r?.type==="member_expression"&&r.childForFieldName("property")===n)return true}return t.type==="member_expression"&&t.childForFieldName("property")===n}function du(n){let e=n;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||kr.has(t.type))return false;e=t;}return false}function mu(n){let e=n.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===n)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===n){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function fu(n){let e=n;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||kr.has(t.type))return false;e=t;}return false}function hu(n){let e=n.parent,t=n;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let r=e.namedChild(1);return r===null?false:r===t||yu(r,n)}if(gu.has(e.type))return true;if(kr.has(e.type))return false;t=e,e=e.parent;}return false}function yu(n,e){let t=e;for(;t!==null;){if(t===n)return true;t=t.parent;}return false}function vu(n){return pt(n,t=>t.type==="type_query")!==null}function bu(n){let e=n.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==n)return false;let t=n.text,r=xu(n);return Cu(r,t)?!wu(n,t):false}function wu(n,e){let t=n.parent;for(;t!==null;){if(Su.has(t.type)&&_u(t,e))return true;t=t.parent;}return false}function _u(n,e){for(let t of n.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 xu(n){let e=n;for(;e.parent!==null;)e=e.parent;return e}function Cu(n,e){for(let t of n.descendantsOfType("namespace_import")){let r=t.namedChild(0);if(r!==null&&r.text===e)return true}return false}function Eu(n){let e=n.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===n}function Pu(n){let e=n.parent;if(e===null||!ls.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===n||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==n)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(!ls.has(r.type))return false;t=r;}return false}var ou,au,gu,Su,ls,jr=f(()=>{ut();Gn();as();ou=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));au=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"]));gu=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"]));Su=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));ls=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function ps(n,e){dt(n,e);}var us=f(()=>{jr();});function ds(n,e){dt(n,e);}var ms=f(()=>{jr();});function fs(n,e){if(!n.rootNode)return;let t=Vu(n.rootNode);gs(n.rootNode,e,t);}function gs(n,e,t){if(Iu.has(n.type)){let r=Ru(n,t);r!==null&&e.set(we(n.startPosition.row,n.startPosition.column),r);}for(let r of n.namedChildren)r&&gs(r,e,t);}function Ru(n,e){if(Nu(n))return "declaration";if(ku(n))return "read";if(Lu(n))return "declaration";if(ju(n))return "type";let t=pt(n,r=>r.type==="decorator");return t!==null&&Au(n,t)||Fu(n)?"call":$u(n)||Du(n)||Mu(n)||Uu(n)||Bu(n)?"write":Hu(n,e)?"import-use":"read"}function Nu(n){let e=n.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===n||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===n)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"||Tu(n))}function Tu(n){let e=n.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function Lu(n){let e=n.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(Hn.has(e.type))return false;e=e.parent;}return false}function ku(n){let e=n.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function ju(n){return pt(n,t=>t.type==="type")!==null}function Au(n,e){let t=e.namedChild(0);if(t===null)return false;if(t===n)return true;if(t.type==="call"){let r=t.childForFieldName("function");if(r===n||r?.type==="attribute"&&r.childForFieldName("attribute")===n)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===n}function Fu(n){let e=n.parent;if(e?.type==="call"&&e.childForFieldName("function")===n)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===n){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function $u(n){let e=n;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||Hn.has(t.type))return false;e=t;}return false}function Du(n){let e=n.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===n)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===n){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function Mu(n){let e=n.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===n}function Uu(n){let e=n;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(Ou.has(t.type)){e=t;continue}if(Hn.has(t.type))return false;e=t;}return false}function Bu(n){let e=n;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(!Gu.has(t.type))return false;e=t;}return false}function Hu(n,e){let t=n.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==n)return false;let r=n.text;return e.has(r)?!zu(n,r):false}function zu(n,e){let t=n.parent;for(;t!==null;){if(Wu.has(t.type)&&Ku(t,e))return true;t=t.parent;}return false}function Ku(n,e){for(let t of n.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 Vu(n){let e=new Set;for(let t of n.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 Iu,Hn,Ou,Gu,Wu,hs=f(()=>{ut();Gn();Iu=Object.freeze(new Set(["identifier"])),Hn=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));Ou=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));Gu=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));Wu=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function vs(n,e){n.rootNode&&bs(n.rootNode,e);}function bs(n,e){if(Ju.has(n.type)){let t=Xu(n);t!==null&&e.set(we(n.startPosition.row,n.startPosition.column),t);}for(let t of n.namedChildren)t&&bs(t,e);}function Xu(n){return Qu(n)?"declaration":Zu(n)?"type":ed(n)?"call":td(n)?"instantiate":rd(n)?"call":nd(n)||id(n)?"write":"read"}function Qu(n){let e=n.parent;return e===null?false:!!(qu.has(e.type)&&e.childForFieldName("name")===n||e.type==="foreach_statement"&&e.childForFieldName("left")===n||e.type==="declaration_pattern"&&e.childForFieldName("name")===n)}function Zu(n){let e=n,t=n.parent;for(;t!==null;){if(Yu.has(t.type)||t.type==="variable_declaration"&&t.childForFieldName("type")===e||t.type==="parameter"&&t.childForFieldName("type")===e||t.type==="method_declaration"&&t.childForFieldName("returns")===e||t.type==="property_declaration"&&t.childForFieldName("type")===e||t.type==="cast_expression"&&t.childForFieldName("type")===e||t.type==="as_expression"&&t.childForFieldName("right")===e||t.type==="is_expression"&&t.childForFieldName("right")===e||t.type==="typeof_expression"&&t.childForFieldName("type")===e||t.type==="default_expression"&&t.childForFieldName("type")===e||t.type==="foreach_statement"&&t.childForFieldName("type")===e||t.type==="catch_declaration"&&t.childForFieldName("type")===e||t.type==="local_function_statement"&&t.childForFieldName("type")===e||t.type==="delegate_declaration"&&t.childForFieldName("type")===e||t.type==="declaration_pattern"&&t.childForFieldName("type")===e)return true;if(t.type==="is_pattern_expression")return t.namedChild(0)!==e;if(ys.has(t.type))return false;e=t,t=t.parent;}return false}function ed(n){let e=n.parent;return e!==null&&e.type==="attribute"&&e.childForFieldName("name")===n}function td(n){let e=n.parent;return e===null?false:e.type==="object_creation_expression"&&e.childForFieldName("type")===n}function rd(n){let e=n.parent;if(e===null)return false;if(e.type==="invocation_expression"&&e.childForFieldName("function")===n)return true;if(e.type==="member_access_expression"&&e.childForFieldName("name")===n){let t=e.parent;if(t!==null&&t.type==="invocation_expression"&&t.childForFieldName("function")===e)return true}return false}function nd(n){let e=n;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment_expression"&&t.childForFieldName("left")===e)return true;if(t.type==="member_access_expression"&&t.childForFieldName("expression")===e||ys.has(t.type))return false;e=t;}return false}function id(n){let e=n.parent;if(e===null)return false;if(e.type==="postfix_unary_expression"||e.type==="prefix_unary_expression"){let t=e.text;if(t.startsWith("++")||t.startsWith("--")||t.endsWith("++")||t.endsWith("--"))return true}return false}var Ju,ys,qu,Yu,Ss=f(()=>{ut();Ju=Object.freeze(new Set(["identifier","generic_name"])),ys=Object.freeze(new Set(["compilation_unit","namespace_declaration","file_scoped_namespace_declaration","class_declaration","struct_declaration","interface_declaration","record_declaration","enum_declaration","method_declaration","constructor_declaration","block"])),qu=Object.freeze(new Set(["class_declaration","interface_declaration","struct_declaration","record_declaration","enum_declaration","delegate_declaration","method_declaration","constructor_declaration","property_declaration","event_declaration","local_function_statement","namespace_declaration","enum_member_declaration","variable_declarator","parameter","catch_declaration"])),Yu=Object.freeze(new Set(["base_list","type_argument_list","type_parameter","type_parameter_list","type_parameter_constraints_clause","type_constraint"]));});function _s(n,e){let t=new Map;switch(e){case "typescript":dt(n,t);break;case "tsx":ps(n,t);break;case "javascript":ds(n,t);break;case "python":fs(n,t);break;case "c-sharp":vs(n,t);break}return t}function we(n,e){return `${n}:${e}`}var ws,ut=f(()=>{jr();us();ms();hs();Ss();ws=Object.freeze(new Set(["typescript","javascript","python","c-sharp"]));});function ad(n,e){return ws.has(n)?n==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":n:null}function ld(n){let e=[];for(let[t,r]of n.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 Ar,Es=f(()=>{ut();le();Ar=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=ru.tsx);let s=new od;s.setLanguage(o);let a=await C.getFileStats(e),l=25*1024*1024,c,u;if(a.size<=l){let g=await C.readFile(e);u=g;let h={bufferSize:1024*1024};c=s.parse(g,void 0,h);}else c=await this.parseWithStream(s,e,a.size);let p=ad(t,e),d=p===null?[]:ld(_s(c,p));return {tree:c,classificationMap:{filePath:e,entries:d},content:u}}async parseWithStream(e,t,r){let o=null;try{o=await se.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}%...
|
|
55
|
+
`),c=m);}let d=Oe.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)}
|
|
56
|
+
`);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var Fr,Is=f(()=>{le();ee();X();Fr=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Ps();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=Ps().add(t.exclude));let s=await se__default.realpath(this.rootPath);for(let a of e)try{let l=k__default.isAbsolute(a)?a:k__default.join(this.rootPath,a),c=await se__default.lstat(l);if(c.isSymbolicLink()){let u=await se__default.realpath(l);if(!u.startsWith(s+k__default.sep)&&u!==s){console.warn(`${W} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let p=await se__default.stat(l);if(!p.isFile())continue;let d=Q(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=Q(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(`${W} Skipping inaccessible file: ${a}`);}return r}async loadGitignoreRules(e,t){let r=[],o=t;for(;;){let s=k__default.join(o,".gitignore");await C.fileIsReadable(s)&&r.unshift(s);let a=k__default.dirname(o);if(a===o)break;o=a;let l=k__default.join(o,".git");if(await C.directoryExists(l)){let c=k__default.join(o,".gitignore");await C.fileIsReadable(c)&&!r.includes(c)&&r.unshift(c);break}}for(let s of r)try{let a=await C.readFile(s);e.add(a);}catch{console.warn(`${W} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,r,o){let s=[],a=t||e,l=r||await se__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=(await se__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=k__default.join(e,p.name),m=Q(a,d);if(p.isDirectory()){if(p.name.startsWith("."))continue;let g=await this.walkDirectory(d,a,l,c);s.push(...g);}else if(p.isFile()){let g=await se__default.stat(d);s.push({path:d,relativePath:m,language:"",size:g.size});}else if(p.isSymbolicLink())try{let g=await se__default.realpath(d);if(!g.startsWith(l+k__default.sep)&&g!==l){console.warn(`${W} Skipping symlink pointing outside project: ${d} -> ${g}`);continue}let h=await se__default.stat(d);if(h.isDirectory()){if(p.name.startsWith(".")||c.has(g))continue;c.add(g);let b=await this.walkDirectory(d,a,l,c);s.push(...b);}else h.isFile()&&s.push({path:d,relativePath:m,language:"",size:h.size});}catch{console.warn(`${W} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${ge} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let r=k__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=k__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return o;return null}};});var cd,pd,ud,Rs,Ns=f(()=>{Nt();cd=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),pd=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(cd).optional()}),ud=z.record(z.string(),pd),Rs=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|swift|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:ud.optional(),classificationMap:mn.optional()});});function dd(n){let e=Math.max(0,n)/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 Ts(){let n=performance.now();return {elapsed:()=>dd(performance.now()-n),reset:()=>{n=performance.now();},ms:()=>performance.now()-n}}var Ls=f(()=>{});function Wn(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(typeof n=="object"&&n!==null)try{return JSON.stringify(n)}catch{return String(n)}return String(n)}var Dr,ks=f(()=>{Tt();Dr=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(Wn).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:stripVTControlCharacters(e.map(Wn).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:stripVTControlCharacters(e.map(Wn).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||!hn.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!hn.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 Ge(n){if(n&&typeof n=="object")try{n.alreadyReported=!0;}catch{}}function xe(n){return !!(n&&typeof n=="object"&&n.alreadyReported)}function zn(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(typeof n=="object"&&n!==null)try{return JSON.stringify(n)}catch{return String(n)}return String(n)}var js,fd,gd,Mr,Kn=f(()=>{Ye();Ls();ks();X();js=Math.floor(1e3/15),fd={interval:100,frames:["\u280B","\u2819","\u281A","\u2813"]},gd=new Set(["EPIPE","ENOTCONN","EBADF"]);Mr=class n{static activeInstance=null;mode;stream;logCollector=new Dr;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(n.activeInstance&&!n.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,n.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),Ge(s),s}}start(e){this.currentPhaseLabel=e,this.currentPhaseTracker=Ts(),this.mode==="spinner"?(this.spinner?this.spinner.text=this.composeSpinnerText(e):this.spinner=md({text:this.composeSpinnerText(e),stream:this.stream,spinner:fd}),this.paused||this.spinner.start()):(this.mode==="verbose"||this.mode==="plain")&&this.writeLine(`${ve} ${e}\u2026`);}update(e){if(!this.currentPhaseLabel)return;if(this.currentPhaseLabel=e,this.mode==="verbose"){this.writeLine(`${ve} ${e}`);return}if(this.mode!=="spinner")return;let t=Date.now();this.pendingUpdate=e;let r=t-this.lastUpdateAt;r>=js?this.flushPendingUpdate():this.pendingUpdateTimer||(this.pendingUpdateTimer=setTimeout(()=>this.flushPendingUpdate(),js-r),this.pendingUpdateTimer.unref?.());}succeed(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",r=`${x} ${t}`;this.terminatePhase(r,"info");}fail(e,t){this.flushPendingUpdate();let r=e??this.currentPhaseLabel??"",o=`${ge} ${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(`${ve} ${e}`);}warn(e,t){if(this.logCollector.record("warn",e,t?.code),!(t?.verboseOnly&&this.mode!=="verbose")){if(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(`${W} ${e}`);}}error(e,t){this.logCollector.record("error",e,t?.code),!(t?.verboseOnly&&this.mode!=="verbose")&&this.writeLine(`${ge} ${e}`);}detail(e){this.logCollector.record("info",e),this.mode==="verbose"&&this.writeLine(` ${oe.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"?x:e==="fail"?ge:oe.muted("-")} ${e==="skip"?oe.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(),n.activeInstance===this&&(n.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(`${W} ${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(`${W} ${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+`
|
|
57
57
|
`),this.spinner.text=this.spinner.text):this.stream.write(e+`
|
|
58
|
-
`);}catch(t){let r=t?.code;if(r&&
|
|
59
|
-
`);}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(
|
|
60
|
-
Wait for it to finish, or kill it, then retry.`}function sd(n){let e=Math.max(0,n);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 Ts,mt,js=f(()=>{Ts=k.join(He.homedir(),".constellation","locks"),mt=k.join(Ts,"index.lock");});function ft(n,e){let t=e??n;return {line:t.startPosition.row+1,column:t.startPosition.column}}function gt(n){return n?n.text:null}function Dr(n,e,t){for(let r=n.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 Fs(n){let e=new Set,t=r=>{if(r.type==="export_statement"&&!ad(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(n),e}function ad(n){for(let e=0;e<n.childCount;e++){let t=n.child(e)?.type;if(t==="from"||t==="string")return true}return false}function Ms(){return {language:"javascript",handlers:new Map(Os)}}function Us(){return {language:"typescript",handlers:new Map([...Os,["interface_declaration",cd],["public_field_definition",As],["property_signature",As],["function_signature",$s],["method_signature",Ds]])}}var $s,ld,cd,Ds,As,pd,Os,Hn=f(()=>{$s=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);r&&e.symbols.push({name:r,kind:"function",...ft(n,t),isExported:Dr(n,r,e)});},ld=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);if(!r)return;let o=Dr(n,r,e);return e.symbols.push({name:r,kind:"class",...ft(n,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},cd=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);if(!r)return;let o=Dr(n,r,e);return e.symbols.push({name:r,kind:"interface",...ft(n,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},Ds=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);r&&e.symbols.push({name:r,kind:"method",...ft(n,t),isExported:e.enclosingExported??false});},As=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);r&&e.symbols.push({name:r,kind:"property",...ft(n,t),isExported:e.enclosingExported??false});},pd=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);if(!r)return;let o=n.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:r,kind:s?"function":"variable",...ft(n,t),isExported:Dr(n,r,e)});},Os=[["function_declaration",$s],["class_declaration",ld],["method_definition",Ds],["variable_declarator",pd]];});function zn(n){return {line:n.startPosition.row+1,column:n.startPosition.column}}function Wn(n){return !n.startsWith("_")}function Gs(){return {language:"python",handlers:new Map([["function_definition",ud],["class_definition",dd],["assignment",md]])}}var ud,dd,md,Bs=f(()=>{ud=(n,e)=>{let t=n.childForFieldName("name");if(!t)return;let r=t.text,o=e.enclosingType?"method":"function",s=Wn(r),a=o==="method"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...zn(t),isExported:a});},dd=(n,e)=>{let t=n.childForFieldName("name");if(!t)return;let r=t.text,o=Wn(r);return e.symbols.push({name:r,kind:"class",...zn(t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},md=(n,e)=>{let t=n.childForFieldName("left");if(!t||t.type!=="identifier")return;let r=t.text,o=e.enclosingType?"property":"variable",s=Wn(r),a=o==="property"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...zn(t),isExported:a});};});var Hs,zs=f(()=>{Hn();Bs();Hs=[Ms(),Us(),Gs()];});var Or,Ws=f(()=>{zs();Hn();Or=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??Hs)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"?Fs(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 fd(n){let e=[];for(let t=0;t<n.childCount;t++){let r=n.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 gd(n,e,t,r){let o=n.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=n.childForFieldName("import_clause"),c=l?fd(l):[];await X(a,s,e,t,r,c);}async function hd(n,e,t,r){let o=n.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await X(a,s,e,t,r,[]);}async function yd(n,e,t,r){let o=n.childForFieldName("function");if(!o||o.type!=="import")return;let s=n.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=n.startPosition.row;await X(l,c,e,t,r,[]);}function Mr(){return {language:"javascript",handlers:new Map([["import_statement",gd],["export_statement",hd],["call_expression",yd]])}}function Kn(){let n=Mr();return {language:"typescript",handlers:new Map(n.handlers)}}var Vn=f(()=>{$e();});function bd(n){let e=n.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Sd(n,e){let t=n.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 Ks(n,e,t,r){let o=n.childForFieldName("path");if(!o)return;let s=bd(o.text);if(!s)return;let a=Sd(n,s);await X(s,n.startPosition.row,e,t,r,a?[a]:[]);}async function wd(n,e,t,r){for(let o=0;o<n.namedChildCount;o++){let s=n.namedChild(o);if(s){if(s.type==="import_spec")await Ks(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 Ks(l,e,t,r);}}}}function Jn(){return {language:"go",handlers:new Map([["import_declaration",wd]]),classifyImportType:vd}}var vd,qn=f(()=>{wr();$e();wr();vd=(n,e,t)=>{if(t){let r=n.split("/")[0];return !r.includes(".")&&Sr.has(r)?"builtin":"external"}return "alias"};});function xd(n){for(let e of _d)if(n===e||n.startsWith(e+"."))return true;return false}function Ed(n,e){let t=n.childForFieldName("name");return t?{local:t.text.trim(),original:e,isDefault:false,isNamespace:true}:{local:e.split(".").pop()??e,original:e,isDefault:false,isNamespace:true}}function Pd(n){let e=null;for(let r=n.childCount-1;r>=0;r--){let o=n.child(r);if(o&&o.isNamed){e=o;break}}return e&&e.text.trim()||null}function Yn(){return {language:"c-sharp",handlers:new Map([["using_directive",Id]]),classifyImportType:Cd}}var _d,Cd,Id,Xn=f(()=>{$e();_d=["System","Microsoft.CSharp","Microsoft.VisualBasic","Microsoft.Win32"];Cd=(n,e,t)=>t?xd(n)?"builtin":"external":n.startsWith("./")||n.startsWith("../")?"relative":"alias";Id=async(n,e,t,r)=>{let o=Pd(n);if(!o)return;let s=Ed(n,o);await X(o,n.startPosition.row,e,t,r,[s]);};});var Vs,Js=f(()=>{Vn();gr();qn();Xn();$e();Vn();gr();qn();Xn();Vs=[Mr(),Kn(),Ln(),Jn(),Yn()];});var qs={};Ii(qs,{ImportExtractor:()=>Qn});var Qn,Ys=f(()=>{Js();$e();Qn=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Vs)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)??Tn,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 Dt,Xs,Zn,Qs,Zs,Ur=f(()=>{Dt=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"]),Xs=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"]),Zn={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"]},Qs={language:"javascript",textIncludedTypes:Xs,fieldNames:Zn},Zs={language:"typescript",textIncludedTypes:Xs,fieldNames:Zn};});var Rd,ea,ta,ei=f(()=>{Rd=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"]),ea={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"]},ta={language:"python",textIncludedTypes:Rd,fieldNames:ea,shouldIncludeText:n=>{if(n.type==="string"&&n.childCount>0)return false}};});var Nd,Gr,ra,Br=f(()=>{Nd=new Set(["package_identifier","field_identifier","type_identifier","predeclared_identifier","blank_identifier","label_name","nil","true","false","iota","dot"]),Gr={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"]},ra={language:"go",textIncludedTypes:Nd,fieldNames:Gr,shouldIncludeText:n=>{switch(n.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}}};});var Td,na,ia,ti=f(()=>{Td=new Set(["identifier","type_identifier","name_equals","qualified_name","predefined_type","null_literal","true","false","this_expression","base_expression","modifier"]),na={compilation_unit:[],extern_alias_directive:["name"],using_directive:["name"],namespace_declaration:["body","name"],file_scoped_namespace_declaration:["name"],global_statement:[],class_declaration:["body","name"],interface_declaration:["body","name","type_parameters"],struct_declaration:["body","name"],record_declaration:["body","name"],enum_declaration:["body","name"],delegate_declaration:["name","parameters","type","type_parameters"],method_declaration:["body","name","parameters","returns","type_parameters"],constructor_declaration:["body","name","parameters"],destructor_declaration:["body","name","parameters"],operator_declaration:["body","operator","parameters","type"],conversion_operator_declaration:["body","parameters","type"],property_declaration:["accessors","name","type","value"],indexer_declaration:["accessors","parameters","type","value"],event_declaration:["accessors","name","type"],event_field_declaration:[],field_declaration:[],enum_member_declaration:["name","value"],local_function_statement:["body","name","parameters","type","type_parameters"],variable_declaration:["type"],variable_declarator:["name"],parameter:["name","type"],parameter_list:[],bracketed_parameter_list:[],type_parameter:["name"],type_parameter_list:[],type_parameter_constraints_clause:[],generic_name:[],predefined_type:[],nullable_type:[],array_type:[],pointer_type:["type"],tuple_type:[],qualified_name:["name","qualifier"],alias_qualified_name:["alias","name"],attribute_list:[],attribute:["name"],attribute_argument:[],invocation_expression:["arguments","function"],member_access_expression:["expression","name"],element_access_expression:["expression","subscript"],conditional_access_expression:["condition"],object_creation_expression:["arguments","initializer","type"],implicit_object_creation_expression:[],cast_expression:["type","value"],lambda_expression:["body","parameters"],anonymous_method_expression:["parameters"],as_expression:["left","right"],is_expression:["left","right"],binary_expression:["left","operator","right"],prefix_unary_expression:[],postfix_unary_expression:[],assignment_expression:["left","operator","right"],conditional_expression:["alternative","condition","consequence"],is_pattern_expression:["expression","pattern"],switch_expression:[],from_clause:["name","type"],join_clause:["type"],declaration_pattern:["name","type"],constant_pattern:[],relational_pattern:[],type_pattern:["type"],property_pattern_clause:[],positional_pattern_clause:[],if_statement:["alternative","condition","consequence"],switch_statement:["body","value"],switch_section:[],for_statement:["body","condition","initializer","update"],foreach_statement:["body","left","right","type"],while_statement:["body","condition"],do_statement:["body","condition"],try_statement:["body"],catch_clause:["body"],catch_declaration:["name","type"],finally_clause:[],using_statement:[],lock_statement:[],checked_statement:[],unsafe_statement:[],fixed_statement:[],yield_statement:[],return_statement:[],throw_statement:[],throw_expression:[],break_statement:[],continue_statement:[],goto_statement:[],labeled_statement:[],initializer_expression:[],tuple_expression:[],accessor_list:[],accessor_declaration:["body","name"],arrow_expression_clause:[]},ia={language:"c-sharp",textIncludedTypes:Td,fieldNames:na,shouldIncludeText:n=>{switch(n.type){case "string_literal":case "verbatim_string_literal":case "interpolated_string_expression":case "interpolated_string_text":case "interpolated_verbatim_string_text":case "interpolation_text":case "raw_string_literal":case "character_literal":case "integer_literal":case "real_literal":case "comment":return false;default:return}}};});function oa(n){return Ot.get(n)}function sa(n){if(!n)return Dt;let e=Ot.get(n);if(!e)return Dt;let t=new Set(Dt);for(let r of e.textIncludedTypes)t.add(r);return t}function ri(n){if(!n){let t=Array.from(Ot.values()).map(r=>r.fieldNames);return Mt(...t)}let e=Ot.get(n);if(!e){let t=Array.from(Ot.values()).map(r=>r.fieldNames);return Mt(...t)}return e.fieldNames}var Ot,aa=f(()=>{ni();Ur();ei();Br();ti();Ur();Ur();ei();Br();ti();Ot=new Map([["javascript",Qs],["typescript",Zs],["python",ta],["go",ra],["c-sharp",ia]]);});var da={};Ii(da,{COMMON_FIELD_NAMES:()=>si,JS_TS_FIELD_NAMES:()=>pa,PYTHON_FIELD_NAMES:()=>ua,TEXT_INCLUDED_TYPES:()=>la,mergeFieldMaps:()=>Mt,serializeAST:()=>kd,serializeASTStream:()=>Ld});function*Ld(n,e,t){yield*oi(n,e,t);}function*oi(n,e,t){if(yield "{",yield `"type":${JSON.stringify(n.type)}`,yield `,"startPosition":${JSON.stringify({row:n.startPosition.row,column:n.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:n.endPosition.row,column:n.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),ca(n,t)&&(yield `,"text":${JSON.stringify(n.text)}`),n.childCount>0){yield ',"children":[';let o=(t?ri(t):si)[n.type]||[],s=new Set,a=true;for(let l of o){let c=n.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*oi(c,l,t));}for(let l=0;l<n.childCount;l++){let c=n.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*oi(c,void 0,t));}yield "]";}yield "}";}async function kd(n,e,t){let r=ii(n,e,t),o=t?ri(t):si,s=[{treeNode:n,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=ii(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=ii(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 ii(n,e,t){let r={type:n.type,startPosition:{row:n.startPosition.row,column:n.startPosition.column},endPosition:{row:n.endPosition.row,column:n.endPosition.column},...e&&{fieldName:e}};return ca(n,t)&&(r.text=n.text),r}function ca(n,e){if(e){let r=oa(e);if(r?.shouldIncludeText){let s=r.shouldIncludeText(n);if(s===false)return false;if(s===true)return true}return sa(e).has(n.type)||n.type.endsWith("_keyword")||n.type.endsWith("_operator")}return n.type==="string"&&n.childCount>0?false:la.has(n.type)||n.type.endsWith("_keyword")||n.type.endsWith("_operator")}function Mt(...n){let e={};for(let t of n)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 la,pa,ua,si,ni=f(()=>{aa();Br();la=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"]);pa={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"]},ua={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"]};si=Mt(pa,ua,Gr);});var Ut,fa=f(()=>{bn();ho();vo();ko();nt();Rr();gs();ys();bs();Un();q();Ps();Zt();Tt();js();oe();wn();Ws();er();Ut=class extends Ie{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 kr(process.cwd()),this.parser=new Lr(this.langRegistry),this.compressor=new $r;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=Ls(process.cwd());if(!o.ok){let d=o.reason==="held"?ks(o.holder):`Another \`constellation index\` may be running, but the lock file is in an indeterminate state. Re-run; if this persists, manually remove ${mt} and retry.`;this.reporter.error(d);let m=new Error(d);throw Ue(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 ir(this.config,d,t,this.reporter),this.reporter.log(`${Ee} Starting indexing procedure...
|
|
61
|
-
`);let m=performance.now();await this.reporter.phase("Pre-flight checks",async $=>{let D=$.step("Project access");await this.validateProject(),D.ok("Project access validated");let A=$.step("Git branch");t?A.skip("Git branch validation skipped (--dirty)"):(await this.validateGitBranch(),A.ok("Git branch validated"));let
|
|
62
|
-
`));};I=(L,G)=>{A={processed:L,total:G},wt();};let _t=(L,G,
|
|
63
|
-
${x} Upload completed in ${
|
|
64
|
-
to set or update your access key.`),
|
|
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 Se)throw this.displayProjectValidationError(e),
|
|
58
|
+
`);}catch(t){let r=t?.code;if(r&&gd.has(r))return;try{process.stderr.write(`reporter write failed: ${String(t)}
|
|
59
|
+
`);}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(zn).join(" ");this.logCollector.record("info",t),this.writeLine(t);},console.warn=(...e)=>{let t=e.map(zn).join(" ");this.logCollector.record("warn",t),this.writeLine(t);},console.error=(...e)=>{let t=e.map(zn).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 yd,Or,$s=f(()=>{vn();yd=promisify(Vn__default.gunzip),Or=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=Vn__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,yn(Buffer.concat(t)).toString("base64")}async compress(e){let t=[],r=Vn__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,yn(Buffer.concat(t)).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),r=await yd(t);return JSON.parse(r.toString("utf-8"))}};});function vd(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}function Ds(n){let e=JSON.stringify(n);try{return Oe.writeFileSync(mt,e,{flag:"wx",mode:384}),!0}catch(t){if(t.code==="EEXIST")return false;throw t}}function Jn(){let n;try{n=Oe.readFileSync(mt,"utf8");}catch{return null}try{let e=JSON.parse(n);return typeof e.pid!="number"||typeof e.projectPath!="string"||typeof e.startTime!="string"?null:e}catch{return null}}function Gs(n){Oe.mkdirSync(Us,{recursive:true,mode:448});let e={pid:process.pid,projectPath:k.resolve(n),startTime:new Date().toISOString()};if(Ds(e))return {ok:true,release:Ms(e)};let t=Jn();if(t===null||!vd(t.pid)){try{Oe.unlinkSync(mt);}catch(o){if(o.code!=="ENOENT")throw o}if(Ds(e))return {ok:true,release:Ms(e)};let r=Jn();return r!==null?{ok:false,reason:"held",holder:r}:{ok:false,reason:"indeterminate"}}return {ok:false,reason:"held",holder:t}}function Ms(n){let e=false;return ()=>{if(e)return;e=true;let t=Jn();if(!(t?.pid!==n.pid||t?.startTime!==n.startTime))try{Oe.unlinkSync(mt);}catch(r){if(r.code!=="ENOENT")throw r}}}function Bs(n){let e=Date.now()-new Date(n.startTime).getTime(),t=bd(e);return `Another \`constellation index\` is already running (pid ${n.pid}, project ${n.projectPath}, started ${t} ago).
|
|
60
|
+
Wait for it to finish, or kill it, then retry.`}function bd(n){let e=Math.max(0,n);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 Us,mt,Hs=f(()=>{Us=k.join(We.homedir(),".constellation","locks"),mt=k.join(Us,"index.lock");});function ft(n,e){let t=e??n;return {line:t.startPosition.row+1,column:t.startPosition.column}}function gt(n){return n?n.text:null}function Ur(n,e,t){for(let r=n.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 zs(n){let e=new Set,t=r=>{if(r.type==="export_statement"&&!Sd(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(n),e}function Sd(n){for(let e=0;e<n.childCount;e++){let t=n.child(e)?.type;if(t==="from"||t==="string")return true}return false}function qs(){return {language:"javascript",handlers:new Map(Js)}}function Ys(){return {language:"typescript",handlers:new Map([...Js,["interface_declaration",_d],["public_field_definition",Ws],["property_signature",Ws],["function_signature",Ks],["method_signature",Vs]])}}var Ks,wd,_d,Vs,Ws,xd,Js,qn=f(()=>{Ks=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);r&&e.symbols.push({name:r,kind:"function",...ft(n,t),isExported:Ur(n,r,e)});},wd=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);if(!r)return;let o=Ur(n,r,e);return e.symbols.push({name:r,kind:"class",...ft(n,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},_d=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);if(!r)return;let o=Ur(n,r,e);return e.symbols.push({name:r,kind:"interface",...ft(n,t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},Vs=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);r&&e.symbols.push({name:r,kind:"method",...ft(n,t),isExported:e.enclosingExported??false});},Ws=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);r&&e.symbols.push({name:r,kind:"property",...ft(n,t),isExported:e.enclosingExported??false});},xd=(n,e)=>{let t=n.childForFieldName("name"),r=gt(t);if(!r)return;let o=n.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:r,kind:s?"function":"variable",...ft(n,t),isExported:Ur(n,r,e)});},Js=[["function_declaration",Ks],["class_declaration",wd],["method_definition",Vs],["variable_declarator",xd]];});function Yn(n){return {line:n.startPosition.row+1,column:n.startPosition.column}}function Xn(n){return !n.startsWith("_")}function Xs(){return {language:"python",handlers:new Map([["function_definition",Cd],["class_definition",Ed],["assignment",Pd]])}}var Cd,Ed,Pd,Qs=f(()=>{Cd=(n,e)=>{let t=n.childForFieldName("name");if(!t)return;let r=t.text,o=e.enclosingType?"method":"function",s=Xn(r),a=o==="method"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...Yn(t),isExported:a});},Ed=(n,e)=>{let t=n.childForFieldName("name");if(!t)return;let r=t.text,o=Xn(r);return e.symbols.push({name:r,kind:"class",...Yn(t),isExported:o}),{...e,enclosingType:r,enclosingExported:o}},Pd=(n,e)=>{let t=n.childForFieldName("left");if(!t||t.type!=="identifier")return;let r=t.text,o=e.enclosingType?"property":"variable",s=Xn(r),a=o==="property"?(e.enclosingExported??false)&&s:s;e.symbols.push({name:r,kind:o,...Yn(t),isExported:a});};});var Zs,ea=f(()=>{qn();Qs();Zs=[qs(),Ys(),Xs()];});var Gr,ta=f(()=>{ea();qn();Gr=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??Zs)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"?zs(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 Id(n){let e=[];for(let t=0;t<n.childCount;t++){let r=n.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 Rd(n,e,t,r){let o=n.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=n.childForFieldName("import_clause"),c=l?Id(l):[];await K(a,s,e,t,r,c);}async function Nd(n,e,t,r){let o=n.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await K(a,s,e,t,r,[]);}async function Td(n,e,t,r){let o=n.childForFieldName("function");if(!o||o.type!=="import")return;let s=n.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=n.startPosition.row;await K(l,c,e,t,r,[]);}function Br(){return {language:"javascript",handlers:new Map([["import_statement",Rd],["export_statement",Nd],["call_expression",Td]])}}function Qn(){let n=Br();return {language:"typescript",handlers:new Map(n.handlers)}}var Zn=f(()=>{Le();});function kd(n){let e=n.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function jd(n,e){let t=n.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 ra(n,e,t,r){let o=n.childForFieldName("path");if(!o)return;let s=kd(o.text);if(!s)return;let a=jd(n,s);await K(s,n.startPosition.row,e,t,r,a?[a]:[]);}async function Ad(n,e,t,r){for(let o=0;o<n.namedChildCount;o++){let s=n.namedChild(o);if(s){if(s.type==="import_spec")await ra(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 ra(l,e,t,r);}}}}function ei(){return {language:"go",handlers:new Map([["import_declaration",Ad]]),classifyImportType:Ld}}var Ld,ti=f(()=>{wr();Le();wr();Ld=(n,e,t)=>{if(t){let r=n.split("/")[0];return !r.includes(".")&&Sr.has(r)?"builtin":"external"}return "alias"};});function $d(n){for(let e of Fd)if(n===e||n.startsWith(e+"."))return true;return false}function Md(n,e){let t=n.childForFieldName("name");return t?{local:t.text.trim(),original:e,isDefault:false,isNamespace:true}:{local:e.split(".").pop()??e,original:e,isDefault:false,isNamespace:true}}function Od(n){let e=null;for(let r=n.childCount-1;r>=0;r--){let o=n.child(r);if(o&&o.isNamed){e=o;break}}return e&&e.text.trim()||null}function ri(){return {language:"c-sharp",handlers:new Map([["using_directive",Ud]]),classifyImportType:Dd}}var Fd,Dd,Ud,ni=f(()=>{Le();Fd=["System","Microsoft.CSharp","Microsoft.VisualBasic","Microsoft.Win32"];Dd=(n,e,t)=>t?$d(n)?"builtin":"external":n.startsWith("./")||n.startsWith("../")?"relative":"alias";Ud=async(n,e,t,r)=>{let o=Od(n);if(!o)return;let s=Md(n,o);await K(o,n.startPosition.row,e,t,r,[s]);};});function Bd(n){let e=n.namedChildren.find(o=>o.type==="identifier");if(!e)return null;let r=(e.namedChildren.find(o=>o.type==="simple_identifier")??e).text.trim();return r.length>0?r:null}async function Hd(n,e,t,r){let o=Bd(n);if(!o)return;let s={local:o,original:o,isDefault:false,isNamespace:true};await K(o,n.startPosition.row,e,t,r,[s]);}function ii(){return {language:"swift",handlers:new Map([["import_declaration",Hd]]),classifyImportType:Gd}}var Gd,oi=f(()=>{Un();Le();Gd=(n,e,t)=>t?On.has(n)?"builtin":"external":"workspace";});var na,ia=f(()=>{Zn();gr();ti();ni();oi();Le();Zn();gr();ti();ni();oi();na=[Br(),Qn(),An(),ei(),ri(),ii()];});var oa={};$i(oa,{ImportExtractor:()=>si});var si,sa=f(()=>{ia();Le();si=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??na)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)??jn,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 Dt,aa,ai,la,ca,Hr=f(()=>{Dt=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"]),aa=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"]),ai={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"]},la={language:"javascript",textIncludedTypes:aa,fieldNames:ai},ca={language:"typescript",textIncludedTypes:aa,fieldNames:ai};});var Wd,pa,ua,li=f(()=>{Wd=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"]),pa={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"]},ua={language:"python",textIncludedTypes:Wd,fieldNames:pa,shouldIncludeText:n=>{if(n.type==="string"&&n.childCount>0)return false}};});var zd,Wr,da,zr=f(()=>{zd=new Set(["package_identifier","field_identifier","type_identifier","predeclared_identifier","blank_identifier","label_name","nil","true","false","iota","dot"]),Wr={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"]},da={language:"go",textIncludedTypes:zd,fieldNames:Wr,shouldIncludeText:n=>{switch(n.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}}};});var Kd,ma,fa,ci=f(()=>{Kd=new Set(["identifier","type_identifier","name_equals","qualified_name","predefined_type","null_literal","true","false","this_expression","base_expression","modifier"]),ma={compilation_unit:[],extern_alias_directive:["name"],using_directive:["name"],namespace_declaration:["body","name"],file_scoped_namespace_declaration:["name"],global_statement:[],class_declaration:["body","name"],interface_declaration:["body","name","type_parameters"],struct_declaration:["body","name"],record_declaration:["body","name"],enum_declaration:["body","name"],delegate_declaration:["name","parameters","type","type_parameters"],method_declaration:["body","name","parameters","returns","type_parameters"],constructor_declaration:["body","name","parameters"],destructor_declaration:["body","name","parameters"],operator_declaration:["body","operator","parameters","type"],conversion_operator_declaration:["body","parameters","type"],property_declaration:["accessors","name","type","value"],indexer_declaration:["accessors","parameters","type","value"],event_declaration:["accessors","name","type"],event_field_declaration:[],field_declaration:[],enum_member_declaration:["name","value"],local_function_statement:["body","name","parameters","type","type_parameters"],variable_declaration:["type"],variable_declarator:["name"],parameter:["name","type"],parameter_list:[],bracketed_parameter_list:[],type_parameter:["name"],type_parameter_list:[],type_parameter_constraints_clause:[],generic_name:[],predefined_type:[],nullable_type:[],array_type:[],pointer_type:["type"],tuple_type:[],qualified_name:["name","qualifier"],alias_qualified_name:["alias","name"],attribute_list:[],attribute:["name"],attribute_argument:[],invocation_expression:["arguments","function"],member_access_expression:["expression","name"],element_access_expression:["expression","subscript"],conditional_access_expression:["condition"],object_creation_expression:["arguments","initializer","type"],implicit_object_creation_expression:[],cast_expression:["type","value"],lambda_expression:["body","parameters"],anonymous_method_expression:["parameters"],as_expression:["left","right"],is_expression:["left","right"],binary_expression:["left","operator","right"],prefix_unary_expression:[],postfix_unary_expression:[],assignment_expression:["left","operator","right"],conditional_expression:["alternative","condition","consequence"],is_pattern_expression:["expression","pattern"],switch_expression:[],from_clause:["name","type"],join_clause:["type"],declaration_pattern:["name","type"],constant_pattern:[],relational_pattern:[],type_pattern:["type"],property_pattern_clause:[],positional_pattern_clause:[],if_statement:["alternative","condition","consequence"],switch_statement:["body","value"],switch_section:[],for_statement:["body","condition","initializer","update"],foreach_statement:["body","left","right","type"],while_statement:["body","condition"],do_statement:["body","condition"],try_statement:["body"],catch_clause:["body"],catch_declaration:["name","type"],finally_clause:[],using_statement:[],lock_statement:[],checked_statement:[],unsafe_statement:[],fixed_statement:[],yield_statement:[],return_statement:[],throw_statement:[],throw_expression:[],break_statement:[],continue_statement:[],goto_statement:[],labeled_statement:[],initializer_expression:[],tuple_expression:[],accessor_list:[],accessor_declaration:["body","name"],arrow_expression_clause:[]},fa={language:"c-sharp",textIncludedTypes:Kd,fieldNames:ma,shouldIncludeText:n=>{switch(n.type){case "string_literal":case "verbatim_string_literal":case "interpolated_string_expression":case "interpolated_string_text":case "interpolated_verbatim_string_text":case "interpolation_text":case "raw_string_literal":case "character_literal":case "integer_literal":case "real_literal":case "comment":return false;default:return}}};});var Vd,ga,ha,pi=f(()=>{Vd=new Set(["simple_identifier","class","struct","enum","actor","extension","protocol","value_binding_pattern","user_type","type_annotation","array_type","dictionary_type","optional_type","function_type","tuple_type","protocol_composition_type","opaque_type","existential_type","metatype","visibility_modifier","inheritance_modifier","member_modifier","function_modifier","property_modifier","parameter_modifier","mutation_modifier","ownership_modifier","property_behavior_modifier","self_expression","super_expression","throws"]),ga={source_file:[],import_declaration:[],class_declaration:["declaration_kind","name","body"],protocol_declaration:["declaration_kind","name","body"],class_body:[],enum_class_body:[],protocol_body:[],inheritance_specifier:["inherits_from"],type_constraints:[],type_constraint:[],inheritance_constraint:[],property_declaration:["name","value","computed_value"],function_declaration:["name","body","default_value"],init_declaration:["name","body"],deinit_declaration:["body"],subscript_declaration:["name"],associatedtype_declaration:["name"],typealias_declaration:["name"],enum_entry:["name","raw_value"],protocol_property_declaration:["name"],protocol_function_declaration:["name"],computed_property:[],parameter:["external_name","name"],type_parameters:[],type_parameter:["name"],type_annotation:[],function_type:["params","name"],tuple_type:["element"],tuple_type_item:[],user_type:[],call_expression:[],navigation_expression:["target"],navigation_suffix:["suffix"],value_arguments:[],value_argument:[]},ha={language:"swift",textIncludedTypes:Vd,fieldNames:ga,shouldIncludeText:n=>{switch(n.type){case "line_string_literal":case "multi_line_string_literal":case "raw_string_literal":case "line_str_text":case "multi_line_str_text":case "raw_str_part":case "raw_str_end_part":case "str_escaped_char":case "interpolated_expression":case "integer_literal":case "real_literal":case "hex_literal":case "oct_literal":case "bin_literal":case "boolean_literal":case "regex_literal":case "array_literal":case "dictionary_literal":case "lambda_literal":case "comment":case "multiline_comment":return false;default:return}}};});function ya(n){return Mt.get(n)}function va(n){if(!n)return Dt;let e=Mt.get(n);if(!e)return Dt;let t=new Set(Dt);for(let r of e.textIncludedTypes)t.add(r);return t}function ui(n){if(!n){let t=Array.from(Mt.values()).map(r=>r.fieldNames);return Ot(...t)}let e=Mt.get(n);if(!e){let t=Array.from(Mt.values()).map(r=>r.fieldNames);return Ot(...t)}return e.fieldNames}var Mt,ba=f(()=>{di();Hr();li();zr();ci();pi();Hr();Hr();li();zr();ci();pi();Mt=new Map([["javascript",la],["typescript",ca],["python",ua],["go",da],["c-sharp",fa],["swift",ha]]);});var Ca={};$i(Ca,{COMMON_FIELD_NAMES:()=>gi,JS_TS_FIELD_NAMES:()=>_a,PYTHON_FIELD_NAMES:()=>xa,TEXT_INCLUDED_TYPES:()=>Sa,mergeFieldMaps:()=>Ot,serializeAST:()=>qd,serializeASTStream:()=>Jd});function*Jd(n,e,t){yield*fi(n,e,t);}function*fi(n,e,t){if(yield "{",yield `"type":${JSON.stringify(n.type)}`,yield `,"startPosition":${JSON.stringify({row:n.startPosition.row,column:n.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:n.endPosition.row,column:n.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),wa(n,t)&&(yield `,"text":${JSON.stringify(n.text)}`),n.childCount>0){yield ',"children":[';let o=(t?ui(t):gi)[n.type]||[],s=new Set,a=true;for(let l of o){let c=n.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*fi(c,l,t));}for(let l=0;l<n.childCount;l++){let c=n.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*fi(c,void 0,t));}yield "]";}yield "}";}async function qd(n,e,t){let r=mi(n,e,t),o=t?ui(t):gi,s=[{treeNode:n,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=mi(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=mi(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 mi(n,e,t){let r={type:n.type,startPosition:{row:n.startPosition.row,column:n.startPosition.column},endPosition:{row:n.endPosition.row,column:n.endPosition.column},...e&&{fieldName:e}};return wa(n,t)&&(r.text=n.text),r}function wa(n,e){if(e){let r=ya(e);if(r?.shouldIncludeText){let s=r.shouldIncludeText(n);if(s===false)return false;if(s===true)return true}return va(e).has(n.type)||n.type.endsWith("_keyword")||n.type.endsWith("_operator")}return n.type==="string"&&n.childCount>0?false:Sa.has(n.type)||n.type.endsWith("_keyword")||n.type.endsWith("_operator")}function Ot(...n){let e={};for(let t of n)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 Sa,_a,xa,gi,di=f(()=>{ba();zr();Sa=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"]);_a={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"]},xa={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"]};gi=Ot(_a,xa,Wr);});var Ut,Pa=f(()=>{_n();Eo();Io();Go();it();Lr();Es();Is();Ns();Kn();X();$s();Zt();Tt();Hs();ee();Cn();ta();er();Ut=class extends Ie{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;discoveredFiles=[];parseSymbols=new Map;parseContent=new Map;symbolExtractor=new Gr;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new Fr(process.cwd()),this.parser=new Ar(this.langRegistry),this.compressor=new Or;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=Gs(process.cwd());if(!o.ok){let d=o.reason==="held"?Bs(o.holder):`Another \`constellation index\` may be running, but the lock file is in an indeterminate state. Re-run; if this persists, manually remove ${mt} and retry.`;this.reporter.error(d);let m=new Error(d);throw Ge(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 ir(this.config,d,t,this.reporter),this.reporter.log(`${Ee} Starting indexing procedure...
|
|
61
|
+
`);let m=performance.now();await this.reporter.phase("Pre-flight checks",async $=>{let D=$.step("Project access");await this.validateProject(),D.ok("Project access validated");let A=$.step("Git branch");t?A.skip("Git branch validation skipped (--dirty)"):(await this.validateGitBranch(),A.ok("Git branch validated"));let ie=$.step("Git status");t?ie.skip("Git status validation skipped (--dirty)"):(await this.validateGitStatus(),ie.ok("Working tree clean"));let Ke=$.step("Repo sync");if(t?Ke.skip("Repository sync skipped (--dirty)"):(await this.synchronizeChanges(),Ke.ok("Repository synchronized")),this.buildConfigManagers.size>0){let wt=$.step("Build configs"),_t=0;for(let[,sn]of this.buildConfigManagers.entries()){let L=await sn.initialize();_t+=L.length;}wt.ok(_t>0?`${_t} build config(s) discovered`:"No build configs discovered");}},{successText:"Pre-flight checks complete"});let g=await this.reporter.phase("Determining index scope",()=>this.determineIndexScope(e),{successText:e?"Full index":"Index scope determined"}),h=await this.git.getLatestCommitHash(),b=await this.git.getCommitTimestamp();if(g.upToDate){this.reporter.summary(`${x} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${h.substring(0,8)}`),p="succeeded";return}let y=await this.reporter.phase("Claiming indexing lock",()=>this.apiClient.claimAstLock(this.config.projectId,this.config.branch,g.isIncremental,h,b),{successText:"Indexing lock claimed"});switch(y.remapped===!0&&(y.effectiveBranchName?this.reporter.warn(`--dirty: server is indexing as default branch "${y.effectiveBranchName}" (transmitted "${this.config.branch}").`):this.reporter.warn("--dirty: server reported a branch remap but did not include the effective branch name.")),y.status){case "current":this.reporter.summary(`${x} 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(`${x} Index for this commit is already in progress on the server.`),p="succeeded";return;case "superseded":this.reporter.summary(`${x} A newer commit is already being indexed; nothing to do.`),p="succeeded";return;case "queued":if(!y.queuedAttemptId)throw new Error("Server returned queued status without an attempt ID");await this.handleQueuedUpload(y.queuedAttemptId,g.isIncremental,h,b),p="succeeded";return;default:break}let S=!1,E=()=>{S||this.reporter.detail("Uploading metadata, processing, and indexing...");},T,w,P=new Promise(($,D)=>{T=$,w=D;}),N=new AbortController,I=()=>{},v=this.createIndexPipeline(g.isIncremental,b,E,T,($,D)=>I($,D)),R=null;try{let[,$]=await this.reporter.phase("Indexing files",async D=>{let A=null,ie=new Map,Ke=new Set,wt=()=>{let L=[];if(A&&A.total>0){let G=Math.min(100,Math.round(A.processed/A.total*100));if(G===100)L.push(`${x} Baseline index complete (${A.processed}/${A.total})`);else {let z=ie?.size>0?`${Yt} `:"";L.push(`${z}Baseline index ${G}% (${A.processed}/${A.total})`);}}else L.push(`${x} Baseline index complete (${A?.processed}/${A?.total})`);for(let[G,z]of ie){if(z.total<=0)continue;let Fi=Math.min(100,Math.round(z.processed/z.total*100));Fi===100?L.push(`${x} ${re(G)} enrichment complete (${z.processed}/${z.total})`):L.push(`${Yt} ${re(G)} enrichment ${Fi}% (${z.processed}/${z.total})`);}for(let G of Ke)ie.has(G)||L.push(`${Yt} LSP (${re(G)}) initializing\u2026`);D.update(L.join(`
|
|
62
|
+
`));};I=(L,G)=>{A={processed:L,total:G},wt();};let _t=(L,G,z)=>{ie.set(L,{processed:G,total:z}),wt();},sn=(L,G)=>{G==="initializing"?Ke.add(L):(Ke.delete(L),G==="ready"&&D.step(`LSP (${re(L)}) initialized`).ok()),wt();};return Promise.all([this.uploadToAPI(v,g.isIncremental,h,y.attemptId).then(L=>(S=!0,L)).catch(L=>{throw N.abort(L),w(L),S=!0,L}),P.then(L=>{let G=this.getEnrichmentEligibleLanguages(r,L);return G?(y.attemptId&&this.apiClient.startEnrichment(y.attemptId,this.config.projectId,this.config.branch),this.runLspEnrichment(L,G,this.parseSymbols,this.parseContent,N.signal,_t,sn).catch(z=>(N.signal.aborted||this.reporter.warn(`Index enrichment failed: ${z instanceof Error?z.message:String(z)}`,{code:"ENRICHMENT_FAILED"}),null))):null}).catch(L=>(N.signal.aborted||this.reporter.warn(`Index enrichment setup failed: ${L instanceof Error?L.message:String(L)}`,{code:"ENRICHMENT_FAILED"}),null))])},{successText:"Index baseline data uploaded"});R=$;}catch($){throw S=!0,$}R&&R.length>0&&await this.reporter.phase("Enrichment upload",async()=>{try{let $=Po(R);this.reporter.detail(`Uploading enrichment data (${R.length} files)...`);let D=!1,A=null;try{D=await this.apiClient.uploadEnrichment($,this.config.projectId,this.config.branch,h);}catch(ie){A=ie;}if(D)this.reporter.detail("Enrichment data uploaded to Constellation Service, index enhancement in progress");else {let ie=A instanceof Error?`: ${A.message}`:"";this.reporter.warn(`Enrichment upload failed${ie} \u2014 re-run 'constellation index --full' after the server finishes baseline index processing to retry.`,{code:"ENRICHMENT_FAILED"});}}catch($){this.reporter.warn(`Enrichment upload failed: ${$ instanceof Error?$.message:String($)}`,{code:"ENRICHMENT_FAILED"});}},{successText:"Index enrichment data uploaded"});let V=(performance.now()-m)/1e3,ye=Math.floor(V/60),Y=(V%60).toFixed(3),O=ye>0?`${ye}m ${Y}s`:`${Y}s`;this.reporter.summary(`
|
|
63
|
+
${x} Upload completed in ${O}! Server indexing in progress.`),p="succeeded";}catch(d){if(d instanceof Se)throw d;if(d instanceof Fe){this.logIndexingInProgress(d.branchName||this.config?.branch),p="succeeded";return}if(d instanceof H)throw xe(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.`),Ge(d)),d;if(d instanceof Ne)throw d;if(d instanceof Error&&d.message==="Access key not configured")throw Ge(d),d;if(xe(d))throw d;let m=d instanceof Error?d.message:"An unexpected error occurred";throw this.reporter.error(`Indexing failed: ${m}`),Ge(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",g=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,h=this.reporter.getReportableErrors();if(!m&&g&&h.length>0){let b=this.reporter.getEntries(),y=h.map(I=>({type:"CLI_ERROR",message:I.message,phase:"indexing"})).slice(0,100),S=b.filter(I=>I.level==="warn").map(I=>({type:"CLI_WARNING",message:I.message,phase:"indexing"})).slice(0,100),E=y.length,T=S.length,w=[];E>0&&w.push(`${E} error${E!==1?"s":""}`),T>0&&w.push(`${T} warning${T!==1?"s":""}`);let P=w.join(", "),N=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:P,errorData:{errors:y,warnings:S},logEntries:b.slice(0,1e3),cliVersion:N,outcome:p,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(Pe);if(!e)throw this.reporter.error("Access key not found.",{code:"ACCESS_KEY_MISSING"}),this.reporter.info(`Set the ${Pe} 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 Se)throw this.displayProjectValidationError(e),Ge(e),e;if(e instanceof Re){this.reporter.detail("Project validated (first index)");return}if(e instanceof H)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.
|
|
66
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.
|
|
67
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
|
|
68
68
|
`);break;case "PROJECT_INACTIVE":this.reporter.error("Project is inactive",{code:"PROJECT_INACTIVE"}),this.reporter.log(` The project "${r}" has been deactivated.
|
|
@@ -80,25 +80,25 @@ To resolve:`),this.reporter.log(" 1. Fix the conflicted files manually"),this.r
|
|
|
80
80
|
Please check your internet connection and try again
|
|
81
81
|
`):e.message.includes("Authentication")&&this.reporter.log(`
|
|
82
82
|
Please check your git credentials and try again
|
|
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 H)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?`${ve} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${ve} Removing ${l} deleted file(s) from graph`;this.reporter.log(u),await this.apiClient.deleteFiles(a);}}}catch(r){if(r instanceof H)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 Qe(u,{preserveOrder:true}).run(e,async(m,g)=>{let h=Math.round((g+1)/s*100);this.reporter.detail(`Analyzing file ${m.path.replace(process.cwd()+"/","")} (${h}%)...`);try{let{tree:b,classificationMap:y,content:S}=await this.parser.parseFile(m.path,m.language),E=this.symbolExtractor.extract(b,m.language);E.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(m.relativePath),E),S!==void 0&&this.parseContent.set(this.normalizePathToCanonical(m.relativePath),S),y.entries.length>5e4&&this.reporter.warn(`Large classification map for ${m.relativePath}: ${y.entries.length} entries`);let w=this.langRegistry.getPlugin(m.language),P;if(w?.getImportResolver){let K=this.buildConfigManagers.get(m.language),ye=K?await K.getConfigForFile(m.path):null,J=w.getImportResolver(m.path,ye);if(J){let{ImportExtractor:M}=await Promise.resolve().then(()=>(Ys(),qs));P=await new M().extractImportResolutions(b,m.path,m.language,J);}}let{serializeASTStream:N}=await Promise.resolve().then(()=>(ni(),da)),I=N(b.rootNode,void 0,m.language),v=await this.compressor.compressStream(I),R=this.normalizePathToCanonical(m.relativePath),_={file:R,language:m.language,commit:c,timestamp:t,ast:v,importResolutions:P,classificationMap:{filePath:R,entries:y.entries}},O=vs.safeParse(_);if(!O.success)throw new Error(`Index validation failed: ${O.error.issues[0].message}`);return a++,o?.(a,s),O.data}catch(b){throw l++,o?.(a+l,s),this.reporter.warn(`Failed to parse ${m.relativePath}: ${b.message}`,{code:"PARSE_FAILURE"}),b}});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 ar(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||Te.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 r=new Set(t.map(s=>s.language)),o=[...r].filter(s=>this.isLanguageLspEligible(s));if(o.length===0){let s=[...r].filter(a=>a).map(te).join(", ");return this.reporter.detail(s?`Index enrichment skipped: no LSP enrichment configured for scanned language(s): ${s}`:"Index enrichment skipped: no language-tagged files were found to enrich"),null}return this.reporter.detail(`Index enrichment enabled for: ${o.map(te).join(", ")}`),new Set(o)}async runLspEnrichment(e,t,r,o,s,a,l){let c=this.reporter,u={log:d=>c.detail(d),warn:d=>c.warn(d,{verboseOnly:true}),error:d=>c.error(d,{verboseOnly:true})},p=new ur(process.cwd(),u);try{if(s?.aborted)return null;this.reporter.detail("Starting index enrichment...");let d=new Map,m=new Map;for(let w of e){if(!t.has(w.language))continue;let P=d.get(w.language)||[];P.push(this.normalizePathToCanonical(w.relativePath)),d.set(w.language,P);}let g=d.size,h=!1;for(let w of [...d.keys()]){if(s?.aborted)return null;let P=this.langRegistry?.getPlugin(w);if(!P?.preflightLsp)continue;let N;try{N=await P.preflightLsp(process.cwd());}catch(I){let v=I instanceof Error?I.message:String(I);this.reporter.warn(`LSP pre-flight failed for ${te(w)} (${v}); proceeding without skip.`);continue}N.skip&&(this.reporter.warn(N.message),d.delete(w),h=!0);}let b=h&&d.size===0&&g>0;for(let w of d.keys()){if(m.has(w))continue;let N=this.config.languages[w]?.lsp;l?.(w,"initializing");let I=null;try{I=await p.startServer(w,N),I&&m.set(w,I);}finally{l?.(w,I?"ready":"failed");}}if(m.size===0)return b||this.reporter.warn("No language servers started, index enrichment skipped"),null;if(s?.aborted)return p.destroyAll(),null;this.reporter.detail(`Language servers started: ${[...m.keys()].map(te).join(", ")}`);let y=new lr(process.cwd(),this.reporter),S=s?new Promise((w,P)=>{s.addEventListener("abort",()=>{p.destroyAll(),P(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,E=await(S?Promise.race([y.enrich(d,r,m,o,a),S]):y.enrich(d,r,m,o,a)),T=E.reduce((w,P)=>w+P.symbols.length,0);return this.reporter.detail(`Index enrichment analysis completed: ${T} symbols across ${E.length} files`),E.length>0?E:null}catch(d){return this.reporter.warn(`Index enrichment failed: ${d instanceof Error?d.message:String(d)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await p.shutdownAll();}}};});function ai(n){return stringify({name:"Constellation Index",on:{push:{branches:[n]}},permissions:{contents:"read"},jobs:{index:{"runs-on":"ubuntu-latest",steps:[{uses:"actions/checkout@v4",with:{"fetch-depth":0}},{uses:"ShiftinBits/constellation-github@v1",with:{"access-key":"${{ secrets.CONSTELLATION_ACCESS_KEY }}"}}]}}},{lineWidth:0})}function Hr(n){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{variables:{GIT_DEPTH:"0"},rules:[{if:`$CI_COMMIT_BRANCH == "${n}"`}]}}}function zr(n){let{includeEntry:e,job:t}=Hr(n);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var li=f(()=>{});var Gt,ya=f(()=>{le();li();Gt=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,r]=await Promise.all([C.directoryExists(k__default.join(this.gitRoot,".github","workflows")),C.fileIsReadable(k__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),r&&e.push("gitlab"),e}async githubWorkflowExists(){return C.fileIsReadable(k__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=k__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(e))return false;try{let r=await C.readFile(e),s=parseDocument(r).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=k__default.join(this.gitRoot,".github","workflows");await se__default.mkdir(t,{recursive:true});let r=k__default.join(t,"constellation-index.yml");return await C.writeFile(r,ai(e)),r}async createOrMergeGitLabCI(e){let t=k__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(t))return await C.writeFile(t,zr(e)),t;let o=await C.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await C.writeFile(t,zr(e)),t;let{includeEntry:a,job:l}=Hr(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await C.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 va=f(()=>{ya();li();});function pi(n){if(n.installedBinaryPath!==void 0)return existsSync(n.installedBinaryPath)?{ok:true,path:n.installedBinaryPath}:{ok:false,reason:"not-installed"};if(!ae(n.prerequisite))return {ok:false,reason:"not-installed"};let e;try{e=execFileSync(n.verifyCommand[0],[...n.verifyCommand.slice(1)],{stdio:["ignore","pipe","pipe"],timeout:Md,maxBuffer:Od}).toString();}catch{return {ok:false,reason:"not-installed"}}let t=e.trim().split(/\r?\n/)[0]?.trim()??"";if(!t||!k.isAbsolute(t))return {ok:false,reason:"invalid-stdout"};let r=k.resolve(n.allowedRootPrefix),o;try{o=realpathSync(t);}catch{return {ok:false,reason:"not-installed"}}return o!==r&&!o.startsWith(r+k.sep)?{ok:false,reason:"untrusted-path"}:{ok:true,path:o}}var Od,Md,ba=f(()=>{le();Od=4096,Md=1e4;});function Sa(n,e){let t=He__default.homedir(),r=process.platform,o=Gd[n];switch(r){case "darwin":return k__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return k__default.join(process.env.APPDATA||k__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return k__default.join(t,".config",o,"User/globalStorage",e)}}function wa(){let n="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:k__default.join(Sa(t,n),"settings","cline_mcp_settings.json")}))}function _a(){return k__default.join(Sa("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Gd,xa=f(()=>{Gd={stable:"Code",insiders:"Code - Insiders"};});function Ea(n){return ui.find(e=>e.id===n)}var Ca,Bd,ui,di=f(()=>{xa();Ca={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Bd={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"},autoUpdate:true}},enabledPlugins:{"constellation@constellation-plugins":true}},ui=[{id:"antigravity",displayName:"Antigravity CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"agy",args:["plugin","install","https://github.com/ShiftinBits/constellation-antigravity"]}},{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:Bd},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:_a(),isGlobalConfig:true,getGlobalConfigPaths:wa,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"},featureFlagsConfig:{flagKeyPath:["features","hooks"],deprecatedRootKeys:["codex_hooks"]}},{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:"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 Pa(){if(!mi)try{let n=await import('@iarna/toml');mi={parse:n.parse,stringify:n.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return mi}function Wd(n){let e="",t=0,r=n.length;for(;t<r;)if(n[t]==='"'){for(e+='"',t++;t<r&&n[t]!=='"';)n[t]==="\\"?(e+=n[t++],t<r&&(e+=n[t++])):e+=n[t++];t<r&&(e+=n[t++]);}else if(n[t]==="/"&&t+1<r&&n[t+1]==="/")for(t+=2;t<r&&n[t]!==`
|
|
84
|
-
`;)t++;else if(n[t]==="/"&&t+1<r&&n[t+1]==="*"){for(t+=2;t<r&&!(n[t]==="*"&&t+1<r&&n[t+1]==="/");)t++;t<r&&(t+=2);}else e+=n[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 H)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?`${ve} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${ve} Removing ${l} deleted file(s) from graph`;this.reporter.log(u),await this.apiClient.deleteFiles(a);}}}catch(r){if(r instanceof H)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 Ze(u,{preserveOrder:true}).run(e,async(m,g)=>{let h=Math.round((g+1)/s*100);this.reporter.detail(`Analyzing file ${m.path.replace(process.cwd()+"/","")} (${h}%)...`);try{let{tree:b,classificationMap:y,content:S}=await this.parser.parseFile(m.path,m.language),E=this.symbolExtractor.extract(b,m.language);E.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(m.relativePath),E),S!==void 0&&this.parseContent.set(this.normalizePathToCanonical(m.relativePath),S),y.entries.length>5e4&&this.reporter.warn(`Large classification map for ${m.relativePath}: ${y.entries.length} entries`);let w=this.langRegistry.getPlugin(m.language),P;if(w?.getImportResolver){let V=this.buildConfigManagers.get(m.language),ye=V?await V.getConfigForFile(m.path):null,Y=w.getImportResolver(m.path,ye);if(Y){let{ImportExtractor:O}=await Promise.resolve().then(()=>(sa(),oa));P=await new O().extractImportResolutions(b,m.path,m.language,Y);}}let{serializeASTStream:N}=await Promise.resolve().then(()=>(di(),Ca)),I=N(b.rootNode,void 0,m.language),v=await this.compressor.compressStream(I),R=this.normalizePathToCanonical(m.relativePath),_={file:R,language:m.language,commit:c,timestamp:t,ast:v,importResolutions:P,classificationMap:{filePath:R,entries:y.entries}},M=Rs.safeParse(_);if(!M.success)throw new Error(`Index validation failed: ${M.error.issues[0].message}`);return a++,o?.(a,s),M.data}catch(b){throw l++,o?.(a+l,s),this.reporter.warn(`Failed to parse ${m.relativePath}: ${b.message}`,{code:"PARSE_FAILURE"}),b}});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 ar(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||Te.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 r=new Set(t.map(s=>s.language)),o=[...r].filter(s=>this.isLanguageLspEligible(s));if(o.length===0){let s=[...r].filter(a=>a).map(re).join(", ");return this.reporter.detail(s?`Index enrichment skipped: no LSP enrichment configured for scanned language(s): ${s}`:"Index enrichment skipped: no language-tagged files were found to enrich"),null}return this.reporter.detail(`Index enrichment enabled for: ${o.map(re).join(", ")}`),new Set(o)}async runLspEnrichment(e,t,r,o,s,a,l){let c=this.reporter,u={log:d=>c.detail(d),warn:d=>c.warn(d,{verboseOnly:true}),error:d=>c.error(d,{verboseOnly:true})},p=new ur(process.cwd(),u);try{if(s?.aborted)return null;this.reporter.detail("Starting index enrichment...");let d=new Map,m=new Map;for(let w of e){if(!t.has(w.language))continue;let P=d.get(w.language)||[];P.push(this.normalizePathToCanonical(w.relativePath)),d.set(w.language,P);}let g=d.size,h=!1;for(let w of [...d.keys()]){if(s?.aborted)return null;let P=this.langRegistry?.getPlugin(w);if(!P?.preflightLsp)continue;let N;try{N=await P.preflightLsp(process.cwd());}catch(I){let v=I instanceof Error?I.message:String(I);this.reporter.warn(`LSP pre-flight failed for ${re(w)} (${v}); proceeding without skip.`);continue}N.skip&&(this.reporter.warn(N.message),d.delete(w),h=!0);}let b=h&&d.size===0&&g>0;for(let w of d.keys()){if(m.has(w))continue;let N=this.config.languages[w]?.lsp;l?.(w,"initializing");let I=null;try{I=await p.startServer(w,N),I&&m.set(w,I);}finally{l?.(w,I?"ready":"failed");}}if(m.size===0)return b||this.reporter.warn("No language servers started, index enrichment skipped"),null;if(s?.aborted)return p.destroyAll(),null;this.reporter.detail(`Language servers started: ${[...m.keys()].map(re).join(", ")}`);let y=new lr(process.cwd(),this.reporter),S=s?new Promise((w,P)=>{s.addEventListener("abort",()=>{p.destroyAll(),P(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,E=await(S?Promise.race([y.enrich(d,r,m,o,a),S]):y.enrich(d,r,m,o,a)),T=E.reduce((w,P)=>w+P.symbols.length,0);return this.reporter.detail(`Index enrichment analysis completed: ${T} symbols across ${E.length} files`),E.length>0?E:null}catch(d){return this.reporter.warn(`Index enrichment failed: ${d instanceof Error?d.message:String(d)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await p.shutdownAll();}}};});function hi(n){return stringify({name:"Constellation Index",on:{push:{branches:[n]}},permissions:{contents:"read"},jobs:{index:{"runs-on":"ubuntu-latest",steps:[{uses:"actions/checkout@v4",with:{"fetch-depth":0}},{uses:"ShiftinBits/constellation-github@v1",with:{"access-key":"${{ secrets.CONSTELLATION_ACCESS_KEY }}"}}]}}},{lineWidth:0})}function Kr(n){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{variables:{GIT_DEPTH:"0"},rules:[{if:`$CI_COMMIT_BRANCH == "${n}"`}]}}}function Vr(n){let{includeEntry:e,job:t}=Kr(n);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var yi=f(()=>{});var Gt,Na=f(()=>{le();yi();Gt=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,r]=await Promise.all([C.directoryExists(k__default.join(this.gitRoot,".github","workflows")),C.fileIsReadable(k__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),r&&e.push("gitlab"),e}async githubWorkflowExists(){return C.fileIsReadable(k__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=k__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(e))return false;try{let r=await C.readFile(e),s=parseDocument(r).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=k__default.join(this.gitRoot,".github","workflows");await se__default.mkdir(t,{recursive:true});let r=k__default.join(t,"constellation-index.yml");return await C.writeFile(r,hi(e)),r}async createOrMergeGitLabCI(e){let t=k__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(t))return await C.writeFile(t,Vr(e)),t;let o=await C.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await C.writeFile(t,Vr(e)),t;let{includeEntry:a,job:l}=Kr(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await C.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 Ta=f(()=>{Na();yi();});function bi(n){if(n.installedBinaryPath!==void 0)return existsSync(n.installedBinaryPath)?{ok:true,path:n.installedBinaryPath}:{ok:false,reason:"not-installed"};if(!ae(n.prerequisite))return {ok:false,reason:"not-installed"};let e;try{e=execFileSync(n.verifyCommand[0],[...n.verifyCommand.slice(1)],{stdio:["ignore","pipe","pipe"],timeout:rm,maxBuffer:tm}).toString();}catch{return {ok:false,reason:"not-installed"}}let t=e.trim().split(/\r?\n/)[0]?.trim()??"";if(!t||!k.isAbsolute(t))return {ok:false,reason:"invalid-stdout"};let r=k.resolve(n.allowedRootPrefix),o;try{o=realpathSync(t);}catch{return {ok:false,reason:"not-installed"}}return o!==r&&!o.startsWith(r+k.sep)?{ok:false,reason:"untrusted-path"}:{ok:true,path:o}}var tm,rm,La=f(()=>{le();tm=4096,rm=1e4;});function ka(n,e){let t=We__default.homedir(),r=process.platform,o=im[n];switch(r){case "darwin":return k__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return k__default.join(process.env.APPDATA||k__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return k__default.join(t,".config",o,"User/globalStorage",e)}}function ja(){let n="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:k__default.join(ka(t,n),"settings","cline_mcp_settings.json")}))}function Aa(){return k__default.join(ka("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var im,Fa=f(()=>{im={stable:"Code",insiders:"Code - Insiders"};});function Da(n){return Si.find(e=>e.id===n)}var $a,om,Si,wi=f(()=>{Fa();$a={command:"npx",args:["-y","@constellationdev/mcp@latest"]},om={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"},autoUpdate:true}},enabledPlugins:{"constellation@constellation-plugins":true}},Si=[{id:"antigravity",displayName:"Antigravity CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"agy",args:["plugin","install","https://github.com/ShiftinBits/constellation-antigravity"]}},{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:om},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Aa(),isGlobalConfig:true,getGlobalConfigPaths:ja,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"},featureFlagsConfig:{flagKeyPath:["features","hooks"],deprecatedRootKeys:["codex_hooks"]}},{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:"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 Ma(){if(!_i)try{let n=await import('@iarna/toml');_i={parse:n.parse,stringify:n.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return _i}function lm(n){let e="",t=0,r=n.length;for(;t<r;)if(n[t]==='"'){for(e+='"',t++;t<r&&n[t]!=='"';)n[t]==="\\"?(e+=n[t++],t<r&&(e+=n[t++])):e+=n[t++];t<r&&(e+=n[t++]);}else if(n[t]==="/"&&t+1<r&&n[t+1]==="/")for(t+=2;t<r&&n[t]!==`
|
|
84
|
+
`;)t++;else if(n[t]==="/"&&t+1<r&&n[t+1]==="*"){for(t+=2;t<r&&!(n[t]==="*"&&t+1<r&&n[t+1]==="/");)t++;t<r&&(t+=2);}else e+=n[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var _i,Jr,Oa=f(()=>{le();wi();_i=null;Jr=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=k__default.join(this.cwd,e.configPath),r=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults||!!e.featureFlagsConfig;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.featureFlagsConfig&&this.applyFeatureFlags(s,e.featureFlagsConfig),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=k__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=k__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=k__default.dirname(e);await se__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await C.fileIsReadable(e))return {};let o=await C.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(lm(o)):(await Ma()).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??$a,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 Ma()).stringify(t),o=o.replace(/\r\n/g,`
|
|
85
85
|
`),o.endsWith(`
|
|
86
86
|
`)||(o+=`
|
|
87
87
|
`),await C.writeFile(e,o);}async configurePermissions(e){let t=k__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await C.fileIsReadable(t)){let c=await C.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 C.writeFile(t,JSON.stringify(r,null," ")+`
|
|
88
88
|
`);}async configureMarketplace(e){let t=k__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await C.fileIsReadable(t)){let s=await C.readFile(t);r=JSON.parse(s);}}catch{}r=this.deepMerge(r,e.config),await C.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}applyFeatureFlags(e,t){let{flagKeyPath:r,deprecatedRootKeys:o}=t,s=e;for(let a=0;a<r.length-1;a++){let l=r[a];(!s[l]||typeof s[l]!="object")&&(s[l]={}),s=s[l];}s[r[r.length-1]]=true;for(let a of o??[])delete e[a];}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(/^~/,
|
|
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=k__default.join(process.cwd(),"constellation.json"),o=null,s=await C.fileIsReadable(r);if(s)try{let v=await C.readFile(r);o=JSON.parse(v),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(v=>v!==p),m=p?[p,...d]:d,g=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:v=>v.trim().length>0||"Project ID is required",theme:B}),h=await select({message:"Branch to index:",choices:m.map(v=>({name:v,value:v})),default:o?.branch??m[0],theme:B}),y=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:B})).reduce((v,R)=>(v[R]={fileExtensions:
|
|
91
|
-
${r}`);}}async installManualOnlyServer(e,t,r,o,s,a,l){let c=h=>l.push({lang:e,command:r.command,outcome:h}),u=
|
|
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:B}))return;let o=new Gt(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:B}))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:B});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:B})){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=
|
|
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}applyFeatureFlags(e,t){let{flagKeyPath:r,deprecatedRootKeys:o}=t,s=e;for(let a=0;a<r.length-1;a++){let l=r[a];(!s[l]||typeof s[l]!="object")&&(s[l]={}),s=s[l];}s[r[r.length-1]]=true;for(let a of o??[])delete e[a];}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(/^~/,We__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 qr(n,e){let t=k__default.normalize(n),r=k__default.normalize(e);return t.startsWith(r+k__default.sep)?k__default.relative(e,n):n}var mm,Bt,Ha=f(()=>{Ta();it();La();Nn();Lr();Oa();wi();le();X();er();Xt();mm=promisify(execFile);Bt=class extends Ie{async run(e={}){try{if(this.reporter.log(`${Ee} 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=k__default.join(process.cwd(),"constellation.json"),o=null,s=await C.fileIsReadable(r);if(s)try{let v=await C.readFile(r);o=JSON.parse(v),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(v=>v!==p),m=p?[p,...d]:d,g=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:v=>v.trim().length>0||"Project ID is required",theme:B}),h=await select({message:"Branch to index:",choices:m.map(v=>({name:v,value:v})),default:o?.branch??m[0],theme:B}),y=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:B})).reduce((v,R)=>(v[R]={fileExtensions:ke[R]||[]},v),{});this.reporter.log(""),this.reporter.info("Checking for LSP servers...");let S=(await this.env?.getKey("CONSTELLATION_AUTO_INSTALL_LSP")??"").trim().toLowerCase(),E=["1","true","yes","on"].includes(S),T=this.env?.isCI()??!1,w=[];for(let[v,R]of Object.entries(y)){let _=Te.get(v);if(!_)continue;let M=!1,V="";if(ae(_.command)&&(M=!0,V="system"),!M){let O=k__default.join(nt,_.command);existsSync(O)&&(M=!0,V="managed");}let ye=_.manualInstall?.autoInstall,Y;if(!M&&ye){let O=bi(ye);O.ok&&(Y=O.path,M=!0,V="managed");}if(M)this.reporter.log(`${x} ${v}: Found ${_.command} (${V})`),R.lsp={command:V==="managed"&&Y!==void 0?Y:_.command,args:_.args};else if(_.npmPackages.length===0&&_.manualInstall){let O=_.manualInstall.autoInstall;if(O&&ae(O.prerequisite)){if(O.installedBinaryPath!==void 0){let D=k__default.resolve(rt),A=k__default.resolve(O.installedBinaryPath);if(!A.startsWith(D+k__default.sep)){this.reporter.error(`${v}: installedBinaryPath (${A}) is outside the managed directory; refusing to install. Report this as a bug.`),R.lspEnrichment=!1;continue}}if(await confirm({message:`${v}: ${_.command} not found. Install via \`${_.manualInstall.command}\`?`,default:!0,theme:B}))try{this.reporter.info(`${v}: Installing ${_.command} via \`${O.argv.join(" ")}\` (this may take a minute)...`),execFileSync(O.argv[0],[...O.argv.slice(1)],{stdio:"pipe",env:{...process.env,...O.env??{}}});let D=bi(O);D.ok?(this.reporter.log(`${x} ${v}: Installed ${_.command} (${D.path})`),R.lsp={command:D.path,args:_.args}):D.reason==="untrusted-path"?(this.reporter.error(`${v}: Install completed but the resolved binary path is outside the allowed prefix; refusing to wire it. Report this as a bug.`),R.lspEnrichment=!1):D.reason==="invalid-stdout"?(this.reporter.error(`${v}: Install completed but the verify command produced no usable absolute path. Try running manually: \`${_.manualInstall.command}\`.`),R.lspEnrichment=!1):(this.reporter.error(`${v}: Install command exited 0 but ${_.command} wasn't found afterwards. Try running manually: \`${_.manualInstall.command}\`.`),R.lspEnrichment=!1);}catch(D){let A=D.stderr?.toString().trim();this.reporter.error(`${v}: Installation failed${A?`: ${A}`:""}`),R.lspEnrichment=!1;}else this.reporter.info(`${v}: To install manually: \`${_.manualInstall.command}\``),this.reporter.info(`${v}: Indexing will continue without LSP enrichment.`),R.lspEnrichment=!1;}else _.manualInstall.verifyToolchain?await this.installManualOnlyServer(v,R,_,_.manualInstall,_.manualInstall.verifyToolchain,{autoInstall:E,nonInteractive:T},w):(this.reporter.info(`${v}: ${_.command} not found. Requires ${_.manualInstall.requires}. Install with: ${_.manualInstall.command}`),_.manualInstall.pathNote&&this.reporter.info(`${v}: ${_.manualInstall.pathNote}`),this.reporter.info(`${v}: Indexing will continue without LSP enrichment.`),R.lspEnrichment=!1);}else if(await confirm({message:`${v}: ${_.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:B}))try{this.reporter.info(`Installing ${_.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",rt,..._.npmPackages],{stdio:"pipe"}),this.reporter.log(`${x} ${v}: Installed ${_.command}`),R.lsp={command:_.command,args:_.args};}catch{this.reporter.error(`${v}: Installation failed`),R.lspEnrichment=!1;}else R.lspEnrichment=!1;}if(w.length>0){let v=ye=>w.filter(Y=>ye.includes(Y.outcome)).map(Y=>Y.command).join(", "),R=v(["installed","installed-pathnote"]),_=v(["already-installed"]),M=v(["prereq-missing","prereq-too-old","declined","ci-skipped"]),V=v(["failed"]);R&&this.reporter.info(`LSP servers installed: ${R}`),_&&this.reporter.info(`LSP servers already present: ${_}`),M&&this.reporter.info(`LSP servers skipped: ${M}`),V&&this.reporter.warn(`LSP servers failed to install: ${V}`);}let P=Object.entries(y).filter(([,v])=>v.lspEnrichment!==!1).map(([v])=>v);P.length>0?this.reporter.log(`${x} Index enrichment enabled for: ${P.map(re).join(", ")}`):this.reporter.warn("No language servers configured. Index enrichment will be skipped.");let N={projectId:g.trim(),branch:h,languages:{...y},...P.length>0&&{lspEnrichment:!0}},I=JSON.stringify(N,void 0,2);await C.writeFile(r,I),this.reporter.log(`${x} ${s?"Updated":"Initialized"} configuration file at ${qr(r,process.cwd())}`),await this.git.stageFile(r),this.reporter.log(`${x} 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 installManualOnlyServer(e,t,r,o,s,a,l){let c=h=>l.push({lang:e,command:r.command,outcome:h}),u=Rn(r);if(u){this.reporter.log(`${x} ${e}: Already installed ${r.command}`),t.lsp={command:u,args:r.args},c("already-installed");return}let p=Lo(s);if(!p.ok){if(p.reason==="missing"){this.reporter.info(`${e}: ${r.command} install skipped \u2014 ${o.requires} required (not detected). Install it, then re-run \`constellation init\`.`),t.lspEnrichment=false,c("prereq-missing");return}if(p.reason==="too-old"){this.reporter.info(`${e}: ${r.command} install skipped \u2014 detected ${p.detected}, requires ${p.required} or later.`),t.lspEnrichment=false,c("prereq-too-old");return}t.lspEnrichment=false,c("prereq-missing");return}if(a.nonInteractive&&!a.autoInstall){this.reporter.info(`${e}: ${r.command} not installed \u2014 non-interactive run cannot prompt. Install manually with \`${o.command}\` or set CONSTELLATION_AUTO_INSTALL_LSP=1 to bypass the prompt.`),c("ci-skipped");return}if(!(a.autoInstall||await confirm({message:`${e}: ${r.command} not found. Required for ${re(e)} LSP enrichment. Install with \`${o.command}\`?`,default:true,theme:B}))){this.reporter.info(`${e}: skipped \u2014 indexing will continue without LSP enrichment.`),t.lspEnrichment=false,c("declined");return}this.reporter.info(`${e}: Installing ${r.command} via \`${o.command}\`...`);let m=ko(r);if(!m.ok){"exitCode"in m?(this.reporter.error(`${e}: ${r.command} install failed (exit ${m.exitCode??"unknown"}). Run \`${o.command}\` manually for details.`),m.stderr&&this.reporter.detail(`${e}: install stderr: ${m.stderr}`)):(this.reporter.error(`${e}: ${r.command} install failed to start. Run \`${o.command}\` manually for details.`),this.reporter.detail(`${e}: install error: ${m.spawnError}`)),t.lspEnrichment=false,c("failed");return}let g=Rn(r);if(g){this.reporter.log(`${x} ${e}: Installed ${r.command} (${g})`),t.lsp={command:g,args:r.args},c("installed");return}this.reporter.info(`${e}: ${r.command} installed but not yet on PATH.`),o.pathNote&&this.reporter.info(`${e}: ${o.pathNote}`),c("installed-pathnote");}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:B}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:Si.map(p=>({name:p.displayName,value:p.id})),required:true,theme:B}),r=new Jr(process.cwd()),o=[];for(let p of t){let d=Da(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(`${x} ${d.displayName} plugin installed successfully`):this.reporter.warn(`${d.displayName}: ${m.error}`);}else if(d.isGlobalConfig&&d.getGlobalConfigPaths){let m=await r.configureGlobalTool(d),g=false;for(let h of m)o.push(h),h.success?(g=true,this.reporter.log(`${x} ${h.tool.displayName} configured at ${qr(h.configuredPath,process.cwd())}`)):h.error&&this.reporter.warn(`${h.tool.displayName}: ${h.error}`);if(g){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(`${x} ${d.displayName} configured at ${qr(m.configuredPath,process.cwd())}`),d.permissionsConfig&&this.reporter.log(`${x} ${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=k__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),this.reporter.log(`${x} 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=k__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),this.reporter.log(`${x} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=k__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),this.reporter.log(`${x} 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(`${x} 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(this.isAlreadyInstalledError(o)){let s=(e.pluginPostInstallCommands?.length??0)>0;this.reporter.info(s?`${e.displayName} plugin source already configured, continuing...`:`${e.displayName} plugin already installed`);}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 mm(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:B}))return;let o=new Gt(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:B}))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:B});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:B})){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=qr(c,process.cwd());a==="github"?this.reporter.log(`${x} Created ${u}`):this.reporter.log(`${x} ${l?"Updated":"Created"} ${u} with Constellation indexing`);try{await this.git.stageFile(c),this.reporter.log(`${x} 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:
|
|
93
93
|
Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret
|
|
94
94
|
Name: CONSTELLATION_ACCESS_KEY`):this.reporter.info(`Add your access key as a CI/CD variable:
|
|
95
95
|
Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable
|
|
96
|
-
Key: CONSTELLATION_ACCESS_KEY`);}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"C#",value:"c-sharp"},{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
|
|
97
|
-
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},
|
|
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}}},
|
|
96
|
+
Key: CONSTELLATION_ACCESS_KEY`);}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"C#",value:"c-sharp"},{name:"Go",value:"go"},{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"Swift",value:"swift"},{name:"TypeScript",value:"typescript"}].map(r=>({...r,checked:t.includes(r.value)}))}};});var Yr,Wa=f(()=>{_n();Tt();le();X();Yr=class n{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 C.fileIsReadable(e)){let r=await C.readFile(e),o=JSON.parse(r),s=new n(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${ge} 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 Ne("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new Ne(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var Qr,xi,Zr,Ci,Ei,Pi,en,za=f(()=>{le();Qr=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,"\\$&")}},xi=class extends Qr{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}}},Zr=class extends Qr{userConfigFiles;constructor(){super(),this.userConfigFiles=[k.join(We.homedir(),".zshenv"),k.join(We.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
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 C.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()+`
|
|
100
100
|
`+r+`
|
|
101
|
-
`,await C.writeFile(e,o);}async assertSafeWriteTarget(e){try{let t=await se__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}}},
|
|
101
|
+
`,await C.writeFile(e,o);}async assertSafeWriteTarget(e){try{let t=await se__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}}},Ci=class n extends Zr{static LAUNCH_AGENT_LABEL="io.constellationdev.env";launchAgentDir;launchAgentScriptDir;launchAgentLogDir;launchAgentPlistPath;launchAgentScriptPath;launchAgentStderrPath;constructor(){super();let e=We.homedir();this.launchAgentDir=k.join(e,"Library","LaunchAgents"),this.launchAgentScriptDir=k.join(e,"Library","Application Support","Constellation"),this.launchAgentLogDir=k.join(e,"Library","Logs","Constellation"),this.launchAgentPlistPath=k.join(this.launchAgentDir,`${n.LAUNCH_AGENT_LABEL}.plist`),this.launchAgentScriptPath=k.join(this.launchAgentScriptDir,"launchd-env.sh"),this.launchAgentStderrPath=k.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 se__default.mkdir(this.launchAgentDir,{recursive:true}),await se__default.mkdir(this.launchAgentScriptDir,{recursive:true}),await se__default.mkdir(this.launchAgentLogDir,{recursive:true}),await se__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 C.readFile(this.launchAgentScriptPath,"utf-8");}catch{}s||(s=`#!/bin/bash
|
|
102
102
|
# Managed by Constellation CLI - do not edit manually
|
|
103
103
|
`);let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^launchctl setenv ${a} .*$`,"gm");l.test(s)?s=s.replace(l,o):s=s.trimEnd()+`
|
|
104
104
|
`+o+`
|
|
@@ -122,17 +122,17 @@ ${e.stderr??""}`.toLowerCase();return t.includes("already installed")||t.include
|
|
|
122
122
|
</dict>
|
|
123
123
|
</plist>
|
|
124
124
|
`;await this.assertSafeWriteTarget(this.launchAgentPlistPath),await C.writeFile(this.launchAgentPlistPath,o),await se__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}/${n.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);}}},
|
|
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}/${n.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);}}},Ei=class n extends Zr{static ENV_D_FILENAME="io.constellationdev.env.conf";envDDir;envDFilePath;constructor(){super(),this.envDDir=k.join(We.homedir(),".config","environment.d"),this.envDFilePath=k.join(this.envDDir,n.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 se__default.mkdir(this.envDDir,{recursive:true});}async updateEnvironmentDFile(e,t){let r=n.escapeEnvironmentDValue(t),o=`${e}=${r}`,s="";try{s=await C.readFile(this.envDFilePath,"utf-8");}catch{}s||(s=`# Managed by Constellation CLI - do not edit manually
|
|
126
126
|
`);let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^${a}=.*$`,"gm");l.test(s)?s=s.replace(l,o):s=s.trimEnd()+`
|
|
127
127
|
`+o+`
|
|
128
128
|
`,await this.assertSafeWriteTarget(this.envDFilePath),await se__default.writeFile(this.envDFilePath,s,{mode:384}),await se__default.chmod(this.envDFilePath,384);}async importToSystemdUser(e,t){if(ae("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.`);}},
|
|
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=
|
|
131
|
-
${ve} Updating ${
|
|
132
|
-
`),await this.packageManager.executeUpdate(
|
|
129
|
+
Shell environments still updated; log out and back in if systemd-launched apps don't see the value.`);}},Pi=class{static create(){let e=We.platform();switch(e){case "win32":return new xi;case "darwin":return new Ci;case "linux":return new Ei;default:throw new Error(`Unsupported platform: ${e}`)}}},en=class{manager;constructor(){this.manager=Pi.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 tn,Ka=f(()=>{tn=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=k__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function Va(n=process.argv,e=process.env){let t=n.includes("--verbose"),r=n.includes("--quiet")||n.includes("-q")||n.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=yo(),s=vo();return o||!s?"plain":"spinner"}var Ja=f(()=>{bn();});function gm(){let n=We.platform();if(n==="darwin")return k.join(We.homedir(),"Library","Caches","constellation");if(n==="win32"){let e=process.env.LOCALAPPDATA||k.join(We.homedir(),"AppData","Local");return k.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||k.join(We.homedir(),".cache");return k.join(e,"constellation")}}var hm,ym,vm,Ht,Ii=f(()=>{hm=gm(),ym="update-state.json",vm=1440*60*1e3,Ht=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??hm,this.stateFile=k.join(this.stateDir,ym);}async load(){if(this.state)return this.state;try{let e=await se.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await se.mkdir(this.stateDir,{recursive:!0}),await se.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>vm}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 se.unlink(this.stateFile),this.state=null;}catch{}}};});var Wt,Ri=f(()=>{Wt=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 zt,Ni=f(()=>{Ye();X();Xt();zt=class{async promptForUpdate(e,t,r){console.log(""),console.log(cyan("\u2501".repeat(60))),console.log(`${Ee} ${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:B})}catch{return false}}};});async function Ti(n){return new nn().check(n)}var wm,rn,_m,nn,qa=f(()=>{X();Ii();Ri();Ni();wm="https://registry.npmjs.org",rn="@constellationdev/cli",_m=5e3,nn=class{cache;packageManager;prompter;constructor(){this.cache=new Ht,this.packageManager=new Wt,this.prompter=new zt;}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(),_m);try{let o=await fetch(`${wm}/${rn}/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
|
+
${ve} Updating ${rn}...
|
|
132
|
+
`),await this.packageManager.executeUpdate(rn)?(console.log(`
|
|
133
133
|
${x} Update complete! Please re-run your command.
|
|
134
134
|
`),true):(console.log(`
|
|
135
|
-
${
|
|
136
|
-
`),false)}};});var
|
|
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(`${x} 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
|
|
138
|
-
`);}catch(n){xe(n)||
|
|
135
|
+
${W} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(rn)}
|
|
136
|
+
`),false)}};});var Ya=f(()=>{Ii();Ri();Ni();qa();});var Kt,Xa=f(()=>{X();Kt=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(`${x} 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 Za,Qa=f(()=>{Za={"tree-sitter":"0.21.1","tree-sitter-typescript":"0.21.2","tree-sitter-javascript":"0.21.4","tree-sitter-python":"0.21.0"};});function el(){let n={};for(let e of Em){let t=Za[e];if(typeof t!="string"||t.length===0)throw new Error(`grammar-versions.json missing entry for ${e}`);n[e]=t;}return n}var Em,tl=f(()=>{Qa();Em=["tree-sitter","tree-sitter-typescript","tree-sitter-javascript","tree-sitter-python"];});var Lm={};var Z,Ae,rl,Li,Nm,Tm,ki,ji,St,nl=f(async()=>{qi();Pa();Ha();Wa();za();Ka();Lr();Ja();Kn();Ya();an();Zt();Xa();tl();Z=new Mr({mode:Va(process.argv)}),Ae=()=>{try{Z.stop();}catch{}};process.on("exit",Ae);process.on("uncaughtException",n=>{n instanceof Error&&n.code==="ERR_USE_AFTER_CLOSE"&&(Ae(),process.exit(0)),xe(n)||Z.error(n?.message??String(n)),Ae(),process.exit(1);});rl=globalThis.__constellationVersion??(()=>{let n=k__default.dirname(fileURLToPath(import.meta.url)),e=k__default.join(n,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})(),Li=(()=>{let n=process.argv[1];return n&&k__default.basename(n).replace(/\.(c|m)?js$/i,"")==="const"?"const":"constellation"})(),Nm=new Set(["print-grammar-versions"]),Tm=Nm.has(process.argv[2]);if(Z.mode!=="quiet"&&!Tm){let n=process.argv[2];["auth","help","init","index"].includes(n)?Qt(Li,n):Qt(Li),Vt.includes(n)||await Ti(rl)&&(Ae(),process.exit(0));}ki=process.cwd(),ji=new en,St=new Command;St.name(Li).description("Connecting stars in your code into intelligent patterns").version(rl).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.");St.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 n=>{try{let t={GitClient:new Kt(ki,Z),Reporter:Z};await new Bt(t).run({skipMcp:n.skipMcp,skipCi:n.skipCi});}catch(e){xe(e)||Z.error(e instanceof Error?e.message:String(e)),Ae(),process.exit(1);}});St.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async n=>{try{let e={Environment:ji,Reporter:Z};await new Ct(e).run(n.manual);}catch(e){xe(e)||Z.error(e instanceof Error?e.message:String(e)),Ae(),process.exit(1);}});St.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 n=>{try{let e=await Yr.loadFromFile(k__default.join(ki,"constellation.json")),t=new Kt(ki,Z),r=new Tr(e),o=new tn(e),s={GitClient:t,Config:e,LanguageRegistry:r,LanguageDetector:o,Environment:ji,Reporter:Z},a=ji.isCI(),l=n.full||!n.incremental&&a,c=n.dirty||!1,u=!0;!n.full&&!n.incremental&&a&&Z.info("CI environment detected \u2014 defaulting to full index. Use --incremental to override."),await new Ut(s).run(l,c,u);}catch(e){xe(e)||Z.error(e instanceof Error?e.message:String(e)),Ae(),process.exit(1);}});St.command("print-grammar-versions",{hidden:true}).description("Emit installed tree-sitter grammar versions as JSON").action(()=>{try{process.stdout.write(JSON.stringify(el())+`
|
|
138
|
+
`);}catch(n){xe(n)||Z.error(n instanceof Error?n.message:String(n)),Ae(),process.exit(1);}});St.parse();});var ol=/^>=\s*\d+\.\d+\.\d+$/;function Di(n,e=process.version){if(!ol.test(n))return {compatible:true,current:e,required:n};let t=n.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:n}}an();var $m=dirname(fileURLToPath(import.meta.url)),Dm=join($m,"..","package.json"),Ai=JSON.parse(readFileSync(Dm,"utf-8")),Mm=process.argv[2];if(!Vt.includes(Mm)&&Ai.engines?.node){let n=Di(Ai.engines.node);n.compatible||(console.error(`Error: Constellation CLI requires Node.js ${n.required} (current: ${n.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=Ai.version;await nl().then(()=>Lm);
|