@constellationdev/cli 0.2.6 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +94 -88
- package/package.json +3 -2
package/dist/main.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {base32}from'@scure/base';import {Readable}from'stream';import
|
|
3
|
-
`,r=Buffer.from(n,"utf8");if(!this.push(r))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};});function
|
|
4
|
-
Caused by: ${l.stack}`,
|
|
2
|
+
import {base32}from'@scure/base';import {Readable}from'stream';import p from'ansi-colors';import*as he from'os';import he__default from'os';import {fetch as fetch$1,Agent}from'undici';import {execFile,execFileSync,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import {confirm,password,input,select,checkbox}from'@inquirer/prompts';import*as P from'path';import P__default,{dirname,join}from'path';import*as jt from'fs';import {readFileSync,existsSync}from'fs';import {fileURLToPath,pathToFileURL}from'url';import*as M from'fs/promises';import M__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import oi from'tree-sitter-javascript';import ii from'tree-sitter-python';import si from'tree-sitter-typescript';import li from'tree-sitter';import gr from'ignore';import {z as z$1}from'zod';import Bt from'zlib';import {pipeline}from'stream/promises';import {performance}from'perf_hooks';import {parseDocument,isMap,isSeq}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var yo=Object.defineProperty;var m=(s,e)=>()=>(s&&(e=s(s=0)),e);var Rn=(s,e)=>{for(var t in e)yo(s,t,{get:e[t],enumerable:true});};var Ue,$t=m(()=>{Ue=["help","--help","-h","--version","-V","-v"];});function Tn(s){return base32.encode(Buffer.from(s))}var kn=m(()=>{});function Nn(s,e,t){let n=`${s}:${e}${t?`:${t}`:""}`;return Tn(n)}var An=m(()=>{kn();});var Be,jn=m(()=>{Be=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
|
|
3
|
+
`,r=Buffer.from(n,"utf8");if(!this.push(r))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};});function _o(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:he.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 Eo,So,bo,Po,xo,Io,Ro,$o,To,ko,Ce,C,b,y,w,J,F=m(()=>{Eo="\u2714",So="\u2717",bo="\u26A0",Po="\u2139",xo="\u26A1",Io="[OK]",Ro="[ERR]",$o="[WARN]",To="[INFO]",ko="[>>]",Ce=_o(),C=p.green(Ce?Eo:Io),b=p.red(Ce?So:Ro),y=p.yellow(Ce?bo:$o),w=p.blue(Ce?Po:To),J=p.yellow(Ce?xo:ko);});var He,Ge,R,Y,D,ae,q,We=m(()=>{An();jn();F();He=class{constructor(e,t){this.config=e;this.accessKey=t;}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[r,i]=n.split("=");r&&i!==void 0&&(this.features[r]=i==="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,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 D(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new D(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new D(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new Y("Project not found - no previous index exists");default:throw e.status===404?new Y("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof D||t instanceof Y?t:e.status===404?new Y("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 r=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let i=await this.sendRequest(r,null,"GET");return !i||!i.ok?null:await i.json()}catch(i){if(i instanceof R)throw i;return null}}async pollIndexStatus(e,t,n,r=300*1e3){let i=Date.now(),o=2e3,a=3e4;for(;Date.now()-i<r;){try{let l=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(n)}`,null,"GET");if(!l)continue;if(l.status===401)throw new R("Authentication failed during index status polling");if(l.status===403||l.status===404)return !1;if(l.ok){let g=await l.json();if(g.status==="current")return !0;if(g.status==="stale"||g.status==="failed")return !1}}catch(l){if(l instanceof R)throw l}await new Promise(l=>setTimeout(l,o)),o=Math.min(o*2,a);}return false}async uploadEnrichment(e,t,n,r){let i=[5e3,1e4,2e4];for(let o=0;o<=i.length;o++)try{let a=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":r},body:e,dispatcher:new Agent({headersTimeout:0,bodyTimeout:0})});if(a.status===401)throw new R("Authentication failed during enrichment upload");if(a.status===409){if((await a.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return console.warn("Enrichment skipped: index state changed since AST upload"),!1;if(o<i.length){await new Promise(g=>setTimeout(g,i[o]));continue}return console.warn("Enrichment skipped: indexing still in progress after retries"),!1}return a.ok||a.status===202?!0:(console.warn(`Enrichment upload failed with status ${a.status}`),!1)}catch(a){if(a instanceof R)throw a;if(o<i.length){console.warn(`Enrichment upload network error (attempt ${o+1}/${i.length+1}): ${a instanceof Error?a.message:String(a)}`),await new Promise(l=>setTimeout(l,i[o]));continue}return console.warn(`Enrichment upload error: ${a instanceof Error?a.message:String(a)}`),false}return false}async deleteFiles(e){for(let t of e){let n=Nn(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,r,i,o){try{let{Readable:a}=await import('stream'),l=new Be(e),g=a.toWeb(l),u=new Agent({headersTimeout:0,bodyTimeout:0}),c=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":r,"x-constellation-index":i?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...o&&{"x-commit-hash":o}},body:g,duplex:"half",dispatcher:u});if(c.status===401)throw new R("Authentication failed");if(c.status===409){let d="Indexing already in progress",h;try{let _=await c.json();d=_?.message||d,h=_?.details?.branchName;}catch{}throw new ae(d,h)}if(c.status===200)try{let d=await c.json();if(d?.status==="current")return console.log(`${C} Index already up to date for ${r} at commit ${d.commitHash||"unknown"}`),!0}catch{}if(c.ok||c.status===202)return !0;let f=`Server returned ${c.status}`;try{let d=await c.json();d?.message&&(f=Array.isArray(d.message)?d.message.join("; "):d.message);}catch{}throw new Error(f)}catch(a){if(a instanceof R||a instanceof ae)throw a;let l=a instanceof Error?a:new Error(String(a)),g="";if(l.message==="fetch failed"||a.code){let c=[],f=a.code||a.cause?.code;if(a.code&&c.push(`Error Code: ${a.code}`),a.cause){let d=a.cause;d.code&&c.push(`Cause Code: ${d.code}`),d.errno&&c.push(`Errno: ${d.errno}`),d.syscall&&c.push(`System Call: ${d.syscall}`),d.address&&c.push(`Address: ${d.address}`),d.port&&c.push(`Port: ${d.port}`);}f==="ERR_INVALID_ARG_VALUE"?g="Invalid argument value - check stream/body format and duplex option":f==="ECONNREFUSED"?g="Connection refused - service may be down or unreachable":f==="ENOTFOUND"?g="DNS lookup failed - check service URL":f==="ETIMEDOUT"?g="Connection timeout - service not responding":f==="ECONNRESET"?g="Connection reset by server":f==="EHOSTUNREACH"?g="Host unreachable - check network connectivity":g="Network failure",c.length>0&&(g+=` (${c.join(", ")})`);}else g=l.message;let u=new Error(`Failed to upload data to Constellation Service: ${g}`);throw u.cause=l,u.stack=`${u.stack}
|
|
4
|
+
Caused by: ${l.stack}`,u}}async sendRequest(e,t,n,r={},i=0,o=3,a=1e3,l=250){for(let g=1;g<=o;g++){let u;try{let c=new AbortController;i>0&&(u=setTimeout(()=>c.abort(),i));let f={...r,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},d=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:f,body:t?JSON.stringify(t):void 0,signal:c.signal});if(u&&clearTimeout(u),d.status===401)throw new R("Authentication failed");if(!d.ok&&this.retryableStatusCodes.includes(d.status))throw new Ge(`${d.statusText} (${d.status})`);return d}catch(c){if(u&&clearTimeout(u),!(c instanceof R)){let f=c instanceof Error?`${c.message}${c.cause?` (Cause: ${c.cause})`:""}`:String(c);console.log(`HTTP request attempt ${g}/${o} failed: ${f}`);}if(g<o&&c instanceof Ge){let f=a+Math.floor(Math.random()*l);await new Promise(d=>setTimeout(d,f));}else throw c}}}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},1e4,1,0,0);if(!t){console.warn("Failed to upload error report: no response received");return}if(t.status===403){console.warn("Error reporting is not available on your current plan");return}t.ok||console.warn(`Failed to upload error report: ${t.statusText} (${t.status})`);}catch(t){console.warn(`Failed to upload error report: ${t?.message||"Unknown error"}`);}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Ge=class extends Error{constructor(e){super(e),this.name="RetryableError";}},R=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},Y=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},D=class extends Error{constructor(t,n,r){super(t);this.code=n;this.projectId=r;this.name="ProjectValidationError";}},ae=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}},q=class extends Error{constructor(t,n){super(t);this.errorCode=n;this.name="GitValidationError";}};});var k,ze=m(()=>{k={prefix:{idle:p.blue("\u25C6"),done:p.green("\u2714")},style:{highlight:s=>p.blue(s),answer:s=>p.green(s),error:s=>p.red(`\u2716 ${s}`),help:s=>p.gray(s)},icon:{checked:p.green("\u25FC"),unchecked:p.gray("\u25FB"),cursor:p.blue("\u276F")}};});async function Dn(s){if(!s.startsWith("http://")&&!s.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await Tt("open",[s]),!0;case "linux":return await Tt("xdg-open",[s]),!0;case "win32":return await Tt("cmd",["/c","start","",s]),!0;default:return !1}}catch{return false}}var Tt,Mn=m(()=>{Tt=promisify(execFile);});function Un(){return new Promise((s,e)=>{let t=createServer(),n,r=false;t.listen(0,"127.0.0.1",()=>{let i=t.address();if(!i||typeof i=="string"){t.close(),e(new Error("Failed to bind callback server"));return}s({port:i.port,close(){n&&(clearTimeout(n),n=void 0),t.close(),t.closeAllConnections();},waitForCallback(o,a=3e5){return new Promise((l,g)=>{n=setTimeout(()=>{n=void 0,r=true,t.close(),t.closeAllConnections(),g(new Error("Authentication timed out"));},a),t.on("request",(u,c)=>{let f=new URL(u.url??"/",`http://127.0.0.1:${i.port}`);if(f.pathname!=="/callback"){c.writeHead(404,{"Content-Type":"text/plain"}),c.end("Not found");return}let d=f.searchParams.get("key");if(f.searchParams.get("state")!==o){c.writeHead(400,{"Content-Type":"text/plain"}),c.end("Invalid state parameter");return}if(!d||!Lo.test(d)){c.writeHead(400,{"Content-Type":"text/plain"}),c.end("Invalid key format");return}if(r)return;r=true;let _=f.searchParams.get("return_url");_?(c.writeHead(302,{Location:_}),c.end()):(c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(Oo)),n&&(clearTimeout(n),n=void 0),t.close(),t.closeAllConnections(),l(d);});})}});}),t.on("error",i=>{e(i);});})}var Lo,Oo,Bn=m(()=>{Lo=/^ak:[0-9a-f]{32}$/i,Oo=`<!DOCTYPE html>
|
|
5
5
|
<html><head><title>Authentication Successful</title></head>
|
|
6
|
-
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function
|
|
7
|
-
\u2502 ${
|
|
8
|
-
\u2502 _____ ${
|
|
9
|
-
\u2502 ${
|
|
10
|
-
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${
|
|
11
|
-
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${
|
|
12
|
-
\u2502 ${
|
|
13
|
-
\u2502${
|
|
14
|
-
\u2502 ${
|
|
15
|
-
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(
|
|
16
|
-
`):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var
|
|
6
|
+
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function kt(s){console.log(`\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
|
|
7
|
+
\u2502 ${p.gray("'")} ${p.blueBright(".")} ${p.dim("`")} ${p.yellowBright("'")} ${p.blueBright("+")} ${p.whiteBright(".")} ${p.gray(".")} ${p.yellowBright("'")} ${p.yellowBright("*")} ${p.whiteBright("'")} ${p.blueBright("+")} ${p.gray(".")} ${p.yellowBright("*")} ${p.whiteBright(",")} ${p.gray.dim(".")}\u2502
|
|
8
|
+
\u2502 _____ ${p.yellowBright("*")} ${p.dim("`")} __${p.whiteBright(".")} ${p.whiteBright("'")} ____ ${p.dim(".")} __ _ ${p.gray("`")} . . ${p.yellowBright("o")} ${p.blueBright("+")} \u2502
|
|
9
|
+
\u2502 ${p.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${p.gray(".")} ${p.yellowBright("'")} ${p.gray("+")} ${p.gray("\\")} ${p.gray("`")} \u2502
|
|
10
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${p.gray("'")} ${p.blueBright("o")}${p.gray("\u2014\u2014\u2014\u2014")}${p.yellowBright("o")} ${p.whiteBright("o")} ${p.whiteBright(".")} \u2502
|
|
11
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${p.gray(".")} ${p.whiteBright("*")} ${p.gray(" \\ \\ ")}${p.gray("/")} \u2502
|
|
12
|
+
\u2502 ${p.whiteBright("'")} ${p.blueBright(".")} ${p.gray("'")} ${p.whiteBright(".")} ${p.blueBright(".")} ${p.gray(".")} ${p.yellowBright("*")} ${p.blueBright.dim("+")} ${p.whiteBright("o o")}${p.gray("\u2014")}${p.blueBright("o")} ${p.yellowBright("*")} \u2502
|
|
13
|
+
\u2502${p.yellowBright("'")} ${p.whiteBright("*")} ${p.blueBright("+")} ${p.yellowBright("*")} ${p.gray(",")} ${p.whiteBright("'")} + ${p.whiteBright("constellationdev.io")} ${p.whiteBright("' .")} ${p.gray(",")} ${p.blueBright("*")} ${p.yellowBright(".")} ${p.whiteBright("+")} \u2502`),s&&s.length>0?console.log(`\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(s.length)}\u2500\u252C${"\u2500".repeat(59-s.length)}\u256F
|
|
14
|
+
\u2502 ${p.bold(`constellation \u203A ${s}`)} \u2502
|
|
15
|
+
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(s.length)}\u2500\u256F
|
|
16
|
+
`):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var X,Hn,Ke=m(()=>{`
|
|
17
17
|
\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
|
|
18
|
-
\u2502 ${
|
|
19
|
-
\u2502 _____ ${
|
|
20
|
-
\u2502 ${
|
|
21
|
-
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${
|
|
22
|
-
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${
|
|
23
|
-
\u2502 ${
|
|
24
|
-
\u2502${
|
|
18
|
+
\u2502 ${p.gray("'")} ${p.blueBright(".")} ${p.dim("`")} ${p.yellowBright("'")} ${p.blueBright("+")} ${p.whiteBright(".")} ${p.gray(".")} ${p.yellowBright("'")} ${p.yellowBright("*")} ${p.whiteBright("'")} ${p.blueBright("+")} ${p.gray(".")} ${p.yellowBright("*")} ${p.whiteBright(",")} ${p.gray.dim(".")}\u2502
|
|
19
|
+
\u2502 _____ ${p.yellowBright("*")} ${p.dim("`")} __${p.whiteBright(".")} ${p.whiteBright("'")} ____ ${p.dim(".")} __ _ ${p.gray("`")} . . ${p.yellowBright("o")} ${p.blueBright("+")} \u2502
|
|
20
|
+
\u2502 ${p.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${p.gray(".")} ${p.yellowBright("'")} ${p.gray("+")} ${p.gray("\\")} ${p.gray("`")} \u2502
|
|
21
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${p.gray("'")} ${p.blueBright("o")}${p.gray("\u2014\u2014\u2014\u2014")}${p.yellowBright("o")} ${p.whiteBright("o")} ${p.whiteBright(".")} \u2502
|
|
22
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${p.gray(".")} ${p.whiteBright("*")} ${p.gray(" \\ \\ ")}${p.gray("/")} \u2502
|
|
23
|
+
\u2502 ${p.whiteBright("'")} ${p.blueBright(".")} ${p.gray("'")} ${p.whiteBright(".")} ${p.blueBright(".")} ${p.gray(".")} ${p.yellowBright("*")} ${p.blueBright.dim("+")} ${p.whiteBright("o o")}${p.gray("\u2014")}${p.blueBright("o")} ${p.yellowBright("*")} \u2502
|
|
24
|
+
\u2502${p.yellowBright("'")} ${p.whiteBright("*")} ${p.blueBright("+")} ${p.yellowBright("*")} ${p.gray(",")} ${p.whiteBright("'")} + ${p.whiteBright("constellationdev.io")} ${p.whiteBright("' .")} ${p.gray(",")} ${p.blueBright("*")} ${p.yellowBright(".")} ${p.whiteBright("+")} \u2502
|
|
25
25
|
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F
|
|
26
26
|
`,`
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
`,
|
|
33
|
-
`),this.env.isCI()){console.error(`${
|
|
27
|
+
${p.yellowBright(" o")}
|
|
28
|
+
${p.gray(" \\")}
|
|
29
|
+
${p.blueBright(" o")}${p.blueBright("----")}${p.yellowBright("o")} ${p.gray("o")}
|
|
30
|
+
${p.gray(" \\ \\ ")}${p.blueBright("/")}
|
|
31
|
+
${p.whiteBright(" o o")}${p.blueBright("-")}${p.blueBright("o")}
|
|
32
|
+
`,X="CONSTELLATION_ACCESS_KEY",Hn="CONSTELLATION_WEB_URL";});var Q,Ve=m(()=>{Q=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};});function Bo(s){return Uo.test(s)}function Ho(s){return s.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Uo,ve,Gn=m(()=>{ze();Mn();Bn();Ke();F();Ve();Uo=/^ak:[0-9a-f]{32}$/i;ve=class extends Q{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${J}Configuring access key authentication...
|
|
33
|
+
`),this.env.isCI()){console.error(`${b} Cannot configure authentication in CI/CD environments
|
|
34
34
|
|
|
35
|
-
The ${
|
|
35
|
+
The ${X} environment variable must be configured
|
|
36
36
|
directly in your pipeline settings:
|
|
37
37
|
|
|
38
38
|
- GitHub Actions: Repository Settings -> Secrets and variables -> Actions
|
|
@@ -40,45 +40,51 @@ ${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
|
|
|
40
40
|
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
41
41
|
- Jenkins: Manage Jenkins -> Credentials
|
|
42
42
|
- CircleCI: Project Settings -> Environment Variables
|
|
43
|
-
`);return}if(await this.env.getKey(
|
|
44
|
-
${r}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await
|
|
45
|
-
`),t++;continue}if(!
|
|
43
|
+
`);return}if(await this.env.getKey(X)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:k})){console.log(`${C} Keeping existing Constellation access key`);return}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred",r=Ho(n);console.error(`${b} Failed to store Constellation access key
|
|
44
|
+
${r}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await password({message:"Constellation Access Key:",theme:k})).trim(),!e){console.log(`${y} Access key cannot be empty.
|
|
45
|
+
`),t++;continue}if(!Bo(e)){if(t++,t<n)console.log(`${y} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
46
46
|
Attempts remaining: ${n-t}
|
|
47
|
-
`);else {console.error(`${
|
|
48
|
-
Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),{port:t,waitForCallback:n}=await
|
|
47
|
+
`);else {console.error(`${b} Invalid access key format after ${n} attempts.
|
|
48
|
+
Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),{port:t,waitForCallback:n}=await Un(),i=`${process.env[Hn]||"https://app.constellationdev.io"}/auth/cli?callback_port=${t}&state=${e}`;console.log(`${w} Opening browser for authentication...`),await Dn(i)||console.log(`${y} Could not open browser automatically.
|
|
49
49
|
Please open this URL manually:
|
|
50
50
|
|
|
51
|
-
${
|
|
52
|
-
`),console.log(`${
|
|
53
|
-
`);try{let a=await n(e);await this.storeKey(a);}catch{console.error(`${
|
|
54
|
-
Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(
|
|
51
|
+
${i}
|
|
52
|
+
`),console.log(`${w} Waiting for authentication... (press Ctrl+C to cancel)
|
|
53
|
+
`);try{let a=await n(e);await this.storeKey(a);}catch{console.error(`${b} Authentication timed out.
|
|
54
|
+
Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(X,e),console.log(`${C} Stored access key in ${X} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${w} To activate in this session, run:
|
|
55
55
|
|
|
56
56
|
source ${t}
|
|
57
57
|
|
|
58
|
-
New terminal sessions will load it automatically.`);}};});var h,D=m(()=>{h={async directoryExists(i){try{return (await A__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await A__default.access(i,A__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await A__default.readFile(i,{encoding:e,flag:A__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 A__default.writeFile(i,n,{encoding:t,flag:A__default.constants.O_WRONLY|A__default.constants.O_CREAT|A__default.constants.O_TRUNC});},async getFileStats(i){return await A__default.stat(i)},async getFileHandle(i,e,t){return await A__default.open(i,e,t)}};});var Me,In=m(()=>{D();Me=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 r=await n();if(!r)throw new Error(`Failed to load language: ${t}`);let o=new ho;o.setLanguage(r);let s=await h.getFileStats(e),a=10*1024*1024;if(s.size<=a){let l=await h.readFile(e),g={bufferSize:1024*1024};return o.parse(l,void 0,g)}else return this.parseWithStream(o,e,s.size)}async parseWithStream(e,t,n){let r=null;try{r=await A.open(t,"r");let o=r.fd,s=64*1024,a=Buffer.alloc(s),l=0;return e.parse(f=>{if(n>50*1024*1024){let u=Math.round(f/n*100);u>l+10&&(console.log(` Parsing large file: ${u}%...`),l=u);}let p=nt.readSync(o,a,0,s,f);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(o){if(r)try{await r.close();}catch(s){console.error(`Warning: Failed to close file handle for ${t}:`,s);}throw o}finally{if(r)try{await r.close();}catch{}}}};});function Tn(i){return i.replace(/\\/g,"/")}function Be(i){return Tn(i).replace(/^\.?\//,"")}function K(i,e){return Tn(S.relative(i,e))}var ee=m(()=>{});var Ue,$n=m(()=>{D();ee();k();Ue=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Rn();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(o=>!t.ignores(o.relativePath)&&this.matchesLanguageExtension(o,e.languages))}async scanSpecificFiles(e,t){let n=[],r=null;t.exclude&&t.exclude.length>0&&(r=Rn().add(t.exclude));let o=await A__default.realpath(this.rootPath);for(let s of e)try{let a=S__default.isAbsolute(s)?s:S__default.join(this.rootPath,s),l=await A__default.lstat(a);if(l.isSymbolicLink()){let g=await A__default.realpath(a);if(!g.startsWith(o+S__default.sep)&&g!==o){console.warn(`${C} Skipping symlink pointing outside project: ${s} -> ${g}`);continue}let f=await A__default.stat(a);if(!f.isFile())continue;let p=K(this.rootPath,a);if(r&&r.ignores(p))continue;let u=this.detectLanguage(p,t.languages);if(!u)continue;n.push({path:a,relativePath:p,language:u,size:f.size});}else if(l.isFile()){let g=K(this.rootPath,a);if(r&&r.ignores(g))continue;let f=this.detectLanguage(g,t.languages);if(!f)continue;n.push({path:a,relativePath:g,language:f,size:l.size});}}catch{console.warn(`${C} Skipping inaccessible file: ${s}`);}return n}async loadGitignoreRules(e,t){let n=[],r=t;for(;;){let o=S__default.join(r,".gitignore");await h.fileIsReadable(o)&&n.unshift(o);let s=S__default.dirname(r);if(s===r)break;r=s;let a=S__default.join(r,".git");if(await h.directoryExists(a)){let l=S__default.join(r,".gitignore");await h.fileIsReadable(l)&&!n.includes(l)&&n.unshift(l);break}}for(let o of n)try{let s=await h.readFile(o);e.add(s);}catch{console.warn(`${C} Failed to load .gitignore: ${o}`);}e.add(".git");}async walkDirectory(e,t,n,r){let o=[],s=t||e,a=n||await A__default.realpath(this.rootPath),l=r||new Set([a]);try{let g=await A__default.readdir(e,{withFileTypes:!0});for(let f of g){let p=S__default.join(e,f.name),u=K(s,p);if(f.isDirectory()){if(f.name.startsWith("."))continue;let d=await this.walkDirectory(p,s,a,l);o.push(...d);}else if(f.isFile()){let d=await A__default.stat(p);o.push({path:p,relativePath:u,language:"",size:d.size});}else if(f.isSymbolicLink())try{let d=await A__default.realpath(p);if(!d.startsWith(a+S__default.sep)&&d!==a){console.warn(`${C} Skipping symlink pointing outside project: ${p} -> ${d}`);continue}let v=await A__default.stat(p);if(v.isDirectory()){if(f.name.startsWith(".")||l.has(d))continue;l.add(d);let _=await this.walkDirectory(p,s,a,l);o.push(..._);}else v.isFile()&&o.push({path:p,relativePath:u,language:"",size:v.size});}catch{console.warn(`${C} Skipping invalid symlink: ${p}`);}}}catch(g){console.error(`${E} Error walking directory ${e}:`,g);}return o}matchesLanguageExtension(e,t){let n=S__default.extname(e.path).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return e.language=r,true;return false}detectLanguage(e,t){let n=S__default.extname(e).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return r;return null}};});var yo,Co,kn,Nn=m(()=>{yo=z$1.object({source:z$1.string().min(1,"Import source cannot be empty"),resolvedPath:z$1.string().optional(),isExternal:z$1.boolean(),importType:z$1.enum(["relative","workspace","alias","external","builtin"])}),Co=z$1.record(z$1.string(),yo),kn=z$1.object({file:z$1.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z$1.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z$1.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z$1.string().datetime({message:"Invalid ISO timestamp"}),ast:z$1.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Co.optional()});});var _o,He,On=m(()=>{_o=promisify(yt.gunzip),He=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=yt.createGzip();n.on("data",s=>t.push(s));let r=new Promise((s,a)=>{n.on("end",s),n.on("error",a);}),o=Readable.from(e);return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=yt.createGzip();n.on("data",s=>t.push(s));let r=new Promise((s,a)=>{n.on("end",s),n.on("error",a);}),o=Readable.from(this.serializeASTChunks(e));return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await _o(t);return JSON.parse(n.toString("utf-8"))}};});var Ct,Ge=m(()=>{Ct=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"]);});var We,Ln=m(()=>{We=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let n=new Map,r=0,o=0;for(;o<e.length&&n.size<this.concurrency;){let s=r++,a=this.processItem(e[o],o,t).then(l=>({result:l!==null?l.result:null,promiseId:s}));n.set(s,a),o++;}for(;n.size>0;){let s=await Promise.race(n.values());if(n.delete(s.promiseId),s.result!==null&&(yield s.result),o<e.length){let a=r++,l=this.processItem(e[o],o,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,l),o++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});function wt(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 Ke,Fn=m(()=>{Ge();Ke=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:c.unstyle(e.map(wt).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:c.unstyle(e.map(wt).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:c.unstyle(e.map(wt).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!Ct.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!Ct.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:c.unstyle(t),timestamp:new Date().toISOString(),code:n});let r=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?r.call(console,t):console[e==="info"?"log":e](t);}};});async function V(i,e,t,n,r){let o=await t.resolve(i),s=Dn(i,o),a=r(i,o,s),l=s?void 0:Be(o);n[e.toString()]={source:i,resolvedPath:l,isExternal:s,importType:a};}function Dn(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var _t,me=m(()=>{ee();_t=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function vo(i,e,t,n){let r=i.childForFieldName("source");if(!r)return;let o=r.startPosition.row,s=r.text.replace(/['"]/g,"");await V(s,o,e,t,n);}async function Eo(i,e,t,n){let r=i.childForFieldName("source");if(!r)return;let o=r.startPosition.row,s=r.text.replace(/['"]/g,"");await V(s,o,e,t,n);}function Ve(){return {language:"javascript",handlers:new Map([["import_statement",vo],["export_statement",Eo]])}}function vt(){return {...Ve(),language:"typescript"}}var Et=m(()=>{me();});async function bo(i,e,t,n){let r=i.childForFieldName("name");if(!r)return;let o;if(r.type==="aliased_import"){let s=r.childForFieldName("name");o=s?s.text:r.text;}else o=r.text;await V(o,i.startPosition.row,e,t,n);}async function xo(i,e,t,n){let r,o=i.childForFieldName("module_name");if(o)r=o.text;else {let s="";for(let a=0;a<i.childCount;a++){let l=i.child(a);if(l){if(l.type==="relative_import"){s=l.text;break}(l.type==="."||l.type==="import_prefix")&&(s+=l.text);}}r=s||".";}await V(r,i.startPosition.row,e,t,n);}async function Io(i,e,t,n){await V("__future__",i.startPosition.row,e,t,n);}function St(){return {language:"python",handlers:new Map([["import_statement",bo],["import_from_statement",xo],["future_import_statement",Io]]),classifyImportType:Po}}var Po,Je=m(()=>{me();Po=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var Bn,Un=m(()=>{Et();Je();me();Et();Je();Bn=[Ve(),vt(),St()];});var Hn={};pn(Hn,{ImportExtractor:()=>Pt});var Pt,Gn=m(()=>{Un();me();Pt=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Bn)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,r){if(!r)return {};let o=this.languageHandlers.get(n);if(!o)return {};let s=this.classifiers.get(n)??_t,a={};return await this.walkAST(e.rootNode,async l=>{let g=o.get(l.type);g&&await g(l,r,a,s);}),a}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let r=e.child(n);r&&await this.walkAST(r,t);}}};});var he,Wn,bt,zn,Kn,Ye=m(()=>{he=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"]),Wn=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"]),bt={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"]},zn={language:"javascript",textIncludedTypes:Wn,fieldNames:bt},Kn={language:"typescript",textIncludedTypes:Wn,fieldNames:bt};});var To,Vn,Jn,xt=m(()=>{To=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"]),Vn={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"]},Jn={language:"python",textIncludedTypes:To,fieldNames:Vn,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function Yn(i){return ye.get(i)}function qn(i){if(!i)return he;let e=ye.get(i);if(!e)return he;let t=new Set(he);for(let n of e.textIncludedTypes)t.add(n);return t}function It(i){if(!i){let t=Array.from(ye.values()).map(n=>n.fieldNames);return Ce(...t)}let e=ye.get(i);if(!e){let t=Array.from(ye.values()).map(n=>n.fieldNames);return Ce(...t)}return e.fieldNames}var ye,Xn=m(()=>{Tt();Ye();xt();Ye();Ye();xt();ye=new Map([["javascript",zn],["typescript",Kn],["python",Jn]]);});var nr={};pn(nr,{COMMON_FIELD_NAMES:()=>kt,JS_TS_FIELD_NAMES:()=>er,PYTHON_FIELD_NAMES:()=>tr,TEXT_INCLUDED_TYPES:()=>Zn,mergeFieldMaps:()=>Ce,serializeAST:()=>$o,serializeASTStream:()=>Ro});function*Ro(i,e,t){yield*$t(i,e,t);}function*$t(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)}`),Qn(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let r=(t?It(t):kt)[i.type]||[],o=new Set,s=true;for(let a of r){let l=i.childForFieldName(a);l&&(s||(yield ","),s=false,o.add(l),yield*$t(l,a,t));}for(let a=0;a<i.childCount;a++){let l=i.child(a);l&&!o.has(l)&&(s||(yield ","),s=false,yield*$t(l,void 0,t));}yield "]";}yield "}";}async function $o(i,e,t){let n=Rt(i,e,t),r=t?It(t):kt,o=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;o.length>0;){let s=o[o.length-1];if(s.childIndex===0&&s.treeNode.childCount>0){let a=r[s.treeNode.type]||[];for(let l of a){let g=s.treeNode.childForFieldName(l);if(g){s.fieldChildren.add(g);let f=Rt(g,l,t);s.serializedNode.children||(s.serializedNode.children=[]),s.serializedNode.children.push(f),o.push({treeNode:g,serializedNode:f,fieldName:l,childIndex:0,fieldChildren:new Set});}}}if(s.childIndex<s.treeNode.childCount){let a=s.treeNode.child(s.childIndex);if(s.childIndex++,a&&!s.fieldChildren.has(a)){let l=Rt(a,void 0,t);s.serializedNode.children||(s.serializedNode.children=[]),s.serializedNode.children.push(l),o.push({treeNode:a,serializedNode:l,childIndex:0,fieldChildren:new Set});}}else o.pop();}return n}function Rt(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 Qn(i,t)&&(n.text=i.text),n}function Qn(i,e){if(e){let n=Yn(e);if(n?.shouldIncludeText){let o=n.shouldIncludeText(i);if(o===false)return false;if(o===true)return true}return qn(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Zn.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function Ce(...i){let e={};for(let t of i)for(let[n,r]of Object.entries(t)){let s=[...e[n]||[]];for(let a of r)s.includes(a)||s.push(a);e[n]=s;}return e}var Zn,er,tr,kt,Tt=m(()=>{Xn();Zn=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","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"]);er={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"]},tr={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"]};kt=Ce(er,tr);});var we,or=m(()=>{Le();In();$n();Nn();On();Fe();Ge();Ln();ee();k();Fn();De();we=class extends z{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new Ue(process.cwd()),this.parser=new Me(this.langRegistry),this.compressor=new He;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let r=n.getBuildConfigManager(process.cwd(),this.config.languages);r&&this.buildConfigManagers.set(t,r);}}}async run(e=false,t=false){let n=new Ke;n.start();let r="failed";try{let o=await this.getAccessKey(n);this.apiClient=new je(this.config,o),await this.validateProject(n),console.log(`${U}Starting indexing procedure...
|
|
59
|
-
`)
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
${E} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),console.log(`${y} Set the ${W} environment variable or run
|
|
65
|
-
|
|
58
|
+
New terminal sessions will load it automatically.`);}};});function Wn(s){return s.replace(/\\/g,"/")}function Je(s){return Wn(s).replace(/^\.?\//,"")}function L(s,e){return Wn(P.relative(s,e))}var ne=m(()=>{});var Wo,zo,Ye,Ko,zn,Kn,qe,Vn=m(()=>{F();ne();Wo={function:{hover:true,definition:false,references:true,callHierarchy:true},method:{hover:true,definition:false,references:true,callHierarchy:true},class:{hover:false,definition:false,references:true,callHierarchy:false},interface:{hover:false,definition:false,references:true,callHierarchy:false},variable:{hover:true,definition:true,references:true,callHierarchy:false},property:{hover:true,definition:true,references:true,callHierarchy:false},import:{hover:true,definition:true,references:false,callHierarchy:false}},zo={hover:true,definition:true,references:true,callHierarchy:false},Ye=1e4,Ko=300*1e3,zn=50,Kn={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},qe=class{constructor(e){this.projectRoot=e;}async enrich(e,t,n){let r=[],i=Date.now(),o={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null};for(let[a,l]of e){let g=n.get(a);if(!g)continue;let u=0,c=l.length;for(let f of l){if(Date.now()-i>Ko)return console.log(`${w} Enrichment timeout reached. Uploading partial results.`),this.logDiagnostics(o),r;let d=t.get(f)||[];if(d.length===0){let _=P.resolve(this.projectRoot,f),$=pathToFileURL(_).href,T;try{T=jt.readFileSync(_,"utf-8");}catch(S){o.filesUnreadable++,o.firstFileError||(o.firstFileError=`${f}: ${S instanceof Error?S.message:String(S)}`);continue}try{g.sendNotification("textDocument/didOpen",{textDocument:{uri:$,languageId:this.getLanguageId(f),version:1,text:T}});}catch(S){o.filesOpenFailed++,o.firstOpenError||(o.firstOpenError=`${f}: ${S instanceof Error?S.message:String(S)}`);continue}if(d=await this.discoverSymbols(g,f,o),d.length===0){o.filesNoSymbols++;try{g.sendNotification("textDocument/didClose",{textDocument:{uri:$}});}catch{}continue}let I=await this.enrichFile(g,f,d,o,T);if(I.length>0&&r.push({filePath:f,language:a,symbols:I}),u++,u%zn===0){let S=Math.round(u/c*100);console.log(`${w} ${Kn[a]??a} index enrichment: ${S}% (${u}/${c} files)`);}continue}let h=await this.enrichFile(g,f,d,o);if(h.length>0&&r.push({filePath:f,language:a,symbols:h}),u++,u%zn===0){let _=Math.round(u/c*100);console.log(`${w} ${Kn[a]??a} index enrichment: ${_}% (${u}/${c} files)`);}}}return this.logDiagnostics(o),r}logDiagnostics(e){let t=[];e.filesUnreadable>0&&t.push(`${e.filesUnreadable} files unreadable`),e.filesOpenFailed>0&&t.push(`${e.filesOpenFailed} files failed to open in language server`),e.discoveryErrors>0&&t.push(`${e.discoveryErrors} symbol discovery failures`),e.symbolQueryErrors>0&&t.push(`${e.symbolQueryErrors} symbol query failures`),e.queryRejections>0&&t.push(`${e.queryRejections} individual LSP query rejections`),t.length!==0&&(console.log(`${y} Enrichment issues: ${t.join(", ")}`),e.firstFileError&&console.log(`${y} First file read error: ${e.firstFileError}`),e.firstOpenError&&console.log(`${y} First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&console.log(`${y} First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&console.log(`${y} First symbol query error: ${e.firstSymbolError}`));}async enrichFile(e,t,n,r,i){let o=P.resolve(this.projectRoot,t),a=pathToFileURL(o).href;if(!(i!==void 0)){let u;try{u=jt.readFileSync(o,"utf-8");}catch(c){return r.filesUnreadable++,r.firstFileError||(r.firstFileError=`${t}: ${c instanceof Error?c.message:String(c)}`),[]}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(t),version:1,text:u}});}catch(c){return r.filesOpenFailed++,r.firstOpenError||(r.firstOpenError=`${t}: ${c instanceof Error?c.message:String(c)}`),[]}}let g=[];for(let u of n)try{let c=await this.querySymbol(e,a,u,r);c&&g.push(c);}catch(c){r.symbolQueryErrors++,r.firstSymbolError||(r.firstSymbolError=`${u.name} in ${t}: ${c instanceof Error?c.message:String(c)}`);}try{e.sendNotification("textDocument/didClose",{textDocument:{uri:a}});}catch{}return g}async querySymbol(e,t,n,r){let i=Wo[n.kind.toLowerCase()]||zo,o={line:n.line-1,character:n.column},a={textDocument:{uri:t},position:o},l={name:n.name,line:n.line,column:n.column,kind:n.kind},g=false,[u,c,f]=await Promise.allSettled([i.hover?e.sendRequest("textDocument/hover",a,Ye):null,i.definition?e.sendRequest("textDocument/definition",a,Ye):null,i.references?e.sendRequest("textDocument/references",{...a,context:{includeDeclaration:false}},Ye):null]);for(let d of [u,c,f])d.status==="rejected"&&r.queryRejections++;if(u.status==="fulfilled"&&u.value?.contents){let d=u.value,h=typeof d.contents=="string"?d.contents:d.contents.value||"";h&&(l.typeInfo={resolvedType:h},g=true);}if(c.status==="fulfilled"&&c.value){let d=c.value,h=Array.isArray(d)?d[0]:d;if(h?.uri||h?.targetUri){let _=h.targetUri||h.uri,$=h.targetRange||h.range,T=this.uriToPath(_),I=L(this.projectRoot,T),S=I.startsWith("..");l.definition={filePath:I,line:($?.start?.line??0)+1,column:$?.start?.character??0,isExternal:S},g=true;}}if(f.status==="fulfilled"&&f.value){let d=f.value;if(d.length>0){let h=d.slice(0,100).map(_=>({filePath:L(this.projectRoot,this.uriToPath(_.uri||"")),line:(_.range?.start?.line??0)+1,column:_.range?.start?.character??0}));l.references={count:d.length,locations:h},g=true;}}if(i.callHierarchy)try{let d=await e.sendRequest("textDocument/prepareCallHierarchy",a,Ye);if(d&&d.length>0){let h=d[0],[_,$]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:h}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:h}).catch(()=>[])]),T=(_||[]).slice(0,200).map(S=>({name:S.from?.name||"",filePath:L(this.projectRoot,this.uriToPath(S.from?.uri||"")),line:(S.from?.range?.start?.line??0)+1,column:S.from?.selectionRange?.start?.character??S.from?.range?.start?.character??0})),I=($||[]).slice(0,200).map(S=>({name:S.to?.name||"",filePath:L(this.projectRoot,this.uriToPath(S.to?.uri||"")),line:(S.to?.range?.start?.line??0)+1,column:S.to?.selectionRange?.start?.character??S.to?.range?.start?.character??0}));(T.length>0||I.length>0)&&(l.callHierarchy={incomingCalls:T,outgoingCalls:I},g=!0);}}catch{r.queryRejections++;}return g?l:null}async discoverSymbols(e,t,n){let r=P.resolve(this.projectRoot,t),i=pathToFileURL(r).href;try{let o=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:i}});return !o||!Array.isArray(o)?[]:this.flattenDocumentSymbols(o)}catch(o){return n.discoveryErrors++,n.firstDiscoveryError||(n.firstDiscoveryError=`${t}: ${o instanceof Error?o.message:String(o)}`),[]}}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 r of e){let i=n[r.kind]||"variable",o=r.selectionRange||r.range||r.location?.range;o&&t.push({name:r.name,line:(o.start?.line??0)+1,column:o.start?.character??0,kind:i}),r.children&&Array.isArray(r.children)&&t.push(...this.flattenDocumentSymbols(r.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=P.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function Jn(s){return s.map(e=>JSON.stringify(e)).join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}var Yn=m(()=>{});function Xe(s){try{return execFileSync(process.platform==="win32"?"where":"which",[s],{stdio:"ignore"}),!0}catch{return false}}var v,z=m(()=>{v={async directoryExists(s){try{return (await M__default.stat(s)).isDirectory()}catch{return false}},async fileIsReadable(s){try{return await M__default.access(s,M__default.constants.R_OK),!0}catch{return false}},async readFile(s,e="utf-8"){let t=await M__default.readFile(s,{encoding:e,flag:M__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(s,e,t="utf-8"){let n=Buffer.from(e,t);await M__default.writeFile(s,n,{encoding:t,flag:M__default.constants.O_WRONLY|M__default.constants.O_CREAT|M__default.constants.O_TRUNC});},async getFileStats(s){return await M__default.stat(s)},async getFileHandle(s,e,t){return await M__default.open(s,e,t)}};});var Qe,qn=m(()=>{Qe=class s{constructor(e,t,n=1e4){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=n;this.stdout.on("data",r=>this.handleData(r)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
|
|
61
|
+
\r
|
|
62
|
+
`);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,n){if(this.disposed)return Promise.reject(new Error("LspClient disposed"));let r=this.nextId++,i={jsonrpc:"2.0",id:r,method:e,...t!==void 0&&{params:t}};return new Promise((o,a)=>{let l=setTimeout(()=>{this.pendingRequests.delete(r),a(new Error(`LSP request '${e}' timed out after ${n??this.defaultTimeoutMs}ms`));},n??this.defaultTimeoutMs);this.pendingRequests.set(r,{resolve:o,reject:a,timer:l}),this.writeMessage(i);})}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),r=`Content-Length: ${Buffer.byteLength(t,"utf-8")}\r
|
|
63
|
+
\r
|
|
64
|
+
`;this.stdin.write(r+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(s.HEADER_SEPARATOR);if(t===-1)break;let r=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!r){this.buffer=this.buffer.subarray(t+4);continue}let i=parseInt(r[1],10),o=t+4;if(this.buffer.length-o<i)break;let a=this.buffer.subarray(o,o+i).toString("utf-8");this.buffer=this.buffer.subarray(o+i);try{let l=JSON.parse(a);this.handleResponse(l);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,console.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var Ot,Ze,ce,et=m(()=>{Ot=P.join(he.homedir(),".constellation","lsp-servers"),Ze=P.join(Ot,"node_modules",".bin"),ce=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});var tt,Zn=m(()=>{z();qn();et();tt=class{constructor(e){this.projectRoot=e;}servers=new Map;unavailable=new Set;nextId=1;async startServer(e,t){if(t===false||this.unavailable.has(e))return null;let n=this.servers.get(e);if(n)return this.toConnection(n);let r=this.resolveCommand(e,t);if(!r)return this.unavailable.add(e),null;let{command:i,args:o}=r;try{let a=spawn(i,o,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((c,f)=>{a.once("spawn",c),a.once("error",f);}),a.stderr?.on("data",c=>{let f=c.toString().trim();f.toLowerCase().includes("error")&&console.error(`[LSP:${e}] ${f}`);});let l=new Qe(a.stdin,a.stdout,12e4),g=await l.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},definition:{linkSupport:!1},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);l.sendNotification("initialized",{});let u={language:e,process:a,client:l};return this.servers.set(e,u),a.on("exit",c=>{let f=this.servers.get(e);f&&(f.client.dispose(),this.servers.delete(e)),c!==0&&c!==null&&console.error(`[LSP:${e}] Server exited unexpectedly with code ${c}`);}),this.toConnection(u)}catch(a){return this.unavailable.add(e),console.error(`[LSP:${e}] Failed to start: ${a instanceof Error?a.message:String(a)}`),null}}async shutdown(e){let t=this.servers.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(n=>{let r=setTimeout(()=>{t.process.kill("SIGKILL"),n();},3e3);t.process.on("exit",()=>{clearTimeout(r),n();});});}catch(n){console.error(`[LSP:${e}] Graceful shutdown failed, force killing: ${n instanceof Error?n.message:String(n)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.servers.delete(e);}}async shutdownAll(){let e=[...this.servers.keys()];await Promise.allSettled(e.map(t=>this.shutdown(t)));}destroyAll(){for(let e of this.servers.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.servers.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let n=ce.get(e);if(!n)return null;let r=P.join(Ze,n.command);return existsSync(r)?{command:r,args:n.args}:Xe(n.command)?{command:n.command,args:n.args}:null}toConnection(e){let t=`lsp-${e.language}-${this.nextId++}`;return {language:e.language,process:e.process,id:t,sendRequest:(n,r,i)=>e.client.sendRequest(n,r,i),sendNotification:(n,r)=>e.client.sendNotification(n,r)}}};});var Z,nt=m(()=>{Z=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var pe,Ft=m(()=>{F();pe=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(`${y} 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 r=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}if(n){if(this.isJavaScriptEnabled)try{let r=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,r),r}catch(r){if(this.isTypeScriptEnabled){let i=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,i),i}throw r}if(this.isTypeScriptEnabled){let r=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}}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 r=t instanceof Error?t.message:String(t);console.warn(`${y} Failed to parse ${n}: ${r}`),console.warn(`${y} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${y} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var rt,tr=m(()=>{ne();rt=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 r=e.substring(t.length+1),i=await this.resolveSubPath(n,r);if(i)return this.toProjectRelative(i)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?P.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[r,i]of Object.entries(t)){if(r.includes("*")||!Array.isArray(i))continue;let o=i[0];if(!o)continue;let a=P.resolve(n,o),l=await this.findEntryPoint(a);l&&(e[r]=l);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=P.join(this.projectRoot,"package.json"),n=await M.readFile(t,"utf-8"),i=JSON.parse(n).workspaces;if(!i)return e;let o=Array.isArray(i)?i:i.packages||[];for(let a of o){let l=await this.findWorkspaceDirs(a);for(let g of l){let u=await this.loadWorkspacePackage(g);u&&Object.assign(e,u);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),r=P.join(this.projectRoot,n);try{let i=await M.readdir(r,{withFileTypes:!0});for(let o of i)o.isDirectory()&&t.push(P.join(r,o.name));}catch{}}else {let n=P.join(this.projectRoot,e);try{(await M.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=P.join(e,"package.json"),n=await M.readFile(t,"utf-8"),r=JSON.parse(n),i=r.name;if(!i)return null;let o=await this.findPackageEntryPoint(e,r);return o?{[i]:o}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let r=t.exports;if(typeof r=="string")return P.join(e,r);if(typeof r=="object"){let i=r["."]||r["./index"];if(typeof i=="string")return P.join(e,i);if(typeof i=="object"){let o=i.import||i.default||i.require;if(o)return P.join(e,o)}}}if(t.main)return P.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let r of n){let i=P.join(e,r);try{if((await M.stat(i)).isFile())return i}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 r=P.join(e,n);try{if((await M.stat(r)).isFile())return r}catch{}}try{if((await M.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?P.dirname(e):P.dirname(e),r=[P.join(n,t+".ts"),P.join(n,t+".tsx"),P.join(n,t+".js"),P.join(n,t+".jsx"),P.join(n,t+".d.ts"),P.join(n,t,"index.ts"),P.join(n,t,"index.tsx"),P.join(n,t,"index.js"),P.join(n,t,"index.jsx")];for(let i of r)try{if((await M.stat(i)).isFile())return i}catch{}return null}toProjectRelative(e){let t=L(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var ge,Dt=m(()=>{ne();tr();ge=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=P.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new rt(this.projectRoot,t);let n=e.toLowerCase(),r=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),i=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(r?this.extensions=[".ts",".tsx",".d.ts"]:i?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=P.dirname(t.tsconfigFile);let o=t.tsconfig?.compilerOptions;o&&(o.baseUrl&&(this.baseUrl=P.resolve(this.tsconfigDir,o.baseUrl)),o.paths&&typeof o.paths=="object"&&(this.paths=o.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=P.resolve(this.sourceDir,e),r=await this.findFileWithExtensions(n);return r?this.toProjectRelative(r):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=L(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let r=this.matchPathPattern(e,t);if(r!==null)for(let i of n){let o=await this.trySubstitution(e,t,i,r);if(o)return o}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,r]=t.split("*");if(!e.startsWith(n)||r&&!e.endsWith(r))return null;let i=n.length,o=r?e.length-r.length:e.length;return e.substring(i,o)}async trySubstitution(e,t,n,r){let i=n.replaceAll("*",r),o=P.resolve(this.tsconfigDir,i);return await this.findFileWithExtensions(o)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=P.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(o=>e.endsWith(o));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],r=n.some(o=>e.endsWith(o)),i=e;if(r&&!t){for(let o of n)if(e.endsWith(o)){i=e.slice(0,-o.length);break}}if(!t)for(let o of this.extensions){let a=i+o;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let o of this.extensions){let a=P.join(i,`index${o}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await M.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await M.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=P.join(t,"package.json");try{if((await M.stat(n)).isFile())return n}catch{}let r=P.dirname(t);if(r===t)break;t=r;}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 M.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=P.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let r=this.matchPathPattern(e,t);if(r!==null){if(typeof n=="string"){let i=await this.tryPackageImportSubstitution(n,r);if(i)return i}if(Array.isArray(n)){for(let i of n)if(typeof i=="string"){let o=await this.tryPackageImportSubstitution(i,r);if(o)return o}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),r=P.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(r)}};});var ot,nr=m(()=>{nt();Ft();Dt();ot=class extends Z{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new pe(e,t)}getImportResolver(e,t){return new ge(e,t)}};});var it,rr=m(()=>{nt();Ft();Dt();it=class extends Z{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new pe(e,t)}getImportResolver(e,t){return new ge(e,t)}};});async function ee(s,e,t,n,r){let i=await t.resolve(s),o=or(s,i),a=r(s,i,o),l=o?void 0:Je(i);n[e.toString()]={source:s,resolvedPath:l,isExternal:o,importType:a};}function or(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var Mt,_e=m(()=>{ne();Mt=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function ti(s,e,t,n){let r=s.childForFieldName("name");if(!r)return;let i;if(r.type==="aliased_import"){let o=r.childForFieldName("name");i=o?o.text:r.text;}else i=r.text;await ee(i,s.startPosition.row,e,t,n);}async function ni(s,e,t,n){let r,i=s.childForFieldName("module_name");if(i)r=i.text;else {let o="";for(let a=0;a<s.childCount;a++){let l=s.child(a);if(l){if(l.type==="relative_import"){o=l.text;break}(l.type==="."||l.type==="import_prefix")&&(o+=l.text);}}r=o||".";}await ee(r,s.startPosition.row,e,t,n);}async function ri(s,e,t,n){await ee("__future__",s.startPosition.row,e,t,n);}function Ut(){return {language:"python",handlers:new Map([["import_statement",ti],["import_from_statement",ni],["future_import_statement",ri]]),classifyImportType:ei}}var ei,st=m(()=>{_e();ei=(s,e,t)=>{if(t)return "external";if(/^\.+/.test(s))return "relative";let n=s.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var at,sr=m(()=>{st();at=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=P.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(PYTHON_STDLIB_MODULES.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),r=await this.tryResolveFile(P.resolve(this.projectRoot,n));return r?P.relative(this.projectRoot,r).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),r=t<=1?"":"../".repeat(t-1),i=n?r+n.replace(/\./g,"/"):r.slice(0,-1)||".",o=P.resolve(this.sourceDir,i),a=await this.tryResolveFile(o);return a?P.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,P.join(e,"__init__.py"),P.join(e,"__init__.pyi")];for(let n of t)try{return await jt.promises.access(n,jt.constants.F_OK),n}catch{continue}return null}};});var ct,ar=m(()=>{nt();sr();ct=class extends Z{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new at(e,process.cwd())}};});function Se(s){return ai[s]??s.charAt(0).toUpperCase()+s.slice(1)}var ai,Ee,pt,gt=m(()=>{nr();rr();ar();ai={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"};Ee={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"]},pt=class{constructor(e){this.config=e;this.registerPlugin(new ot),this.registerPlugin(new it),this.registerPlugin(new ct);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>oi,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Ee.javascript};typescript={language:()=>si.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Ee.typescript};python={language:()=>ii,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Ee.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});var ut,pr=m(()=>{z();ut=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 r=await n();if(!r)throw new Error(`Failed to load language: ${t}`);let i=new li;i.setLanguage(r);let o=await v.getFileStats(e),a=10*1024*1024;if(o.size<=a){let l=await v.readFile(e),g={bufferSize:1024*1024};return i.parse(l,void 0,g)}else return this.parseWithStream(i,e,o.size)}async parseWithStream(e,t,n){let r=null;try{r=await M.open(t,"r");let i=r.fd,o=64*1024,a=Buffer.alloc(o),l=0;return e.parse(u=>{if(n>50*1024*1024){let f=Math.round(u/n*100);f>l+10&&(console.log(` Parsing large file: ${f}%...`),l=f);}let c=jt.readSync(i,a,0,o,u);return c===0?null:a.subarray(0,c).toString("utf-8")})}catch(i){if(r)try{await r.close();}catch(o){console.error(`Warning: Failed to close file handle for ${t}:`,o);}throw i}finally{if(r)try{await r.close();}catch{}}}};});var dt,ur=m(()=>{z();ne();F();dt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=gr();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(i=>!t.ignores(i.relativePath)&&this.matchesLanguageExtension(i,e.languages))}async scanSpecificFiles(e,t){let n=[],r=null;t.exclude&&t.exclude.length>0&&(r=gr().add(t.exclude));let i=await M__default.realpath(this.rootPath);for(let o of e)try{let a=P__default.isAbsolute(o)?o:P__default.join(this.rootPath,o),l=await M__default.lstat(a);if(l.isSymbolicLink()){let g=await M__default.realpath(a);if(!g.startsWith(i+P__default.sep)&&g!==i){console.warn(`${y} Skipping symlink pointing outside project: ${o} -> ${g}`);continue}let u=await M__default.stat(a);if(!u.isFile())continue;let c=L(this.rootPath,a);if(r&&r.ignores(c))continue;let f=this.detectLanguage(c,t.languages);if(!f)continue;n.push({path:a,relativePath:c,language:f,size:u.size});}else if(l.isFile()){let g=L(this.rootPath,a);if(r&&r.ignores(g))continue;let u=this.detectLanguage(g,t.languages);if(!u)continue;n.push({path:a,relativePath:g,language:u,size:l.size});}}catch{console.warn(`${y} Skipping inaccessible file: ${o}`);}return n}async loadGitignoreRules(e,t){let n=[],r=t;for(;;){let i=P__default.join(r,".gitignore");await v.fileIsReadable(i)&&n.unshift(i);let o=P__default.dirname(r);if(o===r)break;r=o;let a=P__default.join(r,".git");if(await v.directoryExists(a)){let l=P__default.join(r,".gitignore");await v.fileIsReadable(l)&&!n.includes(l)&&n.unshift(l);break}}for(let i of n)try{let o=await v.readFile(i);e.add(o);}catch{console.warn(`${y} Failed to load .gitignore: ${i}`);}e.add(".git");}async walkDirectory(e,t,n,r){let i=[],o=t||e,a=n||await M__default.realpath(this.rootPath),l=r||new Set([a]);try{let g=await M__default.readdir(e,{withFileTypes:!0});for(let u of g){let c=P__default.join(e,u.name),f=L(o,c);if(u.isDirectory()){if(u.name.startsWith("."))continue;let d=await this.walkDirectory(c,o,a,l);i.push(...d);}else if(u.isFile()){let d=await M__default.stat(c);i.push({path:c,relativePath:f,language:"",size:d.size});}else if(u.isSymbolicLink())try{let d=await M__default.realpath(c);if(!d.startsWith(a+P__default.sep)&&d!==a){console.warn(`${y} Skipping symlink pointing outside project: ${c} -> ${d}`);continue}let h=await M__default.stat(c);if(h.isDirectory()){if(u.name.startsWith(".")||l.has(d))continue;l.add(d);let _=await this.walkDirectory(c,o,a,l);i.push(..._);}else h.isFile()&&i.push({path:c,relativePath:f,language:"",size:h.size});}catch{console.warn(`${y} Skipping invalid symlink: ${c}`);}}}catch(g){console.error(`${b} Error walking directory ${e}:`,g);}return i}matchesLanguageExtension(e,t){let n=P__default.extname(e.path).toLowerCase();for(let[r,i]of Object.entries(t))if(i.fileExtensions.includes(n))return e.language=r,true;return false}detectLanguage(e,t){let n=P__default.extname(e).toLowerCase();for(let[r,i]of Object.entries(t))if(i.fileExtensions.includes(n))return r;return null}};});var ci,pi,dr,fr=m(()=>{ci=z$1.object({source:z$1.string().min(1,"Import source cannot be empty"),resolvedPath:z$1.string().optional(),isExternal:z$1.boolean(),importType:z$1.enum(["relative","workspace","alias","external","builtin"])}),pi=z$1.record(z$1.string(),ci),dr=z$1.object({file:z$1.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z$1.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z$1.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z$1.string().datetime({message:"Invalid ISO timestamp"}),ast:z$1.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:pi.optional()});});var ui,ft,yr=m(()=>{ui=promisify(Bt.gunzip),ft=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=Bt.createGzip();n.on("data",o=>t.push(o));let r=new Promise((o,a)=>{n.on("end",o),n.on("error",a);}),i=Readable.from(e);return await pipeline(i,n),await r,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=Bt.createGzip();n.on("data",o=>t.push(o));let r=new Promise((o,a)=>{n.on("end",o),n.on("error",a);}),i=Readable.from(this.serializeASTChunks(e));return await pipeline(i,n),await r,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await ui(t);return JSON.parse(n.toString("utf-8"))}};});var Ht,mt=m(()=>{Ht=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"]);});function Gt(s){if(typeof s=="string")return s;if(s instanceof Error)return s.message;if(typeof s=="object"&&s!==null)try{return JSON.stringify(s)}catch{return String(s)}return String(s)}var yt,wr=m(()=>{mt();yt=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:p.unstyle(e.map(Gt).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:p.unstyle(e.map(Gt).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:p.unstyle(e.map(Gt).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!Ht.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!Ht.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:p.unstyle(t),timestamp:new Date().toISOString(),code:n});let r=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?r.call(console,t):console[e==="info"?"log":e](t);}};});var wt,Cr=m(()=>{wt=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let n=new Map,r=0,i=0;for(;i<e.length&&n.size<this.concurrency;){let o=r++,a=this.processItem(e[i],i,t).then(l=>({result:l!==null?l.result:null,promiseId:o}));n.set(o,a),i++;}for(;n.size>0;){let o=await Promise.race(n.values());if(n.delete(o.promiseId),o.result!==null&&(yield o.result),i<e.length){let a=r++,l=this.processItem(e[i],i,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,l),i++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});async function di(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let i=r.startPosition.row,o=r.text.replace(/['"]/g,"");await ee(o,i,e,t,n);}async function fi(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let i=r.startPosition.row,o=r.text.replace(/['"]/g,"");await ee(o,i,e,t,n);}function Ct(){return {language:"javascript",handlers:new Map([["import_statement",di],["export_statement",fi]])}}function Wt(){return {...Ct(),language:"typescript"}}var zt=m(()=>{_e();});var vr,_r=m(()=>{zt();st();_e();zt();st();vr=[Ct(),Wt(),Ut()];});var Er={};Rn(Er,{ImportExtractor:()=>Kt});var Kt,Sr=m(()=>{_r();_e();Kt=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??vr)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,r){if(!r)return {};let i=this.languageHandlers.get(n);if(!i)return {};let o=this.classifiers.get(n)??Mt,a={};return await this.walkAST(e.rootNode,async l=>{let g=i.get(l.type);g&&await g(l,r,a,o);}),a}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let r=e.child(n);r&&await this.walkAST(r,t);}}};});var be,br,Vt,Pr,xr,vt=m(()=>{be=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"]),br=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"]),Vt={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"]},Pr={language:"javascript",textIncludedTypes:br,fieldNames:Vt},xr={language:"typescript",textIncludedTypes:br,fieldNames:Vt};});var mi,Ir,Rr,Jt=m(()=>{mi=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"]),Ir={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"]},Rr={language:"python",textIncludedTypes:mi,fieldNames:Ir,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function $r(s){return Pe.get(s)}function Tr(s){if(!s)return be;let e=Pe.get(s);if(!e)return be;let t=new Set(be);for(let n of e.textIncludedTypes)t.add(n);return t}function Yt(s){if(!s){let t=Array.from(Pe.values()).map(n=>n.fieldNames);return xe(...t)}let e=Pe.get(s);if(!e){let t=Array.from(Pe.values()).map(n=>n.fieldNames);return xe(...t)}return e.fieldNames}var Pe,kr=m(()=>{qt();vt();Jt();vt();vt();Jt();Pe=new Map([["javascript",Pr],["typescript",xr],["python",Rr]]);});var Or={};Rn(Or,{COMMON_FIELD_NAMES:()=>Zt,JS_TS_FIELD_NAMES:()=>jr,PYTHON_FIELD_NAMES:()=>Lr,TEXT_INCLUDED_TYPES:()=>Nr,mergeFieldMaps:()=>xe,serializeAST:()=>yi,serializeASTStream:()=>hi});function*hi(s,e,t){yield*Qt(s,e,t);}function*Qt(s,e,t){if(yield "{",yield `"type":${JSON.stringify(s.type)}`,yield `,"startPosition":${JSON.stringify({row:s.startPosition.row,column:s.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:s.endPosition.row,column:s.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),Ar(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let r=(t?Yt(t):Zt)[s.type]||[],i=new Set,o=true;for(let a of r){let l=s.childForFieldName(a);l&&(o||(yield ","),o=false,i.add(l),yield*Qt(l,a,t));}for(let a=0;a<s.childCount;a++){let l=s.child(a);l&&!i.has(l)&&(o||(yield ","),o=false,yield*Qt(l,void 0,t));}yield "]";}yield "}";}async function yi(s,e,t){let n=Xt(s,e,t),r=t?Yt(t):Zt,i=[{treeNode:s,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;i.length>0;){let o=i[i.length-1];if(o.childIndex===0&&o.treeNode.childCount>0){let a=r[o.treeNode.type]||[];for(let l of a){let g=o.treeNode.childForFieldName(l);if(g){o.fieldChildren.add(g);let u=Xt(g,l,t);o.serializedNode.children||(o.serializedNode.children=[]),o.serializedNode.children.push(u),i.push({treeNode:g,serializedNode:u,fieldName:l,childIndex:0,fieldChildren:new Set});}}}if(o.childIndex<o.treeNode.childCount){let a=o.treeNode.child(o.childIndex);if(o.childIndex++,a&&!o.fieldChildren.has(a)){let l=Xt(a,void 0,t);o.serializedNode.children||(o.serializedNode.children=[]),o.serializedNode.children.push(l),i.push({treeNode:a,serializedNode:l,childIndex:0,fieldChildren:new Set});}}else i.pop();}return n}function Xt(s,e,t){let n={type:s.type,startPosition:{row:s.startPosition.row,column:s.startPosition.column},endPosition:{row:s.endPosition.row,column:s.endPosition.column},...e&&{fieldName:e}};return Ar(s,t)&&(n.text=s.text),n}function Ar(s,e){if(e){let n=$r(e);if(n?.shouldIncludeText){let i=n.shouldIncludeText(s);if(i===false)return false;if(i===true)return true}return Tr(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:Nr.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function xe(...s){let e={};for(let t of s)for(let[n,r]of Object.entries(t)){let o=[...e[n]||[]];for(let a of r)o.includes(a)||o.push(a);e[n]=o;}return e}var Nr,jr,Lr,Zt,qt=m(()=>{kr();Nr=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","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"]);jr={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"]},Lr={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"]};Zt=xe(jr,Lr);});var Ie,Dr=m(()=>{We();Vn();Yn();Zn();et();gt();pr();ur();fr();yr();Ke();mt();wr();ne();Cr();F();Ve();Ie=class extends Q{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new dt(process.cwd()),this.parser=new ut(this.langRegistry),this.compressor=new ft;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let r=n.getBuildConfigManager(process.cwd(),this.config.languages);r&&this.buildConfigManagers.set(t,r);}}}async run(e=false,t=false,n=false){let r=new yt;r.start();let i="failed";try{let o=await this.getAccessKey(r);this.apiClient=new He(this.config,o),await this.validateProject(r),console.log(`${J}Starting indexing procedure...
|
|
65
|
+
`);let a=performance.now();if(t?console.log(`${y} Skipping git branch validation`):await this.validateGitBranch(),t?console.log(`${y} Skipping git status validation`):await this.validateGitStatus(),t?console.log(`${y} Skipping repository synchronization`):await this.synchronizeChanges(r),this.buildConfigManagers.size>0){console.log(`${w} Discovering language build configurations...`);let E=0;for(let[N,W]of this.buildConfigManagers.entries()){let se=await W.initialize();E+=se.length;}E>0&&console.log(`${C} Found ${E} configuration file(s)`);}let l=await this.determineIndexScope(e),g=await this.git.getLatestCommitHash();if(l.upToDate){console.log(`
|
|
66
|
+
${C} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${g.substring(0,8)}`),i="succeeded";return}if(l.isIncremental&&g){let E=await this.apiClient.getIndexStatus(this.config.branch,g);if(E?.status==="current"||E?.status==="processing"&&E?.commitHash===g){console.log(`${C} Index already up to date for branch ${this.config.branch} at commit ${g.substring(0,8)}`),i="succeeded";return}}let u=await this.discoverFiles(l.isIncremental),c=this.getEnrichmentEligibleLanguages(n,u),f=!1,d=()=>{f||console.log(`${w} Uploading metadata, processing, and indexing...`);},h=this.generateASTs(u,d),_=null;try{let[,E]=await Promise.all([this.uploadToAPI(h,l.isIncremental,g).then(N=>(f=!0,N)),c?this.runLspEnrichment(u,c).catch(N=>(console.error(`${y} Index enrichment failed: ${N instanceof Error?N.message:String(N)}`),null)):Promise.resolve(null)]);_=E;}catch(E){throw f=!0,E}if(_&&_.length>0)try{if(console.log(`${w} Waiting for server to finish syntax tree processing...`),await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,g)){console.log(`${w} Uploading enrichment data (${_.length} files)...`);let N=Jn(_),W=await this.apiClient.uploadEnrichment(N,this.config.projectId,this.config.branch,g);console.log(W?`${C} Enrichment data uploaded to Constellation Service, index enhancement in progress`:`${y} Enrichment upload skipped (index state changed)`);}else console.log(`${y} AST processing did not complete in time \u2014 enrichment skipped`);}catch(E){console.error(`${y} Enrichment upload failed: ${E instanceof Error?E.message:String(E)}`);}let I=(performance.now()-a)/1e3,S=Math.floor(I/60),x=(I%60).toFixed(3),j=S>0?`${S}m ${x}s`:`${x}s`;console.log(`
|
|
67
|
+
${C} Upload completed in ${j}! Server indexing in progress.`),i="succeeded";}catch(o){if(o instanceof D)throw o;if(o instanceof ae)throw r.error(`${b} Indexing failed: Another indexing operation is currently in progress for branch ${o.branchName||this.config?.branch||"unknown"}.`,{code:"CONCURRENT_INDEXING"}),console.log(" Your index may be out of date. Re-run this command after the current operation completes."),o;if(o instanceof R)throw r.error(`
|
|
68
|
+
${b} Authentication failed.`,{code:"AUTH_FAILURE"}),console.log(`${w} Your access key may be invalid or expired. Run 'constellation auth'
|
|
69
|
+
to set or update your access key.`),o;if(o instanceof q)throw r.error(`${b} Indexing failed: ${o.message}`,{code:o.errorCode}),o;if(o instanceof Error&&o.message==="Access key not configured")throw o;let a=o instanceof Error?o.message:"An unexpected error occurred";throw r.error(`${b} Indexing failed: ${a}`),o instanceof Error&&o.stack&&console.error(o.stack),o}finally{r.stop();try{let a=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",l=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,g=r.getReportableErrors();if(!a&&l&&g.length>0){let u=r.getEntries(),c=g.map(I=>({type:"CLI_ERROR",message:I.message,phase:"indexing"})).slice(0,100),f=u.filter(I=>I.level==="warn").map(I=>({type:"CLI_WARNING",message:I.message,phase:"indexing"})).slice(0,100),d=c.length,h=f.length,_=[];d>0&&_.push(`${d} error${d!==1?"s":""}`),h>0&&_.push(`${h} warning${h!==1?"s":""}`);let $=_.join(", "),T=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:$,errorData:{errors:c,warnings:f},logEntries:u.slice(0,1e3),cliVersion:T,outcome:i,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(e){let t=await this.env.getKey(X);if(!t)throw e.error(`
|
|
70
|
+
${b} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),console.log(`${w} Set the ${X} environment variable or run
|
|
71
|
+
'constellation auth' to configure your access key.`),new Error("Access key not configured");return t}async validateProject(e){console.log(`${w} Validating project access...`);try{await this.apiClient.getProjectState(),console.log(`${C} Project validated successfully`);}catch(t){if(t instanceof D)throw this.displayProjectValidationError(t,e),t;if(t instanceof Y){console.log(`${C} Project validated (first index)`);return}if(t instanceof R)throw t;let n=t instanceof Error?t.message:String(t);throw n==="fetch failed"||n.includes("ECONNREFUSED")||n.includes("ENOTFOUND")||n.includes("ETIMEDOUT")||n.includes("EHOSTUNREACH")||n.includes("ECONNRESET")?new Error(`Unable to connect to the Constellation service.
|
|
66
72
|
Verify your network connection and that the API URL is correct.`):t}}displayProjectValidationError(e,t){let n=e.projectId||this.config.projectId,r=n.length>40?n.substring(0,37)+"...":n;switch(e.code){case "PROJECT_NOT_REGISTERED":t.error(`
|
|
67
|
-
${
|
|
73
|
+
${b} Project not registered
|
|
68
74
|
`,{code:"PROJECT_NOT_REGISTERED"}),console.log(` The project ID "${r}" in constellation.json`),console.log(` is not associated with your Constellation account.
|
|
69
75
|
`),console.log(" To resolve this:"),console.log(" 1. Verify the project exists at https://app.constellationdev.io"),console.log(" 2. Check that the project ID in constellation.json is correct"),console.log(` 3. Run 'constellation index' again
|
|
70
76
|
`);break;case "PROJECT_INACTIVE":t.error(`
|
|
71
|
-
${
|
|
77
|
+
${b} Project is inactive
|
|
72
78
|
`,{code:"PROJECT_INACTIVE"}),console.log(` The project "${r}" has been deactivated.
|
|
73
79
|
`),console.log(" To resolve this:"),console.log(" 1. Reactivate the project at https://app.constellationdev.io"),console.log(` 2. Run 'constellation index' again
|
|
74
80
|
`);break;case "INVALID_PROJECT_ID":t.error(`
|
|
75
|
-
${
|
|
81
|
+
${b} Invalid project ID
|
|
76
82
|
`,{code:"INVALID_PROJECT_ID"}),console.log(` The project ID "${r}" in constellation.json`),console.log(` is not a valid Constellation project identifier.
|
|
77
83
|
`),console.log(" To resolve this:"),console.log(" 1. Get your project ID from https://app.constellationdev.io"),console.log(" 2. Update the projectId field in constellation.json"),console.log(` 3. Run 'constellation index' again
|
|
78
84
|
`);break;default:t.error(`
|
|
79
|
-
${
|
|
80
|
-
`);}}async validateGitBranch(){console.log(`${
|
|
81
|
-
Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");console.log(`${
|
|
85
|
+
${b} Project validation failed: ${e.message}
|
|
86
|
+
`);}}async validateGitBranch(){console.log(`${w} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),console.log(`${C} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(console.log(`${w} Validating Git status...`),!(await this.git.status()).clean)throw new q(`Outstanding changes detected.
|
|
87
|
+
Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");console.log(`${C} Working tree clean`);}async synchronizeChanges(e){console.log(`${w} Synchronizing latest changes...`);try{await this.git.pull()&&console.log(`${C} Repository synchronized successfully`);}catch(t){throw e.error(`${b} Failed to synchronize repository`,{code:"GIT_SYNC_FAILURE"}),t instanceof Error&&(t.message.includes("uncommitted changes")?(console.log(`
|
|
82
88
|
To resolve:`),console.log(' 1. Commit your changes: git add . && git commit -m "your message"'),console.log(" 2. Or stash them: git stash"),console.log(` 3. Then run the index command again
|
|
83
89
|
`)):t.message.includes("merge conflicts")?(console.log(`
|
|
84
90
|
To resolve:`),console.log(" 1. Fix the conflicted files manually"),console.log(" 2. Stage the resolved files: git add <resolved-files>"),console.log(" 3. Complete the merge: git commit"),console.log(` 4. Then run the index command again
|
|
@@ -86,11 +92,11 @@ To resolve:`),console.log(" 1. Fix the conflicted files manually"),console.log(
|
|
|
86
92
|
Please check your internet connection and try again
|
|
87
93
|
`):t.message.includes("Authentication")&&console.log(`
|
|
88
94
|
Please check your git credentials and try again
|
|
89
|
-
`)),t}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${
|
|
95
|
+
`)),t}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${w} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return console.log(`${w} No previous index found, performing full index`),{isIncremental:!1,upToDate:!1};let r=await this.git.getLatestCommitHash();return n===r?(console.log(`${C} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${w} Last indexed commit: ${n.substring(0,8)}`),console.log(`${w} Current commit: ${r.substring(0,8)}`),console.log(`${w} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof R)throw t;return console.log(`${y} Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){console.log(`${w} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)console.log(`${y} Cannot determine changes (no latestCommit in project state), falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let r=await this.git.getChangedFiles(n.latestCommit),i=[...r.added,...r.modified,...r.renamed.map(a=>a.to)];console.log(`${w} Found ${i.length} changed files`),t=await this.scanner.scanSpecificFiles(i,this.config);let o=[...r.deleted,...r.renamed.map(a=>a.from)];if(o.length>0){let a=r.deleted.length,l=r.renamed.length,g=l>0?`${w} Removing ${a} deleted file(s) and ${l} renamed file(s) from graph`:`${w} Removing ${a} deleted file(s) from graph`;console.log(g),await this.apiClient.deleteFiles(o);}}}catch(n){if(n instanceof R)throw n;console.log(`${y} Cannot determine changes (${n instanceof Error?n.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else console.log(`${w} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return console.log(`${C} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),r=e.length,i=0,o=0;console.log(`${w} Processing ${r} files...`);let a=await this.git.getLatestCommitHash(),l=r>1e4?5:r>5e3?7:10;l<10&&console.log(`${w} Large project detected, using concurrency of ${l} to optimize memory usage`);let u=new wt(l).run(e,async(c,f)=>{let d=Math.round((f+1)/r*100);console.log(`${w} Analyzing file ${c.path.replace(process.cwd()+"/","")} (${d}%)...`);try{let h=await this.parser.parseFile(c.path,c.language),_=this.langRegistry.getPlugin(c.language),$;if(_?.getImportResolver){let E=this.buildConfigManagers.get(c.language),N=E?await E.getConfigForFile(c.path):null,W=_.getImportResolver(c.path,N);if(W){let{ImportExtractor:se}=await Promise.resolve().then(()=>(Sr(),Er));$=await new se().extractImportResolutions(h,c.path,c.language,W);}}let{serializeASTStream:T}=await Promise.resolve().then(()=>(qt(),Or)),I=T(h.rootNode,void 0,c.language),S=await this.compressor.compressStream(I),x={file:this.normalizePathToCanonical(c.relativePath),language:c.language,commit:a,timestamp:n,ast:S,importResolutions:$},j=dr.safeParse(x);if(!j.success)throw new Error(`AST validation failed: ${j.error.issues[0].message}`);return i++,j.data}catch(h){throw o++,console.error(` ${y} Failed to parse ${c.relativePath}: ${h.message}`,h),h}});for await(let c of u)yield c;o>0?console.log(`${y} Completed parsing with ${o} parsing errors`):console.log(`${C} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n))throw new Error("Failed to upload data to Constellation Service");console.log(`${C} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return Je(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||ce.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return console.log(`${w} Index enrichment skipped (--no-enrich flag)`),null;if(this.config.lspEnrichment===false)return console.log(`${w} Index enrichment disabled in constellation.json`),null;let r=[...new Set(t.map(i=>i.language))].filter(i=>this.isLanguageLspEligible(i));return r.length===0?null:(console.log(`${w} Index enrichment enabled for: ${r.map(Se).join(", ")}`),new Set(r))}async runLspEnrichment(e,t){let n=new tt(process.cwd());try{console.log(`${w} Starting index enrichment...`);let r=new Map,i=new Map;for(let u of e){if(!t.has(u.language))continue;let c=r.get(u.language)||[];if(c.push(this.normalizePathToCanonical(u.relativePath)),r.set(u.language,c),!i.has(u.language)){let d=this.config.languages[u.language]?.lsp,h=await n.startServer(u.language,d);h&&i.set(u.language,h);}}if(i.size===0)return console.log(`${y} No language servers started, index enrichment skipped`),null;console.log(`${C} Language servers started: ${[...i.keys()].map(Se).join(", ")}`);let o=new Map,l=await new qe(process.cwd()).enrich(r,o,i),g=l.reduce((u,c)=>u+c.symbols.length,0);return console.log(`${C} Index enrichment analysis completed: ${g} symbols across ${l.length} files`),l.length>0?l:null}catch(r){return console.error(`${y} Index enrichment failed: ${r instanceof Error?r.message:String(r)}`),null}finally{await n.shutdownAll();}}};});function en(s){return `name: Constellation Index
|
|
90
96
|
|
|
91
97
|
on:
|
|
92
98
|
push:
|
|
93
|
-
branches: ["${
|
|
99
|
+
branches: ["${s}"]
|
|
94
100
|
|
|
95
101
|
permissions:
|
|
96
102
|
contents: read
|
|
@@ -104,15 +110,15 @@ jobs:
|
|
|
104
110
|
- uses: ShiftinBits/constellation-github@v1
|
|
105
111
|
with:
|
|
106
112
|
access-key: \${{ secrets.CONSTELLATION_ACCESS_KEY }}
|
|
107
|
-
`}function
|
|
113
|
+
`}function tn(s){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${s}"`}]}}}function _t(s){return `include:
|
|
108
114
|
- component: gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1
|
|
109
115
|
inputs:
|
|
110
116
|
access_key: $CONSTELLATION_ACCESS_KEY
|
|
111
117
|
|
|
112
118
|
constellation-index:
|
|
113
119
|
rules:
|
|
114
|
-
- if: $CI_COMMIT_BRANCH == "${
|
|
115
|
-
`}var
|
|
120
|
+
- if: $CI_COMMIT_BRANCH == "${s}"
|
|
121
|
+
`}var nn=m(()=>{});var Re,Ur=m(()=>{z();nn();Re=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([v.directoryExists(P__default.join(this.gitRoot,".github","workflows")),v.fileIsReadable(P__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return v.fileIsReadable(P__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await v.fileIsReadable(e))return false;try{let n=await v.readFile(e),i=parseDocument(n).contents;return isMap(i)&&i.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=P__default.join(this.gitRoot,".github","workflows");await M__default.mkdir(t,{recursive:true});let n=P__default.join(t,"constellation-index.yml");return await v.writeFile(n,en(e)),n}async createOrMergeGitLabCI(e){let t=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await v.fileIsReadable(t))return await v.writeFile(t,_t(e)),t;let r=await v.readFile(t),i=parseDocument(r);if(!isMap(i.contents))return await v.writeFile(t,_t(e)),t;let{includeEntry:o,job:a}=tn(e);return this.mergeIncludeEntry(i,o),i.set("constellation-index",a),await v.writeFile(t,i.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let r=n.items.filter(i=>{if(isMap(i)){let o=i.get("component");return typeof o!="string"||!o.includes("constellation-gitlab")}return true});n.items=r,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var Br=m(()=>{Ur();nn();});function on(){return Hr}var Hr,Gr=m(()=>{Hr=[{event:"SessionStart",type:"prompt",content:`You have Constellation access. \`{MCP_TOOL_NAME}\` is your PRIMARY tool for understanding this codebase\u2014not an alternative, not a fallback, THE DEFAULT.
|
|
116
122
|
|
|
117
123
|
Mental model:
|
|
118
124
|
- "Where is X defined?" \u2192 {MCP_TOOL_NAME}
|
|
@@ -120,7 +126,7 @@ Mental model:
|
|
|
120
126
|
- "What would break?" \u2192 {MCP_TOOL_NAME}
|
|
121
127
|
- "Find the string 'ERROR_CODE_123'" \u2192 Grep
|
|
122
128
|
|
|
123
|
-
Grep is for literal text. Everything else starts with {MCP_TOOL_NAME}.`,matcher:".*"},{event:"SubagentStart",type:"prompt",content:"You have access to Constellation's {MCP_TOOL_NAME} MCP tool. For structural code questions\u2014symbol definitions, callers/callees, dependencies, dependents, impact analysis, architecture overview\u2014use {MCP_TOOL_NAME} instead of Grep/Glob. It answers in one call what would take 3-5 text searches. Use Grep/Glob only for literal string search, config values, or when the tool is unavailable.",matcher:"Explore|Plan|explore|shell"},{event:"PreCompact",type:"prompt",content:"Preserve: (1) The instruction that {MCP_TOOL_NAME} is the PRIMARY tool for code understanding\u2014Grep is only for literal text, (2) Any architectural insights, dependency relationships, or impact analysis results discovered via Constellation.",matcher:".*"}];});function
|
|
129
|
+
Grep is for literal text. Everything else starts with {MCP_TOOL_NAME}.`,matcher:".*"},{event:"SubagentStart",type:"prompt",content:"You have access to Constellation's {MCP_TOOL_NAME} MCP tool. For structural code questions\u2014symbol definitions, callers/callees, dependencies, dependents, impact analysis, architecture overview\u2014use {MCP_TOOL_NAME} instead of Grep/Glob. It answers in one call what would take 3-5 text searches. Use Grep/Glob only for literal string search, config values, or when the tool is unavailable.",matcher:"Explore|Plan|explore|shell"},{event:"PreCompact",type:"prompt",content:"Preserve: (1) The instruction that {MCP_TOOL_NAME} is the PRIMARY tool for code understanding\u2014Grep is only for literal text, (2) Any architectural insights, dependency relationships, or impact analysis results discovered via Constellation.",matcher:".*"}];});function Ei(s){return Wr[s]}var Wr,_i,$e,sn=m(()=>{Wr={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},_i="code_intel";$e=class{id="cline";displayName="Cline";mapEventName(e){return Wr[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,_i)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){let r=Ei(n.event);if(!r)continue;let i=`.clinerules/hooks/${r}`,o=this.generateScript(n);t.set(i,o);}return t.size>0?t:void 0}generateScript(e){let n=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return `#!/bin/bash
|
|
124
130
|
# Constellation ${e.event} Hook for Cline
|
|
125
131
|
# Generated by constellation-cli - DO NOT EDIT
|
|
126
132
|
#
|
|
@@ -133,7 +139,7 @@ cat << 'CONSTELLATION_EOF'
|
|
|
133
139
|
"contextModification": "${n}"
|
|
134
140
|
}
|
|
135
141
|
CONSTELLATION_EOF
|
|
136
|
-
`}};});var
|
|
142
|
+
`}};});var Si,bi,ue,an=m(()=>{Si={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},bi="constellation__code_intel",ue=class{id="cursor";displayName="Cursor";mapEventName(e){return Si[e]}generateConfig(e){let t={};for(let n of e){let r=this.mapEventName(n.event);if(!r)continue;t[r]||(t[r]=[]);let i={type:n.type};n.type==="prompt"&&(i.prompt=this.customizePrompt(n)),n.matcher&&(i.matcher=n.matcher),t[r].push(i);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,bi)}};});function zr(s){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[s]}.sh`}var Pi,xi,Ii,Te,ln=m(()=>{Pi={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},xi={SessionStart:"startup",SubagentStart:"",PreCompact:""},Ii="code_intel";Te=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return Pi[e]}generateConfig(e){let t={};for(let n of e){let r=this.mapEventName(n.event);if(!r)continue;t[r]||(t[r]=[]);let i=xi[n.event]??"",o=zr(n.event),a=t[r].find(l=>l.matcher===i);a||(a={matcher:i,hooks:[]},t[r].push(a)),a.hooks.push({name:`constellation-${n.event.toLowerCase()}`,type:"command",command:`$GEMINI_PROJECT_DIR/.gemini/hooks/${o}`,timeout:5e3,description:`Constellation: ${this.getHookDescription(n.event)}`});}return {hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,Ii)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){if(!this.mapEventName(n.event))continue;let o=`.gemini/hooks/${zr(n.event)}`,a=this.generateScript(n);t.set(o,a);}return t.size>0?t:void 0}generateScript(e){let n=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return e.event==="PreCompact"?`#!/bin/bash
|
|
137
143
|
# Constellation ${e.event} Hook for Gemini CLI
|
|
138
144
|
# Generated by constellation-cli - DO NOT EDIT
|
|
139
145
|
#
|
|
@@ -156,38 +162,38 @@ cat << 'CONSTELLATION_EOF'
|
|
|
156
162
|
}
|
|
157
163
|
}
|
|
158
164
|
CONSTELLATION_EOF
|
|
159
|
-
`}getHookDescription(e){return {SessionStart:"Inject code intelligence guidance at session start",SubagentStart:"Inject guidance for agent planning",PreCompact:"Context preservation reminder",PreToolUse:"Pre-tool execution hook",PostToolUse:"Post-tool execution hook",SessionEnd:"Session end hook"}[e]}};});function
|
|
165
|
+
`}getHookDescription(e){return {SessionStart:"Inject code intelligence guidance at session start",SubagentStart:"Inject guidance for agent planning",PreCompact:"Context preservation reminder",PreToolUse:"Pre-tool execution hook",PostToolUse:"Post-tool execution hook",SessionEnd:"Session end hook"}[e]}};});function cn(s){return Ri.get(s)}var Ri,pn=m(()=>{sn();an();ln();sn();an();ln();Ri=new Map([["cline",new $e],["cursor",new ue],["gemini",new Te]]);});var ke,Vr=m(()=>{z();pn();ke=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureHooks(e,t){if(!e.hooksConfig)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:"Tool does not support hooks configuration"};let n=cn(e.hooksConfig.adapterId);if(!n)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let r=P__default.join(this.cwd,e.hooksConfig.filePath),i=n.generateConfig(t),o=Object.keys(i).some(l=>{let g=i[l];return g!=null&&(typeof g!="object"||Object.keys(g).length>0)});if(o){await this.ensureDirectoryExists(r);let l=await this.readConfig(r),g=this.mergeHooksConfig(l,i);await this.writeConfig(r,g);}let a;if(n.generateAuxiliaryFiles){let l=n.generateAuxiliaryFiles(t);l&&(await this.writeAuxiliaryFiles(l),a=Array.from(l.keys()));}return {toolId:e.id,toolDisplayName:e.displayName,success:!0,configuredPath:o?r:void 0,auxiliaryPaths:a}}catch(r){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:r instanceof Error?r.message:String(r)}}}async ensureDirectoryExists(e){let t=P__default.dirname(e);await M__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await v.fileIsReadable(e))return {};let n=await v.readFile(e);return JSON.parse(n)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let n=e.hooks??{},r=t.hooks??{},i={...n,...r},o={...e,hooks:i};return t.version!==void 0&&(o.version=t.version),o}async writeConfig(e,t){let n=JSON.stringify(t,null," ");n=n.replace(/\r\n/g,`
|
|
160
166
|
`),n.endsWith(`
|
|
161
167
|
`)||(n+=`
|
|
162
|
-
`),await
|
|
163
|
-
`);
|
|
164
|
-
`)||(
|
|
165
|
-
`),await h.writeFile(r,o),(t.endsWith(".sh")||o.startsWith("#!"))&&await A__default.chmod(r,493);}}};});var fr=m(()=>{cr();ur();Ut();});var J,Xe=m(()=>{J=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var ne,Gt=m(()=>{k();ne=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(`${C} 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 r=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}if(n){if(this.isJavaScriptEnabled)try{let r=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,r),r}catch(r){if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}throw r}if(this.isTypeScriptEnabled){let r=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}}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 r=t instanceof Error?t.message:String(t);console.warn(`${C} Failed to parse ${n}: ${r}`),console.warn(`${C} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${C} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var Ze,hr=m(()=>{ee();Ze=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 r=e.substring(t.length+1),o=await this.resolveSubPath(n,r);if(o)return this.toProjectRelative(o)}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?S.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[r,o]of Object.entries(t)){if(r.includes("*")||!Array.isArray(o))continue;let s=o[0];if(!s)continue;let a=S.resolve(n,s),l=await this.findEntryPoint(a);l&&(e[r]=l);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=S.join(this.projectRoot,"package.json"),n=await A.readFile(t,"utf-8"),o=JSON.parse(n).workspaces;if(!o)return e;let s=Array.isArray(o)?o:o.packages||[];for(let a of s){let l=await this.findWorkspaceDirs(a);for(let g of l){let f=await this.loadWorkspacePackage(g);f&&Object.assign(e,f);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),r=S.join(this.projectRoot,n);try{let o=await A.readdir(r,{withFileTypes:!0});for(let s of o)s.isDirectory()&&t.push(S.join(r,s.name));}catch{}}else {let n=S.join(this.projectRoot,e);try{(await A.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=S.join(e,"package.json"),n=await A.readFile(t,"utf-8"),r=JSON.parse(n),o=r.name;if(!o)return null;let s=await this.findPackageEntryPoint(e,r);return s?{[o]:s}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let r=t.exports;if(typeof r=="string")return S.join(e,r);if(typeof r=="object"){let o=r["."]||r["./index"];if(typeof o=="string")return S.join(e,o);if(typeof o=="object"){let s=o.import||o.default||o.require;if(s)return S.join(e,s)}}}if(t.main)return S.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 r of n){let o=S.join(e,r);try{if((await A.stat(o)).isFile())return o}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 r=S.join(e,n);try{if((await A.stat(r)).isFile())return r}catch{}}try{if((await A.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")?S.dirname(e):S.dirname(e),r=[S.join(n,t+".ts"),S.join(n,t+".tsx"),S.join(n,t+".js"),S.join(n,t+".jsx"),S.join(n,t+".d.ts"),S.join(n,t,"index.ts"),S.join(n,t,"index.tsx"),S.join(n,t,"index.js"),S.join(n,t,"index.jsx")];for(let o of r)try{if((await A.stat(o)).isFile())return o}catch{}return null}toProjectRelative(e){let t=K(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var re,Wt=m(()=>{ee();hr();re=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=S.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Ze(this.projectRoot,t);let n=e.toLowerCase(),r=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),o=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(r?this.extensions=[".ts",".tsx",".d.ts"]:o?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=S.dirname(t.tsconfigFile);let s=t.tsconfig?.compilerOptions;s&&(s.baseUrl&&(this.baseUrl=S.resolve(this.tsconfigDir,s.baseUrl)),s.paths&&typeof s.paths=="object"&&(this.paths=s.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=S.resolve(this.sourceDir,e),r=await this.findFileWithExtensions(n);return r?this.toProjectRelative(r):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=K(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let r=this.matchPathPattern(e,t);if(r!==null)for(let o of n){let s=await this.trySubstitution(e,t,o,r);if(s)return s}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,r]=t.split("*");if(!e.startsWith(n)||r&&!e.endsWith(r))return null;let o=n.length,s=r?e.length-r.length:e.length;return e.substring(o,s)}async trySubstitution(e,t,n,r){let o=n.replaceAll("*",r),s=S.resolve(this.tsconfigDir,o);return await this.findFileWithExtensions(s)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=S.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(s=>e.endsWith(s));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],r=n.some(s=>e.endsWith(s)),o=e;if(r&&!t){for(let s of n)if(e.endsWith(s)){o=e.slice(0,-s.length);break}}if(!t)for(let s of this.extensions){let a=o+s;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let s of this.extensions){let a=S.join(o,`index${s}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await A.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await A.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=S.join(t,"package.json");try{if((await A.stat(n)).isFile())return n}catch{}let r=S.dirname(t);if(r===t)break;t=r;}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 A.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=S.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 r=this.matchPathPattern(e,t);if(r!==null){if(typeof n=="string"){let o=await this.tryPackageImportSubstitution(n,r);if(o)return o}if(Array.isArray(n)){for(let o of n)if(typeof o=="string"){let s=await this.tryPackageImportSubstitution(o,r);if(s)return s}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),r=S.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(r)}};});var Qe,yr=m(()=>{Xe();Gt();Wt();Qe=class extends J{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new ne(e,t)}getImportResolver(e,t){return new re(e,t)}};});var et,Cr=m(()=>{Xe();Gt();Wt();et=class extends J{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new ne(e,t)}getImportResolver(e,t){return new re(e,t)}};});var tt,wr=m(()=>{Je();tt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=S.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(PYTHON_STDLIB_MODULES.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),r=await this.tryResolveFile(S.resolve(this.projectRoot,n));return r?S.relative(this.projectRoot,r).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),r=t<=1?"":"../".repeat(t-1),o=n?r+n.replace(/\./g,"/"):r.slice(0,-1)||".",s=S.resolve(this.sourceDir,o),a=await this.tryResolveFile(s);return a?S.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,S.join(e,"__init__.py"),S.join(e,"__init__.pyi")];for(let n of t)try{return await nt.promises.access(n,nt.constants.F_OK),n}catch{continue}return null}};});var rt,_r=m(()=>{Xe();wr();rt=class extends J{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new tt(e,process.cwd())}};});var Pe,ot,zt=m(()=>{yr();Cr();_r();Pe={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"]},ot=class{constructor(e){this.config=e;this.registerPlugin(new Qe),this.registerPlugin(new et),this.registerPlugin(new rt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Wo,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Pe.javascript};typescript={language:()=>Ko.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Pe.typescript};python={language:()=>zo,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Pe.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function vr(i,e){let t=le__default.homedir(),n=process.platform,r=Jo[i];switch(n){case "darwin":return S__default.join(t,"Library/Application Support",r,"User/globalStorage",e);case "win32":return S__default.join(process.env.APPDATA||S__default.join(t,"AppData/Roaming"),r,"User/globalStorage",e);default:return S__default.join(t,".config",r,"User/globalStorage",e)}}function Er(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:S__default.join(vr(t,i),"settings","cline_mcp_settings.json")}))}function Sr(){return S__default.join(vr("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Jo,Pr=m(()=>{Jo={stable:"Code",insiders:"Code - Insiders"};});function Vt(i){return Kt.find(e=>e.id===i)}var br,Yo,Kt,Jt=m(()=>{Pr();br={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Yo={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},Kt=[{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:Yo},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Sr(),isGlobalConfig:true,getGlobalConfigPaths:Er,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false},hooksConfig:{filePath:".clinerules/hooks/placeholder",schemaVersion:1,adapterId:"cline"}},{id:"codex-cli",displayName:"Codex CLI",configPath:".codex/config.toml",format:"toml",mcpServersKeyPath:["mcp_servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"$CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{enabled_tools:["code_intel"]},envPolicyConfig:{includeOnlyKeyPath:["shell_environment_policy","include_only"],envVarsToAllow:["CONSTELLATION_ACCESS_KEY"],globalConfigPath:"~/.codex/config.toml"}},{id:"copilot-cli",displayName:"Copilot CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","install","ShiftinBits/constellation-copilot"]}},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"},hooksConfig:{filePath:".cursor/hooks.json",schemaVersion:1,adapterId:"cursor"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:".gemini/settings.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${CONSTELLATION_ACCESS_KEY}"},mcpServerExtras:{trust:true},hooksConfig:{filePath:".gemini/settings.json",schemaVersion:1,adapterId:"gemini"}},{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 xr(){if(!Yt)try{let i=await import('@iarna/toml');Yt={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Yt}function Zo(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]!==`
|
|
166
|
-
`;)t++;else if(
|
|
168
|
+
`),await v.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let r=P__default.join(this.cwd,t);await this.ensureDirectoryExists(r);let i=n.replace(/\r\n/g,`
|
|
169
|
+
`);i.endsWith(`
|
|
170
|
+
`)||(i+=`
|
|
171
|
+
`),await v.writeFile(r,i),(t.endsWith(".sh")||i.startsWith("#!"))&&await M__default.chmod(r,493);}}};});var Jr=m(()=>{Gr();Vr();pn();});function Yr(s,e){let t=he__default.homedir(),n=process.platform,r=Ti[s];switch(n){case "darwin":return P__default.join(t,"Library/Application Support",r,"User/globalStorage",e);case "win32":return P__default.join(process.env.APPDATA||P__default.join(t,"AppData/Roaming"),r,"User/globalStorage",e);default:return P__default.join(t,".config",r,"User/globalStorage",e)}}function qr(){let s="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:P__default.join(Yr(t,s),"settings","cline_mcp_settings.json")}))}function Xr(){return P__default.join(Yr("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Ti,Qr=m(()=>{Ti={stable:"Code",insiders:"Code - Insiders"};});function dn(s){return un.find(e=>e.id===s)}var Zr,ki,un,fn=m(()=>{Qr();Zr={command:"npx",args:["-y","@constellationdev/mcp@latest"]},ki={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},un=[{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:ki},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Xr(),isGlobalConfig:true,getGlobalConfigPaths:qr,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false},hooksConfig:{filePath:".clinerules/hooks/placeholder",schemaVersion:1,adapterId:"cline"}},{id:"codex-cli",displayName:"Codex CLI",configPath:".codex/config.toml",format:"toml",mcpServersKeyPath:["mcp_servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"$CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{enabled_tools:["code_intel"]},envPolicyConfig:{includeOnlyKeyPath:["shell_environment_policy","include_only"],envVarsToAllow:["CONSTELLATION_ACCESS_KEY"],globalConfigPath:"~/.codex/config.toml"}},{id:"copilot-cli",displayName:"Copilot CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","install","ShiftinBits/constellation-copilot"]}},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"},hooksConfig:{filePath:".cursor/hooks.json",schemaVersion:1,adapterId:"cursor"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:".gemini/settings.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${CONSTELLATION_ACCESS_KEY}"},mcpServerExtras:{trust:true},hooksConfig:{filePath:".gemini/settings.json",schemaVersion:1,adapterId:"gemini"}},{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 eo(){if(!mn)try{let s=await import('@iarna/toml');mn={parse:s.parse,stringify:s.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return mn}function ji(s){let e="",t=0,n=s.length;for(;t<n;)if(s[t]==='"'){for(e+='"',t++;t<n&&s[t]!=='"';)s[t]==="\\"?(e+=s[t++],t<n&&(e+=s[t++])):e+=s[t++];t<n&&(e+=s[t++]);}else if(s[t]==="/"&&t+1<n&&s[t+1]==="/")for(t+=2;t<n&&s[t]!==`
|
|
172
|
+
`;)t++;else if(s[t]==="/"&&t+1<n&&s[t+1]==="*"){for(t+=2;t<n&&!(s[t]==="*"&&t+1<n&&s[t+1]==="/");)t++;t<n&&(t+=2);}else e+=s[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var mn,Et,to=m(()=>{z();fn();mn=null;Et=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=P__default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){await this.ensureDirectoryExists(t);let i=await this.readConfig(t,e.format);if(e.configDefaults)for(let[o,a]of Object.entries(e.configDefaults))o in i||(i[o]=a);e.pluginConfig&&(i=this.addPluginToArray(i,e.pluginConfig)),e.skipMcpServer||(i=this.addConstellationServer(i,e),await this.configureEnvPolicy(i,e)),await this.writeConfig(t,i,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let r;return n?r=t:e.permissionsConfig?r=P__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?r=P__default.join(this.cwd,e.marketplaceConfig.filePath):r=t,{tool:e,success:!0,configuredPath:r}}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:r,settingsPath:i}of t)try{await this.ensureDirectoryExists(i);let o=await this.readConfig(i,e.format);o=this.addConstellationServer(o,e),await this.writeConfig(i,o,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${r})`},success:!0,configuredPath:i});}catch(o){let a=o instanceof Error?o.message:String(o);a.includes("ENOENT")||a.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${r})`},success:false,error:a});}return n}async ensureDirectoryExists(e){let t=P__default.dirname(e);await M__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await v.fileIsReadable(e))return {};let r=await v.readFile(e);return t==="json"?JSON.parse(r):t==="jsonc"?JSON.parse(ji(r)):(await eo()).parse(r)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let o=0;o<t.mcpServersKeyPath.length-1;o++){let a=t.mcpServersKeyPath[o];(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a];}let r=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[r]||typeof n[r]!="object")&&(n[r]={});let i=n[r];if(!i.constellation){let o=t.mcpServerConfigOverride??Zr,a={...o};if(t.mcpServerExtras&&Object.assign(a,t.mcpServerExtras),t.mcpEnv){let l=t.mcpEnvKey??"env",g=o[l];a[l]={...g,...t.mcpEnv};}i.constellation=a;}return e}async writeConfig(e,t,n){let r;n==="json"||n==="jsonc"?r=JSON.stringify(t,null,2):r=(await eo()).stringify(t),r=r.replace(/\r\n/g,`
|
|
167
173
|
`),r.endsWith(`
|
|
168
174
|
`)||(r+=`
|
|
169
|
-
`),await
|
|
170
|
-
`);}async configureMarketplace(e){let t=
|
|
171
|
-
`);}deepMerge(e,t){let n={...e};for(let r of Object.keys(t)){let
|
|
172
|
-
`),!await this.git.isGitAvailable())throw new Error(`${
|
|
173
|
-
${
|
|
174
|
-
`);}catch{console.log(`${
|
|
175
|
-
`);}if(!await this.git.isGitRepository())throw new Error(`${
|
|
176
|
-
${
|
|
177
|
-
${n}`);}}async configureMCPServers(){
|
|
178
|
-
${
|
|
179
|
-
${
|
|
180
|
-
${
|
|
181
|
-
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},
|
|
182
|
-
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,r)=>{let
|
|
183
|
-
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),r=`export ${e}="${n}"`;try{for(let
|
|
175
|
+
`),await v.writeFile(e,r);}async configurePermissions(e){let t=P__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await v.fileIsReadable(t)){let l=await v.readFile(t);n=JSON.parse(l);}}catch{}let r=n;for(let a=0;a<e.allowKeyPath.length-1;a++){let l=e.allowKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let i=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(r[i])||(r[i]=[]);let o=r[i];o.includes(e.allowValue)||o.push(e.allowValue),await v.writeFile(t,JSON.stringify(n,null," ")+`
|
|
176
|
+
`);}async configureMarketplace(e){let t=P__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await v.fileIsReadable(t)){let i=await v.readFile(t);n=JSON.parse(i);}}catch{}n=this.deepMerge(n,e.config),await v.writeFile(t,JSON.stringify(n,null," ")+`
|
|
177
|
+
`);}deepMerge(e,t){let n={...e};for(let r of Object.keys(t)){let i=t[r],o=e[r];i&&typeof i=="object"&&!Array.isArray(i)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=this.deepMerge(o,i):n[r]=i;}return n}addPluginToArray(e,t){let n=e;for(let o=0;o<t.pluginKeyPath.length-1;o++){let a=t.pluginKeyPath[o];(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a];}let r=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[r])||(n[r]=[]);let i=n[r];return i.includes(t.pluginValue)||i.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:r,globalConfigPath:i}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,r),i&&await this.updateGlobalEnvPolicy(i,n,r,t.format);}addToEnvPolicyWhitelist(e,t,n){let r=e;for(let a=0;a<t.length-1;a++){let l=t[a];if(!r[l]||typeof r[l]!="object")return;r=r[l];}let i=t[t.length-1];if(!Array.isArray(r[i]))return;let o=r[i];for(let a of n)o.includes(a)||o.push(a);}async updateGlobalEnvPolicy(e,t,n,r){let i=e.replace(/^~/,he__default.homedir()),o=await this.readConfig(i,r);if(Object.keys(o).length===0)return;let a=JSON.stringify(o);this.addToEnvPolicyWhitelist(o,t,n);let l=JSON.stringify(o);a!==l&&await this.writeConfig(i,o,r);}};});function me(s,e){let t=P__default.normalize(s),n=P__default.normalize(e);return t.startsWith(n+P__default.sep)?P__default.relative(e,s):s}var Ui,Ae,oo=m(()=>{Br();et();Jr();gt();to();fn();z();F();Ve();ze();Ui=promisify(execFile);Ae=class extends Q{async run(e={}){try{if(console.log(`${J}Initializing project configuration...
|
|
178
|
+
`),!await this.git.isGitAvailable())throw new Error(`${y} Could not find git client installation.
|
|
179
|
+
${w} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=P__default.join(process.cwd(),"constellation.json"),r=null,i=await v.fileIsReadable(n);if(i)try{let x=await v.readFile(n);r=JSON.parse(x),console.log(`${w} Found existing constellation.json, current values will be used as defaults.
|
|
180
|
+
`);}catch{console.log(`${y} Existing constellation.json is invalid, starting fresh.
|
|
181
|
+
`);}if(!await this.git.isGitRepository())throw new Error(`${y} Current directory is not a git repository.
|
|
182
|
+
${w} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[l,g]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:u}=l,c=g.filter(x=>x!==u),f=u?[u,...c]:c,d=await input({message:"Constellation Project ID:",default:r?.projectId??"",validate:x=>x.trim().length>0||"Project ID is required",theme:k}),h=await select({message:"Branch to index:",choices:f.map(x=>({name:x,value:x})),default:r?.branch??f[0],theme:k}),$=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(r),required:!0,theme:k})).reduce((x,j)=>(x[j]={fileExtensions:Ee[j]||[]},x),{});console.log(""),console.log(`${w} Checking for LSP servers...`);for(let[x,j]of Object.entries($)){let E=ce.get(x);if(!E)continue;let N=!1,W="";if(Xe(E.command)&&(N=!0,W="system"),!N){let se=P__default.join(Ze,E.command);existsSync(se)&&(N=!0,W="managed");}if(N)console.log(` ${C} ${x}: Found ${E.command} (${W})`),j.lsp={command:E.command,args:E.args};else if(await confirm({message:`${x}: ${E.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:k}))try{console.log(` ${w} Installing ${E.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",Ot,...E.npmPackages],{stdio:"pipe"}),console.log(` ${C} ${x}: Installed ${E.command}`),j.lsp={command:E.command,args:E.args};}catch{console.log(` ${b} ${x}: Installation failed`),j.lspEnrichment=!1;}else j.lspEnrichment=!1;}let T=Object.entries($).filter(([,x])=>x.lspEnrichment!==!1).map(([x])=>x);T.length>0?console.log(`${C} Index enrichment enabled for: ${T.map(Se).join(", ")}`):console.log(`${y} No language servers configured. Index enrichment will be skipped.`);let I={projectId:d.trim(),branch:h,languages:{...$},...T.length>0&&{lspEnrichment:!0}},S=JSON.stringify(I,void 0,2);await v.writeFile(n,S),console.log(`${C} ${i?"Updated":"Initialized"} configuration file at ${me(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${C} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&a&&await this.configureCICD(h,a);}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred";console.error(`${b} Failed to initialize configuration file.
|
|
183
|
+
${n}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:k}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:un.map(u=>({name:u.displayName,value:u.id})),required:true,theme:k}),n=new Et(process.cwd()),r=[];for(let u of t){let c=dn(u);if(c)if(console.log(` ${w} Configuring ${c.displayName}...`),c.pluginInstallCommand){let f=await this.executePluginInstall(c);r.push(f),f.success?console.log(` ${C} ${c.displayName} plugin installed successfully`):console.log(` ${y} ${c.displayName}: ${f.error}`);}else if(c.isGlobalConfig&&c.getGlobalConfigPaths){let f=await n.configureGlobalTool(c),d=false;for(let h of f)r.push(h),h.success?(d=true,console.log(` ${C} ${h.tool.displayName} configured at ${me(h.configuredPath,process.cwd())}`)):h.error&&console.log(` ${y} ${h.tool.displayName}: ${h.error}`);if(d){let h=c.id==="cline"?"global VS Code settings":"global settings";console.log(` ${w} Note: ${c.displayName} uses ${h} (not project-level)`);}if(f.length===0){let h=c.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${y} ${c.displayName}: ${h}`);}}else {let f=await n.configureTool(c);r.push(f),f.success?(console.log(` ${C} ${c.displayName} configured at ${me(f.configuredPath,process.cwd())}`),c.permissionsConfig&&console.log(` ${C} ${c.displayName} permissions set in ${c.permissionsConfig.filePath}`)):console.log(` ${y} ${c.displayName}: ${f.error}`);}}if(r.find(u=>u.tool.id==="claude-code"&&u.success)){let u=P__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(u),console.log(` ${C} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${y} Could not stage .claude/settings.json in git`);}}if(r.find(u=>u.tool.id==="codex-cli"&&u.success)){let u=P__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(u),console.log(` ${C} Added .codex/config.toml to staged changes in git`);}catch{}}if(r.find(u=>u.tool.id==="opencode"&&u.success)){let u=P__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(u),console.log(` ${C} Added opencode.jsonc to staged changes in git`);}catch{}}let l=r.filter(u=>u.success).length,g=r.filter(u=>!u.success).length;console.log(`
|
|
184
|
+
${C} Plugin + MCP configuration complete: ${l} configured`),g>0&&console.log(`${y} ${g} tool(s) could not be configured`),await this.configureHooks(t,r),console.log(`
|
|
185
|
+
${w} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new ke(process.cwd()),r=on(),i=e.map(l=>dn(l)).filter(l=>l!==void 0&&l.hooksConfig!==void 0&&t.some(g=>g.tool.id===l.id&&g.success));if(i.length===0)return;console.log(`
|
|
186
|
+
${w} Configuring AI hooks...`);let o=[];for(let l of i){let g=await n.configureHooks(l,r);if(o.push(g),g.success){let u=g.configuredPath?[g.configuredPath]:g.auxiliaryPaths??[];if(u.length>0){let c=g.configuredPath?me(g.configuredPath,process.cwd()):P__default.dirname(u[0]);console.log(` ${C} ${l.displayName} hooks configured at ${c}`);for(let f of u){let d=P__default.isAbsolute(f)?me(f,process.cwd()):f;try{await this.git.stageFile(f),console.log(` ${C} Added ${d} to staged changes in git`);}catch{console.log(` ${y} Could not stage ${d} in git`);}}}else console.log(` ${C} ${l.displayName} hooks configured`);}else console.log(` ${y} ${l.displayName}: ${g.error}`);}let a=o.filter(l=>l.success).length;a>0&&console.log(`${C} Hooks configuration complete: ${a} configured`);}async executePluginInstall(e){let{command:t,args:n}=e.pluginInstallCommand;try{return await Ui(t,n,{timeout:3e4,env:process.env}),{tool:e,success:!0}}catch(r){let i=r,o;return i.code==="ENOENT"?o=`${t} not found. Is ${e.displayName} installed and on your PATH?`:i.killed?o="Plugin installation timed out after 30 seconds":i.stderr?o=`Plugin installation failed: ${i.stderr.trim()}`:o=`Plugin installation failed: ${i.message}`,{tool:e,success:false,error:o}}}async configureCICD(e,t){if(!await confirm({message:"Set up a CI/CD pipeline to automatically index your project?",default:true,theme:k}))return;let r=new Re(t),i=await r.detectPlatforms(),o;if(i.length===1){let u=i[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${u}. Configure Constellation CI/CD for this platform?`,default:true,theme:k}))return;o=i[0];}else o=await select({message:"Select CI/CD platform:",choices:[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],theme:k});let a=o==="github"?await r.githubWorkflowExists():await r.gitlabJobExists();if(a&&!await confirm({message:"Constellation CI/CD configuration already exists. Overwrite?",default:false,theme:k})){console.log(`${w} Skipping CI/CD configuration`);return}let l;try{l=o==="github"?await r.createGitHubWorkflow(e):await r.createOrMergeGitLabCI(e);}catch(u){console.log(`${y} Failed to configure CI/CD pipeline: ${u.message}`);return}let g=me(l,process.cwd());console.log(o==="github"?`${C} Created ${g}`:`${C} ${a?"Updated":"Created"} ${g} with Constellation indexing`);try{await this.git.stageFile(l),console.log(`${C} Added ${g} to staged changes in git`);}catch{console.log(`${y} Could not stage ${g} in git`);}o==="github"?(console.log(`${w} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${w} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(n=>({...n,checked:t.includes(n.value)}))}};});var St,io=m(()=>{We();mt();z();F();St=class s{constructor(e,t,n,r,i){this.branch=e;this.languages=t;this.projectId=n;this.exclude=r;this.lspEnrichment=i;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await v.fileIsReadable(e)){let n=await v.readFile(e),r=JSON.parse(n),i=new s(r.branch,r.languages,r.projectId,r.exclude,r.lspEnrichment);return i.validate(),i}else throw new Error(`${b} 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 q("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new q(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var bt,yn,wn,Cn,Pt,ao=m(()=>{z();bt=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(`
|
|
187
|
+
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},yn=class extends bt{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.
|
|
188
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,r)=>{let i=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),o="";i.stderr?.on("data",a=>{o+=a.toString();}),i.on("close",a=>{a===0?n():r(new Error(`setx failed with code ${a}: ${o}`));}),i.on("error",a=>{r(a);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let r=(await new Promise((i,o)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),l="",g="";a.stdout?.on("data",u=>{l+=u.toString();}),a.stderr?.on("data",u=>{g+=u.toString();}),a.on("close",u=>{u===0?i(l):o(new Error(`reg query failed: ${g}`));}),a.on("error",u=>{o(u);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return r?r[1].trim():void 0}catch{return}}},wn=class extends bt{userConfigFiles;constructor(){super(),this.userConfigFiles=[P.join(he.homedir(),".zshenv"),P.join(he.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.
|
|
189
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),r=`export ${e}="${n}"`;try{for(let i of this.userConfigFiles)await this.writeToConfigFile(i,e,r);process.env[e]=t;}catch(i){throw new Error(`Failed to set environment variable ${e}: ${i}`)}}async writeToConfigFile(e,t,n){let r="";try{r=await v.readFile(e,"utf-8");}catch{}let i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^export ${i}=.*$`,"gm");o.test(r)?r=r.replace(o,n):r=r.trimEnd()+`
|
|
184
190
|
`+n+`
|
|
185
|
-
`,await
|
|
186
|
-
${
|
|
187
|
-
`),await this.packageManager.executeUpdate(
|
|
188
|
-
${
|
|
191
|
+
`,await v.writeFile(e,r);}},Cn=class{static create(){let e=he.platform();switch(e){case "win32":return new yn;case "darwin":case "linux":return new wn;default:throw new Error(`Unsupported platform: ${e}`)}}},Pt=class{manager;constructor(){this.manager=Cn.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 xt,lo=m(()=>{xt=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let r of n.fileExtensions)this.extensionToLanguageMap.set(r,t);}detectLanguage(e){let t=P__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function Hi(){let s=he.platform();if(s==="darwin")return P.join(he.homedir(),"Library","Caches","constellation");if(s==="win32"){let e=process.env.LOCALAPPDATA||P.join(he.homedir(),"AppData","Local");return P.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||P.join(he.homedir(),".cache");return P.join(e,"constellation")}}var Gi,Wi,zi,Le,vn=m(()=>{Gi=Hi(),Wi="update-state.json",zi=1440*60*1e3,Le=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??Gi,this.stateFile=P.join(this.stateDir,Wi);}async load(){if(this.state)return this.state;try{let e=await M.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await M.mkdir(this.stateDir,{recursive:!0}),await M.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>zi}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 M.unlink(this.stateFile),this.state=null;}catch{}}};});var Oe,_n=m(()=>{Oe=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(r=>{let i=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});i.on("close",o=>{r(o===0);}),i.on("error",()=>{r(false);});})}};});var Fe,En=m(()=>{ze();F();Fe=class{async promptForUpdate(e,t,n){console.log(""),console.log(p.cyan("\u2501".repeat(60))),console.log(`${J} ${p.bold("Update Available!")}`),console.log(""),console.log(` Current version: ${p.dim(e)}`),console.log(` Latest version: ${p.green.bold(t)}`),console.log(""),console.log(` ${p.dim(`Package manager: ${n}`)}`),console.log(p.cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:k})}catch{return false}}};});async function Sn(s){return new Rt().check(s)}var Ji,It,Yi,Rt,co=m(()=>{F();vn();_n();En();Ji="https://registry.npmjs.org",It="@constellationdev/cli",Yi=5e3,Rt=class{cache;packageManager;prompter;constructor(){this.cache=new Le,this.packageManager=new Oe,this.prompter=new Fe;}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(),Yi);try{let r=await fetch(`${Ji}/${It}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Registry returned ${r.status}`);let o=(await r.json()).version;return {current:e,latest:o,hasUpdate:this.isNewerVersion(o,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=o=>o.split("-")[0],r=n(e).split(".").map(Number),i=n(t).split(".").map(Number);for(let o=0;o<3;o++){let a=r[o]||0,l=i[o]||0;if(a>l)return true;if(a<l)return false}return false}async performUpdate(){return console.log(`
|
|
192
|
+
${w} Updating ${It}...
|
|
193
|
+
`),await this.packageManager.executeUpdate(It)?(console.log(`
|
|
194
|
+
${C} Update complete! Please re-run your command.
|
|
189
195
|
`),true):(console.log(`
|
|
190
|
-
${
|
|
191
|
-
`),false)}};});var
|
|
192
|
-
Modified: ${r.modified}, Created: ${r.created}, Deleted: ${r.deleted}, Conflicted: ${r.conflicted}, Staged: ${r.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let r=await this.git.status();if(r.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",r.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${r.conflicted.length} file(s): ${r.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",n.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(console.error("\u274C Pull failed due to merge conflicts"),console.error(' Run "git status" to see conflicted files'),console.error(' Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?console.error("\u274C Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?console.error("\u274C Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?console.error("\u274C Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&console.error("\u274C Pull failed: Uncommitted changes in working directory"),new Error(`Git pull operation failed: ${e.message}`,{cause:e})):new Error(`Git pull operation failed: ${String(e)}`)}}};});var
|
|
193
|
-
${
|
|
196
|
+
${y} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(It)}
|
|
197
|
+
`),false)}};});var po=m(()=>{vn();_n();En();co();});function Xi(){return qi.some(s=>!!process.env[s])}function Qi(){return !!process.stdout.isTTY}function go(){return !Xi()&&Qi()}var qi,uo=m(()=>{qi=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});var De,fo=m(()=>{De=class{git;constructor(e){let t={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(t);}async getLatestCommitHash(){let e=await this.git.log({maxCount:1});if(!e.latest)throw new Error("No commits found in repository");return e.latest.hash}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},r=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);for(let i of r){let o=i.split(" ");if(o.length<2)continue;let a=o[0];a==="A"?n.added.push(o[1]):a==="M"?n.modified.push(o[1]):a==="D"?n.deleted.push(o[1]):a.startsWith("R")&&o.length>=3&&n.renamed.push({from:o[1],to:o[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 r={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw console.error("\u274C Cannot pull: Working directory has uncommitted changes"),console.error(" Details:",JSON.stringify(r,null,2)),e.conflicted.length>0&&console.error(" \u26A0\uFE0F Conflicted files:",e.conflicted.join(", ")),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
|
|
198
|
+
Modified: ${r.modified}, Created: ${r.created}, Deleted: ${r.deleted}, Conflicted: ${r.conflicted}, Staged: ${r.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let r=await this.git.status();if(r.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",r.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${r.conflicted.length} file(s): ${r.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",n.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(console.error("\u274C Pull failed due to merge conflicts"),console.error(' Run "git status" to see conflicted files'),console.error(' Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?console.error("\u274C Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?console.error("\u274C Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?console.error("\u274C Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&console.error("\u274C Pull failed: Uncommitted changes in working directory"),new Error(`Git pull operation failed: ${e.message}`,{cause:e})):new Error(`Git pull operation failed: ${String(e)}`)}}};});var rs={};var mo,Pn,xn,Me,ho=m(async()=>{We();Gn();Dr();oo();io();ao();lo();gt();po();$t();Ke();uo();fo();F();process.on("uncaughtException",s=>{s instanceof Error&&s.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${b} An unexpected error occurred during the index attempt:
|
|
199
|
+
${s?.message??String(s)}`),process.exit(1);});mo=globalThis.__constellationVersion??(()=>{let s=P__default.dirname(fileURLToPath(import.meta.url)),e=P__default.join(s,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})();if(go()){let s=process.argv[2];["auth","help","init","index"].includes(s)?kt(s):kt(),Ue.includes(s)||await Sn(mo)&&process.exit(0);}Pn=process.cwd(),xn=new Pt,Me=new Command;Me.name("constellation").description("Connecting stars in your code into intelligent patterns").version(mo);Me.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 s=>{try{let t={GitClient:new De(Pn)};await new Ae(t).run({skipMcp:s.skipMcp,skipCi:s.skipCi});}catch(e){console.error(`${b} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Me.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async s=>{try{let e={Environment:xn};await new ve(e).run(s.manual);}catch(e){console.error(`${b} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Me.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 s=>{try{let e=await St.loadFromFile(P__default.join(Pn,"constellation.json")),t=new De(Pn),n=new pt(e),r=new xt(e),i={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:r,Environment:xn},o=xn.isCI(),a=s.full||!s.incremental&&o,l=s.dirty||!1,g=s.enrich===!1;!s.full&&!s.incremental&&o&&console.log(`${w} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new Ie(i).run(a,l,g);}catch(e){!(e instanceof R)&&!(e instanceof D)&&console.error(`${b} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Me.parse();});var wo=/^>=\s*\d+\.\d+\.\d+$/;function $n(s,e=process.version){if(!wo.test(s))return {compatible:true,current:e,required:s};let t=s.replace(/^>=\s*/,""),n=e.replace(/^v/,""),r=t.split(".").map(Number),i=n.split(".").map(Number),o=true;for(let a=0;a<3;a++){let l=r[a]||0,g=i[a]||0;if(g>l)break;if(g<l){o=false;break}}return {compatible:o,current:e,required:s}}$t();var ls=dirname(fileURLToPath(import.meta.url)),cs=join(ls,"..","package.json"),In=JSON.parse(readFileSync(cs,"utf-8")),ps=process.argv[2];if(!Ue.includes(ps)&&In.engines?.node){let s=$n(In.engines.node);s.compatible||(console.error(`Error: Constellation CLI requires Node.js ${s.required} (current: ${s.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=In.version;await ho().then(()=>rs);
|
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.
|
|
4
|
+
"version": "0.4.0",
|
|
5
5
|
"author": "ShiftinBits Inc",
|
|
6
6
|
"main": "dist/main.js",
|
|
7
7
|
"type": "module",
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@constellationdev/types": "github:ShiftinBits/constellation-types#main",
|
|
28
28
|
"@iarna/toml": "^3.0.0",
|
|
29
|
+
"@inquirer/prompts": "^8.4.1",
|
|
29
30
|
"@scure/base": "^2.0.0",
|
|
30
31
|
"ansi-colors": "^4.1.3",
|
|
31
32
|
"commander": "^14.0.1",
|
|
32
|
-
"enquirer": "^2.4.1",
|
|
33
33
|
"ignore": "^7.0.5",
|
|
34
34
|
"simple-git": "^3.28.0",
|
|
35
35
|
"tree-sitter": "^0.21.1",
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"tree-sitter-typescript": "^0.21.2",
|
|
39
39
|
"tsconfck": "^3.1.6",
|
|
40
40
|
"undici": "^7.22.0",
|
|
41
|
+
"vscode-languageserver-protocol": "^3.17.5",
|
|
41
42
|
"yaml": "^2.8.3",
|
|
42
43
|
"zod": "^3.23.8"
|
|
43
44
|
},
|