@constellationdev/cli 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +38 -38
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import {bold,blue,gray,green,red,dim,yellow,cyan}from'yoctocolors';import*as Ce from'os';import Ce__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 Gt from'fs';import {readFileSync,existsSync}from'fs';import {pipeline}from'stream/promises';import*as Wr from'zlib';import Wr__default from'zlib';import {Agent,fetch as fetch$1}from'undici';import*as E from'path';import E__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as G from'fs/promises';import G__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import Il from'tree-sitter-javascript';import Nl from'tree-sitter-python';import Tl from'tree-sitter-typescript';import wc from'tree-sitter';import Gi from'ignore';import {performance}from'perf_hooks';import Mc from'yocto-spinner';import {parseDocument,isMap,isSeq,stringify}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var us=Object.defineProperty;var f=(i,e)=>()=>(i&&(e=i(i=0)),e);var En=(i,e)=>{for(var t in e)us(i,t,{get:e[t],enumerable:true});};var ht,hr=f(()=>{ht=["help","--help","-h","--version","-V","-v"];});function gs(){let i=process.env;return i.FORCE_COLOR&&i.FORCE_COLOR!=="0"&&i.FORCE_COLOR!=="false"?true:i.NO_COLOR?false:!!process.stdout.isTTY}function Pn(i,e,t){return [Math.round(i[0]+(e[0]-i[0])*t),Math.round(i[1]+(e[1]-i[1])*t),Math.round(i[2]+(e[2]-i[2])*t)]}function J(i,e=0,t=false){let n=[],o=0;for(let p of i.matchAll(hs))p.index>o&&n.push({ansi:false,value:i.slice(o,p.index)}),n.push({ansi:true,value:p[0]}),o=p.index+p[0].length;o<i.length&&n.push({ansi:false,value:i.slice(o)});let a=[...n.filter(p=>!p.ansi).map(p=>p.value).join("")],l=ze.length,c=a.length,u=0;return n.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),v=Math.floor(y),x=Math.min(v+1,l-1),j=y-v;[g,h,b]=Pn(ze[v],ze[x],j);}else {let y=(c>1?m/(c-1):0)*(l-1),v=Math.floor(y),x=Math.min(v+1,l-1),j=y-v;[g,h,b]=Pn(ze[v],ze[x],j);}return fs(g,h,b,d)}).join("")).join("")}var V,ze,fs,hs,Ie=f(()=>{V={info:i=>blue(i),success:i=>green(i),warn:i=>yellow(i),error:i=>red(i),accent:i=>bold(blue(i)),muted:i=>gray(i),dim:i=>dim(i)},ze=[[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]];fs=(i,e,t,n)=>gs()?`\x1B[38;2;${i};${e};${t}m${n}\x1B[0m`:n;hs=/\x1b\[[0-9;]*m/g;});function ys(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Ce.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 vs,bs,Ss,ws,Cs,xs,Es,_s,Ps,Is,He,w,q,T,Z,ae,O=f(()=>{Ie();vs="\u2714",bs="\u2717",Ss="\u26A0",ws="\u2139",Cs="\u26A1",xs="[OK]",Es="[ERR]",_s="[WARN]",Ps="[INFO]",Is="[>>]",He=ys(),w=V.success(He?vs:xs),q=V.error(He?bs:Es),T=V.warn(He?Ss:_s),Z=V.info(He?ws:Ps),ae=V.warn(He?Cs:Is);});var L,bt=f(()=>{Ie();O();L={prefix:{idle:blue("\u25C6"),done:w},style:{highlight:i=>blue(i),answer:i=>green(i),error:i=>red(`${q} ${i}`),help:i=>gray(i)},icon:{checked:green("\u25FC"),unchecked:gray("\u25FB"),cursor:blue("\u276F")}};});async function Nn(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await br("open",[i]),!0;case "linux":return await br("xdg-open",[i]),!0;case "win32":return await br("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var br,Tn=f(()=>{br=promisify(execFile);});function As(i,e){if(!e)return false;let t,n;try{t=new URL(e),n=new URL(i);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"?false:n.origin===t.origin}function Rn(i={}){let e=i.allowedOrigin;return new Promise((t,n)=>{let o=createServer(),s,a=false;o.listen(0,"127.0.0.1",()=>{let l=o.address();if(!l||typeof l=="string"){o.close(),n(new Error("Failed to bind callback server"));return}t({port:l.port,close(){s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections();},waitForCallback(c,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||!js.test(b)){g.writeHead(400,{"Content-Type":"text/plain"}),g.end("Invalid key format");return}if(a)return;a=true;let v=h.searchParams.get("return_url");v&&As(v,e)?(g.writeHead(302,{Location:v}),g.end()):(g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(Ls)),s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections(),p(b);});})}});}),o.on("error",l=>{n(l);});})}var js,Ls,jn=f(()=>{js=/^ak:[0-9a-f]{32}$/i,Ls=`<!DOCTYPE html>
2
+ import {bold,blue,gray,green,red,dim,yellow,cyan}from'yoctocolors';import*as Ce from'os';import Ce__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 Bt from'fs';import {readFileSync,existsSync}from'fs';import {pipeline}from'stream/promises';import*as Wr from'zlib';import Wr__default from'zlib';import {Agent,fetch as fetch$1}from'undici';import*as E from'path';import E__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as G from'fs/promises';import G__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import Il from'tree-sitter-javascript';import Nl from'tree-sitter-python';import Tl from'tree-sitter-typescript';import wc from'tree-sitter';import Gi from'ignore';import {performance}from'perf_hooks';import Mc from'yocto-spinner';import {parseDocument,isMap,isSeq,stringify}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var us=Object.defineProperty;var f=(i,e)=>()=>(i&&(e=i(i=0)),e);var _n=(i,e)=>{for(var t in e)us(i,t,{get:e[t],enumerable:true});};var ht,yr=f(()=>{ht=["help","--help","-h","--version","-V","-v"];});function gs(){let i=process.env;return i.FORCE_COLOR&&i.FORCE_COLOR!=="0"&&i.FORCE_COLOR!=="false"?true:i.NO_COLOR?false:!!process.stdout.isTTY}function In(i,e,t){return [Math.round(i[0]+(e[0]-i[0])*t),Math.round(i[1]+(e[1]-i[1])*t),Math.round(i[2]+(e[2]-i[2])*t)]}function J(i,e=0,t=false){let n=[],o=0;for(let p of i.matchAll(hs))p.index>o&&n.push({ansi:false,value:i.slice(o,p.index)}),n.push({ansi:true,value:p[0]}),o=p.index+p[0].length;o<i.length&&n.push({ansi:false,value:i.slice(o)});let a=[...n.filter(p=>!p.ansi).map(p=>p.value).join("")],l=We.length,c=a.length,u=0;return n.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),v=Math.floor(y),x=Math.min(v+1,l-1),j=y-v;[g,h,b]=In(We[v],We[x],j);}else {let y=(c>1?m/(c-1):0)*(l-1),v=Math.floor(y),x=Math.min(v+1,l-1),j=y-v;[g,h,b]=In(We[v],We[x],j);}return fs(g,h,b,d)}).join("")).join("")}var V,We,fs,hs,Ie=f(()=>{V={info:i=>blue(i),success:i=>green(i),warn:i=>yellow(i),error:i=>red(i),accent:i=>bold(blue(i)),muted:i=>gray(i),dim:i=>dim(i)},We=[[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]];fs=(i,e,t,n)=>gs()?`\x1B[38;2;${i};${e};${t}m${n}\x1B[0m`:n;hs=/\x1b\[[0-9;]*m/g;});function ys(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Ce.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 vs,bs,Ss,ws,Cs,xs,Es,_s,Ps,Is,He,w,q,T,Z,ae,O=f(()=>{Ie();vs="\u2714",bs="\u2717",Ss="\u26A0",ws="\u2139",Cs="\u26A1",xs="[OK]",Es="[ERR]",_s="[WARN]",Ps="[INFO]",Is="[>>]",He=ys(),w=V.success(He?vs:xs),q=V.error(He?bs:Es),T=V.warn(He?Ss:_s),Z=V.info(He?ws:Ps),ae=V.warn(He?Cs:Is);});var L,bt=f(()=>{Ie();O();L={prefix:{idle:blue("\u25C6"),done:w},style:{highlight:i=>blue(i),answer:i=>green(i),error:i=>red(`${q} ${i}`),help:i=>gray(i)},icon:{checked:green("\u25FC"),unchecked:gray("\u25FB"),cursor:blue("\u276F")}};});async function Tn(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await Sr("open",[i]),!0;case "linux":return await Sr("xdg-open",[i]),!0;case "win32":return await Sr("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var Sr,Rn=f(()=>{Sr=promisify(execFile);});function As(i,e){if(!e)return false;let t,n;try{t=new URL(e),n=new URL(i);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"?false:n.origin===t.origin}function jn(i={}){let e=i.allowedOrigin;return new Promise((t,n)=>{let o=createServer(),s,a=false;o.listen(0,"127.0.0.1",()=>{let l=o.address();if(!l||typeof l=="string"){o.close(),n(new Error("Failed to bind callback server"));return}t({port:l.port,close(){s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections();},waitForCallback(c,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||!js.test(b)){g.writeHead(400,{"Content-Type":"text/plain"}),g.end("Invalid key format");return}if(a)return;a=true;let v=h.searchParams.get("return_url");v&&As(v,e)?(g.writeHead(302,{Location:v}),g.end()):(g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(Ls)),s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections(),p(b);});})}});}),o.on("error",l=>{n(l);});})}var js,Ls,Ln=f(()=>{js=/^ak:[0-9a-f]{32}$/i,Ls=`<!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 Sr(i){process.stdout.write(i+`
5
- `);}function St(i,e){let t=`${i} \u203A ${e}`;Sr(`${J("\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")}
4
+ <body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function wr(i){process.stdout.write(i+`
5
+ `);}function St(i,e){let t=`${i} \u203A ${e}`;wr(`${J("\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
  ${J("\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
  ${J("\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
  ${J("\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
- ${J("\u2502 CONSTELLATIONDEV.IO \u2502")}`),e&&e.length>0?Sr(`${J(`\u251C\u2500${"\u2500".repeat(t.length)}\u2500\u252C\u2500${"\u2500".repeat(78-t.length)}\u256F`)}
9
+ ${J("\u2502 CONSTELLATIONDEV.IO \u2502")}`),e&&e.length>0?wr(`${J(`\u251C\u2500${"\u2500".repeat(t.length)}\u2500\u252C\u2500${"\u2500".repeat(78-t.length)}\u256F`)}
10
10
  ${J(`\u2502 ${bold(t)} \u2502${" ".repeat(80-t.length)}`)}
11
11
  ${J(`\u2570\u2500${"\u2500".repeat(t.length)}\u2500\u256F${" ".repeat(80-t.length)}`)}
12
- `):Sr(J("\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 Ln=f(()=>{Ie();});var le,An,wt=f(()=>{Ln();le="CONSTELLATION_ACCESS_KEY",An="CONSTELLATION_WEB_URL";});var ce,Ct=f(()=>{ce=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 Os(i){return Ds.test(i)}function Ms(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Ds,Ke,Fn=f(()=>{bt();Tn();jn();wt();O();Ct();Ds=/^ak:[0-9a-f]{32}$/i;Ke=class extends ce{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(this.reporter.log(`${ae} Configuring access key authentication...
12
+ `):wr(J("\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 An=f(()=>{Ie();});var le,kn,wt=f(()=>{An();le="CONSTELLATION_ACCESS_KEY",kn="CONSTELLATION_WEB_URL";});var ce,Ct=f(()=>{ce=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 Os(i){return Ds.test(i)}function Ms(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Ds,Ke,$n=f(()=>{bt();Rn();Ln();wt();O();Ct();Ds=/^ak:[0-9a-f]{32}$/i;Ke=class extends ce{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(this.reporter.log(`${ae} Configuring access key authentication...
13
13
  `),this.env.isCI()){this.reporter.error(`Cannot configure authentication in CI/CD environments
14
14
 
15
15
  The ${le} environment variable must be configured
@@ -23,7 +23,7 @@ ${J(`\u2570\u2500${"\u2500".repeat(t.length)}\u2500\u256F${" ".repeat(80-t.lengt
23
23
  `);return}if(await this.env.getKey(le)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:L})){this.reporter.log(`${w} Keeping existing Constellation access key`);return}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred",o=Ms(n);this.reporter.error(`Failed to store Constellation access key
24
24
  ${o}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await password({message:"Constellation Access Key:",theme:L})).trim(),!e){this.reporter.warn("Access key cannot be empty."),t++;continue}if(!Os(e)){if(t++,t<n)this.reporter.warn(`Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
25
25
  Attempts remaining: ${n-t}`);else {this.reporter.error(`Invalid access key format after ${n} 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[An]||"https://app.constellationdev.io",{port:n,waitForCallback:o}=await Rn({allowedOrigin:t}),s=`${t}/auth/cli?callback_port=${n}&state=${e}`;this.reporter.info("Opening browser for authentication..."),await Nn(s)||this.reporter.warn(`Could not open browser automatically.
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[kn]||"https://app.constellationdev.io",{port:n,waitForCallback:o}=await jn({allowedOrigin:t}),s=`${t}/auth/cli?callback_port=${n}&state=${e}`;this.reporter.info("Opening browser for authentication..."),await Tn(s)||this.reporter.warn(`Could not open browser automatically.
27
27
  Please open this URL manually:
28
28
 
29
29
  ${s}
@@ -31,30 +31,30 @@ ${J(`\u2570\u2500${"\u2500".repeat(t.length)}\u2500\u256F${" ".repeat(80-t.lengt
31
31
 
32
32
  source ${t}
33
33
 
34
- New terminal sessions will load it automatically.`),Ce.platform()==="darwin"&&this.reporter.info("Already-running desktop apps (Claude Desktop, Codex, etc.) must be quit and relaunched to see the new value.");}};});var Us,ee,Ve,Gs,Ne,Je,Bs,Ws,zs,qe,Hs,Ks,Vs,Js,qs,Ys,Xs,Qs,Zs,ea,ta,ra,na,ia,oa,sa,aa,$n,la,ca,pa,ua,da,ma,ga,fa,ha,ya,va,ba,Sa,wa,Ca,xa,On,Ea,_a,wr,Pa,Ia,Na,Ta,Ye,Ra,ja,La,Aa,ka,Mn,Fa,$a,xt,Un,Dn,Da,Oa,Ma,Cr,Gn,Ua,Ga,Ba,Wa,xr,za,Ha,Ka,Va,Ja,qa,Bn,Wn,zn,Hn,Ya,Xa,Qa,Kn,Vn,Xe=f(()=>{Us=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()}),ee=z.object({language:z.string(),features:z.array(z.string()).optional(),visibility:z.string().optional(),decorators:z.array(z.string()).optional(),typeInfo:z.any().optional(),custom:z.record(z.string(),z.any()).optional()}),z.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),Ve=z.enum(["low","medium","high","critical"]),Gs=z.enum(["low","moderate","high","very_high"]),Ne=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:Gs}),Je=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()}),Je.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())}),Bs=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),Ws=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),zs=z.object({nodes:z.array(Bs),edges:z.array(Ws),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),qe=new Set(["abc","aifc","argparse","array","ast","asynchat","asyncio","asyncore","atexit","audioop","base64","bdb","binascii","bisect","builtins","bz2","cProfile","calendar","cgi","cgitb","chunk","cmath","cmd","code","codecs","codeop","collections","colorsys","compileall","concurrent","configparser","contextlib","contextvars","copy","copyreg","crypt","csv","ctypes","curses","dataclasses","datetime","dbm","decimal","difflib","dis","distutils","doctest","email","encodings","ensurepip","enum","errno","faulthandler","fcntl","filecmp","fileinput","fnmatch","fractions","ftplib","functools","gc","getopt","getpass","gettext","glob","graphlib","grp","gzip","hashlib","heapq","hmac","html","http","idlelib","imaplib","imghdr","imp","importlib","inspect","io","ipaddress","itertools","json","keyword","lib2to3","linecache","locale","logging","lzma","mailbox","mailcap","marshal","math","mimetypes","mmap","modulefinder","msilib","msvcrt","multiprocessing","netrc","nis","nntplib","numbers","operator","optparse","os","ossaudiodev","pathlib","pdb","pickle","pickletools","pipes","pkgutil","platform","plistlib","poplib","posix","posixpath","pprint","profile","pstats","pty","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","readline","reprlib","resource","rlcompleter","runpy","sched","secrets","select","selectors","shelve","shlex","shutil","signal","site","sitecustomize","smtpd","smtplib","sndhdr","socket","socketserver","spwd","sqlite3","ssl","stat","statistics","string","stringprep","struct","subprocess","sunau","symtable","sys","sysconfig","syslog","tabnanny","tarfile","telnetlib","tempfile","termios","test","textwrap","threading","time","timeit","tkinter","token","tokenize","tomllib","trace","traceback","tracemalloc","tty","turtle","turtledemo","types","typing","unicodedata","unittest","urllib","usercustomize","uu","uuid","venv","warnings","wave","weakref","webbrowser","winreg","winsound","wsgiref","xdrlib","xml","xmlrpc","zipapp","zipfile","zipimport","zlib","zoneinfo","_thread","_tkinter","__future__","__main__"]),z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.any().optional()})}),z.object({query:z.string().max(200),filterByKind:z.array(z.string()).optional(),filterByVisibility:z.array(z.string()).optional(),isExported:z.boolean().optional(),filterByFile:z.string().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeUsageCount:z.boolean().optional(),includeDocumentation:z.boolean().optional()}).refine(i=>i.query.length>0||i.filterByKind&&i.filterByKind.length>0||i.filterByVisibility&&i.filterByVisibility.length>0||i.isExported!==void 0||i.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),Hs=Je.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:Ne.optional(),languageMetadata:ee.optional()}),z.object({symbols:z.array(Hs),pagination:Us.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()}),Ks=Je.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:Ne.optional(),languageMetadata:ee.optional()}),Vs=Je.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),Js=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())}),qs=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Ve}),z.object({symbol:Ks,references:z.array(Vs).optional(),relationships:Js.optional(),impactScore:qs.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)}),Ys=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()}),Xs=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),Qs=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(Ys),transitiveDependencies:z.array(Xs).optional(),packages:z.array(Qs).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)}),Zs=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),ea=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:Ve}),z.object({file:z.string(),directDependents:z.array(Zs),transitiveDependents:z.array(ea).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()}),ta=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Ve}),z.object({cycles:z.array(ta)}),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)}),ra=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:Ne.optional(),languageMetadata:ee.optional()}),na=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()}),ia=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:ra,directUsages:z.array(na),transitiveUsages:z.array(ia).optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:z.enum(["callers","callees","both"]).default("both"),depth:z.number().int().positive().max(10).default(3),excludeExternal:z.boolean().optional(),includeGraph:z.boolean().optional(),limit:z.number().int().positive().max(100).default(25),offset:z.number().int().nonnegative().default(0)}),oa=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:Ne.optional(),languageMetadata:ee.optional()}),sa=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),depth:z.number().int().nonnegative(),complexity:Ne.optional(),languageMetadata:ee.optional()}),aa=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:Ne.optional(),languageMetadata:ee.optional()}),z.object({root:oa,callers:z.array(sa).optional(),callees:z.array(aa).optional(),graph:zs.optional()}),z.object({symbolId:z.string().optional(),qualifiedName:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeDirectDependents:z.boolean().default(true),includeTransitiveDependents:z.boolean().default(true),depth:z.number().int().min(1).max(5).default(3),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),$n=Je.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:ee.optional()}),la=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()}))}),ca=z.object({riskLevel:Ve,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:ee.optional()}),directDependents:z.array($n).optional(),transitiveDependents:z.array($n).optional(),impactedFiles:z.array(la),breakingChangeRisk:ca.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()}),pa=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:ee.optional()}),ua=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(pa),orphanedFiles:z.array(ua)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),da=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),ma=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),ga=z.object({languages:z.array(da),frameworks:z.array(ma),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),fa=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()})}),ha=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()}))})}),ya=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()}),va=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),ba=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),Sa=z.object({nodes:z.array(va),edges:z.array(ba)}),z.object({metadata:ga,structure:fa,dependencies:ha,metrics:ya.optional(),moduleGraph:Sa.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),wa=z.enum(["relative","workspace","alias","external","builtin"]),Ca=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:wa}),xa=z.record(z.string(),Ca),On=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),Ea=On.exclude(["import-use","declaration"]),_a=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:On}).strict(),wr=z.object({filePath:z.string().min(1),entries:z.array(_a)}).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:xa.optional(),classificationMap:wr.optional()}).strict(),Pa=z.object({file:z.string(),error:z.string()}),Ia=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),Na=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(Ia)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(Pa).optional(),relationships:Na}),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())}),Ta=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(Ta),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:Ea,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"]),Ye={branchName:z.string().optional(),effectiveBranchName:z.string().optional(),remapped:z.boolean().optional()},Ra=z.object({status:z.literal("acquired"),attemptId:z.string().uuid(),...Ye}),ja=z.object({status:z.literal("current"),...Ye}),La=z.object({status:z.literal("duplicate"),...Ye}),Aa=z.object({status:z.literal("superseded"),activeCommit:z.string().optional(),...Ye}),ka=z.object({status:z.literal("queued"),queuedAttemptId:z.string().uuid(),...Ye}),Mn=z.discriminatedUnion("status",[Ra,ja,La,Aa,ka]),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()}),Fa=z.enum(["pass1","pass2","pass2b","pass3"]),$a=z.object({phase:Fa,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()}),xt=z.array($a),Un=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),Dn=Un.extend({name:z.string().min(1)}).strict(),Da=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().optional()}).strict(),Oa=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:Da.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(Un).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(Dn).max(200),outgoingCalls:z.array(Dn).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(Oa)}).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(),Ma=z.enum(["pending","processing","completed","failed","skipped"]),Cr=z.object({status:Ma,filesProcessed:z.number().int().nonnegative().nullable(),completedAt:z.union([z.string().datetime({offset:true}),z.date()]).nullable()}),z.enum(["current","processing","stale","failed"]),Gn=z.union([z.string().datetime({offset:true}),z.date()]),Ua=z.object({status:z.literal("processing"),commitHash:z.string().nullable().optional(),startedAt:Gn.optional(),phaseMetrics:xt.optional()}).passthrough(),Ga=z.object({status:z.literal("current"),commitHash:z.string().nullable().optional(),completedAt:Gn.nullable().optional(),enrichment:Cr.optional(),phaseMetrics:xt.optional()}).passthrough(),Ba=z.object({status:z.literal("stale"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:Cr.optional(),phaseMetrics:xt.optional()}).passthrough(),Wa=z.object({status:z.literal("failed"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:Cr.optional(),phaseMetrics:xt.optional()}).passthrough(),xr=z.discriminatedUnion("status",[Ua,Ga,Ba,Wa]),za=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),Ha=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),Ka=z.object({id:z.string(),label:z.string(),type:za,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),Va=z.object({id:z.string(),source:z.string(),target:z.string(),type:Ha,label:z.string().optional()}),Ja=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Ve.optional()}),qa=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(Ka),edges:z.array(Va),summary:Ja,metadata:qa,features:z.record(z.string(),z.boolean()).optional()}),Bn=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(Bn)}),Bn.pick({projectId:true,projectName:true,defaultBranch:true}),Wn=z.enum(["unresolved","resolved","archived"]),zn=z.enum(["succeeded","failed"]),Hn=z.enum(["full","incremental"]),Ya=z.enum(["info","warn","error"]),Xa=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),Qa=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),Kn=z.object({errors:z.array(Xa),warnings:z.array(Qa)}),Vn=z.object({level:Ya,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:Kn,logEntries:z.array(Vn),cliVersion:z.string(),outcome:zn,indexType:Hn}),z.object({status:Wn.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:Hn,status:Wn,outcome:zn,errorSummary:z.string(),errorData:Kn,logEntries:z.array(Vn),cliVersion:z.string(),resolvedAt:z.string().nullable(),resolvedBy:z.string().nullable(),createdAt:z.string(),updatedAt:z.string(),organizationName:z.string().optional(),projectName:z.string().optional(),userEmail:z.string().optional(),resolvedByEmail:z.string().optional()}),z.object({unresolvedCount:z.number(),failedRunCount:z.number(),resolvedLast30d:z.number(),avgResolutionDays:z.number().nullable(),affectedOrgCount:z.number()});});function Er(i){return i.length>Et&&(i[Et]=Jn),i}function qn(){let i=false,e=0;return new Transform({transform(t,n,o){if(i){o(null,t);return}if(e+t.length>Et){let s=Et-e;t[s]=Jn,i=true;}e+=t.length,o(null,t);}})}var Et,Jn,_r=f(()=>{Et=9,Jn=255;});function Yn(i){return base32.encode(Buffer.from(i))}var Xn=f(()=>{});function Qn(i,e,t){let n=`${i}:${e}${t?`:${t}`:""}`;return Yn(n)}var Zn=f(()=>{Xn();});var _t,ei=f(()=>{_t=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
35
- `,o=Buffer.from(n,"utf8");if(!this.push(o))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};});var Pt,It,R,pe,te,Te,ue,Nr=f(()=>{Xe();O();_r();Zn();ei();Pt=class{constructor(e,t,n=false,o){this.config=e;this.accessKey=t;this.dirty=n;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 n of t.split(",")){let[o,s]=n.split("=");o&&s!==void 0&&(this.features[o]=s==="true");}}async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),this.parseFeatureHeader(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new te(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new te(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new te(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new pe("Project not found - no previous index exists");default:throw e.status===404?new pe("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof te||t instanceof pe?t:e.status===404?new pe("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let s=await this.sendRequest(o,null,"GET");if(!s||!s.ok)return null;let a=await s.json(),l=xr.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 R)throw s;return null}}async claimAstLock(e,t,n,o,s){let a=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":n?"incremental":"full","x-commit-hash":o,"x-commit-timestamp":s,"x-constellation-dirty":this.dirty?"true":"false"});if(!a)throw new Error("Failed to claim indexing lock: no response");if(a.status===409)throw await this.parseIndexingConflict(a);if(a.status===401)throw new R("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=Mn.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,n,o=300*1e3){let s=Date.now(),a=2e3,l=3e4;for(;Date.now()-s<o;){try{let c=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(n)}`,null,"GET",{"x-constellation-dirty":this.dirty?"true":"false"});if(!c)continue;if(c.status===401)throw new R("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let u=await c.json(),p=xr.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 R)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadToQueue(e,t,n,o,s){return this.streamToApi(e,"ast/queue",t,n,true,o,s)}async startEnrichment(e,t,n){let o=new Agent({headersTimeout:1e4,bodyTimeout:1e4});try{let s=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment/start`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/json; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-attempt-id":e,"x-constellation-dirty":this.dirty?"true":"false"},dispatcher:o});if(s.ok)return !0;let a=`status ${s.status}`;try{let l=await s.json();l?.message?a=Array.isArray(l.message)?l.message.join("; "):String(l.message):l?.code&&(a=`status ${s.status} (${String(l.code)})`);}catch{}return 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,n,o){let s=[5e3,1e4,2e4];for(let a=0;a<=s.length;a++)try{let l=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-commit-hash":o,"x-constellation-dirty":this.dirty?"true":"false"},body:e,dispatcher:new Agent({headersTimeout:0,bodyTimeout:0})});if(l.status===401)throw new R("Authentication failed during enrichment upload");if(l.status===409){if((await l.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return this.reporter?.warn("Enrichment skipped: index state changed since AST upload"),!1;if(a<s.length){await new Promise(u=>setTimeout(u,s[a]));continue}return this.reporter?.warn("Enrichment skipped: indexing still in progress after retries"),!1}return l.ok||l.status===202?!0:(this.reporter?.warn(`Enrichment upload failed with status ${l.status}`),!1)}catch(l){if(l instanceof R)throw l;if(a<s.length){this.reporter?.warn(`Enrichment upload network error (attempt ${a+1}/${s.length+1}): ${l instanceof Error?l.message:String(l)}`),await new Promise(c=>setTimeout(c,s[a]));continue}return this.reporter?.warn(`Enrichment upload error: ${l instanceof Error?l.message:String(l)}`),false}return false}async deleteFiles(e){for(let t of e){let n=Qn(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",n;try{let o=await e.json();t=o?.message||t,n=o?.details?.branchName;}catch{}return new Te(t,n)}async formatErrorBody(e){try{let t=await e.json();if(typeof t?.message=="string"){let n=typeof t.code=="string"&&t.code.length>0?` [${t.code}]`:"";return `${t.message}${n}`}if(Array.isArray(t?.message))return t.message.join("; ");if(typeof t?.code=="string")return t.code}catch{}return ""}async streamToApi(e,t,n,o,s,a,l){try{let{Readable:c}=await import('stream'),u=new _t(e),p=process.env.CAPTURE_PAYLOAD_PATH,d=null,m=c.toWeb(u);if(p){let[h,b]=m.tee(),y=Gt.createWriteStream(p);d=pipeline(c.fromWeb(b),Wr.createGzip(),qn(),y).catch(v=>{this.reporter?.warn(`[constellation] capture tap failed: ${v instanceof Error?v.message:String(v)}`);}),m=h;}let g=new Agent({headersTimeout:0,bodyTimeout:0});try{let h=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":n,"x-branch-name":o,"x-constellation-index":s?"incremental":"full","x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`,...a&&{"x-commit-hash":a},...l&&{"x-attempt-id":l}},body:m,duplex:"half",dispatcher:g});if(!h.ok&&typeof u.destroy=="function"&&u.destroy(),h.status===401)throw new R("Authentication failed");if(h.status===409)throw await this.parseIndexingConflict(h);if(h.status===200)try{let y=await h.json();if(y?.status==="current")return this.reporter?.summary(`${w} Index already up to date for ${o} at commit ${y.commitHash||"unknown"}`),!0}catch{}if(h.ok||h.status===202)return !0;let b=`Server returned ${h.status}`;try{let y=await h.json();y?.message&&(b=Array.isArray(y.message)?y.message.join("; "):y.message);}catch{}throw new Error(b)}finally{d&&await d;}}catch(c){if(c instanceof R||c instanceof Te)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,n,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",Authorization:`Bearer ${this.accessKey}`},g=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:m,body:t?JSON.stringify(t):void 0,signal:d.signal});if(p&&clearTimeout(p),g.status===401)throw new R("Authentication failed");if(!g.ok&&this.retryableStatusCodes.includes(g.status))throw new It(`${g.statusText} (${g.status})`);return g}catch(d){if(p&&clearTimeout(p),!(d instanceof R)){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 It){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"},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},It=class extends Error{constructor(e){super(e),this.name="RetryableError";}},R=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},pe=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},te=class extends Error{constructor(t,n,o){super(t);this.code=n;this.projectId=o;this.name="ProjectValidationError";}},Te=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}},ue=class extends Error{constructor(t,n){super(t);this.errorCode=n;this.name="GitValidationError";}};});function ni(i){return i.replace(/\\/g,"/")}function Nt(i){return ni(i).replace(/^\.?\//,"")}function U(i,e){return ni(E.relative(i,e))}var ve=f(()=>{});var Re,Rr=f(()=>{Re=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 n=new Map,o=0,s=0,a=new Map,l=new Set,c=0;for(;s<e.length&&n.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}));n.set(u,d),s++;}for(;n.size>0;){let u=await Promise.race(n.values());if(n.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}));n.set(p,m),s++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});var ol,sl,jr,al,ll,cl,Tt,oi=f(()=>{ve();Rr();ol={function:{hover:true,references:true,callHierarchy:true},method:{hover:true,references:true,callHierarchy:true},class:{hover:false,references:true,callHierarchy:false},interface:{hover:false,references:true,callHierarchy:false},variable:{hover:true,references:true,callHierarchy:false},property:{hover:true,references:true,callHierarchy:false},import:{hover:true,references:false,callHierarchy:false}},sl={hover:true,references:true,callHierarchy:false},jr=1e4,al=1200*1e3,ll=50,cl={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},Tt=class{constructor(e,t){this.projectRoot=e;this.reporter=t;}async enrich(e,t,n,o){let s=[],a=Date.now(),l={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null},c=false;return await Promise.all([...e.entries()].map(async([u,p])=>{let d=n.get(u);if(!d)return;let m=p.length,g=m>1e4?4:m>5e3?6:8,h=new Re(g),b=0,y=h.run(p,async v=>{try{if(c||Date.now()-a>al)return c=!0,null;let x=await this.openFile(d,v,l,o?.get(v));if(!x)return null;let{uri:j}=x;try{let C=t.get(v)??[];if(C.length===0&&(C=await this.discoverSymbols(d,v,j,l),C.length===0))return l.filesNoSymbols++,null;let A=await this.enrichOpenFile(d,v,j,C,l);return A.length>0?{filePath:v,language:u,symbols:A}:null}finally{this.closeFile(d,j);}}finally{if(b++,b%ll===0){let x=Math.round(b/m*100);this.reporter?.info(`${cl[u]??u} index enrichment: ${x}% (${b}/${m} files)`);}}});for await(let v of y)v&&s.push(v);})),c&&this.reporter?.info("Enrichment timeout reached. Uploading partial results."),this.logDiagnostics(l),s}async openFile(e,t,n,o){let s=E.resolve(this.projectRoot,t),a=pathToFileURL(s).href,l=o;if(l===void 0)try{l=Gt.readFileSync(s,"utf-8");}catch(c){return n.filesUnreadable++,n.firstFileError||(n.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 n.filesOpenFailed++,n.firstOpenError||(n.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,n,o,s){let a=await Promise.allSettled(o.map(c=>this.querySymbol(e,n,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`);let n=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(n.length>0){let o=n.reduce((a,[,l])=>a+l,0),s=n.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(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,n,o){let s=ol[n.kind.toLowerCase()]||sl,a={line:n.line-1,character:n.column},l={textDocument:{uri:t},position:a},c={name:n.name,line:n.line,column:n.column,kind:n.kind},u=false,[p,d]=await Promise.allSettled([s.hover?e.sendRequest("textDocument/hover",l,jr):null,s.references?e.sendRequest("textDocument/references",{...l,context:{includeDeclaration:false}},jr):null]);for(let m of [p,d])m.status==="rejected"&&o.queryRejections++;if(p.status==="fulfilled"&&p.value?.contents){let m=p.value,g=typeof m.contents=="string"?m.contents:m.contents.value||"";g&&(c.typeInfo={resolvedType:g},u=true);}if(d.status==="fulfilled"&&d.value){let m=d.value;if(m.length>0){let g=m.slice(0,100).map(h=>({filePath:U(this.projectRoot,this.uriToPath(h.uri||"")),line:(h.range?.start?.line??0)+1,column:h.range?.start?.character??0}));c.references={count:m.length,locations:g},u=true;}}if(s.callHierarchy)try{let m=await e.sendRequest("textDocument/prepareCallHierarchy",l,jr);if(m&&m.length>0){let g=m[0],[h,b]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:g}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:g}).catch(()=>[])]),y=(h||[]).slice(0,200).map(x=>({name:x.from?.name||"",filePath:U(this.projectRoot,this.uriToPath(x.from?.uri||"")),line:(x.from?.range?.start?.line??0)+1,column:x.from?.selectionRange?.start?.character??x.from?.range?.start?.character??0})),v=(b||[]).slice(0,200).map(x=>({name:x.to?.name||"",filePath:U(this.projectRoot,this.uriToPath(x.to?.uri||"")),line:(x.to?.range?.start?.line??0)+1,column:x.to?.selectionRange?.start?.character??x.to?.range?.start?.character??0}));(y.length>0||v.length>0)&&(c.callHierarchy={incomingCalls:y,outgoingCalls:v},u=!0);}}catch{o.queryRejections++;}if(!u){let m=n.kind.toLowerCase();o.symbolsWithNoEnrichment[m]=(o.symbolsWithNoEnrichment[m]??0)+1;}return u?c:null}async discoverSymbols(e,t,n,o){try{let s=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:n}});return !s||!Array.isArray(s)?[]:this.flattenDocumentSymbols(s)}catch(s){return o.discoveryErrors++,o.firstDiscoveryError||(o.firstDiscoveryError=`${t}: ${s instanceof Error?s.message:String(s)}`),[]}}flattenDocumentSymbols(e){let t=[],n={1:"file",2:"module",3:"namespace",4:"package",5:"class",6:"method",7:"property",8:"field",9:"constructor",10:"enum",11:"interface",12:"function",13:"variable",14:"constant",15:"string",16:"number",17:"boolean",18:"array",19:"object",20:"key",21:"null",22:"enumMember",23:"struct",24:"event",25:"operator",26:"typeParameter"};for(let o of e){let s=n[o.kind]||"variable",a=o.selectionRange||o.range||o.location?.range;a&&t.push({name:o.name,line:(a.start?.line??0)+1,column:a.start?.character??0,kind:s}),o.children&&Array.isArray(o.children)&&t.push(...this.flattenDocumentSymbols(o.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=E.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function si(i){return i.map(e=>JSON.stringify(e)).join(`
34
+ New terminal sessions will load it automatically.`),Ce.platform()==="darwin"&&this.reporter.info("Already-running desktop apps (Claude Desktop, Codex, etc.) must be quit and relaunched to see the new value.");}};});var Us,ee,Ve,Gs,Ne,Je,Bs,zs,Ws,qe,Hs,Ks,Vs,Js,qs,Ys,Xs,Qs,Zs,ea,ta,ra,na,ia,oa,sa,aa,Dn,la,ca,pa,ua,da,ma,ga,fa,ha,ya,va,ba,Sa,wa,Ca,xa,Mn,Ea,_a,Cr,Pa,Ia,Na,Ta,Ye,Ra,ja,La,Aa,ka,Un,Fa,$a,xt,Gn,On,Da,Oa,Ma,xr,Bn,Ua,Ga,Ba,za,Er,Wa,Ha,Ka,Va,Ja,qa,zn,Wn,Hn,Kn,Ya,Xa,Qa,Vn,Jn,Xe=f(()=>{Us=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()}),ee=z.object({language:z.string(),features:z.array(z.string()).optional(),visibility:z.string().optional(),decorators:z.array(z.string()).optional(),typeInfo:z.any().optional(),custom:z.record(z.string(),z.any()).optional()}),z.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),Ve=z.enum(["low","medium","high","critical"]),Gs=z.enum(["low","moderate","high","very_high"]),Ne=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:Gs}),Je=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()}),Je.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())}),Bs=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),zs=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),Ws=z.object({nodes:z.array(Bs),edges:z.array(zs),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),qe=new Set(["abc","aifc","argparse","array","ast","asynchat","asyncio","asyncore","atexit","audioop","base64","bdb","binascii","bisect","builtins","bz2","cProfile","calendar","cgi","cgitb","chunk","cmath","cmd","code","codecs","codeop","collections","colorsys","compileall","concurrent","configparser","contextlib","contextvars","copy","copyreg","crypt","csv","ctypes","curses","dataclasses","datetime","dbm","decimal","difflib","dis","distutils","doctest","email","encodings","ensurepip","enum","errno","faulthandler","fcntl","filecmp","fileinput","fnmatch","fractions","ftplib","functools","gc","getopt","getpass","gettext","glob","graphlib","grp","gzip","hashlib","heapq","hmac","html","http","idlelib","imaplib","imghdr","imp","importlib","inspect","io","ipaddress","itertools","json","keyword","lib2to3","linecache","locale","logging","lzma","mailbox","mailcap","marshal","math","mimetypes","mmap","modulefinder","msilib","msvcrt","multiprocessing","netrc","nis","nntplib","numbers","operator","optparse","os","ossaudiodev","pathlib","pdb","pickle","pickletools","pipes","pkgutil","platform","plistlib","poplib","posix","posixpath","pprint","profile","pstats","pty","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","readline","reprlib","resource","rlcompleter","runpy","sched","secrets","select","selectors","shelve","shlex","shutil","signal","site","sitecustomize","smtpd","smtplib","sndhdr","socket","socketserver","spwd","sqlite3","ssl","stat","statistics","string","stringprep","struct","subprocess","sunau","symtable","sys","sysconfig","syslog","tabnanny","tarfile","telnetlib","tempfile","termios","test","textwrap","threading","time","timeit","tkinter","token","tokenize","tomllib","trace","traceback","tracemalloc","tty","turtle","turtledemo","types","typing","unicodedata","unittest","urllib","usercustomize","uu","uuid","venv","warnings","wave","weakref","webbrowser","winreg","winsound","wsgiref","xdrlib","xml","xmlrpc","zipapp","zipfile","zipimport","zlib","zoneinfo","_thread","_tkinter","__future__","__main__"]),z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.any().optional()})}),z.object({query:z.string().max(200),filterByKind:z.array(z.string()).optional(),filterByVisibility:z.array(z.string()).optional(),isExported:z.boolean().optional(),filterByFile:z.string().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeUsageCount:z.boolean().optional(),includeDocumentation:z.boolean().optional()}).refine(i=>i.query.length>0||i.filterByKind&&i.filterByKind.length>0||i.filterByVisibility&&i.filterByVisibility.length>0||i.isExported!==void 0||i.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),Hs=Je.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:Ne.optional(),languageMetadata:ee.optional()}),z.object({symbols:z.array(Hs),pagination:Us.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()}),Ks=Je.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:Ne.optional(),languageMetadata:ee.optional()}),Vs=Je.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),Js=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())}),qs=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Ve}),z.object({symbol:Ks,references:z.array(Vs).optional(),relationships:Js.optional(),impactScore:qs.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)}),Ys=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()}),Xs=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),Qs=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(Ys),transitiveDependencies:z.array(Xs).optional(),packages:z.array(Qs).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)}),Zs=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),ea=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:Ve}),z.object({file:z.string(),directDependents:z.array(Zs),transitiveDependents:z.array(ea).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()}),ta=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Ve}),z.object({cycles:z.array(ta)}),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)}),ra=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:Ne.optional(),languageMetadata:ee.optional()}),na=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()}),ia=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:ra,directUsages:z.array(na),transitiveUsages:z.array(ia).optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:z.enum(["callers","callees","both"]).default("both"),depth:z.number().int().positive().max(10).default(3),excludeExternal:z.boolean().optional(),includeGraph:z.boolean().optional(),limit:z.number().int().positive().max(100).default(25),offset:z.number().int().nonnegative().default(0)}),oa=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:Ne.optional(),languageMetadata:ee.optional()}),sa=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),depth:z.number().int().nonnegative(),complexity:Ne.optional(),languageMetadata:ee.optional()}),aa=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:Ne.optional(),languageMetadata:ee.optional()}),z.object({root:oa,callers:z.array(sa).optional(),callees:z.array(aa).optional(),graph:Ws.optional()}),z.object({symbolId:z.string().optional(),qualifiedName:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeDirectDependents:z.boolean().default(true),includeTransitiveDependents:z.boolean().default(true),depth:z.number().int().min(1).max(5).default(3),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),Dn=Je.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:ee.optional()}),la=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()}))}),ca=z.object({riskLevel:Ve,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:ee.optional()}),directDependents:z.array(Dn).optional(),transitiveDependents:z.array(Dn).optional(),impactedFiles:z.array(la),breakingChangeRisk:ca.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()}),pa=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:ee.optional()}),ua=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(pa),orphanedFiles:z.array(ua)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),da=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),ma=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),ga=z.object({languages:z.array(da),frameworks:z.array(ma),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),fa=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()})}),ha=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()}))})}),ya=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()}),va=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),ba=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),Sa=z.object({nodes:z.array(va),edges:z.array(ba)}),z.object({metadata:ga,structure:fa,dependencies:ha,metrics:ya.optional(),moduleGraph:Sa.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),wa=z.enum(["relative","workspace","alias","external","builtin"]),Ca=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:wa}),xa=z.record(z.string(),Ca),Mn=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),Ea=Mn.exclude(["import-use","declaration"]),_a=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:Mn}).strict(),Cr=z.object({filePath:z.string().min(1),entries:z.array(_a).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:xa.optional(),classificationMap:Cr.optional()}).strict(),Pa=z.object({file:z.string(),error:z.string()}),Ia=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),Na=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(Ia)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(Pa).optional(),relationships:Na}),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())}),Ta=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(Ta),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:Ea,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"]),Ye={branchName:z.string().optional(),effectiveBranchName:z.string().optional(),remapped:z.boolean().optional()},Ra=z.object({status:z.literal("acquired"),attemptId:z.string().uuid(),...Ye}),ja=z.object({status:z.literal("current"),...Ye}),La=z.object({status:z.literal("duplicate"),...Ye}),Aa=z.object({status:z.literal("superseded"),activeCommit:z.string().optional(),...Ye}),ka=z.object({status:z.literal("queued"),queuedAttemptId:z.string().uuid(),...Ye}),Un=z.discriminatedUnion("status",[Ra,ja,La,Aa,ka]),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()}),Fa=z.enum(["pass1","pass2","pass2b","pass3"]),$a=z.object({phase:Fa,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()}),xt=z.array($a),Gn=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),On=Gn.extend({name:z.string().min(1)}).strict(),Da=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().max(16384).optional()}).strict(),Oa=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:Da.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(Gn).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(On).max(200),outgoingCalls:z.array(On).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(Oa).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(),Ma=z.enum(["pending","processing","completed","failed","skipped"]),xr=z.object({status:Ma,filesProcessed:z.number().int().nonnegative().nullable(),completedAt:z.union([z.string().datetime({offset:true}),z.date()]).nullable()}),z.enum(["current","processing","stale","failed"]),Bn=z.union([z.string().datetime({offset:true}),z.date()]),Ua=z.object({status:z.literal("processing"),commitHash:z.string().nullable().optional(),startedAt:Bn.optional(),phaseMetrics:xt.optional()}).passthrough(),Ga=z.object({status:z.literal("current"),commitHash:z.string().nullable().optional(),completedAt:Bn.nullable().optional(),enrichment:xr.optional(),phaseMetrics:xt.optional()}).passthrough(),Ba=z.object({status:z.literal("stale"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:xr.optional(),phaseMetrics:xt.optional()}).passthrough(),za=z.object({status:z.literal("failed"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:xr.optional(),phaseMetrics:xt.optional()}).passthrough(),Er=z.discriminatedUnion("status",[Ua,Ga,Ba,za]),Wa=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),Ha=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),Ka=z.object({id:z.string(),label:z.string(),type:Wa,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),Va=z.object({id:z.string(),source:z.string(),target:z.string(),type:Ha,label:z.string().optional()}),Ja=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Ve.optional()}),qa=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(Ka),edges:z.array(Va),summary:Ja,metadata:qa,features:z.record(z.string(),z.boolean()).optional()}),zn=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(zn)}),zn.pick({projectId:true,projectName:true,defaultBranch:true}),Wn=z.enum(["unresolved","resolved","archived"]),Hn=z.enum(["succeeded","failed"]),Kn=z.enum(["full","incremental"]),Ya=z.enum(["info","warn","error"]),Xa=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),Qa=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),Vn=z.object({errors:z.array(Xa),warnings:z.array(Qa)}),Jn=z.object({level:Ya,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:Vn,logEntries:z.array(Jn),cliVersion:z.string(),outcome:Hn,indexType:Kn}),z.object({status:Wn.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:Kn,status:Wn,outcome:Hn,errorSummary:z.string(),errorData:Vn,logEntries:z.array(Jn),cliVersion:z.string(),resolvedAt:z.string().nullable(),resolvedBy:z.string().nullable(),createdAt:z.string(),updatedAt:z.string(),organizationName:z.string().optional(),projectName:z.string().optional(),userEmail:z.string().optional(),resolvedByEmail:z.string().optional()}),z.object({unresolvedCount:z.number(),failedRunCount:z.number(),resolvedLast30d:z.number(),avgResolutionDays:z.number().nullable(),affectedOrgCount:z.number()});});function _r(i){return i.length>Et&&(i[Et]=qn),i}function Yn(){let i=false,e=0;return new Transform({transform(t,n,o){if(i){o(null,t);return}if(e+t.length>Et){let s=Et-e;t[s]=qn,i=true;}e+=t.length,o(null,t);}})}var Et,qn,Pr=f(()=>{Et=9,qn=255;});function Xn(i){return base32.encode(Buffer.from(i))}var Qn=f(()=>{});function Zn(i,e,t){let n=`${i}:${e}${t?`:${t}`:""}`;return Xn(n)}var ei=f(()=>{Qn();});var _t,ti=f(()=>{_t=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
35
+ `,o=Buffer.from(n,"utf8");if(!this.push(o))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};});var Pt,It,R,pe,te,Te,ue,Tr=f(()=>{Xe();O();Pr();ei();ti();Pt=class{constructor(e,t,n=false,o){this.config=e;this.accessKey=t;this.dirty=n;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 n of t.split(",")){let[o,s]=n.split("=");o&&s!==void 0&&(this.features[o]=s==="true");}}async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),this.parseFeatureHeader(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new te(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new te(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new te(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new pe("Project not found - no previous index exists");default:throw e.status===404?new pe("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof te||t instanceof pe?t:e.status===404?new pe("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let s=await this.sendRequest(o,null,"GET");if(!s||!s.ok)return null;let a=await s.json(),l=Er.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 R)throw s;return null}}async claimAstLock(e,t,n,o,s){let a=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":n?"incremental":"full","x-commit-hash":o,"x-commit-timestamp":s,"x-constellation-dirty":this.dirty?"true":"false"});if(!a)throw new Error("Failed to claim indexing lock: no response");if(a.status===409)throw await this.parseIndexingConflict(a);if(a.status===401)throw new R("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=Un.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,n,o=300*1e3){let s=Date.now(),a=2e3,l=3e4;for(;Date.now()-s<o;){try{let c=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(n)}`,null,"GET",{"x-constellation-dirty":this.dirty?"true":"false"});if(!c)continue;if(c.status===401)throw new R("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let u=await c.json(),p=Er.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 R)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadToQueue(e,t,n,o,s){return this.streamToApi(e,"ast/queue",t,n,true,o,s)}async startEnrichment(e,t,n){let o=new Agent({headersTimeout:1e4,bodyTimeout:1e4});try{let s=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment/start`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/json; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-attempt-id":e,"x-constellation-dirty":this.dirty?"true":"false"},dispatcher:o});if(s.ok)return !0;let a=`status ${s.status}`;try{let l=await s.json();l?.message?a=Array.isArray(l.message)?l.message.join("; "):String(l.message):l?.code&&(a=`status ${s.status} (${String(l.code)})`);}catch{}return 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,n,o){let s=[5e3,1e4,2e4],a=Wr.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","x-project-id":t,"x-branch-name":n,"x-commit-hash":o,"x-constellation-dirty":this.dirty?"true":"false"},body:a,dispatcher:l});if(u.status===401)throw new R("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 AST 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 R)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 n=Zn(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",n;try{let o=await e.json();t=o?.message||t,n=o?.details?.branchName;}catch{}return new Te(t,n)}async formatErrorBody(e){try{let t=await e.json();if(typeof t?.message=="string"){let n=typeof t.code=="string"&&t.code.length>0?` [${t.code}]`:"";return `${t.message}${n}`}if(Array.isArray(t?.message))return t.message.join("; ");if(typeof t?.code=="string")return t.code}catch{}return ""}async streamToApi(e,t,n,o,s,a,l){try{let{Readable:c}=await import('stream'),u=new _t(e),p=process.env.CAPTURE_PAYLOAD_PATH,d=null,m=c.toWeb(u);if(p){let[h,b]=m.tee(),y=Bt.createWriteStream(p);d=pipeline(c.fromWeb(b),Wr.createGzip(),Yn(),y).catch(v=>{this.reporter?.warn(`[constellation] capture tap failed: ${v instanceof Error?v.message:String(v)}`);}),m=h;}let g=new Agent({headersTimeout:0,bodyTimeout:0});try{let h=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":n,"x-branch-name":o,"x-constellation-index":s?"incremental":"full","x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`,...a&&{"x-commit-hash":a},...l&&{"x-attempt-id":l}},body:m,duplex:"half",dispatcher:g});if(!h.ok&&typeof u.destroy=="function"&&u.destroy(),h.status===401)throw new R("Authentication failed");if(h.status===409)throw await this.parseIndexingConflict(h);if(h.status===200)try{let y=await h.json();if(y?.status==="current")return this.reporter?.summary(`${w} Index already up to date for ${o} at commit ${y.commitHash||"unknown"}`),!0}catch{}if(h.ok||h.status===202)return !0;let b=`Server returned ${h.status}`;try{let y=await h.json();y?.message&&(b=Array.isArray(y.message)?y.message.join("; "):y.message);}catch{}throw new Error(b)}finally{d&&await d;}}catch(c){if(c instanceof R||c instanceof Te)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,n,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",Authorization:`Bearer ${this.accessKey}`},g=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:m,body:t?JSON.stringify(t):void 0,signal:d.signal});if(p&&clearTimeout(p),g.status===401)throw new R("Authentication failed");if(!g.ok&&this.retryableStatusCodes.includes(g.status))throw new It(`${g.statusText} (${g.status})`);return g}catch(d){if(p&&clearTimeout(p),!(d instanceof R)){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 It){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"},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},It=class extends Error{constructor(e){super(e),this.name="RetryableError";}},R=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},pe=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},te=class extends Error{constructor(t,n,o){super(t);this.code=n;this.projectId=o;this.name="ProjectValidationError";}},Te=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}},ue=class extends Error{constructor(t,n){super(t);this.errorCode=n;this.name="GitValidationError";}};});function ni(i){return i.replace(/\\/g,"/")}function Tt(i){return ni(i).replace(/^\.?\//,"")}function U(i,e){return ni(E.relative(i,e))}var ve=f(()=>{});var Re,jr=f(()=>{Re=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 n=new Map,o=0,s=0,a=new Map,l=new Set,c=0;for(;s<e.length&&n.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}));n.set(u,d),s++;}for(;n.size>0;){let u=await Promise.race(n.values());if(n.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}));n.set(p,m),s++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});var ol,sl,Lr,al,ll,cl,Rt,oi=f(()=>{ve();jr();ol={function:{hover:true,references:true,callHierarchy:true},method:{hover:true,references:true,callHierarchy:true},class:{hover:false,references:true,callHierarchy:false},interface:{hover:false,references:true,callHierarchy:false},variable:{hover:true,references:true,callHierarchy:false},property:{hover:true,references:true,callHierarchy:false},import:{hover:true,references:false,callHierarchy:false}},sl={hover:true,references:true,callHierarchy:false},Lr=1e4,al=1200*1e3,ll=50,cl={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},Rt=class{constructor(e,t){this.projectRoot=e;this.reporter=t;}async enrich(e,t,n,o){let s=[],a=Date.now(),l={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null},c=false;return await Promise.all([...e.entries()].map(async([u,p])=>{let d=n.get(u);if(!d)return;let m=p.length,g=m>1e4?4:m>5e3?6:8,h=new Re(g),b=0,y=h.run(p,async v=>{try{if(c||Date.now()-a>al)return c=!0,null;let x=await this.openFile(d,v,l,o?.get(v));if(!x)return null;let{uri:j}=x;try{let C=t.get(v)??[];if(C.length===0&&(C=await this.discoverSymbols(d,v,j,l),C.length===0))return l.filesNoSymbols++,null;let A=await this.enrichOpenFile(d,v,j,C,l);return A.length>0?{filePath:v,language:u,symbols:A}:null}finally{this.closeFile(d,j);}}finally{if(b++,b%ll===0){let x=Math.round(b/m*100);this.reporter?.info(`${cl[u]??u} index enrichment: ${x}% (${b}/${m} files)`);}}});for await(let v of y)v&&s.push(v);})),c&&this.reporter?.info("Enrichment timeout reached. Uploading partial results."),this.logDiagnostics(l),s}async openFile(e,t,n,o){let s=E.resolve(this.projectRoot,t),a=pathToFileURL(s).href,l=o;if(l===void 0)try{l=Bt.readFileSync(s,"utf-8");}catch(c){return n.filesUnreadable++,n.firstFileError||(n.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 n.filesOpenFailed++,n.firstOpenError||(n.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,n,o,s){let a=await Promise.allSettled(o.map(c=>this.querySymbol(e,n,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`);let n=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(n.length>0){let o=n.reduce((a,[,l])=>a+l,0),s=n.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(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,n,o){let s=ol[n.kind.toLowerCase()]||sl,a={line:n.line-1,character:n.column},l={textDocument:{uri:t},position:a},c={name:n.name,line:n.line,column:n.column,kind:n.kind},u=false,[p,d]=await Promise.allSettled([s.hover?e.sendRequest("textDocument/hover",l,Lr):null,s.references?e.sendRequest("textDocument/references",{...l,context:{includeDeclaration:false}},Lr):null]);for(let m of [p,d])m.status==="rejected"&&o.queryRejections++;if(p.status==="fulfilled"&&p.value?.contents){let m=p.value,g=typeof m.contents=="string"?m.contents:m.contents.value||"";g&&(c.typeInfo={resolvedType:g},u=true);}if(d.status==="fulfilled"&&d.value){let m=d.value;if(m.length>0){let g=m.slice(0,100).map(h=>({filePath:U(this.projectRoot,this.uriToPath(h.uri||"")),line:(h.range?.start?.line??0)+1,column:h.range?.start?.character??0}));c.references={count:m.length,locations:g},u=true;}}if(s.callHierarchy)try{let m=await e.sendRequest("textDocument/prepareCallHierarchy",l,Lr);if(m&&m.length>0){let g=m[0],[h,b]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:g}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:g}).catch(()=>[])]),y=(h||[]).slice(0,200).map(x=>({name:x.from?.name||"",filePath:U(this.projectRoot,this.uriToPath(x.from?.uri||"")),line:(x.from?.range?.start?.line??0)+1,column:x.from?.selectionRange?.start?.character??x.from?.range?.start?.character??0})),v=(b||[]).slice(0,200).map(x=>({name:x.to?.name||"",filePath:U(this.projectRoot,this.uriToPath(x.to?.uri||"")),line:(x.to?.range?.start?.line??0)+1,column:x.to?.selectionRange?.start?.character??x.to?.range?.start?.character??0}));(y.length>0||v.length>0)&&(c.callHierarchy={incomingCalls:y,outgoingCalls:v},u=!0);}}catch{o.queryRejections++;}if(!u){let m=n.kind.toLowerCase();o.symbolsWithNoEnrichment[m]=(o.symbolsWithNoEnrichment[m]??0)+1;}return u?c:null}async discoverSymbols(e,t,n,o){try{let s=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:n}});return !s||!Array.isArray(s)?[]:this.flattenDocumentSymbols(s)}catch(s){return o.discoveryErrors++,o.firstDiscoveryError||(o.firstDiscoveryError=`${t}: ${s instanceof Error?s.message:String(s)}`),[]}}flattenDocumentSymbols(e){let t=[],n={1:"file",2:"module",3:"namespace",4:"package",5:"class",6:"method",7:"property",8:"field",9:"constructor",10:"enum",11:"interface",12:"function",13:"variable",14:"constant",15:"string",16:"number",17:"boolean",18:"array",19:"object",20:"key",21:"null",22:"enumMember",23:"struct",24:"event",25:"operator",26:"typeParameter"};for(let o of e){let s=n[o.kind]||"variable",a=o.selectionRange||o.range||o.location?.range;a&&t.push({name:o.name,line:(a.start?.line??0)+1,column:a.start?.character??0,kind:s}),o.children&&Array.isArray(o.children)&&t.push(...this.flattenDocumentSymbols(o.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=E.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function si(i){return i.map(e=>JSON.stringify(e)).join(`
37
37
  `)+`
38
- `}var ai=f(()=>{});function je(i){try{return execFileSync(process.platform==="win32"?"where":"which",[i],{stdio:"ignore"}),!0}catch{return false}}var S,re=f(()=>{S={async directoryExists(i){try{return (await G__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await G__default.access(i,G__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await G__default.readFile(i,{encoding:e,flag:G__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let n=Buffer.from(e,t);await G__default.writeFile(i,n,{encoding:t,flag:G__default.constants.O_WRONLY|G__default.constants.O_CREAT|G__default.constants.O_TRUNC});},async getFileStats(i){return await G__default.stat(i)},async getFileHandle(i,e,t){return await G__default.open(i,e,t)}};});var jt,li=f(()=>{jt=class i{constructor(e,t,n=1e4,o){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=n;this.reporter=o;this.stdout.on("data",s=>this.handleData(s)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
38
+ `}var ai=f(()=>{});function je(i){try{return execFileSync(process.platform==="win32"?"where":"which",[i],{stdio:"ignore"}),!0}catch{return false}}var S,re=f(()=>{S={async directoryExists(i){try{return (await G__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await G__default.access(i,G__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await G__default.readFile(i,{encoding:e,flag:G__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let n=Buffer.from(e,t);await G__default.writeFile(i,n,{encoding:t,flag:G__default.constants.O_WRONLY|G__default.constants.O_CREAT|G__default.constants.O_TRUNC});},async getFileStats(i){return await G__default.stat(i)},async getFileHandle(i,e,t){return await G__default.open(i,e,t)}};});var Lt,li=f(()=>{Lt=class i{constructor(e,t,n=1e4,o){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=n;this.reporter=o;this.stdout.on("data",s=>this.handleData(s)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
39
39
  \r
40
40
  `);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,n){if(this.disposed)return Promise.reject(new Error("LspClient disposed"));let o=this.nextId++,s={jsonrpc:"2.0",id:o,method:e,...t!==void 0&&{params:t}};return new Promise((a,l)=>{let c=setTimeout(()=>{this.pendingRequests.delete(o),l(new Error(`LSP request '${e}' timed out after ${n??this.defaultTimeoutMs}ms`));},n??this.defaultTimeoutMs);this.pendingRequests.set(o,{resolve:a,reject:l,timer:c}),this.writeMessage(s);})}sendNotification(e,t){if(this.disposed)return;let n={jsonrpc:"2.0",method:e,...t!==void 0&&{params:t}};this.writeMessage(n);}dispose(){this.disposed=true;for(let[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("LspClient disposed"));this.pendingRequests.clear(),this.stdout.removeAllListeners("data");}writeMessage(e){let t=JSON.stringify(e),o=`Content-Length: ${Buffer.byteLength(t,"utf-8")}\r
41
41
  \r
42
- `;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(i.HEADER_SEPARATOR);if(t===-1)break;let o=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!o){this.buffer=this.buffer.subarray(t+4);continue}let s=parseInt(o[1],10),a=t+4;if(this.buffer.length-a<s)break;let l=this.buffer.subarray(a,a+s).toString("utf-8");this.buffer=this.buffer.subarray(a+s);try{let c=JSON.parse(l);this.handleResponse(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,this.reporter?.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var Ar,Lt,de,Qe=f(()=>{Ar=E.join(Ce.homedir(),".constellation","lsp-servers"),Lt=E.join(Ar,"node_modules",".bin"),de=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});function ui(i){return i.replace(/\\/g,"/")}function ml(i){let e=ui(i);return E.posix.basename(e).toLowerCase().replace(/\.(exe|com|bat|cmd|ps1)$/i,"")}function di(i,e){if(!i||i.trim().length===0)return {classification:"denied",reason:"LSP command is empty"};let t=ui(i);if(dl.test(t))return {classification:"denied",reason:"LSP command contains shell metacharacters"};for(let o of e){if(typeof o!="string")return {classification:"denied",reason:"LSP argument is not a string"};if(o.includes("\0"))return {classification:"denied",reason:"LSP argument contains a null byte"};if(o.includes(`
43
- `)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let n=ml(i);if(ul.has(n))return {classification:"denied",reason:`LSP command resolves to a shell or interpreter ('${n}')`};for(let[,o]of de)if(n===o.command.toLowerCase())return {classification:"known-safe"};return {classification:"custom-untrusted"}}var ul,dl,mi=f(()=>{Qe();ul=new Set(["sh","bash","zsh","zsh5","fish","dash","ash","ksh","csh","tcsh","rc","yash","cmd","command","powershell","pwsh","node","nodejs","deno","bun","python","python2","python3","pypy","pypy3","perl","ruby","php","lua","luajit","tclsh","wish","osascript","wscript","cscript","mshta","rundll32","sudo","su","doas","pkexec","runas","gsudo","env","xargs","exec","nohup","timeout","setsid"].map(i=>i.toLowerCase())),dl=/[;&|`$<>\n\r\0"']/;});function gi(i,e,t,n){return i.projectRoot===e&&i.command===t&&i.args.length===n.length&&i.args.every((o,s)=>o===n[s])}function gl(i){if(!i||typeof i!="object")return false;let e=i;return typeof e.projectRoot=="string"&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var Le,kr=f(()=>{Le=class{constructor(e){this.trustFilePath=e;}async isTrusted(e,t,n){return (await this.load()).entries.some(s=>gi(s,e,t,n))}async recordTrust(e,t,n){let o=await this.load();if(o.entries.some(l=>gi(l,e,t,n)))return;o.entries.push({projectRoot:e,command:t,args:[...n],trustedAt:new Date().toISOString()}),await G.mkdir(E.dirname(this.trustFilePath),{recursive:true});let a=`${this.trustFilePath}.${process.pid}.tmp`;try{await G.writeFile(a,JSON.stringify(o,null,2)+`
44
- `,"utf-8"),await G.rename(a,this.trustFilePath);}catch(l){throw await G.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await G.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(gl)}:{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 At,hi=f(()=>{mi();kr();At=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??Le.isCIEnvironment;}async authorize(e,t,n){let{classification:o,reason:s}=di(t,n);if(o==="denied")return this.logger.error(`[LSP:${e}] Refusing unsafe LSP command '${t}': ${s??"denied"}.`),false;if(o==="known-safe"||await this.trustStore.isTrusted(this.projectRoot,t,n))return true;if(this.isCI())return this.logger.warn(`[LSP:${e}] Skipping untrusted custom LSP command '${t}' in CI. Run 'constellation index' interactively once to approve it, or set the 'lsp' field to a known binary.`),false;let a=n.length>0?` ${n.join(" ")}`:"",l=`Trust custom LSP command for this project?
42
+ `;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(i.HEADER_SEPARATOR);if(t===-1)break;let o=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!o){this.buffer=this.buffer.subarray(t+4);continue}let s=parseInt(o[1],10),a=t+4;if(this.buffer.length-a<s)break;let l=this.buffer.subarray(a,a+s).toString("utf-8");this.buffer=this.buffer.subarray(a+s);try{let c=JSON.parse(l);this.handleResponse(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,this.reporter?.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var kr,At,de,Qe=f(()=>{kr=E.join(Ce.homedir(),".constellation","lsp-servers"),At=E.join(kr,"node_modules",".bin"),de=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});function ui(i){return i.replace(/\\/g,"/")}function ml(i){let e=ui(i);return E.posix.basename(e).toLowerCase().replace(/\.(exe|com|bat|cmd|ps1)$/i,"")}function di(i,e){if(!i||i.trim().length===0)return {classification:"denied",reason:"LSP command is empty"};let t=ui(i);if(dl.test(t))return {classification:"denied",reason:"LSP command contains shell metacharacters"};for(let o of e){if(typeof o!="string")return {classification:"denied",reason:"LSP argument is not a string"};if(o.includes("\0"))return {classification:"denied",reason:"LSP argument contains a null byte"};if(o.includes(`
43
+ `)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let n=ml(i);if(ul.has(n))return {classification:"denied",reason:`LSP command resolves to a shell or interpreter ('${n}')`};for(let[,o]of de)if(n===o.command.toLowerCase())return {classification:"known-safe"};return {classification:"custom-untrusted"}}var ul,dl,mi=f(()=>{Qe();ul=new Set(["sh","bash","zsh","zsh5","fish","dash","ash","ksh","csh","tcsh","rc","yash","cmd","command","powershell","pwsh","node","nodejs","deno","bun","python","python2","python3","pypy","pypy3","perl","ruby","php","lua","luajit","tclsh","wish","osascript","wscript","cscript","mshta","rundll32","sudo","su","doas","pkexec","runas","gsudo","env","xargs","exec","nohup","timeout","setsid"].map(i=>i.toLowerCase())),dl=/[;&|`$<>\n\r\0"']/;});function gi(i,e,t,n){return i.projectRoot===e&&i.command===t&&i.args.length===n.length&&i.args.every((o,s)=>o===n[s])}function gl(i){if(!i||typeof i!="object")return false;let e=i;return typeof e.projectRoot=="string"&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var Le,Fr=f(()=>{Le=class{constructor(e){this.trustFilePath=e;}async isTrusted(e,t,n){return (await this.load()).entries.some(s=>gi(s,e,t,n))}async recordTrust(e,t,n){let o=await this.load();if(o.entries.some(l=>gi(l,e,t,n)))return;o.entries.push({projectRoot:e,command:t,args:[...n],trustedAt:new Date().toISOString()}),await G.mkdir(E.dirname(this.trustFilePath),{recursive:true});let a=`${this.trustFilePath}.${process.pid}.tmp`;try{await G.writeFile(a,JSON.stringify(o,null,2)+`
44
+ `,"utf-8"),await G.rename(a,this.trustFilePath);}catch(l){throw await G.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await G.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(gl)}:{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 kt,hi=f(()=>{mi();Fr();kt=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??Le.isCIEnvironment;}async authorize(e,t,n){let{classification:o,reason:s}=di(t,n);if(o==="denied")return this.logger.error(`[LSP:${e}] Refusing unsafe LSP command '${t}': ${s??"denied"}.`),false;if(o==="known-safe"||await this.trustStore.isTrusted(this.projectRoot,t,n))return true;if(this.isCI())return this.logger.warn(`[LSP:${e}] Skipping untrusted custom LSP command '${t}' in CI. Run 'constellation index' interactively once to approve it, or set the 'lsp' field to a known binary.`),false;let a=n.length>0?` ${n.join(" ")}`:"",l=`Trust custom LSP command for this project?
45
45
  ${t}${a}
46
46
 
47
47
  Only approve commands you recognize. Untrusted commands can execute arbitrary code.
48
- Approve?`,c=false;try{c=await this.prompt(l);}catch{c=false;}return c?(await this.trustStore.recordTrust(this.projectRoot,t,n),this.logger.log(`[LSP:${e}] Trusted custom LSP command '${t}' for this project.`),true):(this.logger.warn(`[LSP:${e}] User declined to trust LSP command '${t}'. Skipping enrichment for this language.`),false)}};});var vl,bl,kt,vi=f(()=>{re();li();Qe();hi();kr();vl={log:i=>process.stderr.write(i+`
48
+ Approve?`,c=false;try{c=await this.prompt(l);}catch{c=false;}return c?(await this.trustStore.recordTrust(this.projectRoot,t,n),this.logger.log(`[LSP:${e}] Trusted custom LSP command '${t}' for this project.`),true):(this.logger.warn(`[LSP:${e}] User declined to trust LSP command '${t}'. Skipping enrichment for this language.`),false)}};});var vl,bl,Ft,vi=f(()=>{re();li();Qe();hi();Fr();vl={log:i=>process.stderr.write(i+`
49
49
  `),warn:i=>process.stderr.write(i+`
50
50
  `),error:i=>process.stderr.write(i+`
51
- `)},bl=E.join(Ce.homedir(),".constellation","lsp-trust.json"),kt=class{constructor(e,t,n){this.projectRoot=e;this.logger=t??vl,this.policy=n??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new At({projectRoot:this.projectRoot,logger:this.logger,trustStore:new Le(bl),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 n=this.languageToServerKey.get(e),o=n?this.serversByKey.get(n):void 0;if(o)return this.toConnection(o,e);let s=this.resolveCommand(e,t);if(!s)return this.unavailableLanguages.add(e),null;let{command:a,args:l}=s,c=this.getServerKey(a,l);if(this.unavailableServerKeys.has(c))return this.unavailableLanguages.add(e),null;let u=this.serversByKey.get(c);if(u)return u.languages.add(e),this.languageToServerKey.set(e,c),this.toConnection(u,e);if(!await this.policy.authorize(e,a,l))return this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c),null;try{let d=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((b,y)=>{d.once("spawn",b),d.once("error",y);}),d.stderr?.on("data",b=>{let y=b.toString().trim();y.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${y}`);});let m=new jt(d.stdin,d.stdout,12e4),g=await m.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);m.sendNotification("initialized",{});let h={key:c,language:e,languages:new Set([e]),process:d,client:m};return this.serversByKey.set(c,h),this.languageToServerKey.set(e,c),d.on("exit",b=>{let y=this.serversByKey.get(c);if(y){y.client.dispose(),this.serversByKey.delete(c);for(let[v,x]of this.languageToServerKey.entries())x===c&&this.languageToServerKey.delete(v);}b!==0&&b!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${b}`);}),this.toConnection(h,e)}catch(d){this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let m=`[LSP:${e}] Failed to start: ${d instanceof Error?d.message:String(d)}`,g=d?.code;return g==="ENOENT"||g==="EACCES"?this.logger.warn(m):this.logger.error(m),null}}async shutdown(e){let t=this.languageToServerKey.get(e);if(!t)return;this.languageToServerKey.delete(e);let n=this.serversByKey.get(t);n&&(n.languages.delete(e),!(n.languages.size>0)&&await this.shutdownByKey(t));}async shutdownByKey(e){let t=this.serversByKey.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(n=>{let o=setTimeout(()=>{t.process.kill("SIGKILL"),n();},3e3);t.process.on("exit",()=>{clearTimeout(o),n();});});}catch(n){this.logger.warn(`[LSP:${t.language}] Graceful shutdown failed, force killing: ${n instanceof Error?n.message:String(n)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.serversByKey.delete(e);for(let[n,o]of this.languageToServerKey.entries())o===e&&this.languageToServerKey.delete(n);}}async shutdownAll(){let e=[...this.serversByKey.keys()];await Promise.allSettled(e.map(t=>this.shutdownByKey(t)));}destroyAll(){for(let e of this.serversByKey.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.serversByKey.clear(),this.languageToServerKey.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let n=de.get(e);if(!n)return null;let o=E.join(Lt,n.command);return existsSync(o)?{command:o,args:n.args}:je(n.command)?{command:n.command,args:n.args}:null}getServerKey(e,t){return `${e}\0${t.join("\0")}`}toConnection(e,t){let n=`lsp-${t}-${this.nextId++}`;return {language:t,process:e.process,id:n,sendRequest:(o,s,a)=>e.client.sendRequest(o,s,a),sendNotification:(o,s)=>e.client.sendNotification(o,s)}}};});var me,Ft=f(()=>{me=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var Ae,$r=f(()=>{O();Ae=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${T} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}if(n){if(this.isJavaScriptEnabled)try{let o=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let s=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,s),s}throw o}if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let n=await find(e,{root:this.projectRoot,configName:t});return !n||this.failedConfigFiles.has(n)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let n=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(n&&!this.failedConfigFiles.has(n)){this.failedConfigFiles.add(n);let o=t instanceof Error?t.message:String(t);console.warn(`${T} Failed to parse ${n}: ${o}`),console.warn(`${T} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${T} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var $t,Si=f(()=>{ve();$t=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),s=await this.resolveSubPath(n,o);if(s)return this.toProjectRelative(s)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?E.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,s]of Object.entries(t)){if(o.includes("*")||!Array.isArray(s))continue;let a=s[0];if(!a)continue;let l=E.resolve(n,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=E.join(this.projectRoot,"package.json"),n=await G.readFile(t,"utf-8"),s=JSON.parse(n).workspaces;if(!s)return e;let a=Array.isArray(s)?s:s.packages||[];for(let l of a){let c=await this.findWorkspaceDirs(l);for(let 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 n=e.slice(0,-2),o=E.join(this.projectRoot,n);try{let s=await G.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(E.join(o,a.name));}catch{}}else {let n=E.join(this.projectRoot,e);try{(await G.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=E.join(e,"package.json"),n=await G.readFile(t,"utf-8"),o=JSON.parse(n),s=o.name;if(!s)return null;let a=await this.findPackageEntryPoint(e,o);return a?{[s]:a}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return E.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return E.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return E.join(e,a)}}}if(t.main)return E.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let o of n){let s=E.join(e,o);try{if((await G.stat(s)).isFile())return s}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let o=E.join(e,n);try{if((await G.stat(o)).isFile())return o}catch{}}try{if((await G.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?E.dirname(e):E.dirname(e),o=[E.join(n,t+".ts"),E.join(n,t+".tsx"),E.join(n,t+".js"),E.join(n,t+".jsx"),E.join(n,t+".d.ts"),E.join(n,t,"index.ts"),E.join(n,t,"index.tsx"),E.join(n,t,"index.js"),E.join(n,t,"index.jsx")];for(let s of o)try{if((await G.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=U(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var ke,Dr=f(()=>{ve();Si();ke=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=E.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new $t(this.projectRoot,t);let n=e.toLowerCase(),o=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),s=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:s?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=E.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=E.resolve(this.tsconfigDir,a.baseUrl)),a.paths&&typeof a.paths=="object"&&(this.paths=a.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=E.resolve(this.sourceDir,e),o=await this.findFileWithExtensions(n);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=U(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let s of n){let a=await this.trySubstitution(e,t,s,o);if(a)return a}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,o]=t.split("*");if(!e.startsWith(n)||o&&!e.endsWith(o))return null;let s=n.length,a=o?e.length-o.length:e.length;return e.substring(s,a)}async trySubstitution(e,t,n,o){let s=n.replaceAll("*",o),a=E.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=E.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(a=>e.endsWith(a));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],o=n.some(a=>e.endsWith(a)),s=e;if(o&&!t){for(let a of n)if(e.endsWith(a)){s=e.slice(0,-a.length);break}}if(!t)for(let a of this.extensions){let l=s+a;if(await this.fileExists(l))return await this.resolveSymlink(l)}for(let a of this.extensions){let l=E.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await G.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await G.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=E.join(t,"package.json");try{if((await G.stat(n)).isFile())return n}catch{}let o=E.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await G.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=E.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let o=this.matchPathPattern(e,t);if(o!==null){if(typeof n=="string"){let s=await this.tryPackageImportSubstitution(n,o);if(s)return s}if(Array.isArray(n)){for(let s of n)if(typeof s=="string"){let a=await this.tryPackageImportSubstitution(s,o);if(a)return a}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),o=E.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(o)}};});var Dt,wi=f(()=>{Ft();$r();Dr();Dt=class extends me{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new Ae(e,t)}getImportResolver(e,t){return new ke(e,t)}};});var Ot,Ci=f(()=>{Ft();$r();Dr();Ot=class extends me{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new Ae(e,t)}getImportResolver(e,t){return new ke(e,t)}};});async function ge(i,e,t,n,o,s=[]){let a=await t.resolve(i),l=xi(i,a),c=o(i,a,l),u=l?void 0:Nt(a);n[e.toString()]={source:i,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function xi(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var Or,Ze=f(()=>{ve();Or=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function xl(i,e,t,n){let o=i.childForFieldName("name");if(!o)return;let s,a;if(o.type==="aliased_import"){let l=o.childForFieldName("name"),c=o.childForFieldName("alias");s=l?l.text:o.text,a={local:c?c.text:s.split(".")[0],original:s,isDefault:false,isNamespace:false};}else s=o.text,a={local:s.split(".")[0],original:s,isDefault:false,isNamespace:false};await ge(s,i.startPosition.row,e,t,n,[a]);}function El(i,e){if(!e)return [];let t=[],n=i.childForFieldName("name");if(n){if(n.type==="aliased_import"){let s=n.childForFieldName("name"),a=n.childForFieldName("alias");s&&t.push({local:a?a.text:s.text,original:s.text,isDefault:false,isNamespace:false});}else t.push({local:n.text,original:n.text,isDefault:false,isNamespace:false});return t}let o=false;for(let s=0;s<i.childCount;s++){let a=i.child(s);if(a){if(a.type==="import"){o=true;continue}if(o){if(a.type==="dotted_name"||a.type==="identifier")t.push({local:a.text,original:a.text,isDefault:false,isNamespace:false});else if(a.type==="aliased_import"){let l=a.childForFieldName("name"),c=a.childForFieldName("alias");l&&t.push({local:c?c.text:l.text,original:l.text,isDefault:false,isNamespace:false});}}}}return t}async function _l(i,e,t,n){let o,s=i.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<i.childCount;c++){let u=i.child(c);if(u){if(u.type==="relative_import"){l=u.text;break}(u.type==="."||u.type==="import_prefix")&&(l+=u.text);}}o=l||".";}let a=El(i,!!s);await ge(o,i.startPosition.row,e,t,n,a);}async function Pl(i,e,t,n){await ge("__future__",i.startPosition.row,e,t,n,[]);}function Mr(){return {language:"python",handlers:new Map([["import_statement",xl],["import_from_statement",_l],["future_import_statement",Pl]]),classifyImportType:Cl}}var Cl,Mt=f(()=>{Xe();Ze();Xe();Cl=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return qe.has(n)?"builtin":"alias"};});var Ut,Ei=f(()=>{Mt();Ut=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=E.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(qe.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),o=await this.tryResolveFile(E.resolve(this.projectRoot,n));return o?E.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),o=t<=1?"":"../".repeat(t-1),s=n?o+n.replace(/\./g,"/"):o.slice(0,-1)||".",a=E.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?E.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,E.join(e,"__init__.py"),E.join(e,"__init__.pyi")];for(let n of t)try{return await Gt.promises.access(n,Gt.constants.F_OK),n}catch{continue}return null}};});var Bt,_i=f(()=>{Ft();Ei();Bt=class extends me{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new Ut(e,process.cwd())}};});function tt(i){return Rl[i]??i.charAt(0).toUpperCase()+i.slice(1)}var Rl,et,Wt,zt=f(()=>{wi();Ci();_i();Rl={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"};et={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},Wt=class{constructor(e){this.config=e;this.registerPlugin(new Dt),this.registerPlugin(new Ot),this.registerPlugin(new Bt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Il,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??et.javascript};typescript={language:()=>Tl.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??et.typescript};python={language:()=>Nl,fileExtensions:()=>this.config?.languages.python?.fileExtensions??et.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function Fe(i,e,t=32){let n=i.parent,o=0;for(;n!==null&&o<t;){if(e(n))return n;n=n.parent,o++;}return null}var Ht,Ur=f(()=>{Ht=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function Gr(i,e){if(i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"||i.type==="jsx_closing_element"){let t=i.childForFieldName("name");t!==null&&jl(t,e);}for(let t of i.namedChildren)t&&Gr(t,e);}function jl(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(Se(i.startPosition.row,i.startPosition.column),"call");return}if(i.type==="member_expression"||i.type==="nested_identifier"){let t=i.childForFieldName("property");t!==null&&e.set(Se(t.startPosition.row,t.startPosition.column),"call");}}var Pi=f(()=>{rt();});function $e(i,e){i.rootNode&&(Ni(i.rootNode,e),Gr(i.rootNode,e));}function Ni(i,e){if(Ll.has(i.type)){let t=Al(i);t!==null&&e.set(Se(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&Ni(t,e);}function Al(i){if(Fl(i))return "declaration";if(Hl(i))return "read";if(Wl(i))return "type";let e=Fe(i,t=>t.type==="decorator");return e!==null&&Ol(i,e)?"call":Dl(i)?"instantiate":$l(i)?"call":Ml(i)||Ul(i)||Gl(i)||Zl(i)||Ql(i)?"write":Kl(i)?"import-use":"read"}function Fl(i){let e=i.parent;return e===null?false:!!(kl.has(e.type)&&(e.childForFieldName("name")===i||e.childForFieldName("property")===i)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===i||e.type==="import_specifier"&&(e.childForFieldName("name")===i||e.childForFieldName("alias")===i)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===i&&i.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===i||e.type==="enum_body")}function $l(i){let e=i.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function Dl(i){let e=i.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function Ol(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call_expression"){let n=t.childForFieldName("function");if(n===i||n?.type==="member_expression"&&n.childForFieldName("property")===i)return true}return t.type==="member_expression"&&t.childForFieldName("property")===i}function Ml(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="unary_expression")return t.child(0)?.type==="delete";if(t.type==="member_expression"&&t.childForFieldName("object")===e||Ht.has(t.type))return false;e=t;}return false}function Ul(i){let e=i.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===i)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function Gl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="assignment_expression"||t.type==="augmented_assignment_expression")&&t.childForFieldName("left")===e)return true;if(t.type==="member_expression"&&t.childForFieldName("object")===e||t.type==="subscript_expression"&&t.childForFieldName("object")!==e||Ht.has(t.type))return false;e=t;}return false}function Wl(i){let e=i.parent,t=i;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let n=e.namedChild(1);return n===null?false:n===t||zl(n,i)}if(Bl.has(e.type))return true;if(Ht.has(e.type))return false;t=e,e=e.parent;}return false}function zl(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function Hl(i){return Fe(i,t=>t.type==="type_query")!==null}function Kl(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,n=Yl(i);return Xl(n,t)?!Jl(i,t):false}function Jl(i,e){let t=i.parent;for(;t!==null;){if(Vl.has(t.type)&&ql(t,e))return true;t=t.parent;}return false}function ql(i,e){for(let t of i.namedChildren){if(t.type==="lexical_declaration"||t.type==="variable_declaration")for(let n of t.namedChildren){if(n.type!=="variable_declarator")continue;if(n.childForFieldName("name")?.text===e)return true}if(t.type==="formal_parameters")for(let n of t.namedChildren){if(n.type!=="required_parameter"&&n.type!=="optional_parameter")continue;let o=n.childForFieldName("pattern");if(o?.type==="identifier"&&o.text===e)return true}}return false}function Yl(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function Xl(i,e){for(let t of i.descendantsOfType("namespace_import")){let n=t.namedChild(0);if(n!==null&&n.text===e)return true}return false}function Ql(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function Zl(i){let e=i.parent;if(e===null||!Ii.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===i||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==i)return false;let t=e;for(;t!==null;){let n=t.parent;if(n===null)return false;if(n.type==="variable_declarator"&&n.childForFieldName("name")===t||(n.type==="assignment_expression"||n.type==="augmented_assignment_expression")&&n.childForFieldName("left")===t||(n.type==="required_parameter"||n.type==="optional_parameter")&&n.childForFieldName("pattern")===t||n.type==="formal_parameters"||n.type==="for_in_statement"&&n.childForFieldName("left")===t)return true;if(!Ii.has(n.type))return false;t=n;}return false}var Ll,kl,Bl,Vl,Ii,Kt=f(()=>{rt();Ur();Pi();Ll=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));kl=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"]));Bl=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"]));Vl=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Ii=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function Ti(i,e){$e(i,e);}var Ri=f(()=>{Kt();});function ji(i,e){$e(i,e);}var Li=f(()=>{Kt();});function Ai(i,e){if(!i.rootNode)return;let t=Sc(i.rootNode);ki(i.rootNode,e,t);}function ki(i,e,t){if(ec.has(i.type)){let n=tc(i,t);n!==null&&e.set(Se(i.startPosition.row,i.startPosition.column),n);}for(let n of i.namedChildren)n&&ki(n,e,t);}function tc(i,e){if(rc(i))return "declaration";if(oc(i))return "read";if(ic(i))return "declaration";if(sc(i))return "type";let t=Fe(i,n=>n.type==="decorator");return t!==null&&ac(i,t)||lc(i)?"call":cc(i)||pc(i)||uc(i)||mc(i)||fc(i)?"write":hc(i,e)?"import-use":"read"}function rc(i){let e=i.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===i||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===i)return true;if(e.type==="list_splat_pattern"||e.type==="dictionary_splat_pattern"){let t=e.parent;if(t?.type==="parameters"||t?.type==="lambda_parameters")return true}return !!(e.type==="as_pattern_target"||nc(i))}function nc(i){let e=i.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function ic(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(Br.has(e.type))return false;e=e.parent;}return false}function oc(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function sc(i){return Fe(i,t=>t.type==="type")!==null}function ac(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call"){let n=t.childForFieldName("function");if(n===i||n?.type==="attribute"&&n.childForFieldName("attribute")===i)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===i}function lc(i){let e=i.parent;if(e?.type==="call"&&e.childForFieldName("function")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function cc(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="delete_statement")return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||Br.has(t.type))return false;e=t;}return false}function pc(i){let e=i.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function uc(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function mc(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment"&&t.childForFieldName("left")===e)return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||t.type==="subscript"&&t.childForFieldName("value")!==e)return false;if(dc.has(t.type)){e=t;continue}if(Br.has(t.type))return false;e=t;}return false}function fc(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="for_statement"||t.type==="for_in_clause")&&t.childForFieldName("left")===e)return true;if(!gc.has(t.type))return false;e=t;}return false}function hc(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let n=i.text;return e.has(n)?!vc(i,n):false}function vc(i,e){let t=i.parent;for(;t!==null;){if(yc.has(t.type)&&bc(t,e))return true;t=t.parent;}return false}function bc(i,e){for(let t of i.namedChildren){if(t.type==="expression_statement"){let n=t.namedChild(0);if(n?.type==="assignment"){let o=n.childForFieldName("left");if(o?.type==="identifier"&&o.text===e)return true}}if(t.type==="parameters"){for(let n of t.namedChildren)if(n.type==="identifier"&&n.text===e||(n.type==="typed_parameter"||n.type==="typed_default_parameter"||n.type==="default_parameter")&&n.namedChild(0)?.type==="identifier"&&n.namedChild(0)?.text===e)return true}}return false}function Sc(i){let e=new Set;for(let t of i.descendantsOfType("import_statement"))for(let n of t.namedChildren)if(n.type==="dotted_name"&&e.add(n.text),n.type==="aliased_import"){let o=n.childForFieldName("alias");o&&e.add(o.text);}return e}var ec,Br,dc,gc,yc,Fi=f(()=>{rt();Ur();ec=Object.freeze(new Set(["identifier"])),Br=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));dc=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));gc=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));yc=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function Di(i,e){let t=new Map;switch(e){case "typescript":$e(i,t);break;case "tsx":Ti(i,t);break;case "javascript":ji(i,t);break;case "python":Ai(i,t);break}return t}function Se(i,e){return `${i}:${e}`}var $i,rt=f(()=>{Kt();Ri();Li();Fi();$i=Object.freeze(new Set(["typescript","javascript","python"]));});function xc(i,e){return $i.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function Ec(i){let e=[];for(let[t,n]of i.entries()){let o=t.indexOf(":");if(o<0)continue;let s=Number(t.slice(0,o)),a=Number(t.slice(o+1));!Number.isFinite(s)||!Number.isFinite(a)||e.push({line:s,column:a,referenceType:n});}return e.sort((t,n)=>t.line-n.line||t.column-n.column),e}var Vt,Ui=f(()=>{rt();re();Vt=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let o=await n();if(!o)throw new Error(`Failed to load language: ${t}`);t==="typescript"&&e.toLowerCase().endsWith(".tsx")&&(o=Tl.tsx);let s=new wc;s.setLanguage(o);let a=await S.getFileStats(e),l=10*1024*1024,c,u;if(a.size<=l){let g=await S.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=xc(t,e),d=p===null?[]:Ec(Di(c,p));return {tree:c,classificationMap:{filePath:e,entries:d},content:u}}async parseWithStream(e,t,n){let o=null;try{o=await G.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(p=>{if(n>50*1024*1024){let m=Math.round(p/n*100);m>c+10&&(process.stderr.write(` Parsing large file: ${m}%...
52
- `),c=m);}let d=Gt.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)}
53
- `);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var Jt,Bi=f(()=>{re();ve();O();Jt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Gi();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(s=>!t.ignores(s.relativePath)&&this.matchesLanguageExtension(s,e.languages))}async scanSpecificFiles(e,t){let n=[],o=null;t.exclude&&t.exclude.length>0&&(o=Gi().add(t.exclude));let s=await G__default.realpath(this.rootPath);for(let a of e)try{let l=E__default.isAbsolute(a)?a:E__default.join(this.rootPath,a),c=await G__default.lstat(l);if(c.isSymbolicLink()){let u=await G__default.realpath(l);if(!u.startsWith(s+E__default.sep)&&u!==s){console.warn(`${T} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let p=await G__default.stat(l);if(!p.isFile())continue;let d=U(this.rootPath,l);if(o&&o.ignores(d))continue;let m=this.detectLanguage(d,t.languages);if(!m)continue;n.push({path:l,relativePath:d,language:m,size:p.size});}else if(c.isFile()){let u=U(this.rootPath,l);if(o&&o.ignores(u))continue;let p=this.detectLanguage(u,t.languages);if(!p)continue;n.push({path:l,relativePath:u,language:p,size:c.size});}}catch{console.warn(`${T} Skipping inaccessible file: ${a}`);}return n}async loadGitignoreRules(e,t){let n=[],o=t;for(;;){let s=E__default.join(o,".gitignore");await S.fileIsReadable(s)&&n.unshift(s);let a=E__default.dirname(o);if(a===o)break;o=a;let l=E__default.join(o,".git");if(await S.directoryExists(l)){let c=E__default.join(o,".gitignore");await S.fileIsReadable(c)&&!n.includes(c)&&n.unshift(c);break}}for(let s of n)try{let a=await S.readFile(s);e.add(a);}catch{console.warn(`${T} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,n,o){let s=[],a=t||e,l=n||await G__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=(await G__default.readdir(e,{withFileTypes:!0})).map(p=>(p.name=p.name.normalize("NFC"),p)).sort((p,d)=>p.name<d.name?-1:p.name>d.name?1:0);for(let p of u){let d=E__default.join(e,p.name),m=U(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 G__default.stat(d);s.push({path:d,relativePath:m,language:"",size:g.size});}else if(p.isSymbolicLink())try{let g=await G__default.realpath(d);if(!g.startsWith(l+E__default.sep)&&g!==l){console.warn(`${T} Skipping symlink pointing outside project: ${d} -> ${g}`);continue}let h=await G__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(`${T} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${q} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let n=E__default.extname(e.path).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return e.language=o,true;return false}detectLanguage(e,t){let n=E__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return o;return null}};});var _c,Pc,Ic,Wi,zi=f(()=>{Xe();_c=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Pc=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(_c).optional()}),Ic=z.record(z.string(),Pc),Wi=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Ic.optional(),classificationMap:wr.optional()});});var Tc,qt,Vi=f(()=>{_r();Tc=promisify(Wr__default.gunzip),qt=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],n=Wr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(e);return await pipeline(s,n),await o,Er(Buffer.concat(t)).toString("base64")}async compress(e){let t=[],n=Wr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(this.serializeASTChunks(e));return await pipeline(s,n),await o,Er(Buffer.concat(t)).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await Tc(t);return JSON.parse(n.toString("utf-8"))}};});function qi(i){let n=i>=5e4?27e5:i>=1e4?18e5:9e5,o=process.env.CONSTELLATION_AST_WAIT_MAX_MS,s=n;if(o!==void 0&&o!==""){let a=Number(o);Number.isFinite(a)&&Number.isInteger(a)&&a>0?s=a:Ji||(process.stderr.write(`[constellation] Ignoring invalid CONSTELLATION_AST_WAIT_MAX_MS=${o}; using default tier cap.
54
- `),Ji=true);}return Math.min(12e4+i*1e3,s)}var Ji,Yi=f(()=>{Ji=false;});var zr,Yt=f(()=>{zr=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 De(i,e){let t=e??i;return {line:t.startPosition.row+1,column:t.startPosition.column}}function Oe(i){return i?i.text:null}function Zi(){return {language:"javascript",handlers:new Map(Qi)}}function eo(){return {language:"typescript",handlers:new Map([...Qi,["interface_declaration",Lc],["public_field_definition",Xi],["property_signature",Xi]])}}var Rc,jc,Lc,Ac,Xi,kc,Qi,to=f(()=>{Rc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);n&&e.symbols.push({name:n,kind:"function",...De(i,t)});},jc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);if(n)return e.symbols.push({name:n,kind:"class",...De(i,t)}),{...e,enclosingType:n}},Lc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);if(n)return e.symbols.push({name:n,kind:"interface",...De(i,t)}),{...e,enclosingType:n}},Ac=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);n&&e.symbols.push({name:n,kind:"method",...De(i,t)});},Xi=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);n&&e.symbols.push({name:n,kind:"property",...De(i,t)});},kc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);if(!n)return;let o=i.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:n,kind:s?"function":"variable",...De(i,t)});},Qi=[["function_declaration",Rc],["class_declaration",jc],["method_definition",Ac],["variable_declarator",kc]];});function Hr(i){return {line:i.startPosition.row+1,column:i.startPosition.column}}function ro(){return {language:"python",handlers:new Map([["function_definition",Fc],["class_definition",$c],["assignment",Dc]])}}var Fc,$c,Dc,no=f(()=>{Fc=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let n=e.enclosingType?"method":"function";e.symbols.push({name:t.text,kind:n,...Hr(t)});},$c=(i,e)=>{let t=i.childForFieldName("name");if(t)return e.symbols.push({name:t.text,kind:"class",...Hr(t)}),{...e,enclosingType:t.text}},Dc=(i,e)=>{let t=i.childForFieldName("left");if(!t||t.type!=="identifier")return;let n=e.enclosingType?"property":"variable";e.symbols.push({name:t.text,kind:n,...Hr(t)});};});var io,oo=f(()=>{to();no();io=[Zi(),eo(),ro()];});var Xt,so=f(()=>{oo();Xt=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??io)this.languageHandlers.set(t.language,t.handlers);}extract(e,t){let n=this.languageHandlers.get(t);if(!n)return [];let o={symbols:[]};return this.walk(e.rootNode,o,n),o.symbols}walk(e,t,n){let s=n.get(e.type)?.(e,t)??t;for(let a=0;a<e.childCount;a++){let l=e.child(a);l&&this.walk(l,s,n);}}};});function Oc(i){let e=Math.max(0,i)/1e3;if(e<60)return `(${e.toFixed(1)}s)`;let t=Math.floor(e/60),n=Math.floor(e%60);return `(${t}m ${n}s)`}function ao(){let i=performance.now();return {elapsed:()=>Oc(performance.now()-i),reset:()=>{i=performance.now();},ms:()=>performance.now()-i}}var lo=f(()=>{});function Kr(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var Zt,co=f(()=>{Yt();Zt=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(Kr).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:stripVTControlCharacters(e.map(Kr).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:stripVTControlCharacters(e.map(Kr).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,n){this.entries.push({level:e,message:stripVTControlCharacters(t),timestamp:new Date().toISOString(),code:n});}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||!zr.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!zr.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:stripVTControlCharacters(t),timestamp:new Date().toISOString(),code:n});let o=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?o.call(console,t):console[e==="info"?"log":e](t);}};});function Me(i){if(i&&typeof i=="object")try{i.alreadyReported=!0;}catch{}}function ie(i){return !!(i&&typeof i=="object"&&i.alreadyReported)}function Vr(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var po,Uc,Gc,er,Jr=f(()=>{Ie();lo();co();O();po=Math.floor(1e3/15),Uc={interval:100,frames:["\u280B","\u2819","\u281A","\u2813"]},Gc=new Set(["EPIPE","ENOTCONN","EBADF"]);er=class i{static activeInstance=null;mode;stream;logCollector=new Zt;spinner=null;currentPhaseLabel=null;currentPhaseTracker=null;lastUpdateAt=0;pendingUpdate=null;pendingUpdateTimer=null;paused=false;originalConsole=null;intercepting=false;warningBucket=new Map;stopped=false;constructor(e){if(i.activeInstance&&!i.activeInstance.stopped)throw new Error("Reporter is a singleton \u2014 only one instance may be active at a time. Call stop() on the existing Reporter before constructing another.");this.mode=e.mode,this.stream=e.stream??process.stderr,i.activeInstance=this,this.installConsoleInterception();}async phase(e,t,n){this.start(e);let o=this.makePhaseContext();try{let s=await t(o);return this.flushPendingUpdate(),this.flushAggregatedWarnings(),this.succeed(n?.successText??e),s}catch(s){this.flushPendingUpdate(),this.flushAggregatedWarnings();let a=n?.failText??`${e} failed: ${s instanceof Error?s.message:String(s)}`;throw this.fail(a),Me(s),s}}start(e){this.currentPhaseLabel=e,this.currentPhaseTracker=ao(),this.mode==="spinner"?(this.spinner?this.spinner.text=this.composeSpinnerText(e):this.spinner=Mc({text:this.composeSpinnerText(e),stream:this.stream,spinner:Uc}),this.paused||this.spinner.start()):(this.mode==="verbose"||this.mode==="plain")&&this.writeLine(`${Z} ${e}\u2026`);}update(e){if(!this.currentPhaseLabel)return;if(this.currentPhaseLabel=e,this.mode==="verbose"){this.writeLine(`${Z} ${e}`);return}if(this.mode!=="spinner")return;let t=Date.now();this.pendingUpdate=e;let n=t-this.lastUpdateAt;n>=po?this.flushPendingUpdate():this.pendingUpdateTimer||(this.pendingUpdateTimer=setTimeout(()=>this.flushPendingUpdate(),po-n),this.pendingUpdateTimer.unref?.());}succeed(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",n=`${w} ${t}`;this.terminatePhase(n,"info");}fail(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",n=`${q} ${t}`;this.terminatePhase(n,"error");}info(e){if(this.mode==="quiet"){this.logCollector.record("info",e);return}this.logCollector.record("info",e),this.writeLine(`${Z} ${e}`);}warn(e,t){if(this.logCollector.record("warn",e,t?.code),this.currentPhaseLabel&&t?.code){let n=this.warningBucket.get(t.code);n?(n.count+=1,n.samples.length<3&&n.samples.push(e)):this.warningBucket.set(t.code,{code:t.code,count:1,samples:[e]});return}this.writeLine(`${T} ${e}`);}error(e,t){this.logCollector.record("error",e,t?.code),this.writeLine(`${q} ${e}`);}detail(e){this.logCollector.record("info",e),this.mode==="verbose"&&this.writeLine(` ${V.muted(e)}`);}log(e){this.logCollector.record("info",e),this.mode!=="quiet"&&this.writeLine(e);}summary(e){this.logCollector.record("info",e),this.writeLine(e);}step(e){let t=this;return {ok(n){t.renderSubStep("ok",n??e);},fail(n){t.renderSubStep("fail",n??e);},skip(n){t.renderSubStep("skip",n??e);}}}renderSubStep(e,t){let o=`${e==="ok"?w:e==="fail"?q:V.muted("-")} ${e==="skip"?V.muted(t):t}`,s=e==="fail"?"error":"info";this.logCollector.record(s,t),!(this.mode==="quiet"&&e!=="fail")&&this.writeLine(o);}pause(){this.paused||(this.paused=true,this.spinner?.isSpinning&&this.spinner.stop());}resume(){this.paused&&(this.paused=false,this.mode==="spinner"&&this.currentPhaseLabel&&this.spinner&&(this.spinner.text=this.composeSpinnerText(this.currentPhaseLabel),this.spinner.start()));}getEntries(){return this.logCollector.getEntries()}getReportableErrors(){return this.logCollector.getReportableErrors()}hasErrors(){return this.logCollector.hasErrors()}hasWarnings(){return this.logCollector.hasWarnings()}hasReportableErrors(){return this.logCollector.hasReportableErrors()}stop(){this.stopped||(this.stopped=true,this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.flushAggregatedWarnings(),this.spinner?.isSpinning&&this.spinner.stop(),this.spinner=null,this.uninstallConsoleInterception(),i.activeInstance===this&&(i.activeInstance=null));}composeSpinnerText(e){return e}flushPendingUpdate(){if(this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.pendingUpdate===null||!this.spinner){this.pendingUpdate=null;return}this.spinner.text=this.composeSpinnerText(this.pendingUpdate),this.pendingUpdate=null,this.lastUpdateAt=Date.now();}terminatePhase(e,t){this.logCollector.record(t,e),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:n}of this.warningBucket.values()){if(t===1){this.writeLine(`${T} ${n[0]}`);continue}let o=`${t} ${e} warnings (showing ${Math.min(n.length,3)}): ${n.slice(0,3).join(" | ")}. Use --verbose to see all.`;this.logCollector.record("warn",o,e),this.writeLine(`${T} ${o}`);}this.warningBucket.clear();}}makePhaseContext(){return {update:e=>this.update(e),detail:e=>this.detail(e),step:e=>this.step(e),warn:(e,t)=>this.warn(e,t),elapsed:()=>this.currentPhaseTracker?.elapsed()??"(0.0s)"}}writeLine(e){try{this.mode==="spinner"&&this.spinner?.isSpinning?(this.spinner.clear(),this.stream.write(e+`
51
+ `)},bl=E.join(Ce.homedir(),".constellation","lsp-trust.json"),Ft=class{constructor(e,t,n){this.projectRoot=e;this.logger=t??vl,this.policy=n??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new kt({projectRoot:this.projectRoot,logger:this.logger,trustStore:new Le(bl),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 n=this.languageToServerKey.get(e),o=n?this.serversByKey.get(n):void 0;if(o)return this.toConnection(o,e);let s=this.resolveCommand(e,t);if(!s)return this.unavailableLanguages.add(e),null;let{command:a,args:l}=s,c=this.getServerKey(a,l);if(this.unavailableServerKeys.has(c))return this.unavailableLanguages.add(e),null;let u=this.serversByKey.get(c);if(u)return u.languages.add(e),this.languageToServerKey.set(e,c),this.toConnection(u,e);if(!await this.policy.authorize(e,a,l))return this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c),null;try{let d=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((b,y)=>{d.once("spawn",b),d.once("error",y);}),d.stderr?.on("data",b=>{let y=b.toString().trim();y.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${y}`);});let m=new Lt(d.stdin,d.stdout,12e4),g=await m.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);m.sendNotification("initialized",{});let h={key:c,language:e,languages:new Set([e]),process:d,client:m};return this.serversByKey.set(c,h),this.languageToServerKey.set(e,c),d.on("exit",b=>{let y=this.serversByKey.get(c);if(y){y.client.dispose(),this.serversByKey.delete(c);for(let[v,x]of this.languageToServerKey.entries())x===c&&this.languageToServerKey.delete(v);}b!==0&&b!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${b}`);}),this.toConnection(h,e)}catch(d){this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let m=`[LSP:${e}] Failed to start: ${d instanceof Error?d.message:String(d)}`,g=d?.code;return g==="ENOENT"||g==="EACCES"?this.logger.warn(m):this.logger.error(m),null}}async shutdown(e){let t=this.languageToServerKey.get(e);if(!t)return;this.languageToServerKey.delete(e);let n=this.serversByKey.get(t);n&&(n.languages.delete(e),!(n.languages.size>0)&&await this.shutdownByKey(t));}async shutdownByKey(e){let t=this.serversByKey.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(n=>{let o=setTimeout(()=>{t.process.kill("SIGKILL"),n();},3e3);t.process.on("exit",()=>{clearTimeout(o),n();});});}catch(n){this.logger.warn(`[LSP:${t.language}] Graceful shutdown failed, force killing: ${n instanceof Error?n.message:String(n)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.serversByKey.delete(e);for(let[n,o]of this.languageToServerKey.entries())o===e&&this.languageToServerKey.delete(n);}}async shutdownAll(){let e=[...this.serversByKey.keys()];await Promise.allSettled(e.map(t=>this.shutdownByKey(t)));}destroyAll(){for(let e of this.serversByKey.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.serversByKey.clear(),this.languageToServerKey.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let n=de.get(e);if(!n)return null;let o=E.join(At,n.command);return existsSync(o)?{command:o,args:n.args}:je(n.command)?{command:n.command,args:n.args}:null}getServerKey(e,t){return `${e}\0${t.join("\0")}`}toConnection(e,t){let n=`lsp-${t}-${this.nextId++}`;return {language:t,process:e.process,id:n,sendRequest:(o,s,a)=>e.client.sendRequest(o,s,a),sendNotification:(o,s)=>e.client.sendNotification(o,s)}}};});var me,$t=f(()=>{me=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var Ae,Dr=f(()=>{O();Ae=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${T} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}if(n){if(this.isJavaScriptEnabled)try{let o=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let s=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,s),s}throw o}if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let n=await find(e,{root:this.projectRoot,configName:t});return !n||this.failedConfigFiles.has(n)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let n=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(n&&!this.failedConfigFiles.has(n)){this.failedConfigFiles.add(n);let o=t instanceof Error?t.message:String(t);console.warn(`${T} Failed to parse ${n}: ${o}`),console.warn(`${T} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${T} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var Dt,Si=f(()=>{ve();Dt=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),s=await this.resolveSubPath(n,o);if(s)return this.toProjectRelative(s)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?E.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,s]of Object.entries(t)){if(o.includes("*")||!Array.isArray(s))continue;let a=s[0];if(!a)continue;let l=E.resolve(n,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=E.join(this.projectRoot,"package.json"),n=await G.readFile(t,"utf-8"),s=JSON.parse(n).workspaces;if(!s)return e;let a=Array.isArray(s)?s:s.packages||[];for(let l of a){let c=await this.findWorkspaceDirs(l);for(let 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 n=e.slice(0,-2),o=E.join(this.projectRoot,n);try{let s=await G.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(E.join(o,a.name));}catch{}}else {let n=E.join(this.projectRoot,e);try{(await G.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=E.join(e,"package.json"),n=await G.readFile(t,"utf-8"),o=JSON.parse(n),s=o.name;if(!s)return null;let a=await this.findPackageEntryPoint(e,o);return a?{[s]:a}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return E.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return E.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return E.join(e,a)}}}if(t.main)return E.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let o of n){let s=E.join(e,o);try{if((await G.stat(s)).isFile())return s}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let o=E.join(e,n);try{if((await G.stat(o)).isFile())return o}catch{}}try{if((await G.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?E.dirname(e):E.dirname(e),o=[E.join(n,t+".ts"),E.join(n,t+".tsx"),E.join(n,t+".js"),E.join(n,t+".jsx"),E.join(n,t+".d.ts"),E.join(n,t,"index.ts"),E.join(n,t,"index.tsx"),E.join(n,t,"index.js"),E.join(n,t,"index.jsx")];for(let s of o)try{if((await G.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=U(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var ke,Or=f(()=>{ve();Si();ke=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=E.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Dt(this.projectRoot,t);let n=e.toLowerCase(),o=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),s=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:s?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=E.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=E.resolve(this.tsconfigDir,a.baseUrl)),a.paths&&typeof a.paths=="object"&&(this.paths=a.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=E.resolve(this.sourceDir,e),o=await this.findFileWithExtensions(n);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=U(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let s of n){let a=await this.trySubstitution(e,t,s,o);if(a)return a}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,o]=t.split("*");if(!e.startsWith(n)||o&&!e.endsWith(o))return null;let s=n.length,a=o?e.length-o.length:e.length;return e.substring(s,a)}async trySubstitution(e,t,n,o){let s=n.replaceAll("*",o),a=E.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=E.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(a=>e.endsWith(a));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],o=n.some(a=>e.endsWith(a)),s=e;if(o&&!t){for(let a of n)if(e.endsWith(a)){s=e.slice(0,-a.length);break}}if(!t)for(let a of this.extensions){let l=s+a;if(await this.fileExists(l))return await this.resolveSymlink(l)}for(let a of this.extensions){let l=E.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await G.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await G.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=E.join(t,"package.json");try{if((await G.stat(n)).isFile())return n}catch{}let o=E.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await G.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=E.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let o=this.matchPathPattern(e,t);if(o!==null){if(typeof n=="string"){let s=await this.tryPackageImportSubstitution(n,o);if(s)return s}if(Array.isArray(n)){for(let s of n)if(typeof s=="string"){let a=await this.tryPackageImportSubstitution(s,o);if(a)return a}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),o=E.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(o)}};});var Ot,wi=f(()=>{$t();Dr();Or();Ot=class extends me{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new Ae(e,t)}getImportResolver(e,t){return new ke(e,t)}};});var Mt,Ci=f(()=>{$t();Dr();Or();Mt=class extends me{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new Ae(e,t)}getImportResolver(e,t){return new ke(e,t)}};});async function ge(i,e,t,n,o,s=[]){let a=await t.resolve(i),l=xi(i,a),c=o(i,a,l),u=l?void 0:Tt(a);n[e.toString()]={source:i,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function xi(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var Mr,Ze=f(()=>{ve();Mr=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function xl(i,e,t,n){let o=i.childForFieldName("name");if(!o)return;let s,a;if(o.type==="aliased_import"){let l=o.childForFieldName("name"),c=o.childForFieldName("alias");s=l?l.text:o.text,a={local:c?c.text:s.split(".")[0],original:s,isDefault:false,isNamespace:false};}else s=o.text,a={local:s.split(".")[0],original:s,isDefault:false,isNamespace:false};await ge(s,i.startPosition.row,e,t,n,[a]);}function El(i,e){if(!e)return [];let t=[],n=i.childForFieldName("name");if(n){if(n.type==="aliased_import"){let s=n.childForFieldName("name"),a=n.childForFieldName("alias");s&&t.push({local:a?a.text:s.text,original:s.text,isDefault:false,isNamespace:false});}else t.push({local:n.text,original:n.text,isDefault:false,isNamespace:false});return t}let o=false;for(let s=0;s<i.childCount;s++){let a=i.child(s);if(a){if(a.type==="import"){o=true;continue}if(o){if(a.type==="dotted_name"||a.type==="identifier")t.push({local:a.text,original:a.text,isDefault:false,isNamespace:false});else if(a.type==="aliased_import"){let l=a.childForFieldName("name"),c=a.childForFieldName("alias");l&&t.push({local:c?c.text:l.text,original:l.text,isDefault:false,isNamespace:false});}}}}return t}async function _l(i,e,t,n){let o,s=i.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<i.childCount;c++){let u=i.child(c);if(u){if(u.type==="relative_import"){l=u.text;break}(u.type==="."||u.type==="import_prefix")&&(l+=u.text);}}o=l||".";}let a=El(i,!!s);await ge(o,i.startPosition.row,e,t,n,a);}async function Pl(i,e,t,n){await ge("__future__",i.startPosition.row,e,t,n,[]);}function Ur(){return {language:"python",handlers:new Map([["import_statement",xl],["import_from_statement",_l],["future_import_statement",Pl]]),classifyImportType:Cl}}var Cl,Ut=f(()=>{Xe();Ze();Xe();Cl=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return qe.has(n)?"builtin":"alias"};});var Gt,Ei=f(()=>{Ut();Gt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=E.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(qe.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),o=await this.tryResolveFile(E.resolve(this.projectRoot,n));return o?E.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),o=t<=1?"":"../".repeat(t-1),s=n?o+n.replace(/\./g,"/"):o.slice(0,-1)||".",a=E.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?E.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,E.join(e,"__init__.py"),E.join(e,"__init__.pyi")];for(let n of t)try{return await Bt.promises.access(n,Bt.constants.F_OK),n}catch{continue}return null}};});var zt,_i=f(()=>{$t();Ei();zt=class extends me{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new Gt(e,process.cwd())}};});function tt(i){return Rl[i]??i.charAt(0).toUpperCase()+i.slice(1)}var Rl,et,Wt,Ht=f(()=>{wi();Ci();_i();Rl={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"};et={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},Wt=class{constructor(e){this.config=e;this.registerPlugin(new Ot),this.registerPlugin(new Mt),this.registerPlugin(new zt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Il,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??et.javascript};typescript={language:()=>Tl.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??et.typescript};python={language:()=>Nl,fileExtensions:()=>this.config?.languages.python?.fileExtensions??et.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function Fe(i,e,t=32){let n=i.parent,o=0;for(;n!==null&&o<t;){if(e(n))return n;n=n.parent,o++;}return null}var Kt,Gr=f(()=>{Kt=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function Br(i,e){if(i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"||i.type==="jsx_closing_element"){let t=i.childForFieldName("name");t!==null&&jl(t,e);}for(let t of i.namedChildren)t&&Br(t,e);}function jl(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(Se(i.startPosition.row,i.startPosition.column),"call");return}if(i.type==="member_expression"||i.type==="nested_identifier"){let t=i.childForFieldName("property");t!==null&&e.set(Se(t.startPosition.row,t.startPosition.column),"call");}}var Pi=f(()=>{rt();});function $e(i,e){i.rootNode&&(Ni(i.rootNode,e),Br(i.rootNode,e));}function Ni(i,e){if(Ll.has(i.type)){let t=Al(i);t!==null&&e.set(Se(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&Ni(t,e);}function Al(i){if(Fl(i))return "declaration";if(Hl(i))return "read";if(zl(i))return "type";let e=Fe(i,t=>t.type==="decorator");return e!==null&&Ol(i,e)?"call":Dl(i)?"instantiate":$l(i)?"call":Ml(i)||Ul(i)||Gl(i)||Zl(i)||Ql(i)?"write":Kl(i)?"import-use":"read"}function Fl(i){let e=i.parent;return e===null?false:!!(kl.has(e.type)&&(e.childForFieldName("name")===i||e.childForFieldName("property")===i)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===i||e.type==="import_specifier"&&(e.childForFieldName("name")===i||e.childForFieldName("alias")===i)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===i&&i.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===i||e.type==="enum_body")}function $l(i){let e=i.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function Dl(i){let e=i.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function Ol(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call_expression"){let n=t.childForFieldName("function");if(n===i||n?.type==="member_expression"&&n.childForFieldName("property")===i)return true}return t.type==="member_expression"&&t.childForFieldName("property")===i}function Ml(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="unary_expression")return t.child(0)?.type==="delete";if(t.type==="member_expression"&&t.childForFieldName("object")===e||Kt.has(t.type))return false;e=t;}return false}function Ul(i){let e=i.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===i)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function Gl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="assignment_expression"||t.type==="augmented_assignment_expression")&&t.childForFieldName("left")===e)return true;if(t.type==="member_expression"&&t.childForFieldName("object")===e||t.type==="subscript_expression"&&t.childForFieldName("object")!==e||Kt.has(t.type))return false;e=t;}return false}function zl(i){let e=i.parent,t=i;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let n=e.namedChild(1);return n===null?false:n===t||Wl(n,i)}if(Bl.has(e.type))return true;if(Kt.has(e.type))return false;t=e,e=e.parent;}return false}function Wl(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function Hl(i){return Fe(i,t=>t.type==="type_query")!==null}function Kl(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,n=Yl(i);return Xl(n,t)?!Jl(i,t):false}function Jl(i,e){let t=i.parent;for(;t!==null;){if(Vl.has(t.type)&&ql(t,e))return true;t=t.parent;}return false}function ql(i,e){for(let t of i.namedChildren){if(t.type==="lexical_declaration"||t.type==="variable_declaration")for(let n of t.namedChildren){if(n.type!=="variable_declarator")continue;if(n.childForFieldName("name")?.text===e)return true}if(t.type==="formal_parameters")for(let n of t.namedChildren){if(n.type!=="required_parameter"&&n.type!=="optional_parameter")continue;let o=n.childForFieldName("pattern");if(o?.type==="identifier"&&o.text===e)return true}}return false}function Yl(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function Xl(i,e){for(let t of i.descendantsOfType("namespace_import")){let n=t.namedChild(0);if(n!==null&&n.text===e)return true}return false}function Ql(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function Zl(i){let e=i.parent;if(e===null||!Ii.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===i||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==i)return false;let t=e;for(;t!==null;){let n=t.parent;if(n===null)return false;if(n.type==="variable_declarator"&&n.childForFieldName("name")===t||(n.type==="assignment_expression"||n.type==="augmented_assignment_expression")&&n.childForFieldName("left")===t||(n.type==="required_parameter"||n.type==="optional_parameter")&&n.childForFieldName("pattern")===t||n.type==="formal_parameters"||n.type==="for_in_statement"&&n.childForFieldName("left")===t)return true;if(!Ii.has(n.type))return false;t=n;}return false}var Ll,kl,Bl,Vl,Ii,Vt=f(()=>{rt();Gr();Pi();Ll=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));kl=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"]));Bl=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"]));Vl=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Ii=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function Ti(i,e){$e(i,e);}var Ri=f(()=>{Vt();});function ji(i,e){$e(i,e);}var Li=f(()=>{Vt();});function Ai(i,e){if(!i.rootNode)return;let t=Sc(i.rootNode);ki(i.rootNode,e,t);}function ki(i,e,t){if(ec.has(i.type)){let n=tc(i,t);n!==null&&e.set(Se(i.startPosition.row,i.startPosition.column),n);}for(let n of i.namedChildren)n&&ki(n,e,t);}function tc(i,e){if(rc(i))return "declaration";if(oc(i))return "read";if(ic(i))return "declaration";if(sc(i))return "type";let t=Fe(i,n=>n.type==="decorator");return t!==null&&ac(i,t)||lc(i)?"call":cc(i)||pc(i)||uc(i)||mc(i)||fc(i)?"write":hc(i,e)?"import-use":"read"}function rc(i){let e=i.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===i||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===i)return true;if(e.type==="list_splat_pattern"||e.type==="dictionary_splat_pattern"){let t=e.parent;if(t?.type==="parameters"||t?.type==="lambda_parameters")return true}return !!(e.type==="as_pattern_target"||nc(i))}function nc(i){let e=i.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function ic(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(zr.has(e.type))return false;e=e.parent;}return false}function oc(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function sc(i){return Fe(i,t=>t.type==="type")!==null}function ac(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call"){let n=t.childForFieldName("function");if(n===i||n?.type==="attribute"&&n.childForFieldName("attribute")===i)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===i}function lc(i){let e=i.parent;if(e?.type==="call"&&e.childForFieldName("function")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function cc(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="delete_statement")return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||zr.has(t.type))return false;e=t;}return false}function pc(i){let e=i.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function uc(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function mc(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment"&&t.childForFieldName("left")===e)return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||t.type==="subscript"&&t.childForFieldName("value")!==e)return false;if(dc.has(t.type)){e=t;continue}if(zr.has(t.type))return false;e=t;}return false}function fc(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="for_statement"||t.type==="for_in_clause")&&t.childForFieldName("left")===e)return true;if(!gc.has(t.type))return false;e=t;}return false}function hc(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let n=i.text;return e.has(n)?!vc(i,n):false}function vc(i,e){let t=i.parent;for(;t!==null;){if(yc.has(t.type)&&bc(t,e))return true;t=t.parent;}return false}function bc(i,e){for(let t of i.namedChildren){if(t.type==="expression_statement"){let n=t.namedChild(0);if(n?.type==="assignment"){let o=n.childForFieldName("left");if(o?.type==="identifier"&&o.text===e)return true}}if(t.type==="parameters"){for(let n of t.namedChildren)if(n.type==="identifier"&&n.text===e||(n.type==="typed_parameter"||n.type==="typed_default_parameter"||n.type==="default_parameter")&&n.namedChild(0)?.type==="identifier"&&n.namedChild(0)?.text===e)return true}}return false}function Sc(i){let e=new Set;for(let t of i.descendantsOfType("import_statement"))for(let n of t.namedChildren)if(n.type==="dotted_name"&&e.add(n.text),n.type==="aliased_import"){let o=n.childForFieldName("alias");o&&e.add(o.text);}return e}var ec,zr,dc,gc,yc,Fi=f(()=>{rt();Gr();ec=Object.freeze(new Set(["identifier"])),zr=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));dc=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));gc=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));yc=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function Di(i,e){let t=new Map;switch(e){case "typescript":$e(i,t);break;case "tsx":Ti(i,t);break;case "javascript":ji(i,t);break;case "python":Ai(i,t);break}return t}function Se(i,e){return `${i}:${e}`}var $i,rt=f(()=>{Vt();Ri();Li();Fi();$i=Object.freeze(new Set(["typescript","javascript","python"]));});function xc(i,e){return $i.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function Ec(i){let e=[];for(let[t,n]of i.entries()){let o=t.indexOf(":");if(o<0)continue;let s=Number(t.slice(0,o)),a=Number(t.slice(o+1));!Number.isFinite(s)||!Number.isFinite(a)||e.push({line:s,column:a,referenceType:n});}return e.sort((t,n)=>t.line-n.line||t.column-n.column),e}var Jt,Ui=f(()=>{rt();re();Jt=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let o=await n();if(!o)throw new Error(`Failed to load language: ${t}`);t==="typescript"&&e.toLowerCase().endsWith(".tsx")&&(o=Tl.tsx);let s=new wc;s.setLanguage(o);let a=await S.getFileStats(e),l=10*1024*1024,c,u;if(a.size<=l){let g=await S.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=xc(t,e),d=p===null?[]:Ec(Di(c,p));return {tree:c,classificationMap:{filePath:e,entries:d},content:u}}async parseWithStream(e,t,n){let o=null;try{o=await G.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(p=>{if(n>50*1024*1024){let m=Math.round(p/n*100);m>c+10&&(process.stderr.write(` Parsing large file: ${m}%...
52
+ `),c=m);}let d=Bt.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)}
53
+ `);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var qt,Bi=f(()=>{re();ve();O();qt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Gi();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(s=>!t.ignores(s.relativePath)&&this.matchesLanguageExtension(s,e.languages))}async scanSpecificFiles(e,t){let n=[],o=null;t.exclude&&t.exclude.length>0&&(o=Gi().add(t.exclude));let s=await G__default.realpath(this.rootPath);for(let a of e)try{let l=E__default.isAbsolute(a)?a:E__default.join(this.rootPath,a),c=await G__default.lstat(l);if(c.isSymbolicLink()){let u=await G__default.realpath(l);if(!u.startsWith(s+E__default.sep)&&u!==s){console.warn(`${T} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let p=await G__default.stat(l);if(!p.isFile())continue;let d=U(this.rootPath,l);if(o&&o.ignores(d))continue;let m=this.detectLanguage(d,t.languages);if(!m)continue;n.push({path:l,relativePath:d,language:m,size:p.size});}else if(c.isFile()){let u=U(this.rootPath,l);if(o&&o.ignores(u))continue;let p=this.detectLanguage(u,t.languages);if(!p)continue;n.push({path:l,relativePath:u,language:p,size:c.size});}}catch{console.warn(`${T} Skipping inaccessible file: ${a}`);}return n}async loadGitignoreRules(e,t){let n=[],o=t;for(;;){let s=E__default.join(o,".gitignore");await S.fileIsReadable(s)&&n.unshift(s);let a=E__default.dirname(o);if(a===o)break;o=a;let l=E__default.join(o,".git");if(await S.directoryExists(l)){let c=E__default.join(o,".gitignore");await S.fileIsReadable(c)&&!n.includes(c)&&n.unshift(c);break}}for(let s of n)try{let a=await S.readFile(s);e.add(a);}catch{console.warn(`${T} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,n,o){let s=[],a=t||e,l=n||await G__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=(await G__default.readdir(e,{withFileTypes:!0})).map(p=>(p.name=p.name.normalize("NFC"),p)).sort((p,d)=>p.name<d.name?-1:p.name>d.name?1:0);for(let p of u){let d=E__default.join(e,p.name),m=U(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 G__default.stat(d);s.push({path:d,relativePath:m,language:"",size:g.size});}else if(p.isSymbolicLink())try{let g=await G__default.realpath(d);if(!g.startsWith(l+E__default.sep)&&g!==l){console.warn(`${T} Skipping symlink pointing outside project: ${d} -> ${g}`);continue}let h=await G__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(`${T} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${q} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let n=E__default.extname(e.path).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return e.language=o,true;return false}detectLanguage(e,t){let n=E__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return o;return null}};});var _c,Pc,Ic,zi,Wi=f(()=>{Xe();_c=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Pc=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(_c).optional()}),Ic=z.record(z.string(),Pc),zi=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Ic.optional(),classificationMap:Cr.optional()});});var Tc,Yt,Vi=f(()=>{Pr();Tc=promisify(Wr__default.gunzip),Yt=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],n=Wr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(e);return await pipeline(s,n),await o,_r(Buffer.concat(t)).toString("base64")}async compress(e){let t=[],n=Wr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(this.serializeASTChunks(e));return await pipeline(s,n),await o,_r(Buffer.concat(t)).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await Tc(t);return JSON.parse(n.toString("utf-8"))}};});function qi(i){let n=i>=5e4?27e5:i>=1e4?18e5:9e5,o=process.env.CONSTELLATION_AST_WAIT_MAX_MS,s=n;if(o!==void 0&&o!==""){let a=Number(o);Number.isFinite(a)&&Number.isInteger(a)&&a>0?s=a:Ji||(process.stderr.write(`[constellation] Ignoring invalid CONSTELLATION_AST_WAIT_MAX_MS=${o}; using default tier cap.
54
+ `),Ji=true);}return Math.min(12e4+i*1e3,s)}var Ji,Yi=f(()=>{Ji=false;});var Hr,Xt=f(()=>{Hr=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 De(i,e){let t=e??i;return {line:t.startPosition.row+1,column:t.startPosition.column}}function Oe(i){return i?i.text:null}function Zi(){return {language:"javascript",handlers:new Map(Qi)}}function eo(){return {language:"typescript",handlers:new Map([...Qi,["interface_declaration",Lc],["public_field_definition",Xi],["property_signature",Xi]])}}var Rc,jc,Lc,Ac,Xi,kc,Qi,to=f(()=>{Rc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);n&&e.symbols.push({name:n,kind:"function",...De(i,t)});},jc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);if(n)return e.symbols.push({name:n,kind:"class",...De(i,t)}),{...e,enclosingType:n}},Lc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);if(n)return e.symbols.push({name:n,kind:"interface",...De(i,t)}),{...e,enclosingType:n}},Ac=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);n&&e.symbols.push({name:n,kind:"method",...De(i,t)});},Xi=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);n&&e.symbols.push({name:n,kind:"property",...De(i,t)});},kc=(i,e)=>{let t=i.childForFieldName("name"),n=Oe(t);if(!n)return;let o=i.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:n,kind:s?"function":"variable",...De(i,t)});},Qi=[["function_declaration",Rc],["class_declaration",jc],["method_definition",Ac],["variable_declarator",kc]];});function Kr(i){return {line:i.startPosition.row+1,column:i.startPosition.column}}function ro(){return {language:"python",handlers:new Map([["function_definition",Fc],["class_definition",$c],["assignment",Dc]])}}var Fc,$c,Dc,no=f(()=>{Fc=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let n=e.enclosingType?"method":"function";e.symbols.push({name:t.text,kind:n,...Kr(t)});},$c=(i,e)=>{let t=i.childForFieldName("name");if(t)return e.symbols.push({name:t.text,kind:"class",...Kr(t)}),{...e,enclosingType:t.text}},Dc=(i,e)=>{let t=i.childForFieldName("left");if(!t||t.type!=="identifier")return;let n=e.enclosingType?"property":"variable";e.symbols.push({name:t.text,kind:n,...Kr(t)});};});var io,oo=f(()=>{to();no();io=[Zi(),eo(),ro()];});var Qt,so=f(()=>{oo();Qt=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??io)this.languageHandlers.set(t.language,t.handlers);}extract(e,t){let n=this.languageHandlers.get(t);if(!n)return [];let o={symbols:[]};return this.walk(e.rootNode,o,n),o.symbols}walk(e,t,n){let s=n.get(e.type)?.(e,t)??t;for(let a=0;a<e.childCount;a++){let l=e.child(a);l&&this.walk(l,s,n);}}};});function Oc(i){let e=Math.max(0,i)/1e3;if(e<60)return `(${e.toFixed(1)}s)`;let t=Math.floor(e/60),n=Math.floor(e%60);return `(${t}m ${n}s)`}function ao(){let i=performance.now();return {elapsed:()=>Oc(performance.now()-i),reset:()=>{i=performance.now();},ms:()=>performance.now()-i}}var lo=f(()=>{});function Vr(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var er,co=f(()=>{Xt();er=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:stripVTControlCharacters(e.map(Vr).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:stripVTControlCharacters(e.map(Vr).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:stripVTControlCharacters(e.map(Vr).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,n){this.entries.push({level:e,message:stripVTControlCharacters(t),timestamp:new Date().toISOString(),code:n});}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||!Hr.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!Hr.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:stripVTControlCharacters(t),timestamp:new Date().toISOString(),code:n});let o=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?o.call(console,t):console[e==="info"?"log":e](t);}};});function Me(i){if(i&&typeof i=="object")try{i.alreadyReported=!0;}catch{}}function ie(i){return !!(i&&typeof i=="object"&&i.alreadyReported)}function Jr(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var po,Uc,Gc,tr,qr=f(()=>{Ie();lo();co();O();po=Math.floor(1e3/15),Uc={interval:100,frames:["\u280B","\u2819","\u281A","\u2813"]},Gc=new Set(["EPIPE","ENOTCONN","EBADF"]);tr=class i{static activeInstance=null;mode;stream;logCollector=new er;spinner=null;currentPhaseLabel=null;currentPhaseTracker=null;lastUpdateAt=0;pendingUpdate=null;pendingUpdateTimer=null;paused=false;originalConsole=null;intercepting=false;warningBucket=new Map;stopped=false;constructor(e){if(i.activeInstance&&!i.activeInstance.stopped)throw new Error("Reporter is a singleton \u2014 only one instance may be active at a time. Call stop() on the existing Reporter before constructing another.");this.mode=e.mode,this.stream=e.stream??process.stderr,i.activeInstance=this,this.installConsoleInterception();}async phase(e,t,n){this.start(e);let o=this.makePhaseContext();try{let s=await t(o);return this.flushPendingUpdate(),this.flushAggregatedWarnings(),this.succeed(n?.successText??e),s}catch(s){this.flushPendingUpdate(),this.flushAggregatedWarnings();let a=n?.failText??`${e} failed: ${s instanceof Error?s.message:String(s)}`;throw this.fail(a),Me(s),s}}start(e){this.currentPhaseLabel=e,this.currentPhaseTracker=ao(),this.mode==="spinner"?(this.spinner?this.spinner.text=this.composeSpinnerText(e):this.spinner=Mc({text:this.composeSpinnerText(e),stream:this.stream,spinner:Uc}),this.paused||this.spinner.start()):(this.mode==="verbose"||this.mode==="plain")&&this.writeLine(`${Z} ${e}\u2026`);}update(e){if(!this.currentPhaseLabel)return;if(this.currentPhaseLabel=e,this.mode==="verbose"){this.writeLine(`${Z} ${e}`);return}if(this.mode!=="spinner")return;let t=Date.now();this.pendingUpdate=e;let n=t-this.lastUpdateAt;n>=po?this.flushPendingUpdate():this.pendingUpdateTimer||(this.pendingUpdateTimer=setTimeout(()=>this.flushPendingUpdate(),po-n),this.pendingUpdateTimer.unref?.());}succeed(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",n=`${w} ${t}`;this.terminatePhase(n,"info");}fail(e){this.flushPendingUpdate();let t=e??this.currentPhaseLabel??"",n=`${q} ${t}`;this.terminatePhase(n,"error");}info(e){if(this.mode==="quiet"){this.logCollector.record("info",e);return}this.logCollector.record("info",e),this.writeLine(`${Z} ${e}`);}warn(e,t){if(this.logCollector.record("warn",e,t?.code),this.currentPhaseLabel&&t?.code){let n=this.warningBucket.get(t.code);n?(n.count+=1,n.samples.length<3&&n.samples.push(e)):this.warningBucket.set(t.code,{code:t.code,count:1,samples:[e]});return}this.writeLine(`${T} ${e}`);}error(e,t){this.logCollector.record("error",e,t?.code),this.writeLine(`${q} ${e}`);}detail(e){this.logCollector.record("info",e),this.mode==="verbose"&&this.writeLine(` ${V.muted(e)}`);}log(e){this.logCollector.record("info",e),this.mode!=="quiet"&&this.writeLine(e);}summary(e){this.logCollector.record("info",e),this.writeLine(e);}step(e){let t=this;return {ok(n){t.renderSubStep("ok",n??e);},fail(n){t.renderSubStep("fail",n??e);},skip(n){t.renderSubStep("skip",n??e);}}}renderSubStep(e,t){let o=`${e==="ok"?w:e==="fail"?q:V.muted("-")} ${e==="skip"?V.muted(t):t}`,s=e==="fail"?"error":"info";this.logCollector.record(s,t),!(this.mode==="quiet"&&e!=="fail")&&this.writeLine(o);}pause(){this.paused||(this.paused=true,this.spinner?.isSpinning&&this.spinner.stop());}resume(){this.paused&&(this.paused=false,this.mode==="spinner"&&this.currentPhaseLabel&&this.spinner&&(this.spinner.text=this.composeSpinnerText(this.currentPhaseLabel),this.spinner.start()));}getEntries(){return this.logCollector.getEntries()}getReportableErrors(){return this.logCollector.getReportableErrors()}hasErrors(){return this.logCollector.hasErrors()}hasWarnings(){return this.logCollector.hasWarnings()}hasReportableErrors(){return this.logCollector.hasReportableErrors()}stop(){this.stopped||(this.stopped=true,this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.flushAggregatedWarnings(),this.spinner?.isSpinning&&this.spinner.stop(),this.spinner=null,this.uninstallConsoleInterception(),i.activeInstance===this&&(i.activeInstance=null));}composeSpinnerText(e){return e}flushPendingUpdate(){if(this.pendingUpdateTimer&&(clearTimeout(this.pendingUpdateTimer),this.pendingUpdateTimer=null),this.pendingUpdate===null||!this.spinner){this.pendingUpdate=null;return}this.spinner.text=this.composeSpinnerText(this.pendingUpdate),this.pendingUpdate=null,this.lastUpdateAt=Date.now();}terminatePhase(e,t){this.logCollector.record(t,e),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:n}of this.warningBucket.values()){if(t===1){this.writeLine(`${T} ${n[0]}`);continue}let o=`${t} ${e} warnings (showing ${Math.min(n.length,3)}): ${n.slice(0,3).join(" | ")}. Use --verbose to see all.`;this.logCollector.record("warn",o,e),this.writeLine(`${T} ${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+`
55
55
  `),this.spinner.text=this.spinner.text):this.stream.write(e+`
56
56
  `);}catch(t){let n=t?.code;if(n&&Gc.has(n))return;try{process.stderr.write(`reporter write failed: ${String(t)}
57
- `);}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(Vr).join(" ");this.logCollector.record("info",t),this.writeLine(t);},console.warn=(...e)=>{let t=e.map(Vr).join(" ");this.logCollector.record("warn",t),this.writeLine(t);},console.error=(...e)=>{let t=e.map(Vr).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);}};});function Bc(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n){if(n.type==="identifier")e.push({local:n.text,original:"default",isDefault:true,isNamespace:false});else if(n.type==="namespace_import"){let o;for(let s=0;s<n.childCount;s++){let a=n.child(s);if(a?.type==="identifier"){o=a.text;break}}o!==void 0&&e.push({local:o,original:void 0,isDefault:false,isNamespace:true});}else if(n.type==="named_imports")for(let o=0;o<n.childCount;o++){let s=n.child(o);if(!s||s.type!=="import_specifier")continue;let a=s.childForFieldName("name"),l=s.childForFieldName("alias");if(!a)continue;let c=a.text,u=l?l.text:c,p=c==="default";e.push({local:u,original:c,isDefault:p,isNamespace:false});}}}return e}async function Wc(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=i.childForFieldName("import_clause"),c=l?Bc(l):[];await ge(a,s,e,t,n,c);}async function zc(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await ge(a,s,e,t,n,[]);}function tr(){return {language:"javascript",handlers:new Map([["import_statement",Wc],["export_statement",zc]])}}function qr(){return {...tr(),language:"typescript"}}var Yr=f(()=>{Ze();});var uo,mo=f(()=>{Yr();Mt();Ze();Yr();Mt();uo=[tr(),qr(),Mr()];});var go={};En(go,{ImportExtractor:()=>Xr});var Xr,fo=f(()=>{mo();Ze();Xr=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??uo)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,o){if(!o)return {};let s=this.languageHandlers.get(n);if(!s)return {};let a=this.classifiers.get(n)??Or,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 n=0;n<e.childCount;n++){let o=e.child(n);o&&await this.walkAST(o,t);}}};});var it,ho,Qr,yo,vo,rr=f(()=>{it=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),ho=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"]),Qr={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"]},yo={language:"javascript",textIncludedTypes:ho,fieldNames:Qr},vo={language:"typescript",textIncludedTypes:ho,fieldNames:Qr};});var Hc,bo,So,Zr=f(()=>{Hc=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"]),bo={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"]},So={language:"python",textIncludedTypes:Hc,fieldNames:bo,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function wo(i){return ot.get(i)}function Co(i){if(!i)return it;let e=ot.get(i);if(!e)return it;let t=new Set(it);for(let n of e.textIncludedTypes)t.add(n);return t}function en(i){if(!i){let t=Array.from(ot.values()).map(n=>n.fieldNames);return st(...t)}let e=ot.get(i);if(!e){let t=Array.from(ot.values()).map(n=>n.fieldNames);return st(...t)}return e.fieldNames}var ot,xo=f(()=>{tn();rr();Zr();rr();rr();Zr();ot=new Map([["javascript",yo],["typescript",vo],["python",So]]);});var No={};En(No,{COMMON_FIELD_NAMES:()=>on,JS_TS_FIELD_NAMES:()=>Po,PYTHON_FIELD_NAMES:()=>Io,TEXT_INCLUDED_TYPES:()=>Eo,mergeFieldMaps:()=>st,serializeAST:()=>Vc,serializeASTStream:()=>Kc});function*Kc(i,e,t){yield*nn(i,e,t);}function*nn(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),_o(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?en(t):on)[i.type]||[],s=new Set,a=true;for(let l of o){let c=i.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*nn(c,l,t));}for(let l=0;l<i.childCount;l++){let c=i.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*nn(c,void 0,t));}yield "]";}yield "}";}async function Vc(i,e,t){let n=rn(i,e,t),o=t?en(t):on,s=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;s.length>0;){let a=s[s.length-1];if(a.childIndex===0&&a.treeNode.childCount>0){let l=o[a.treeNode.type]||[];for(let c of l){let u=a.treeNode.childForFieldName(c);if(u){a.fieldChildren.add(u);let p=rn(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=rn(l,void 0,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(c),s.push({treeNode:l,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else s.pop();}return n}function rn(i,e,t){let n={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return _o(i,t)&&(n.text=i.text),n}function _o(i,e){if(e){let n=wo(e);if(n?.shouldIncludeText){let s=n.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return Co(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Eo.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function st(...i){let e={};for(let t of i)for(let[n,o]of Object.entries(t)){let a=[...e[n]||[]];for(let l of o)a.includes(l)||a.push(l);e[n]=a;}return e}var Eo,Po,Io,on,tn=f(()=>{xo();Eo=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"]);Po={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"]},Io={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"]};on=st(Po,Io);});var at,Ro=f(()=>{Nr();oi();ai();vi();Qe();zt();Ui();Bi();zi();Vi();Yi();wt();Yt();ve();Rr();so();Jr();O();Ct();at=class extends ce{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;discoveredFiles=[];parseSymbols=new Map;parseContent=new Map;symbolExtractor=new Xt;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new Jt(process.cwd()),this.parser=new Vt(this.langRegistry),this.compressor=new qt;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let o=n.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false,n=false){if(!this.reporter)throw new Error("IndexCommand requires a Reporter dependency");let o="failed";try{let s=await this.getAccessKey();this.apiClient=new Pt(this.config,s,t,this.reporter),this.reporter.log(`${ae} Starting indexing procedure...
57
+ `);}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(Jr).join(" ");this.logCollector.record("info",t),this.writeLine(t);},console.warn=(...e)=>{let t=e.map(Jr).join(" ");this.logCollector.record("warn",t),this.writeLine(t);},console.error=(...e)=>{let t=e.map(Jr).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);}};});function Bc(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n){if(n.type==="identifier")e.push({local:n.text,original:"default",isDefault:true,isNamespace:false});else if(n.type==="namespace_import"){let o;for(let s=0;s<n.childCount;s++){let a=n.child(s);if(a?.type==="identifier"){o=a.text;break}}o!==void 0&&e.push({local:o,original:void 0,isDefault:false,isNamespace:true});}else if(n.type==="named_imports")for(let o=0;o<n.childCount;o++){let s=n.child(o);if(!s||s.type!=="import_specifier")continue;let a=s.childForFieldName("name"),l=s.childForFieldName("alias");if(!a)continue;let c=a.text,u=l?l.text:c,p=c==="default";e.push({local:u,original:c,isDefault:p,isNamespace:false});}}}return e}async function zc(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=i.childForFieldName("import_clause"),c=l?Bc(l):[];await ge(a,s,e,t,n,c);}async function Wc(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await ge(a,s,e,t,n,[]);}function rr(){return {language:"javascript",handlers:new Map([["import_statement",zc],["export_statement",Wc]])}}function Yr(){return {...rr(),language:"typescript"}}var Xr=f(()=>{Ze();});var uo,mo=f(()=>{Xr();Ut();Ze();Xr();Ut();uo=[rr(),Yr(),Ur()];});var go={};_n(go,{ImportExtractor:()=>Qr});var Qr,fo=f(()=>{mo();Ze();Qr=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??uo)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,o){if(!o)return {};let s=this.languageHandlers.get(n);if(!s)return {};let a=this.classifiers.get(n)??Mr,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 n=0;n<e.childCount;n++){let o=e.child(n);o&&await this.walkAST(o,t);}}};});var it,ho,Zr,yo,vo,nr=f(()=>{it=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),ho=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"]),Zr={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"]},yo={language:"javascript",textIncludedTypes:ho,fieldNames:Zr},vo={language:"typescript",textIncludedTypes:ho,fieldNames:Zr};});var Hc,bo,So,en=f(()=>{Hc=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"]),bo={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"]},So={language:"python",textIncludedTypes:Hc,fieldNames:bo,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function wo(i){return ot.get(i)}function Co(i){if(!i)return it;let e=ot.get(i);if(!e)return it;let t=new Set(it);for(let n of e.textIncludedTypes)t.add(n);return t}function tn(i){if(!i){let t=Array.from(ot.values()).map(n=>n.fieldNames);return st(...t)}let e=ot.get(i);if(!e){let t=Array.from(ot.values()).map(n=>n.fieldNames);return st(...t)}return e.fieldNames}var ot,xo=f(()=>{rn();nr();en();nr();nr();en();ot=new Map([["javascript",yo],["typescript",vo],["python",So]]);});var No={};_n(No,{COMMON_FIELD_NAMES:()=>sn,JS_TS_FIELD_NAMES:()=>Po,PYTHON_FIELD_NAMES:()=>Io,TEXT_INCLUDED_TYPES:()=>Eo,mergeFieldMaps:()=>st,serializeAST:()=>Vc,serializeASTStream:()=>Kc});function*Kc(i,e,t){yield*on(i,e,t);}function*on(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),_o(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?tn(t):sn)[i.type]||[],s=new Set,a=true;for(let l of o){let c=i.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*on(c,l,t));}for(let l=0;l<i.childCount;l++){let c=i.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*on(c,void 0,t));}yield "]";}yield "}";}async function Vc(i,e,t){let n=nn(i,e,t),o=t?tn(t):sn,s=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;s.length>0;){let a=s[s.length-1];if(a.childIndex===0&&a.treeNode.childCount>0){let l=o[a.treeNode.type]||[];for(let c of l){let u=a.treeNode.childForFieldName(c);if(u){a.fieldChildren.add(u);let p=nn(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=nn(l,void 0,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(c),s.push({treeNode:l,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else s.pop();}return n}function nn(i,e,t){let n={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return _o(i,t)&&(n.text=i.text),n}function _o(i,e){if(e){let n=wo(e);if(n?.shouldIncludeText){let s=n.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return Co(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Eo.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function st(...i){let e={};for(let t of i)for(let[n,o]of Object.entries(t)){let a=[...e[n]||[]];for(let l of o)a.includes(l)||a.push(l);e[n]=a;}return e}var Eo,Po,Io,sn,rn=f(()=>{xo();Eo=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"]);Po={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"]},Io={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"]};sn=st(Po,Io);});var at,Ro=f(()=>{Tr();oi();ai();vi();Qe();Ht();Ui();Bi();Wi();Vi();Yi();wt();Xt();ve();jr();so();qr();O();Ct();at=class extends ce{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;discoveredFiles=[];parseSymbols=new Map;parseContent=new Map;symbolExtractor=new Qt;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new qt(process.cwd()),this.parser=new Jt(this.langRegistry),this.compressor=new Yt;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let o=n.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false,n=false){if(!this.reporter)throw new Error("IndexCommand requires a Reporter dependency");let o="failed";try{let s=await this.getAccessKey();this.apiClient=new Pt(this.config,s,t,this.reporter),this.reporter.log(`${ae} Starting indexing procedure...
58
58
  `);let a=performance.now();await this.reporter.phase("Pre-flight checks",async _=>{let k=_.step("Project access");await this.validateProject(),k.ok("Project access validated");let P=_.step("Git branch");t?P.skip("Git branch validation skipped (--dirty)"):(await this.validateGitBranch(),P.ok("Git branch validated"));let D=_.step("Git status");t?D.skip("Git status validation skipped (--dirty)"):(await this.validateGitStatus(),D.ok("Working tree clean"));let F=_.step("Repo sync");if(t?F.skip("Repository sync skipped (--dirty)"):(await this.synchronizeChanges(),F.ok("Repository synchronized")),this.buildConfigManagers.size>0){let Q=_.step("Build configs"),ft=0;for(let[,cs]of this.buildConfigManagers.entries()){let ps=await cs.initialize();ft+=ps.length;}Q.ok(ft>0?`${ft} build config(s) discovered`:"No build configs discovered");}},{successText:"Pre-flight checks complete"});let l=await this.reporter.phase("Determining index scope",()=>this.determineIndexScope(e),{successText:e?"Full index":"Index scope determined"}),c=await this.git.getLatestCommitHash(),u=await this.git.getCommitTimestamp();if(l.upToDate){this.reporter.summary(`${w} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${c.substring(0,8)}`),o="succeeded";return}let p=await this.reporter.phase("Claiming indexing lock",()=>this.apiClient.claimAstLock(this.config.projectId,this.config.branch,l.isIncremental,c,u),{successText:"Indexing lock claimed"});switch(p.remapped===!0&&(p.effectiveBranchName?this.reporter.warn(`--dirty: server is indexing as default branch "${p.effectiveBranchName}" (transmitted "${this.config.branch}").`):this.reporter.warn("--dirty: server reported a branch remap but did not include the effective branch name.")),p.status){case "current":this.reporter.summary(`${w} Index already up to date for branch ${this.config.branch} at commit ${c?.substring(0,8)||"unknown"}`),o="succeeded";return;case "duplicate":this.reporter.summary(`${w} Index for this commit is already in progress on the server.`),o="succeeded";return;case "superseded":this.reporter.summary(`${w} A newer commit is already being indexed; nothing to do.`),o="succeeded";return;case "queued":if(!p.queuedAttemptId)throw new Error("Server returned queued status without an attempt ID");await this.handleQueuedUpload(p.queuedAttemptId,l.isIncremental,c,u),o="succeeded";return;default:break}let d=!1,m=()=>{d||this.reporter.detail("Uploading metadata, processing, and indexing...");},g,h,b=new Promise((_,k)=>{g=_,h=k;}),y=new AbortController,v=()=>{},x=this.createIndexPipeline(l.isIncremental,u,m,g,(_,k)=>v(_,k)),j=null;try{let[,_]=await this.reporter.phase("Indexing files",async k=>(v=(P,D)=>{if(D<=0)return;let F=Math.min(100,Math.round(P/D*100));k.update(`Indexing files ${F}% (${P}/${D})`);},Promise.all([this.uploadToAPI(x,l.isIncremental,c,p.attemptId).then(P=>(d=!0,P)).catch(P=>{throw y.abort(P),h(P),d=!0,P}),b.then(P=>{let D=this.getEnrichmentEligibleLanguages(n,P);return D?(p.attemptId&&this.apiClient.startEnrichment(p.attemptId,this.config.projectId,this.config.branch),this.runLspEnrichment(P,D,this.parseSymbols,this.parseContent,y.signal).catch(F=>(y.signal.aborted||this.reporter.warn(`Index enrichment failed: ${F instanceof Error?F.message:String(F)}`,{code:"ENRICHMENT_FAILED"}),null))):null}).catch(()=>null)])),{successText:"Files indexed and uploaded"});j=_;}catch(_){throw d=!0,_}j&&j.length>0&&await this.reporter.phase("Server processing & enrichment upload",async()=>{try{let _=this.discoveredFiles.length,k=qi(_),P=Math.round(k/1e3);this.reporter.detail(`Waiting for server to finish syntax tree processing (${_} files, timeout ${P}s)...`);let D=await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,c,k),F=si(j);if(D){this.reporter.detail(`Uploading enrichment data (${j.length} files)...`);let Q=!1;try{Q=await this.apiClient.uploadEnrichment(F,this.config.projectId,this.config.branch,c);}catch{}Q?this.reporter.detail("Enrichment data uploaded to Constellation Service, index enhancement in progress"):this.reporter.warn("Enrichment upload failed \u2014 re-run 'constellation index --full' after the server finishes AST processing to retry.",{code:"ENRICHMENT_FAILED"});}else {this.reporter.warn(`AST processing not complete after ${P}s \u2014 attempting enrichment upload anyway.`);let Q=!1;try{Q=await this.apiClient.uploadEnrichment(F,this.config.projectId,this.config.branch,c);}catch{}Q?this.reporter.detail("Enrichment data uploaded to Constellation Service, index enhancement in progress"):this.reporter.warn("Enrichment upload failed \u2014 re-run 'constellation index --full' after the server finishes AST processing to retry.",{code:"ENRICHMENT_FAILED"});}}catch(_){this.reporter.warn(`Enrichment upload failed: ${_ instanceof Error?_.message:String(_)}`,{code:"ENRICHMENT_FAILED"});}},{successText:"Server processing complete"});let N=(performance.now()-a)/1e3,X=Math.floor(N/60),se=(N%60).toFixed(3),ye=X>0?`${X}m ${se}s`:`${se}s`;this.reporter.summary(`
59
59
  ${w} Upload completed in ${ye}! Server indexing in progress.`),o="succeeded";}catch(s){if(s instanceof te)throw s;if(s instanceof Te){this.logIndexingInProgress(s.branchName||this.config?.branch),o="succeeded";return}if(s instanceof R)throw ie(s)||(this.reporter.error("Authentication failed.",{code:"AUTH_FAILURE"}),this.reporter.info(`Your access key may be invalid or expired. Run 'constellation auth'
60
60
  to set or update your access key.`),Me(s)),s;if(s instanceof ue)throw s;if(s instanceof Error&&s.message==="Access key not configured")throw Me(s),s;if(ie(s))throw s;let a=s instanceof Error?s.message:"An unexpected error occurred";throw this.reporter.error(`Indexing failed: ${a}`),Me(s),s}finally{this.parseSymbols.clear(),this.parseContent.clear();try{let a=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",l=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,c=this.reporter.getReportableErrors();if(!a&&l&&c.length>0){let u=this.reporter.getEntries(),p=c.map(v=>({type:"CLI_ERROR",message:v.message,phase:"indexing"})).slice(0,100),d=u.filter(v=>v.level==="warn").map(v=>({type:"CLI_WARNING",message:v.message,phase:"indexing"})).slice(0,100),m=p.length,g=d.length,h=[];m>0&&h.push(`${m} error${m!==1?"s":""}`),g>0&&h.push(`${g} warning${g!==1?"s":""}`);let b=h.join(", "),y=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:b,errorData:{errors:p,warnings:d},logEntries:u.slice(0,1e3),cliVersion:y,outcome:o,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(le);if(!e)throw this.reporter.error("Access key not found.",{code:"ACCESS_KEY_MISSING"}),this.reporter.info(`Set the ${le} environment variable or run
@@ -76,25 +76,25 @@ To resolve:`),this.reporter.log(" 1. Fix the conflicted files manually"),this.r
76
76
  Please check your internet connection and try again
77
77
  `):e.message.includes("Authentication")&&this.reporter.log(`
78
78
  Please check your git credentials and try again
79
- `)),e}finally{this.reporter.resume();}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.reporter.detail("Determining index scope...");try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return this.reporter.detail("No previous index found, performing full index"),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return n===o?(this.reporter.detail("Already up to date"),{isIncremental:!0,upToDate:!0}):(this.reporter.detail(`Last indexed commit: ${n.substring(0,8)}`),this.reporter.detail(`Current commit: ${o.substring(0,8)}`),this.reporter.detail(`Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof R)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 n=await this.apiClient.getProjectState();if(!n?.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(n.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?`${Z} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${Z} Removing ${l} deleted file(s) from graph`;this.reporter.log(u),await this.apiClient.deleteFiles(a);}}}catch(n){if(n instanceof R)throw n;this.reporter.warn(`Cannot determine changes (${n instanceof Error?n.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,n,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 Re(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:v}=await this.parser.parseFile(m.path,m.language),x=this.symbolExtractor.extract(b,m.language);x.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(m.relativePath),x),v!==void 0&&this.parseContent.set(this.normalizePathToCanonical(m.relativePath),v),y.entries.length>5e4&&this.reporter.warn(`Large classification map for ${m.relativePath}: ${y.entries.length} entries`);let C=this.langRegistry.getPlugin(m.language),A;if(C?.getImportResolver){let P=this.buildConfigManagers.get(m.language),D=P?await P.getConfigForFile(m.path):null,F=C.getImportResolver(m.path,D);if(F){let{ImportExtractor:Q}=await Promise.resolve().then(()=>(fo(),go));A=await new Q().extractImportResolutions(b,m.path,m.language,F);}}let{serializeASTStream:N}=await Promise.resolve().then(()=>(tn(),No)),X=N(b.rootNode,void 0,m.language),se=await this.compressor.compressStream(X),ye=this.normalizePathToCanonical(m.relativePath),_={file:ye,language:m.language,commit:c,timestamp:t,ast:se,importResolutions:A,classificationMap:{filePath:ye,entries:y.entries}},k=Wi.safeParse(_);if(!k.success)throw new Error(`AST validation failed: ${k.error.issues[0].message}`);return a++,o?.(a,s),k.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"),n&&n();}async uploadToAPI(e,t,n,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n,o))throw new Error("Failed to upload data to Constellation Service");this.reporter.detail("Data uploaded to Constellation Service, indexing in progress");}async*createIndexPipeline(e,t,n,o,s){let a=await this.discoverFiles(e);this.discoveredFiles=a,o(a),yield*this.generateASTs(a,t,n,s);}async handleQueuedUpload(e,t,n,o){this.reporter.log("Generating AST data for queue upload...");let s=this.createIndexPipeline(t,o,()=>{},()=>{});await this.apiClient.uploadToQueue(s,this.config.projectId,this.config.branch,n,e),this.reporter.detail("Changes queued for indexing behind the current operation.");}normalizePathToCanonical(e){return Nt(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||de.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.reporter.detail("Index enrichment skipped"),null;if(this.config.lspEnrichment===false)return this.reporter.detail("Index enrichment disabled in constellation.json"),null;let o=[...new Set(t.map(s=>s.language))].filter(s=>this.isLanguageLspEligible(s));return o.length===0?null:(this.reporter.detail(`Index enrichment enabled for: ${o.map(tt).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,n,o,s){let a=new kt(process.cwd(),this.reporter);try{if(s?.aborted)return null;this.reporter.detail("Starting index enrichment...");let l=new Map,c=new Map;for(let g of e){if(!t.has(g.language))continue;let h=l.get(g.language)||[];h.push(this.normalizePathToCanonical(g.relativePath)),l.set(g.language,h);}for(let g of l.keys()){if(c.has(g))continue;let b=this.config.languages[g]?.lsp,y=await a.startServer(g,b);y&&c.set(g,y);}if(c.size===0)return this.reporter.warn("No language servers started, index enrichment skipped"),null;if(s?.aborted)return a.destroyAll(),null;this.reporter.detail(`Language servers started: ${[...c.keys()].map(tt).join(", ")}`);let u=new Tt(process.cwd(),this.reporter),p=s?new Promise((g,h)=>{s.addEventListener("abort",()=>{a.destroyAll(),h(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,d=await(p?Promise.race([u.enrich(l,n,c,o),p]):u.enrich(l,n,c,o)),m=d.reduce((g,h)=>g+h.symbols.length,0);return this.reporter.detail(`Index enrichment analysis completed: ${m} symbols across ${d.length} files`),d.length>0?d:null}catch(l){return this.reporter.warn(`Index enrichment failed: ${l instanceof Error?l.message:String(l)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await a.shutdownAll();}}};});function sn(i){return stringify({name:"Constellation Index",on:{push:{branches:[i]}},permissions:{contents:"read"},jobs:{index:{"runs-on":"ubuntu-latest",steps:[{uses:"actions/checkout@v4"},{uses:"ShiftinBits/constellation-github@v1",with:{"access-key":"${{ secrets.CONSTELLATION_ACCESS_KEY }}"}}]}}},{lineWidth:0})}function nr(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function ir(i){let{includeEntry:e,job:t}=nr(i);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var an=f(()=>{});var lt,Ao=f(()=>{re();an();lt=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([S.directoryExists(E__default.join(this.gitRoot,".github","workflows")),S.fileIsReadable(E__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return S.fileIsReadable(E__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=E__default.join(this.gitRoot,".gitlab-ci.yml");if(!await S.fileIsReadable(e))return false;try{let n=await S.readFile(e),s=parseDocument(n).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=E__default.join(this.gitRoot,".github","workflows");await G__default.mkdir(t,{recursive:true});let n=E__default.join(t,"constellation-index.yml");return await S.writeFile(n,sn(e)),n}async createOrMergeGitLabCI(e){let t=E__default.join(this.gitRoot,".gitlab-ci.yml");if(!await S.fileIsReadable(t))return await S.writeFile(t,ir(e)),t;let o=await S.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await S.writeFile(t,ir(e)),t;let{includeEntry:a,job:l}=nr(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await S.writeFile(t,s.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let o=n.items.filter(s=>{if(isMap(s)){let a=s.get("component");return typeof a!="string"||!a.includes("constellation-gitlab")}return true});n.items=o,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var ko=f(()=>{Ao();an();});function Fo(i,e){let t=Ce__default.homedir(),n=process.platform,o=Qc[i];switch(n){case "darwin":return E__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return E__default.join(process.env.APPDATA||E__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return E__default.join(t,".config",o,"User/globalStorage",e)}}function $o(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:E__default.join(Fo(t,i),"settings","cline_mcp_settings.json")}))}function Do(){return E__default.join(Fo("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Qc,Oo=f(()=>{Qc={stable:"Code",insiders:"Code - Insiders"};});function Uo(i){return cn.find(e=>e.id===i)}var Mo,Zc,cn,pn=f(()=>{Oo();Mo={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Zc={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},cn=[{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:Zc},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Do(),isGlobalConfig:true,getGlobalConfigPaths:$o,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false}},{id:"codex-cli",displayName:"Codex CLI",configPath:".codex/config.toml",format:"toml",mcpServersKeyPath:["mcp_servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"$CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{enabled_tools:["code_intel"]},envPolicyConfig:{includeOnlyKeyPath:["shell_environment_policy","include_only"],envVarsToAllow:["CONSTELLATION_ACCESS_KEY"],globalConfigPath:"~/.codex/config.toml"}},{id:"copilot-cli",displayName:"Copilot CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","marketplace","add","ShiftinBits/constellation-copilot"]},pluginPostInstallCommands:[{command:"copilot",args:["plugin","install","constellation@constellation-plugins"]}]},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"gemini",args:["extensions","install","https://github.com/ShiftinBits/constellation-gemini"]},pluginUpdateCommand:{command:"gemini",args:["extensions","update","constellation"]},pluginPostInstallCommands:[{command:"gemini",args:["extensions","disable","--scope","user","constellation"]},{command:"gemini",args:["extensions","enable","--scope","workspace","constellation"]}]},{id:"jetbrains-ai",displayName:"JetBrains",configPath:".ai/mcp/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}},{id:"kilo-code",displayName:"Kilo Code",configPath:".kilocode/mcp.json",format:"json",permissionsConfig:{filePath:".kilocode/mcp.json",allowKeyPath:["mcpServers","constellation","alwaysAllow"],allowValue:"code_intel"},mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"opencode",displayName:"OpenCode",configPath:"opencode.jsonc",format:"jsonc",mcpServersKeyPath:["mcp"],skipMcpServer:true,pluginConfig:{pluginKeyPath:["plugin"],pluginValue:"@constellationdev/opencode"},configDefaults:{$schema:"https://opencode.ai/config.json"}},{id:"tabnine",displayName:"Tabnine",configPath:".tabnine/mcp_servers.json",format:"json",mcpServersKeyPath:["mcpServers"]},{id:"vscode-copilot",displayName:"VSCode",configPath:".vscode/mcp.json",format:"json",mcpServersKeyPath:["servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}}];});async function Go(){if(!un)try{let i=await import('@iarna/toml');un={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return un}function rp(i){let e="",t=0,n=i.length;for(;t<n;)if(i[t]==='"'){for(e+='"',t++;t<n&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<n&&(e+=i[t++])):e+=i[t++];t<n&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<n&&i[t+1]==="/")for(t+=2;t<n&&i[t]!==`
80
- `;)t++;else if(i[t]==="/"&&t+1<n&&i[t+1]==="*"){for(t+=2;t<n&&!(i[t]==="*"&&t+1<n&&i[t+1]==="/");)t++;t<n&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var un,or,Bo=f(()=>{re();pn();un=null;or=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=E__default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){await this.ensureDirectoryExists(t);let s=await this.readConfig(t,e.format);if(e.configDefaults)for(let[a,l]of Object.entries(e.configDefaults))a in s||(s[a]=l);e.pluginConfig&&(s=this.addPluginToArray(s,e.pluginConfig)),e.skipMcpServer||(s=this.addConstellationServer(s,e),await this.configureEnvPolicy(s,e)),await this.writeConfig(t,s,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let o;return n?o=t:e.permissionsConfig?o=E__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=E__default.join(this.cwd,e.marketplaceConfig.filePath):o=t,{tool:e,success:!0,configuredPath:o}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),n=[];for(let{displayName:o,settingsPath:s}of t)try{await this.ensureDirectoryExists(s);let a=await this.readConfig(s,e.format);a=this.addConstellationServer(a,e),await this.writeConfig(s,a,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:s});}catch(a){let l=a instanceof Error?a.message:String(a);l.includes("ENOENT")||l.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:l});}return n}async ensureDirectoryExists(e){let t=E__default.dirname(e);await G__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await S.fileIsReadable(e))return {};let o=await S.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(rp(o)):(await Go()).parse(o)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let a=0;a<t.mcpServersKeyPath.length-1;a++){let l=t.mcpServersKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[o]||typeof n[o]!="object")&&(n[o]={});let s=n[o];if(!s.constellation){let a=t.mcpServerConfigOverride??Mo,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,n){let o;n==="json"||n==="jsonc"?o=JSON.stringify(t,null,2):o=(await Go()).stringify(t),o=o.replace(/\r\n/g,`
79
+ `)),e}finally{this.reporter.resume();}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.reporter.detail("Determining index scope...");try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return this.reporter.detail("No previous index found, performing full index"),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return n===o?(this.reporter.detail("Already up to date"),{isIncremental:!0,upToDate:!0}):(this.reporter.detail(`Last indexed commit: ${n.substring(0,8)}`),this.reporter.detail(`Current commit: ${o.substring(0,8)}`),this.reporter.detail(`Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof R)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 n=await this.apiClient.getProjectState();if(!n?.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(n.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?`${Z} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${Z} Removing ${l} deleted file(s) from graph`;this.reporter.log(u),await this.apiClient.deleteFiles(a);}}}catch(n){if(n instanceof R)throw n;this.reporter.warn(`Cannot determine changes (${n instanceof Error?n.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,n,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 Re(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:v}=await this.parser.parseFile(m.path,m.language),x=this.symbolExtractor.extract(b,m.language);x.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(m.relativePath),x),v!==void 0&&this.parseContent.set(this.normalizePathToCanonical(m.relativePath),v),y.entries.length>5e4&&this.reporter.warn(`Large classification map for ${m.relativePath}: ${y.entries.length} entries`);let C=this.langRegistry.getPlugin(m.language),A;if(C?.getImportResolver){let P=this.buildConfigManagers.get(m.language),D=P?await P.getConfigForFile(m.path):null,F=C.getImportResolver(m.path,D);if(F){let{ImportExtractor:Q}=await Promise.resolve().then(()=>(fo(),go));A=await new Q().extractImportResolutions(b,m.path,m.language,F);}}let{serializeASTStream:N}=await Promise.resolve().then(()=>(rn(),No)),X=N(b.rootNode,void 0,m.language),se=await this.compressor.compressStream(X),ye=this.normalizePathToCanonical(m.relativePath),_={file:ye,language:m.language,commit:c,timestamp:t,ast:se,importResolutions:A,classificationMap:{filePath:ye,entries:y.entries}},k=zi.safeParse(_);if(!k.success)throw new Error(`AST validation failed: ${k.error.issues[0].message}`);return a++,o?.(a,s),k.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"),n&&n();}async uploadToAPI(e,t,n,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n,o))throw new Error("Failed to upload data to Constellation Service");this.reporter.detail("Data uploaded to Constellation Service, indexing in progress");}async*createIndexPipeline(e,t,n,o,s){let a=await this.discoverFiles(e);this.discoveredFiles=a,o(a),yield*this.generateASTs(a,t,n,s);}async handleQueuedUpload(e,t,n,o){this.reporter.log("Generating AST data for queue upload...");let s=this.createIndexPipeline(t,o,()=>{},()=>{});await this.apiClient.uploadToQueue(s,this.config.projectId,this.config.branch,n,e),this.reporter.detail("Changes queued for indexing behind the current operation.");}normalizePathToCanonical(e){return Tt(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||de.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.reporter.detail("Index enrichment skipped"),null;if(this.config.lspEnrichment===false)return this.reporter.detail("Index enrichment disabled in constellation.json"),null;let o=[...new Set(t.map(s=>s.language))].filter(s=>this.isLanguageLspEligible(s));return o.length===0?null:(this.reporter.detail(`Index enrichment enabled for: ${o.map(tt).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,n,o,s){let a=new Ft(process.cwd(),this.reporter);try{if(s?.aborted)return null;this.reporter.detail("Starting index enrichment...");let l=new Map,c=new Map;for(let g of e){if(!t.has(g.language))continue;let h=l.get(g.language)||[];h.push(this.normalizePathToCanonical(g.relativePath)),l.set(g.language,h);}for(let g of l.keys()){if(c.has(g))continue;let b=this.config.languages[g]?.lsp,y=await a.startServer(g,b);y&&c.set(g,y);}if(c.size===0)return this.reporter.warn("No language servers started, index enrichment skipped"),null;if(s?.aborted)return a.destroyAll(),null;this.reporter.detail(`Language servers started: ${[...c.keys()].map(tt).join(", ")}`);let u=new Rt(process.cwd(),this.reporter),p=s?new Promise((g,h)=>{s.addEventListener("abort",()=>{a.destroyAll(),h(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,d=await(p?Promise.race([u.enrich(l,n,c,o),p]):u.enrich(l,n,c,o)),m=d.reduce((g,h)=>g+h.symbols.length,0);return this.reporter.detail(`Index enrichment analysis completed: ${m} symbols across ${d.length} files`),d.length>0?d:null}catch(l){return this.reporter.warn(`Index enrichment failed: ${l instanceof Error?l.message:String(l)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await a.shutdownAll();}}};});function an(i){return stringify({name:"Constellation Index",on:{push:{branches:[i]}},permissions:{contents:"read"},jobs:{index:{"runs-on":"ubuntu-latest",steps:[{uses:"actions/checkout@v4"},{uses:"ShiftinBits/constellation-github@v1",with:{"access-key":"${{ secrets.CONSTELLATION_ACCESS_KEY }}"}}]}}},{lineWidth:0})}function ir(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function or(i){let{includeEntry:e,job:t}=ir(i);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var ln=f(()=>{});var lt,Ao=f(()=>{re();ln();lt=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([S.directoryExists(E__default.join(this.gitRoot,".github","workflows")),S.fileIsReadable(E__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return S.fileIsReadable(E__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=E__default.join(this.gitRoot,".gitlab-ci.yml");if(!await S.fileIsReadable(e))return false;try{let n=await S.readFile(e),s=parseDocument(n).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=E__default.join(this.gitRoot,".github","workflows");await G__default.mkdir(t,{recursive:true});let n=E__default.join(t,"constellation-index.yml");return await S.writeFile(n,an(e)),n}async createOrMergeGitLabCI(e){let t=E__default.join(this.gitRoot,".gitlab-ci.yml");if(!await S.fileIsReadable(t))return await S.writeFile(t,or(e)),t;let o=await S.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await S.writeFile(t,or(e)),t;let{includeEntry:a,job:l}=ir(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await S.writeFile(t,s.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let o=n.items.filter(s=>{if(isMap(s)){let a=s.get("component");return typeof a!="string"||!a.includes("constellation-gitlab")}return true});n.items=o,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var ko=f(()=>{Ao();ln();});function Fo(i,e){let t=Ce__default.homedir(),n=process.platform,o=Qc[i];switch(n){case "darwin":return E__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return E__default.join(process.env.APPDATA||E__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return E__default.join(t,".config",o,"User/globalStorage",e)}}function $o(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:E__default.join(Fo(t,i),"settings","cline_mcp_settings.json")}))}function Do(){return E__default.join(Fo("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Qc,Oo=f(()=>{Qc={stable:"Code",insiders:"Code - Insiders"};});function Uo(i){return pn.find(e=>e.id===i)}var Mo,Zc,pn,un=f(()=>{Oo();Mo={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Zc={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"},autoUpdate:true}},enabledPlugins:{"constellation@constellation-plugins":true}},pn=[{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:Zc},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Do(),isGlobalConfig:true,getGlobalConfigPaths:$o,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false}},{id:"codex-cli",displayName:"Codex CLI",configPath:".codex/config.toml",format:"toml",mcpServersKeyPath:["mcp_servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"$CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{enabled_tools:["code_intel"]},envPolicyConfig:{includeOnlyKeyPath:["shell_environment_policy","include_only"],envVarsToAllow:["CONSTELLATION_ACCESS_KEY"],globalConfigPath:"~/.codex/config.toml"}},{id:"copilot-cli",displayName:"Copilot CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","marketplace","add","ShiftinBits/constellation-copilot"]},pluginPostInstallCommands:[{command:"copilot",args:["plugin","install","constellation@constellation-plugins"]}]},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"gemini",args:["extensions","install","https://github.com/ShiftinBits/constellation-gemini"]},pluginUpdateCommand:{command:"gemini",args:["extensions","update","constellation"]},pluginPostInstallCommands:[{command:"gemini",args:["extensions","disable","--scope","user","constellation"]},{command:"gemini",args:["extensions","enable","--scope","workspace","constellation"]}]},{id:"jetbrains-ai",displayName:"JetBrains",configPath:".ai/mcp/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}},{id:"kilo-code",displayName:"Kilo Code",configPath:".kilocode/mcp.json",format:"json",permissionsConfig:{filePath:".kilocode/mcp.json",allowKeyPath:["mcpServers","constellation","alwaysAllow"],allowValue:"code_intel"},mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"opencode",displayName:"OpenCode",configPath:"opencode.jsonc",format:"jsonc",mcpServersKeyPath:["mcp"],skipMcpServer:true,pluginConfig:{pluginKeyPath:["plugin"],pluginValue:"@constellationdev/opencode"},configDefaults:{$schema:"https://opencode.ai/config.json"}},{id:"tabnine",displayName:"Tabnine",configPath:".tabnine/mcp_servers.json",format:"json",mcpServersKeyPath:["mcpServers"]},{id:"vscode-copilot",displayName:"VSCode",configPath:".vscode/mcp.json",format:"json",mcpServersKeyPath:["servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}}];});async function Go(){if(!dn)try{let i=await import('@iarna/toml');dn={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return dn}function rp(i){let e="",t=0,n=i.length;for(;t<n;)if(i[t]==='"'){for(e+='"',t++;t<n&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<n&&(e+=i[t++])):e+=i[t++];t<n&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<n&&i[t+1]==="/")for(t+=2;t<n&&i[t]!==`
80
+ `;)t++;else if(i[t]==="/"&&t+1<n&&i[t+1]==="*"){for(t+=2;t<n&&!(i[t]==="*"&&t+1<n&&i[t+1]==="/");)t++;t<n&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var dn,sr,Bo=f(()=>{re();un();dn=null;sr=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=E__default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){await this.ensureDirectoryExists(t);let s=await this.readConfig(t,e.format);if(e.configDefaults)for(let[a,l]of Object.entries(e.configDefaults))a in s||(s[a]=l);e.pluginConfig&&(s=this.addPluginToArray(s,e.pluginConfig)),e.skipMcpServer||(s=this.addConstellationServer(s,e),await this.configureEnvPolicy(s,e)),await this.writeConfig(t,s,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let o;return n?o=t:e.permissionsConfig?o=E__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=E__default.join(this.cwd,e.marketplaceConfig.filePath):o=t,{tool:e,success:!0,configuredPath:o}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),n=[];for(let{displayName:o,settingsPath:s}of t)try{await this.ensureDirectoryExists(s);let a=await this.readConfig(s,e.format);a=this.addConstellationServer(a,e),await this.writeConfig(s,a,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:s});}catch(a){let l=a instanceof Error?a.message:String(a);l.includes("ENOENT")||l.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:l});}return n}async ensureDirectoryExists(e){let t=E__default.dirname(e);await G__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await S.fileIsReadable(e))return {};let o=await S.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(rp(o)):(await Go()).parse(o)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let a=0;a<t.mcpServersKeyPath.length-1;a++){let l=t.mcpServersKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[o]||typeof n[o]!="object")&&(n[o]={});let s=n[o];if(!s.constellation){let a=t.mcpServerConfigOverride??Mo,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,n){let o;n==="json"||n==="jsonc"?o=JSON.stringify(t,null,2):o=(await Go()).stringify(t),o=o.replace(/\r\n/g,`
81
81
  `),o.endsWith(`
82
82
  `)||(o+=`
83
83
  `),await S.writeFile(e,o);}async configurePermissions(e){let t=E__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await S.fileIsReadable(t)){let c=await S.readFile(t);n=JSON.parse(c);}}catch{}let o=n;for(let l=0;l<e.allowKeyPath.length-1;l++){let c=e.allowKeyPath[l];(!o[c]||typeof o[c]!="object")&&(o[c]={}),o=o[c];}let s=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(o[s])||(o[s]=[]);let a=o[s];a.includes(e.allowValue)||a.push(e.allowValue),await S.writeFile(t,JSON.stringify(n,null," ")+`
84
84
  `);}async configureMarketplace(e){let t=E__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await S.fileIsReadable(t)){let s=await S.readFile(t);n=JSON.parse(s);}}catch{}n=this.deepMerge(n,e.config),await S.writeFile(t,JSON.stringify(n,null," ")+`
85
- `);}deepMerge(e,t){let n={...e};for(let o of Object.keys(t)){let s=t[o],a=e[o];s&&typeof s=="object"&&!Array.isArray(s)&&a&&typeof a=="object"&&!Array.isArray(a)?n[o]=this.deepMerge(a,s):n[o]=s;}return n}addPluginToArray(e,t){let n=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let s=n[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,o),s&&await this.updateGlobalEnvPolicy(s,n,o,t.format);}addToEnvPolicyWhitelist(e,t,n){let o=e;for(let l=0;l<t.length-1;l++){let c=t[l];if(!o[c]||typeof o[c]!="object")return;o=o[c];}let s=t[t.length-1];if(!Array.isArray(o[s]))return;let a=o[s];for(let l of n)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,n,o){let s=e.replace(/^~/,Ce__default.homedir()),a=await this.readConfig(s,o);if(Object.keys(a).length===0)return;let l=JSON.stringify(a);this.addToEnvPolicyWhitelist(a,t,n);let c=JSON.stringify(a);l!==c&&await this.writeConfig(s,a,o);}};});function sr(i,e){let t=E__default.normalize(i),n=E__default.normalize(e);return t.startsWith(n+E__default.sep)?E__default.relative(e,i):i}var lp,pt,Ho=f(()=>{ko();Qe();zt();Bo();pn();re();O();Ct();bt();lp=promisify(execFile);pt=class extends ce{async run(e={}){try{if(this.reporter.log(`${ae} Initializing project configuration...
86
- `),!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 n=E__default.join(process.cwd(),"constellation.json"),o=null,s=await S.fileIsReadable(n);if(s)try{let C=await S.readFile(n);o=JSON.parse(C),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(C=>C!==p),m=p?[p,...d]:d,g=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:C=>C.trim().length>0||"Project ID is required",theme:L}),h=await select({message:"Branch to index:",choices:m.map(C=>({name:C,value:C})),default:o?.branch??m[0],theme:L}),y=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:L})).reduce((C,A)=>(C[A]={fileExtensions:et[A]||[]},C),{});this.reporter.log(""),this.reporter.info("Checking for LSP servers...");for(let[C,A]of Object.entries(y)){let N=de.get(C);if(!N)continue;let X=!1,se="";if(je(N.command)&&(X=!0,se="system"),!X){let ye=E__default.join(Lt,N.command);existsSync(ye)&&(X=!0,se="managed");}if(X)this.reporter.log(`${w} ${C}: Found ${N.command} (${se})`),A.lsp={command:N.command,args:N.args};else if(await confirm({message:`${C}: ${N.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:L}))try{this.reporter.info(`Installing ${N.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",Ar,...N.npmPackages],{stdio:"pipe"}),this.reporter.log(`${w} ${C}: Installed ${N.command}`),A.lsp={command:N.command,args:N.args};}catch{this.reporter.error(`${C}: Installation failed`),A.lspEnrichment=!1;}else A.lspEnrichment=!1;}let v=Object.entries(y).filter(([,C])=>C.lspEnrichment!==!1).map(([C])=>C);v.length>0?this.reporter.log(`${w} Index enrichment enabled for: ${v.map(tt).join(", ")}`):this.reporter.warn("No language servers configured. Index enrichment will be skipped.");let x={projectId:g.trim(),branch:h,languages:{...y},...v.length>0&&{lspEnrichment:!0}},j=JSON.stringify(x,void 0,2);await S.writeFile(n,j),this.reporter.log(`${w} ${s?"Updated":"Initialized"} configuration file at ${sr(n,process.cwd())}`),await this.git.stageFile(n),this.reporter.log(`${w} 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 n=t.message??"An unexpected error occurred";this.reporter.error(`Failed to initialize configuration file.
87
- ${n}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:L}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:cn.map(p=>({name:p.displayName,value:p.id})),required:true,theme:L}),n=new or(process.cwd()),o=[];for(let p of t){let d=Uo(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(`${w} ${d.displayName} plugin installed successfully`):this.reporter.warn(`${d.displayName}: ${m.error}`);}else if(d.isGlobalConfig&&d.getGlobalConfigPaths){let m=await n.configureGlobalTool(d),g=false;for(let h of m)o.push(h),h.success?(g=true,this.reporter.log(`${w} ${h.tool.displayName} configured at ${sr(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 n.configureTool(d);o.push(m),m.success?(this.reporter.log(`${w} ${d.displayName} configured at ${sr(m.configuredPath,process.cwd())}`),d.permissionsConfig&&this.reporter.log(`${w} ${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=E__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),this.reporter.log(`${w} 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=E__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),this.reporter.log(`${w} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=E__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),this.reporter.log(`${w} 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(`${w} 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(n){let o=n;if(e.pluginUpdateCommand&&this.isAlreadyInstalledError(o)){this.reporter.info(`${e.displayName} extension already installed, attempting update...`);try{await this.runPluginCommand(e.pluginUpdateCommand);}catch(s){let a=s;return {tool:e,success:false,error:this.formatPluginCommandError(e.pluginUpdateCommand.command,a)}}}else if(this.isAlreadyInstalledError(o)&&(e.pluginPostInstallCommands?.length??0)>0)this.reporter.info(`${e.displayName} plugin source already configured, continuing...`);else return {tool:e,success:false,error:this.formatPluginCommandError(t.command,o)}}for(let n of e.pluginPostInstallCommands??[])try{await this.runPluginCommand(n);}catch(o){let s=o;return {tool:e,success:false,error:this.formatPluginCommandError(n.command,s)}}return {tool:e,success:true}}async runPluginCommand(e){await lp(e.command,e.args,{timeout:3e4,env:process.env});}isAlreadyInstalledError(e){let t=`${e.message??""}
88
- ${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:L}))return;let o=new lt(t),s=await o.detectPlatforms(),a;if(s.length===1){let p=s[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${p}. Configure Constellation CI/CD for this platform?`,default:true,theme:L}))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:L});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:L})){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=sr(c,process.cwd());a==="github"?this.reporter.log(`${w} Created ${u}`):this.reporter.log(`${w} ${l?"Updated":"Created"} ${u} with Constellation indexing`);try{await this.git.stageFile(c),this.reporter.log(`${w} 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:
85
+ `);}deepMerge(e,t){let n={...e};for(let o of Object.keys(t)){let s=t[o],a=e[o];s&&typeof s=="object"&&!Array.isArray(s)&&a&&typeof a=="object"&&!Array.isArray(a)?n[o]=this.deepMerge(a,s):n[o]=s;}return n}addPluginToArray(e,t){let n=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let s=n[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,o),s&&await this.updateGlobalEnvPolicy(s,n,o,t.format);}addToEnvPolicyWhitelist(e,t,n){let o=e;for(let l=0;l<t.length-1;l++){let c=t[l];if(!o[c]||typeof o[c]!="object")return;o=o[c];}let s=t[t.length-1];if(!Array.isArray(o[s]))return;let a=o[s];for(let l of n)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,n,o){let s=e.replace(/^~/,Ce__default.homedir()),a=await this.readConfig(s,o);if(Object.keys(a).length===0)return;let l=JSON.stringify(a);this.addToEnvPolicyWhitelist(a,t,n);let c=JSON.stringify(a);l!==c&&await this.writeConfig(s,a,o);}};});function ar(i,e){let t=E__default.normalize(i),n=E__default.normalize(e);return t.startsWith(n+E__default.sep)?E__default.relative(e,i):i}var lp,pt,Ho=f(()=>{ko();Qe();Ht();Bo();un();re();O();Ct();bt();lp=promisify(execFile);pt=class extends ce{async run(e={}){try{if(this.reporter.log(`${ae} Initializing project configuration...
86
+ `),!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 n=E__default.join(process.cwd(),"constellation.json"),o=null,s=await S.fileIsReadable(n);if(s)try{let C=await S.readFile(n);o=JSON.parse(C),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(C=>C!==p),m=p?[p,...d]:d,g=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:C=>C.trim().length>0||"Project ID is required",theme:L}),h=await select({message:"Branch to index:",choices:m.map(C=>({name:C,value:C})),default:o?.branch??m[0],theme:L}),y=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:L})).reduce((C,A)=>(C[A]={fileExtensions:et[A]||[]},C),{});this.reporter.log(""),this.reporter.info("Checking for LSP servers...");for(let[C,A]of Object.entries(y)){let N=de.get(C);if(!N)continue;let X=!1,se="";if(je(N.command)&&(X=!0,se="system"),!X){let ye=E__default.join(At,N.command);existsSync(ye)&&(X=!0,se="managed");}if(X)this.reporter.log(`${w} ${C}: Found ${N.command} (${se})`),A.lsp={command:N.command,args:N.args};else if(await confirm({message:`${C}: ${N.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:L}))try{this.reporter.info(`Installing ${N.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",kr,...N.npmPackages],{stdio:"pipe"}),this.reporter.log(`${w} ${C}: Installed ${N.command}`),A.lsp={command:N.command,args:N.args};}catch{this.reporter.error(`${C}: Installation failed`),A.lspEnrichment=!1;}else A.lspEnrichment=!1;}let v=Object.entries(y).filter(([,C])=>C.lspEnrichment!==!1).map(([C])=>C);v.length>0?this.reporter.log(`${w} Index enrichment enabled for: ${v.map(tt).join(", ")}`):this.reporter.warn("No language servers configured. Index enrichment will be skipped.");let x={projectId:g.trim(),branch:h,languages:{...y},...v.length>0&&{lspEnrichment:!0}},j=JSON.stringify(x,void 0,2);await S.writeFile(n,j),this.reporter.log(`${w} ${s?"Updated":"Initialized"} configuration file at ${ar(n,process.cwd())}`),await this.git.stageFile(n),this.reporter.log(`${w} 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 n=t.message??"An unexpected error occurred";this.reporter.error(`Failed to initialize configuration file.
87
+ ${n}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:L}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:pn.map(p=>({name:p.displayName,value:p.id})),required:true,theme:L}),n=new sr(process.cwd()),o=[];for(let p of t){let d=Uo(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(`${w} ${d.displayName} plugin installed successfully`):this.reporter.warn(`${d.displayName}: ${m.error}`);}else if(d.isGlobalConfig&&d.getGlobalConfigPaths){let m=await n.configureGlobalTool(d),g=false;for(let h of m)o.push(h),h.success?(g=true,this.reporter.log(`${w} ${h.tool.displayName} configured at ${ar(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 n.configureTool(d);o.push(m),m.success?(this.reporter.log(`${w} ${d.displayName} configured at ${ar(m.configuredPath,process.cwd())}`),d.permissionsConfig&&this.reporter.log(`${w} ${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=E__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),this.reporter.log(`${w} 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=E__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),this.reporter.log(`${w} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=E__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),this.reporter.log(`${w} 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(`${w} 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(n){let o=n;if(e.pluginUpdateCommand&&this.isAlreadyInstalledError(o)){this.reporter.info(`${e.displayName} extension already installed, attempting update...`);try{await this.runPluginCommand(e.pluginUpdateCommand);}catch(s){let a=s;return {tool:e,success:false,error:this.formatPluginCommandError(e.pluginUpdateCommand.command,a)}}}else if(this.isAlreadyInstalledError(o)&&(e.pluginPostInstallCommands?.length??0)>0)this.reporter.info(`${e.displayName} plugin source already configured, continuing...`);else return {tool:e,success:false,error:this.formatPluginCommandError(t.command,o)}}for(let n of e.pluginPostInstallCommands??[])try{await this.runPluginCommand(n);}catch(o){let s=o;return {tool:e,success:false,error:this.formatPluginCommandError(n.command,s)}}return {tool:e,success:true}}async runPluginCommand(e){await lp(e.command,e.args,{timeout:3e4,env:process.env});}isAlreadyInstalledError(e){let t=`${e.message??""}
88
+ ${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:L}))return;let o=new lt(t),s=await o.detectPlatforms(),a;if(s.length===1){let p=s[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${p}. Configure Constellation CI/CD for this platform?`,default:true,theme:L}))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:L});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:L})){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=ar(c,process.cwd());a==="github"?this.reporter.log(`${w} Created ${u}`):this.reporter.log(`${w} ${l?"Updated":"Created"} ${u} with Constellation indexing`);try{await this.git.stageFile(c),this.reporter.log(`${w} 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:
89
89
  Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret
90
90
  Name: CONSTELLATION_ACCESS_KEY`):this.reporter.info(`Add your access key as a CI/CD variable:
91
91
  Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable
92
- Key: CONSTELLATION_ACCESS_KEY`);}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(n=>({...n,checked:t.includes(n.value)}))}};});var ar,Ko=f(()=>{Nr();Yt();re();O();ar=class i{constructor(e,t,n,o,s){this.branch=e;this.languages=t;this.projectId=n;this.exclude=o;this.lspEnrichment=s;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await S.fileIsReadable(e)){let n=await S.readFile(e),o=JSON.parse(n),s=new i(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${q} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let n of t.fileExtensions)if(!n.startsWith("."))throw new Error(`Invalid configuration: file extension "${n}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new ue("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new ue(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var cr,dn,pr,mn,gn,fn,ur,Vo=f(()=>{re();cr=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(`
93
- `)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},dn=class extends cr{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.
94
- Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,o)=>{let s=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0?n():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let o=(await new Promise((s,a)=>{let l=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",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}}},pr=class extends cr{userConfigFiles;constructor(){super(),this.userConfigFiles=[E.join(Ce.homedir(),".zshenv"),E.join(Ce.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.
92
+ Key: CONSTELLATION_ACCESS_KEY`);}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(n=>({...n,checked:t.includes(n.value)}))}};});var lr,Ko=f(()=>{Tr();Xt();re();O();lr=class i{constructor(e,t,n,o,s){this.branch=e;this.languages=t;this.projectId=n;this.exclude=o;this.lspEnrichment=s;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await S.fileIsReadable(e)){let n=await S.readFile(e),o=JSON.parse(n),s=new i(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${q} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let n of t.fileExtensions)if(!n.startsWith("."))throw new Error(`Invalid configuration: file extension "${n}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new ue("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new ue(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var pr,mn,ur,gn,fn,hn,dr,Vo=f(()=>{re();pr=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(`
93
+ `)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},mn=class extends pr{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.
94
+ Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,o)=>{let s=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0?n():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let o=(await new Promise((s,a)=>{let l=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",u="";l.stdout?.on("data",p=>{c+=p.toString();}),l.stderr?.on("data",p=>{u+=p.toString();}),l.on("close",p=>{p===0?s(c):a(new Error(`reg query failed: ${u}`));}),l.on("error",p=>{a(p);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},ur=class extends pr{userConfigFiles;constructor(){super(),this.userConfigFiles=[E.join(Ce.homedir(),".zshenv"),E.join(Ce.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.
95
95
  Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),o=`export ${e}="${n}"`;try{for(let s of this.userConfigFiles)await this.writeToConfigFile(s,e,o);process.env[e]=t;}catch(s){throw new Error(`Failed to set environment variable ${e}: ${s}`)}}async writeToConfigFile(e,t,n){let o="";try{o=await S.readFile(e,"utf-8");}catch{}let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^export ${s}=.*$`,"gm");a.test(o)?o=o.replace(a,n):o=o.trimEnd()+`
96
96
  `+n+`
97
- `,await S.writeFile(e,o);}async assertSafeWriteTarget(e){try{let t=await G__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 n=process.getuid?.();if(n!==void 0&&t.uid!==n)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}}},mn=class i extends pr{static LAUNCH_AGENT_LABEL="io.constellationdev.env";launchAgentDir;launchAgentScriptDir;launchAgentLogDir;launchAgentPlistPath;launchAgentScriptPath;launchAgentStderrPath;constructor(){super();let e=Ce.homedir();this.launchAgentDir=E.join(e,"Library","LaunchAgents"),this.launchAgentScriptDir=E.join(e,"Library","Application Support","Constellation"),this.launchAgentLogDir=E.join(e,"Library","Logs","Constellation"),this.launchAgentPlistPath=E.join(this.launchAgentDir,`${i.LAUNCH_AGENT_LABEL}.plist`),this.launchAgentScriptPath=E.join(this.launchAgentScriptDir,"launchd-env.sh"),this.launchAgentStderrPath=E.join(this.launchAgentLogDir,"launchd-env.err");}async setVariable(e,t){await super.setVariable(e,t);try{await this.ensureLaunchAgentDirs();}catch(n){this.warnLaunchd("create LaunchAgent directories",n);return}try{await this.updateLaunchAgentScript(e,t);}catch(n){this.warnLaunchd("write launchd-env.sh wrapper script",n);return}try{await this.ensureLaunchAgentPlist();}catch(n){this.warnLaunchd("write LaunchAgent plist",n);return}await this.reloadLaunchAgent(),await this.setLaunchctlEnv(e,t);}async ensureLaunchAgentDirs(){await G__default.mkdir(this.launchAgentDir,{recursive:true}),await G__default.mkdir(this.launchAgentScriptDir,{recursive:true}),await G__default.mkdir(this.launchAgentLogDir,{recursive:true}),await G__default.chmod(this.launchAgentScriptDir,448);}static escapeXml(e){return e.replace(/[&<>"']/g,t=>{switch(t){case "&":return "&amp;";case "<":return "&lt;";case ">":return "&gt;";case '"':return "&quot;";case "'":return "&apos;";default:return t}})}async updateLaunchAgentScript(e,t){let n=this.escapeShellValue(t),o=`launchctl setenv ${e} "${n}"`,s="";try{s=await S.readFile(this.launchAgentScriptPath,"utf-8");}catch{}s||(s=`#!/bin/bash
97
+ `,await S.writeFile(e,o);}async assertSafeWriteTarget(e){try{let t=await G__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 n=process.getuid?.();if(n!==void 0&&t.uid!==n)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}}},gn=class i extends ur{static LAUNCH_AGENT_LABEL="io.constellationdev.env";launchAgentDir;launchAgentScriptDir;launchAgentLogDir;launchAgentPlistPath;launchAgentScriptPath;launchAgentStderrPath;constructor(){super();let e=Ce.homedir();this.launchAgentDir=E.join(e,"Library","LaunchAgents"),this.launchAgentScriptDir=E.join(e,"Library","Application Support","Constellation"),this.launchAgentLogDir=E.join(e,"Library","Logs","Constellation"),this.launchAgentPlistPath=E.join(this.launchAgentDir,`${i.LAUNCH_AGENT_LABEL}.plist`),this.launchAgentScriptPath=E.join(this.launchAgentScriptDir,"launchd-env.sh"),this.launchAgentStderrPath=E.join(this.launchAgentLogDir,"launchd-env.err");}async setVariable(e,t){await super.setVariable(e,t);try{await this.ensureLaunchAgentDirs();}catch(n){this.warnLaunchd("create LaunchAgent directories",n);return}try{await this.updateLaunchAgentScript(e,t);}catch(n){this.warnLaunchd("write launchd-env.sh wrapper script",n);return}try{await this.ensureLaunchAgentPlist();}catch(n){this.warnLaunchd("write LaunchAgent plist",n);return}await this.reloadLaunchAgent(),await this.setLaunchctlEnv(e,t);}async ensureLaunchAgentDirs(){await G__default.mkdir(this.launchAgentDir,{recursive:true}),await G__default.mkdir(this.launchAgentScriptDir,{recursive:true}),await G__default.mkdir(this.launchAgentLogDir,{recursive:true}),await G__default.chmod(this.launchAgentScriptDir,448);}static escapeXml(e){return e.replace(/[&<>"']/g,t=>{switch(t){case "&":return "&amp;";case "<":return "&lt;";case ">":return "&gt;";case '"':return "&quot;";case "'":return "&apos;";default:return t}})}async updateLaunchAgentScript(e,t){let n=this.escapeShellValue(t),o=`launchctl setenv ${e} "${n}"`,s="";try{s=await S.readFile(this.launchAgentScriptPath,"utf-8");}catch{}s||(s=`#!/bin/bash
98
98
  # Managed by Constellation CLI - do not edit manually
99
99
  `);let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^launchctl setenv ${a} .*$`,"gm");l.test(s)?s=s.replace(l,o):s=s.trimEnd()+`
100
100
  `+o+`
@@ -118,17 +118,17 @@ ${e.stderr??""}`.toLowerCase();return t.includes("already installed")||t.include
118
118
  </dict>
119
119
  </plist>
120
120
  `;await this.assertSafeWriteTarget(this.launchAgentPlistPath),await S.writeFile(this.launchAgentPlistPath,o),await G__default.chmod(this.launchAgentPlistPath,384);}warnLaunchd(e,t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: failed to ${e} for GUI apps: ${n}
121
- Shell environments still updated; log out and back in if GUI apps don't see the value.`);}runLaunchctl(e,t){return new Promise((n,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?n():o(new Error(`launchctl ${e[0]} failed (code ${l}): ${a.trim()}`));}),s.on("error",l=>{t?n():o(l);});})}async reloadLaunchAgent(){let e=process.getuid?.();if(e!==void 0)try{await this.runLaunchctl(["bootout",`gui/${e}/${i.LAUNCH_AGENT_LABEL}`],!0),await this.runLaunchctl(["bootstrap",`gui/${e}`,this.launchAgentPlistPath],!1);}catch(t){this.warnLaunchd("register LaunchAgent for next login",t);}}async setLaunchctlEnv(e,t){try{await this.runLaunchctl(["setenv",e,t],!0);}catch(n){this.warnLaunchd("run launchctl setenv",n);}}},gn=class i extends pr{static ENV_D_FILENAME="io.constellationdev.env.conf";envDDir;envDFilePath;constructor(){super(),this.envDDir=E.join(Ce.homedir(),".config","environment.d"),this.envDFilePath=E.join(this.envDDir,i.ENV_D_FILENAME);}async setVariable(e,t){await super.setVariable(e,t);try{await this.ensureEnvironmentDDir();}catch(n){this.warnSystemd("create environment.d directory",n);return}try{await this.updateEnvironmentDFile(e,t);}catch(n){this.warnSystemd("write environment.d conf file",n);return}await this.importToSystemdUser(e,t);}async ensureEnvironmentDDir(){await G__default.mkdir(this.envDDir,{recursive:true});}async updateEnvironmentDFile(e,t){let n=i.escapeEnvironmentDValue(t),o=`${e}=${n}`,s="";try{s=await S.readFile(this.envDFilePath,"utf-8");}catch{}s||(s=`# Managed by Constellation CLI - do not edit manually
121
+ Shell environments still updated; log out and back in if GUI apps don't see the value.`);}runLaunchctl(e,t){return new Promise((n,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?n():o(new Error(`launchctl ${e[0]} failed (code ${l}): ${a.trim()}`));}),s.on("error",l=>{t?n():o(l);});})}async reloadLaunchAgent(){let e=process.getuid?.();if(e!==void 0)try{await this.runLaunchctl(["bootout",`gui/${e}/${i.LAUNCH_AGENT_LABEL}`],!0),await this.runLaunchctl(["bootstrap",`gui/${e}`,this.launchAgentPlistPath],!1);}catch(t){this.warnLaunchd("register LaunchAgent for next login",t);}}async setLaunchctlEnv(e,t){try{await this.runLaunchctl(["setenv",e,t],!0);}catch(n){this.warnLaunchd("run launchctl setenv",n);}}},fn=class i extends ur{static ENV_D_FILENAME="io.constellationdev.env.conf";envDDir;envDFilePath;constructor(){super(),this.envDDir=E.join(Ce.homedir(),".config","environment.d"),this.envDFilePath=E.join(this.envDDir,i.ENV_D_FILENAME);}async setVariable(e,t){await super.setVariable(e,t);try{await this.ensureEnvironmentDDir();}catch(n){this.warnSystemd("create environment.d directory",n);return}try{await this.updateEnvironmentDFile(e,t);}catch(n){this.warnSystemd("write environment.d conf file",n);return}await this.importToSystemdUser(e,t);}async ensureEnvironmentDDir(){await G__default.mkdir(this.envDDir,{recursive:true});}async updateEnvironmentDFile(e,t){let n=i.escapeEnvironmentDValue(t),o=`${e}=${n}`,s="";try{s=await S.readFile(this.envDFilePath,"utf-8");}catch{}s||(s=`# Managed by Constellation CLI - do not edit manually
122
122
  `);let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^${a}=.*$`,"gm");l.test(s)?s=s.replace(l,o):s=s.trimEnd()+`
123
123
  `+o+`
124
124
  `,await this.assertSafeWriteTarget(this.envDFilePath),await G__default.writeFile(this.envDFilePath,s,{mode:384}),await G__default.chmod(this.envDFilePath,384);}async importToSystemdUser(e,t){if(je("systemctl")&&process.env.XDG_RUNTIME_DIR)try{await this.runSystemctl(["--user","set-environment",`${e}=${t}`],!1);}catch(n){this.warnSystemd("run systemctl --user set-environment",n);}}runSystemctl(e,t){return new Promise((n,o)=>{let s=spawn("systemctl",e,{shell:false}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0||t?n():o(new Error(`systemctl ${e.slice(0,2).join(" ")} failed (code ${l}): ${a.trim()}`));}),s.on("error",l=>{t?n():o(l);});})}static escapeEnvironmentDValue(e){return e.replace(/\\/g,"\\\\").replace(/\$/g,"$$$$")}warnSystemd(e,t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: failed to ${e} for systemd user services: ${n}
125
- Shell environments still updated; log out and back in if systemd-launched apps don't see the value.`);}},fn=class{static create(){let e=Ce.platform();switch(e){case "win32":return new dn;case "darwin":return new mn;case "linux":return new gn;default:throw new Error(`Unsupported platform: ${e}`)}}},ur=class{manager;constructor(){this.manager=fn.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 dr,Jo=f(()=>{dr=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let o of n.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=E__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function qo(){return pp.some(i=>!!process.env[i])}function Yo(){return !!process.stdout.isTTY}var pp,Xo=f(()=>{pp=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});function Qo(i=process.argv,e=process.env){let t=i.includes("--verbose"),n=i.includes("--quiet")||i.includes("-q")||i.includes("-Q");if(t&&n){try{process.stderr.write(`note: --verbose and --quiet are mutually exclusive; --verbose wins.
126
- `);}catch{}return "verbose"}if(t)return "verbose";if(n)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=qo(),s=Yo();return o||!s?"plain":"spinner"}var Zo=f(()=>{Xo();});function up(){let i=Ce.platform();if(i==="darwin")return E.join(Ce.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||E.join(Ce.homedir(),"AppData","Local");return E.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||E.join(Ce.homedir(),".cache");return E.join(e,"constellation")}}var dp,mp,gp,ut,hn=f(()=>{dp=up(),mp="update-state.json",gp=1440*60*1e3,ut=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??dp,this.stateFile=E.join(this.stateDir,mp);}async load(){if(this.state)return this.state;try{let e=await G.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await G.mkdir(this.stateDir,{recursive:!0}),await G.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>gp}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 G.unlink(this.stateFile),this.state=null;}catch{}}};});var dt,yn=f(()=>{dt=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...n]=this.getUpdateCommand(e);return new Promise(o=>{let s=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});s.on("close",a=>{o(a===0);}),s.on("error",()=>{o(false);});})}};});var mt,vn=f(()=>{Ie();O();bt();mt=class{async promptForUpdate(e,t,n){console.log(""),console.log(cyan("\u2501".repeat(60))),console.log(`${ae} ${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: ${n}`)}`),console.log(cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:L})}catch{return false}}};});async function bn(i){return new gr().check(i)}var yp,mr,vp,gr,es=f(()=>{O();hn();yn();vn();yp="https://registry.npmjs.org",mr="@constellationdev/cli",vp=5e3,gr=class{cache;packageManager;prompter;constructor(){this.cache=new ut,this.packageManager=new dt,this.prompter=new mt;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,n=setTimeout(()=>t.abort(),vp);try{let o=await fetch(`${yp}/${mr}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let a=(await o.json()).version;return {current:e,latest:a,hasUpdate:this.isNewerVersion(a,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=a=>a.split("-")[0],o=n(e).split(".").map(Number),s=n(t).split(".").map(Number);for(let a=0;a<3;a++){let l=o[a]||0,c=s[a]||0;if(l>c)return true;if(l<c)return false}return false}async performUpdate(){return console.log(`
127
- ${Z} Updating ${mr}...
128
- `),await this.packageManager.executeUpdate(mr)?(console.log(`
125
+ Shell environments still updated; log out and back in if systemd-launched apps don't see the value.`);}},hn=class{static create(){let e=Ce.platform();switch(e){case "win32":return new mn;case "darwin":return new gn;case "linux":return new fn;default:throw new Error(`Unsupported platform: ${e}`)}}},dr=class{manager;constructor(){this.manager=hn.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 mr,Jo=f(()=>{mr=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let o of n.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=E__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function qo(){return pp.some(i=>!!process.env[i])}function Yo(){return !!process.stdout.isTTY}var pp,Xo=f(()=>{pp=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});function Qo(i=process.argv,e=process.env){let t=i.includes("--verbose"),n=i.includes("--quiet")||i.includes("-q")||i.includes("-Q");if(t&&n){try{process.stderr.write(`note: --verbose and --quiet are mutually exclusive; --verbose wins.
126
+ `);}catch{}return "verbose"}if(t)return "verbose";if(n)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=qo(),s=Yo();return o||!s?"plain":"spinner"}var Zo=f(()=>{Xo();});function up(){let i=Ce.platform();if(i==="darwin")return E.join(Ce.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||E.join(Ce.homedir(),"AppData","Local");return E.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||E.join(Ce.homedir(),".cache");return E.join(e,"constellation")}}var dp,mp,gp,ut,yn=f(()=>{dp=up(),mp="update-state.json",gp=1440*60*1e3,ut=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??dp,this.stateFile=E.join(this.stateDir,mp);}async load(){if(this.state)return this.state;try{let e=await G.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await G.mkdir(this.stateDir,{recursive:!0}),await G.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>gp}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 G.unlink(this.stateFile),this.state=null;}catch{}}};});var dt,vn=f(()=>{dt=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...n]=this.getUpdateCommand(e);return new Promise(o=>{let s=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});s.on("close",a=>{o(a===0);}),s.on("error",()=>{o(false);});})}};});var mt,bn=f(()=>{Ie();O();bt();mt=class{async promptForUpdate(e,t,n){console.log(""),console.log(cyan("\u2501".repeat(60))),console.log(`${ae} ${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: ${n}`)}`),console.log(cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:L})}catch{return false}}};});async function Sn(i){return new fr().check(i)}var yp,gr,vp,fr,es=f(()=>{O();yn();vn();bn();yp="https://registry.npmjs.org",gr="@constellationdev/cli",vp=5e3,fr=class{cache;packageManager;prompter;constructor(){this.cache=new ut,this.packageManager=new dt,this.prompter=new mt;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,n=setTimeout(()=>t.abort(),vp);try{let o=await fetch(`${yp}/${gr}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let a=(await o.json()).version;return {current:e,latest:a,hasUpdate:this.isNewerVersion(a,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=a=>a.split("-")[0],o=n(e).split(".").map(Number),s=n(t).split(".").map(Number);for(let a=0;a<3;a++){let l=o[a]||0,c=s[a]||0;if(l>c)return true;if(l<c)return false}return false}async performUpdate(){return console.log(`
127
+ ${Z} Updating ${gr}...
128
+ `),await this.packageManager.executeUpdate(gr)?(console.log(`
129
129
  ${w} Update complete! Please re-run your command.
130
130
  `),true):(console.log(`
131
- ${T} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(mr)}
132
- `),false)}};});var ts=f(()=>{hn();yn();vn();es();});var gt,rs=f(()=>{O();gt=class{constructor(e,t){this.reporter=t;let n={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(n);}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 n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Could not parse commit timestamp: ${t}`);return n.toISOString()}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},o=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);for(let s of o){let a=s.split(" ");if(a.length<2)continue;let l=a[0];l==="A"?n.added.push(a[1]):l==="M"?n.modified.push(a[1]):l==="D"?n.deleted.push(a[1]):l.startsWith("R")&&a.length>=3&&n.renamed.push({from:a[1],to:a[2]});}return n}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(n=>n.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,n=e.current;return {clean:t,currentBranch:n}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let o={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw 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.
133
- 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(`${w} Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw this.reporter?.error("Unexpected conflicts after pull:"),this.reporter?.detail(`Conflicted files: ${n.conflicted.join(", ")}`),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(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 is,ns=f(()=>{is={"tree-sitter":"0.21.1","tree-sitter-typescript":"0.21.2","tree-sitter-javascript":"0.21.4","tree-sitter-python":"0.21.0"};});function os(){let i={};for(let e of wp){let t=is[e];if(typeof t!="string"||t.length===0)throw new Error(`grammar-versions.json missing entry for ${e}`);i[e]=t;}return i}var wp,ss=f(()=>{ns();wp=["tree-sitter","tree-sitter-typescript","tree-sitter-javascript","tree-sitter-python"];});var Ip={};var M,he,as,Sn,_p,Pp,wn,Cn,We,ls=f(async()=>{Fn();Ro();Ho();Ko();Vo();Jo();zt();Zo();Jr();ts();hr();wt();rs();ss();M=new er({mode:Qo(process.argv)}),he=()=>{try{M.stop();}catch{}};process.on("exit",he);process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&(he(),process.exit(0)),ie(i)||M.error(i?.message??String(i)),he(),process.exit(1);});as=globalThis.__constellationVersion??(()=>{let i=E__default.dirname(fileURLToPath(import.meta.url)),e=E__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})(),Sn=(()=>{let i=process.argv[1];return i&&E__default.basename(i).replace(/\.(c|m)?js$/i,"")==="const"?"const":"constellation"})(),_p=new Set(["print-grammar-versions"]),Pp=_p.has(process.argv[2]);if(M.mode!=="quiet"&&!Pp){let i=process.argv[2];["auth","help","init","index"].includes(i)?St(Sn,i):St(Sn),ht.includes(i)||await bn(as)&&(he(),process.exit(0));}wn=process.cwd(),Cn=new ur,We=new Command;We.name(Sn).description("Connecting stars in your code into intelligent patterns").version(as).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.");We.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async i=>{try{let t={GitClient:new gt(wn,M),Reporter:M};await new pt(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){ie(e)||M.error(e instanceof Error?e.message:String(e)),he(),process.exit(1);}});We.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async i=>{try{let e={Environment:Cn,Reporter:M};await new Ke(e).run(i.manual);}catch(e){ie(e)||M.error(e instanceof Error?e.message:String(e)),he(),process.exit(1);}});We.command("index").description("Create or update the Constellation data indices for the current project").option("--full","Conduct a full project re-index").option("--incremental","Conduct an incremental project index update").option("--dirty","Skip git validation checks (branch and working tree status)").option("--no-enrich","Skip LSP enrichment (only perform parse tree indexing)").action(async i=>{try{let e=await ar.loadFromFile(E__default.join(wn,"constellation.json")),t=new gt(wn,M),n=new Wt(e),o=new dr(e),s={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:o,Environment:Cn,Reporter:M},a=Cn.isCI(),l=i.full||!i.incremental&&a,c=i.dirty||!1,u=!0;!i.full&&!i.incremental&&a&&M.info("CI environment detected \u2014 defaulting to full index. Use --incremental to override."),await new at(s).run(l,c,u);}catch(e){ie(e)||M.error(e instanceof Error?e.message:String(e)),he(),process.exit(1);}});We.command("print-grammar-versions",{hidden:true}).description("Emit installed tree-sitter grammar versions as JSON").action(()=>{try{process.stdout.write(JSON.stringify(os())+`
134
- `);}catch(i){ie(i)||M.error(i instanceof Error?i.message:String(i)),he(),process.exit(1);}});We.parse();});var ds=/^>=\s*\d+\.\d+\.\d+$/;function _n(i,e=process.version){if(!ds.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),n=e.replace(/^v/,""),o=t.split(".").map(Number),s=n.split(".").map(Number),a=true;for(let l=0;l<3;l++){let c=o[l]||0,u=s[l]||0;if(u>c)break;if(u<c){a=false;break}}return {compatible:a,current:e,required:i}}hr();var Lp=dirname(fileURLToPath(import.meta.url)),Ap=join(Lp,"..","package.json"),xn=JSON.parse(readFileSync(Ap,"utf-8")),kp=process.argv[2];if(!ht.includes(kp)&&xn.engines?.node){let i=_n(xn.engines.node);i.compatible||(console.error(`Error: Constellation CLI requires Node.js ${i.required} (current: ${i.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=xn.version;await ls().then(()=>Ip);
131
+ ${T} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(gr)}
132
+ `),false)}};});var ts=f(()=>{yn();vn();bn();es();});var gt,rs=f(()=>{O();gt=class{constructor(e,t){this.reporter=t;let n={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(n);}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 n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Could not parse commit timestamp: ${t}`);return n.toISOString()}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},o=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);for(let s of o){let a=s.split(" ");if(a.length<2)continue;let l=a[0];l==="A"?n.added.push(a[1]):l==="M"?n.modified.push(a[1]):l==="D"?n.deleted.push(a[1]):l.startsWith("R")&&a.length>=3&&n.renamed.push({from:a[1],to:a[2]});}return n}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(n=>n.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,n=e.current;return {clean:t,currentBranch:n}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let o={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw 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.
133
+ 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(`${w} Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw this.reporter?.error("Unexpected conflicts after pull:"),this.reporter?.detail(`Conflicted files: ${n.conflicted.join(", ")}`),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(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 is,ns=f(()=>{is={"tree-sitter":"0.21.1","tree-sitter-typescript":"0.21.2","tree-sitter-javascript":"0.21.4","tree-sitter-python":"0.21.0"};});function os(){let i={};for(let e of wp){let t=is[e];if(typeof t!="string"||t.length===0)throw new Error(`grammar-versions.json missing entry for ${e}`);i[e]=t;}return i}var wp,ss=f(()=>{ns();wp=["tree-sitter","tree-sitter-typescript","tree-sitter-javascript","tree-sitter-python"];});var Ip={};var M,he,as,wn,_p,Pp,Cn,xn,ze,ls=f(async()=>{$n();Ro();Ho();Ko();Vo();Jo();Ht();Zo();qr();ts();yr();wt();rs();ss();M=new tr({mode:Qo(process.argv)}),he=()=>{try{M.stop();}catch{}};process.on("exit",he);process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&(he(),process.exit(0)),ie(i)||M.error(i?.message??String(i)),he(),process.exit(1);});as=globalThis.__constellationVersion??(()=>{let i=E__default.dirname(fileURLToPath(import.meta.url)),e=E__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})(),wn=(()=>{let i=process.argv[1];return i&&E__default.basename(i).replace(/\.(c|m)?js$/i,"")==="const"?"const":"constellation"})(),_p=new Set(["print-grammar-versions"]),Pp=_p.has(process.argv[2]);if(M.mode!=="quiet"&&!Pp){let i=process.argv[2];["auth","help","init","index"].includes(i)?St(wn,i):St(wn),ht.includes(i)||await Sn(as)&&(he(),process.exit(0));}Cn=process.cwd(),xn=new dr,ze=new Command;ze.name(wn).description("Connecting stars in your code into intelligent patterns").version(as).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.");ze.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async i=>{try{let t={GitClient:new gt(Cn,M),Reporter:M};await new pt(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){ie(e)||M.error(e instanceof Error?e.message:String(e)),he(),process.exit(1);}});ze.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async i=>{try{let e={Environment:xn,Reporter:M};await new Ke(e).run(i.manual);}catch(e){ie(e)||M.error(e instanceof Error?e.message:String(e)),he(),process.exit(1);}});ze.command("index").description("Create or update the Constellation data indices for the current project").option("--full","Conduct a full project re-index").option("--incremental","Conduct an incremental project index update").option("--dirty","Skip git validation checks (branch and working tree status)").option("--no-enrich","Skip LSP enrichment (only perform parse tree indexing)").action(async i=>{try{let e=await lr.loadFromFile(E__default.join(Cn,"constellation.json")),t=new gt(Cn,M),n=new Wt(e),o=new mr(e),s={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:o,Environment:xn,Reporter:M},a=xn.isCI(),l=i.full||!i.incremental&&a,c=i.dirty||!1,u=!0;!i.full&&!i.incremental&&a&&M.info("CI environment detected \u2014 defaulting to full index. Use --incremental to override."),await new at(s).run(l,c,u);}catch(e){ie(e)||M.error(e instanceof Error?e.message:String(e)),he(),process.exit(1);}});ze.command("print-grammar-versions",{hidden:true}).description("Emit installed tree-sitter grammar versions as JSON").action(()=>{try{process.stdout.write(JSON.stringify(os())+`
134
+ `);}catch(i){ie(i)||M.error(i instanceof Error?i.message:String(i)),he(),process.exit(1);}});ze.parse();});var ds=/^>=\s*\d+\.\d+\.\d+$/;function Pn(i,e=process.version){if(!ds.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),n=e.replace(/^v/,""),o=t.split(".").map(Number),s=n.split(".").map(Number),a=true;for(let l=0;l<3;l++){let c=o[l]||0,u=s[l]||0;if(u>c)break;if(u<c){a=false;break}}return {compatible:a,current:e,required:i}}yr();var Lp=dirname(fileURLToPath(import.meta.url)),Ap=join(Lp,"..","package.json"),En=JSON.parse(readFileSync(Ap,"utf-8")),kp=process.argv[2];if(!ht.includes(kp)&&En.engines?.node){let i=Pn(En.engines.node);i.compatible||(console.error(`Error: Constellation CLI requires Node.js ${i.required} (current: ${i.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=En.version;await ls().then(()=>Ip);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@constellationdev/cli",
3
3
  "description": "Codebase Understanding for AI Coding Agents",
4
- "version": "0.8.0",
4
+ "version": "0.8.1",
5
5
  "author": "ShiftinBits Inc",
6
6
  "main": "dist/main.js",
7
7
  "type": "module",
@@ -25,7 +25,7 @@
25
25
  "prepare": "node -e \"try{require('husky').default()}catch(e){}\""
26
26
  },
27
27
  "dependencies": {
28
- "@constellationdev/types": "^1.1.1",
28
+ "@constellationdev/types": "^1.1.2",
29
29
  "@iarna/toml": "^3.0.0",
30
30
  "@inquirer/prompts": "^8.4.1",
31
31
  "@scure/base": "^2.0.0",